Skip to content
This repository was archived by the owner on Mar 10, 2020. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -26,17 +28,22 @@ module.exports = (common) => {
let ipfsdB

before(function (done) {
this.timeout(30 * 1000)
this.timeout(60 * 1000)

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 || 30000
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