From f3b06d96731b5d95cc9e14d1073ea9d4f7bec71a Mon Sep 17 00:00:00 2001 From: Vasco Santos Date: Mon, 15 Jun 2020 13:27:09 +0200 Subject: [PATCH] fix: not create stream if it already exists (#48) --- src/index.js | 4 ++++ test/pubsub.spec.js | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/index.js b/src/index.js index 79e2fc8705..9daa573e28 100644 --- a/src/index.js +++ b/src/index.js @@ -196,6 +196,10 @@ class PubsubBaseProtocol extends EventEmitter { protocols: this.multicodecs })) + if (peer.isConnected) { + return + } + try { const { stream } = await conn.newStream(this.multicodecs) peer.attachConnection(stream) diff --git a/test/pubsub.spec.js b/test/pubsub.spec.js index a74b6b79de..52cc9fedae 100644 --- a/test/pubsub.spec.js +++ b/test/pubsub.spec.js @@ -189,6 +189,29 @@ describe('pubsub base protocol', () => { expect(pubsubB.peers.size).to.be.eql(1) }) + it('should not create a new stream if onConnect is called twice', async () => { + const onConnectA = registrarRecordA[protocol].onConnect + const handlerB = registrarRecordB[protocol].handler + + // Notice peers of connection + const [c0, c1] = ConnectionPair() + + const spyNewStream = sinon.spy(c0, 'newStream') + + await onConnectA(peerIdB, c0) + await handlerB({ + protocol, + stream: c1.stream, + connection: { + remotePeer: peerIdA + } + }) + expect(spyNewStream).to.have.property('callCount', 1) + + await onConnectA(peerIdB, c0) + expect(spyNewStream).to.have.property('callCount', 1) + }) + it('should handle newStream errors in onConnect', async () => { const onConnectA = registrarRecordA[protocol].onConnect const handlerB = registrarRecordB[protocol].handler