Skip to content

Commit f3b06d9

Browse files
authored
fix: not create stream if it already exists (#48)
1 parent d478ed0 commit f3b06d9

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/index.js

+4
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,10 @@ class PubsubBaseProtocol extends EventEmitter {
196196
protocols: this.multicodecs
197197
}))
198198

199+
if (peer.isConnected) {
200+
return
201+
}
202+
199203
try {
200204
const { stream } = await conn.newStream(this.multicodecs)
201205
peer.attachConnection(stream)

test/pubsub.spec.js

+23
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,29 @@ describe('pubsub base protocol', () => {
189189
expect(pubsubB.peers.size).to.be.eql(1)
190190
})
191191

192+
it('should not create a new stream if onConnect is called twice', async () => {
193+
const onConnectA = registrarRecordA[protocol].onConnect
194+
const handlerB = registrarRecordB[protocol].handler
195+
196+
// Notice peers of connection
197+
const [c0, c1] = ConnectionPair()
198+
199+
const spyNewStream = sinon.spy(c0, 'newStream')
200+
201+
await onConnectA(peerIdB, c0)
202+
await handlerB({
203+
protocol,
204+
stream: c1.stream,
205+
connection: {
206+
remotePeer: peerIdA
207+
}
208+
})
209+
expect(spyNewStream).to.have.property('callCount', 1)
210+
211+
await onConnectA(peerIdB, c0)
212+
expect(spyNewStream).to.have.property('callCount', 1)
213+
})
214+
192215
it('should handle newStream errors in onConnect', async () => {
193216
const onConnectA = registrarRecordA[protocol].onConnect
194217
const handlerB = registrarRecordB[protocol].handler

0 commit comments

Comments
 (0)