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

Commit 1b60f24

Browse files
committedMay 16, 2018
fix: wait until nodes are connected before starting ping tests
License: MIT Signed-off-by: Alan Shaw <[email protected]>
1 parent f5ccada commit 1b60f24

File tree

2 files changed

+65
-7
lines changed

2 files changed

+65
-7
lines changed
 

‎js/src/ping.js

+14-7
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ const dirtyChai = require('dirty-chai')
66
const pull = require('pull-stream')
77
const pump = require('pump')
88
const { Writable } = require('stream')
9+
const series = require('async/series')
910
const { spawnNodesWithId } = require('./utils/spawn')
11+
const { waitUntilConnected } = require('./utils/connections')
1012

1113
const expect = chai.expect
1214
chai.use(dirtyChai)
@@ -21,7 +23,7 @@ function expectIsPingResponse (obj) {
2123
}
2224

2325
module.exports = (common) => {
24-
describe('.ping', function () {
26+
describe.only('.ping', function () {
2527
let ipfsdA
2628
let ipfsdB
2729

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

34-
spawnNodesWithId(2, factory, (err, nodes) => {
35-
if (err) return done(err)
36-
ipfsdA = nodes[0]
37-
ipfsdB = nodes[1]
38-
done()
39-
})
36+
series([
37+
(cb) => {
38+
spawnNodesWithId(2, factory, (err, nodes) => {
39+
if (err) return cb(err)
40+
ipfsdA = nodes[0]
41+
ipfsdB = nodes[1]
42+
cb()
43+
})
44+
},
45+
(cb) => waitUntilConnected(ipfsdA, ipfsdB, cb)
46+
], done)
4047
})
4148
})
4249

‎js/src/utils/connections.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
const waterfall = require('async/waterfall')
2+
3+
function waitUntilConnected (fromNode, toNode, opts, cb) {
4+
if (typeof opts === 'function') {
5+
cb = opts
6+
opts = {}
7+
}
8+
9+
opts = opts || {}
10+
opts.timeout = opts.timeout || 15000
11+
opts.interval = opts.interval || 1000
12+
13+
const startTime = Date.now()
14+
const checkConnected = () => {
15+
isConnected(fromNode, toNode, (err, connected) => {
16+
if (err) return cb(err)
17+
if (connected) return cb()
18+
19+
if (Date.now() > startTime + opts.timeout) {
20+
return cb(new Error('timeout waiting for connected nodes'))
21+
}
22+
23+
setTimeout(checkConnected, opts.interval)
24+
})
25+
}
26+
27+
checkConnected()
28+
}
29+
30+
exports.waitUntilConnected = waitUntilConnected
31+
32+
function isConnected (fromNode, toNode, cb) {
33+
waterfall([
34+
(cb) => {
35+
if (toNode.peerId) return cb(null, toNode.peerId)
36+
toNode.id((err, id) => {
37+
if (err) return cb(err)
38+
toNode.peerId = id
39+
cb(null, id)
40+
})
41+
},
42+
(toPeerId, cb) => {
43+
fromNode.swarm.peers((err, peers) => {
44+
if (err) return cb(err)
45+
cb(null, peers.some((p) => p.peer.toJSON().id === toPeerId.id))
46+
})
47+
}
48+
], cb)
49+
}
50+
51+
exports.isConnected = isConnected

0 commit comments

Comments
 (0)