Skip to content

Commit be8fc9d

Browse files
authored
fix: stop stream after first pong received (#545)
When connecting to go-IPFS from a webworker, the stream opened by the ping protocol is never closed. The change here uses `take` to only receive one buffer from the remote node before closing the stream.
1 parent f39e8f0 commit be8fc9d

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/ping/index.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ const errCode = require('err-code')
88
const crypto = require('libp2p-crypto')
99
const pipe = require('it-pipe')
1010
const { toBuffer } = require('it-buffer')
11-
const { collect } = require('streaming-iterables')
11+
const { collect, take } = require('streaming-iterables')
1212

1313
const { PROTOCOL, PING_LENGTH } = require('./constants')
1414

@@ -29,6 +29,7 @@ async function ping (node, peer) {
2929
const [result] = await pipe(
3030
[data],
3131
stream,
32+
stream => take(1, stream),
3233
toBuffer,
3334
collect
3435
)

test/core/ping.node.js

+38
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@ chai.use(require('dirty-chai'))
66
const { expect } = chai
77

88
const pTimes = require('p-times')
9+
const pipe = require('it-pipe')
910

1011
const peerUtils = require('../utils/creators/peer')
1112
const baseOptions = require('../utils/base-options')
13+
const { PROTOCOL } = require('../../src/ping/constants')
1214

1315
describe('ping', () => {
1416
let nodes
@@ -32,4 +34,40 @@ describe('ping', () => {
3234
const averageLatency = latencies.reduce((p, c) => p + c, 0) / latencies.length
3335
expect(averageLatency).to.be.a('Number')
3436
})
37+
38+
it('only waits for the first response to arrive', async () => {
39+
nodes[1].handle(PROTOCOL, async ({ connection, stream }) => {
40+
let firstInvocation = true
41+
42+
await pipe(
43+
stream,
44+
function (stream) {
45+
const output = {
46+
[Symbol.asyncIterator]: () => output,
47+
next: async () => {
48+
if (firstInvocation) {
49+
firstInvocation = false
50+
51+
for await (const data of stream) {
52+
return {
53+
value: data,
54+
done: false
55+
}
56+
}
57+
} else {
58+
return new Promise() // never resolve
59+
}
60+
}
61+
}
62+
63+
return output
64+
},
65+
stream
66+
)
67+
})
68+
69+
const latency = await nodes[0].ping(nodes[1].peerInfo)
70+
71+
expect(latency).to.be.a('Number')
72+
})
3573
})

0 commit comments

Comments
 (0)