Skip to content

Commit

Permalink
fix: catch newStream errors (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobheun authored and vasco-santos committed Jan 7, 2020
1 parent 1b866ca commit 57453d4
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -171,10 +171,13 @@ class PubsubBaseProtocol extends EventEmitter {
this.log('connected', idB58Str)

const peer = this._addPeer(new Peer(peerInfo))
const { stream } = await conn.newStream(this.multicodecs)

peer.attachConnection(stream)
this._processMessages(idB58Str, stream, peer)
try {
const { stream } = await conn.newStream(this.multicodecs)
peer.attachConnection(stream)
this._processMessages(idB58Str, stream, peer)
} catch (err) {
this.log.err(err)
}
}

/**
Expand Down Expand Up @@ -220,6 +223,7 @@ class PubsubBaseProtocol extends EventEmitter {
* @returns {PeerInfo}
*/
_removePeer (peer) {
if (!peer) return
const id = peer.info.id.toB58String()

this.log('remove', id, peer._references)
Expand Down
32 changes: 32 additions & 0 deletions test/pubsub.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,27 @@ describe('pubsub base protocol', () => {
expect(pubsubB.peers.size).to.be.eql(1)
})

it('should handle newStream errors in onConnect', async () => {
const onConnectA = registrarRecordA[protocol].onConnect
const handlerB = registrarRecordB[protocol].handler

// Notice peers of connection
const [c0, c1] = ConnectionPair()
const error = new Error('new stream error')
sinon.stub(c0, 'newStream').throws(error)

await onConnectA(peerInfoB, c0)
await handlerB({
protocol,
stream: c1.stream,
connection: {
remotePeer: peerInfoA.id
}
})

expect(c0.newStream).to.have.property('callCount', 1)
})

it('should handle onDisconnect as expected', async () => {
const onConnectA = registrarRecordA[protocol].onConnect
const onDisconnectA = registrarRecordA[protocol].onDisconnect
Expand All @@ -214,6 +235,17 @@ describe('pubsub base protocol', () => {
expect(pubsubA.peers.size).to.be.eql(0)
expect(pubsubB.peers.size).to.be.eql(0)
})

it('should handle onDisconnect for unknown peers', () => {
const onDisconnectA = registrarRecordA[protocol].onDisconnect

expect(pubsubA.peers.size).to.be.eql(0)

// Notice peers of disconnect
onDisconnectA(peerInfoB)

expect(pubsubA.peers.size).to.be.eql(0)
})
})

describe('getSubscribers', () => {
Expand Down

0 comments on commit 57453d4

Please sign in to comment.