This repository has been archived by the owner on Mar 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 124
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: wait until nodes are connected before starting ping tests
License: MIT Signed-off-by: Alan Shaw <alan@tableflip.io>
- Loading branch information
Showing
2 changed files
with
65 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
const waterfall = require('async/waterfall') | ||
|
||
function waitUntilConnected (fromNode, toNode, opts, cb) { | ||
if (typeof opts === 'function') { | ||
cb = opts | ||
opts = {} | ||
} | ||
|
||
opts = opts || {} | ||
opts.timeout = opts.timeout || 15000 | ||
opts.interval = opts.interval || 1000 | ||
|
||
const startTime = Date.now() | ||
const checkConnected = () => { | ||
isConnected(fromNode, toNode, (err, connected) => { | ||
if (err) return cb(err) | ||
if (connected) return cb() | ||
|
||
if (Date.now() > startTime + opts.timeout) { | ||
return cb(new Error('timeout waiting for connected nodes')) | ||
} | ||
|
||
setTimeout(checkConnected, opts.interval) | ||
}) | ||
} | ||
|
||
checkConnected() | ||
} | ||
|
||
exports.waitUntilConnected = waitUntilConnected | ||
|
||
function isConnected (fromNode, toNode, cb) { | ||
waterfall([ | ||
(cb) => { | ||
if (toNode.peerId) return cb(null, toNode.peerId) | ||
toNode.id((err, id) => { | ||
if (err) return cb(err) | ||
toNode.peerId = id | ||
cb(null, id) | ||
}) | ||
}, | ||
(toPeerId, cb) => { | ||
fromNode.swarm.peers((err, peers) => { | ||
if (err) return cb(err) | ||
cb(null, peers.some((p) => p.peer.toJSON().id === toPeerId.id)) | ||
}) | ||
} | ||
], cb) | ||
} | ||
|
||
exports.isConnected = isConnected |