Skip to content

Commit

Permalink
Also keep track of server connections
Browse files Browse the repository at this point in the history
  • Loading branch information
HDegroote committed Jun 10, 2024
1 parent ed21507 commit 40abbf2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
8 changes: 8 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,13 @@ module.exports = class Hyperswarm extends EventEmitter {
return
}

// The _handleServerConnectionSwam path above calls _handleServerConnection
// again, so this is the moment where the conn is actually considered 'attempted'
this.stats.connects.attempted++
conn.on('open', () => {
this.stats.connects.opened++
})

const peerInfo = this._upsertPeer(conn.remotePublicKey, null)

this.connections.add(conn)
Expand All @@ -314,6 +321,7 @@ module.exports = class Hyperswarm extends EventEmitter {
this.connections.delete(conn)
this._allConnections.delete(conn)
this._serverConnections--
this.stats.connects.closed++

this._maybeDeletePeer(peerInfo)

Expand Down
23 changes: 19 additions & 4 deletions test/stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ test('connectionsOpened and connectionsClosed stats', async (t) => {
const swarm2 = new Hyperswarm({ bootstrap })

const tOpen = t.test('Open connection')
tOpen.plan(2)
tOpen.plan(4)
const tClose = t.test('Close connection')
tClose.plan(2)
tClose.plan(4)

t.teardown(async () => {
await swarm1.destroy()
Expand All @@ -21,6 +21,7 @@ test('connectionsOpened and connectionsClosed stats', async (t) => {

swarm2.on('connection', (conn) => {
conn.on('error', noop)

tOpen.is(swarm2.stats.connects.opened, 1, 'opened connection is in stats')
tOpen.is(swarm2.stats.connects.attempted, 1, 'attemped connection is in stats')
tClose.is(swarm2.stats.connects.closed, 0, 'sanity check')
Expand All @@ -29,16 +30,30 @@ test('connectionsOpened and connectionsClosed stats', async (t) => {
tClose.is(swarm2.stats.connects.closed, 1, 'closed connection is in stats')
})

conn.destroy()
conn.end()
})

swarm1.on('connection', (conn) => {
conn.on('error', noop)
conn.on('error', () => noop)

conn.on('open', () => {
tOpen.is(swarm1.stats.connects.opened, 1, 'opened server connection is in stats')
tOpen.is(swarm1.stats.connects.attempted, 1, 'attempted connection is in status')
tClose.is(swarm1.stats.connects.closed, 0, 'Sanity checks')
})

conn.on('close', () => {
tClose.is(swarm1.stats.connects.closed, 1, 'closed connections is in stats')
})

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 })

await tClose
})

function noop () {}

0 comments on commit 40abbf2

Please sign in to comment.