Skip to content
This repository has been archived by the owner on Mar 10, 2020. It is now read-only.

Commit

Permalink
fix: wait until nodes are connected before starting ping tests
Browse files Browse the repository at this point in the history
License: MIT
Signed-off-by: Alan Shaw <alan@tableflip.io>
  • Loading branch information
alanshaw committed May 16, 2018
1 parent f5ccada commit 1b60f24
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 7 deletions.
21 changes: 14 additions & 7 deletions js/src/ping.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ const dirtyChai = require('dirty-chai')
const pull = require('pull-stream')
const pump = require('pump')
const { Writable } = require('stream')
const series = require('async/series')
const { spawnNodesWithId } = require('./utils/spawn')
const { waitUntilConnected } = require('./utils/connections')

const expect = chai.expect
chai.use(dirtyChai)
Expand All @@ -21,7 +23,7 @@ function expectIsPingResponse (obj) {
}

module.exports = (common) => {
describe('.ping', function () {
describe.only('.ping', function () {
let ipfsdA
let ipfsdB

Expand All @@ -31,12 +33,17 @@ module.exports = (common) => {
common.setup((err, factory) => {
if (err) return done(err)

spawnNodesWithId(2, factory, (err, nodes) => {
if (err) return done(err)
ipfsdA = nodes[0]
ipfsdB = nodes[1]
done()
})
series([
(cb) => {
spawnNodesWithId(2, factory, (err, nodes) => {
if (err) return cb(err)
ipfsdA = nodes[0]
ipfsdB = nodes[1]
cb()
})
},
(cb) => waitUntilConnected(ipfsdA, ipfsdB, cb)
], done)
})
})

Expand Down
51 changes: 51 additions & 0 deletions js/src/utils/connections.js
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

0 comments on commit 1b60f24

Please sign in to comment.