Skip to content

Commit

Permalink
Bugfix: remove initial error handler when a conn opens (#180)
Browse files Browse the repository at this point in the history
* Bugfix: remove initial error handler when a conn opens

* rename to onerror

---------

Co-authored-by: Mathias Buus <[email protected]>
  • Loading branch information
HDegroote and mafintosh authored Jul 24, 2024
1 parent 9cd179c commit bc7a67e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
20 changes: 12 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,27 +187,31 @@ module.exports = class Hyperswarm extends EventEmitter {
this._clientConnections++
let opened = false

const onerror = (err) => {
if (this.relayThrough && shouldForceRelaying(err.code)) {
peerInfo.forceRelaying = true
// Reset the attempts in order to fast connect to relay
peerInfo.attempts = 0
}
}

// Removed once a connection is opened
conn.on('error', onerror)

conn.on('open', () => {
opened = true
this.stats.connects.client.opened++

this._connectDone()
this.connections.add(conn)
conn.removeListener('error', noop)
conn.removeListener('error', onerror)
peerInfo._connected()
peerInfo.client = true
this.emit('connection', conn, peerInfo)
this._flushMaybe(peerInfo)

this.emit('update')
})
conn.on('error', err => {
if (this.relayThrough && shouldForceRelaying(err.code)) {
peerInfo.forceRelaying = true
// Reset the attempts in order to fast connect to relay
peerInfo.attempts = 0
}
})
conn.on('close', () => {
if (!opened) this._connectDone()
this.stats.connects.client.closed++
Expand Down
29 changes: 29 additions & 0 deletions test/swarm.js
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,35 @@ test('peer-discovery object deleted when corresponding connection closes (client
await swarm1.destroy()
})

test('no default error handler set when connection event is emitted', async (t) => {
t.plan(2)

const { bootstrap } = await createTestnet(3, t.teardown)

const swarm1 = new Hyperswarm({ bootstrap })
const swarm2 = new Hyperswarm({ bootstrap })

t.teardown(async () => {
await swarm1.destroy()
await swarm2.destroy()
})

swarm2.on('connection', (conn) => {
t.is(conn.listeners('error').length, 0, 'no error listeners')
conn.on('error', noop)
conn.end()
})
swarm1.on('connection', (conn) => {
t.is(conn.listeners('error').length, 0, 'no error listeners')
conn.on('error', noop)
conn.end()
})

const topic = Buffer.alloc(32).fill('hello world')
await swarm1.join(topic, { server: true, client: false }).flushed()
swarm2.join(topic, { client: true, server: false })
})

function noop () {}

function eventFlush () {
Expand Down

0 comments on commit bc7a67e

Please sign in to comment.