Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix: remove initial error handler when a conn opens #180

Merged
merged 2 commits into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading