Skip to content
Draft
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
6 changes: 3 additions & 3 deletions lib/dispatcher/round-robin-pool.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ class RoundRobinPool extends PoolBase {

// Round-robin through existing clients
let checked = 0
while (checked < clientsLength) {
this[kIndex] = (this[kIndex] + 1) % clientsLength
while (checked < clientsLength && this[kClients].length > 0) {
this[kIndex] = (this[kIndex] + 1) % this[kClients].length
const client = this[kClients][this[kIndex]]

// Check if client is stale (TTL expired)
Expand All @@ -123,7 +123,7 @@ class RoundRobinPool extends PoolBase {
}

// All clients are busy, create a new one if we haven't reached the limit
if (!this[kConnections] || clientsLength < this[kConnections]) {
if (!this[kConnections] || this[kClients].length < this[kConnections]) {
const dispatcher = this[kFactory](this[kUrl], this[kOptions])
this[kAddClient](dispatcher)
return dispatcher
Expand Down
45 changes: 45 additions & 0 deletions test/round-robin-pool.js
Original file line number Diff line number Diff line change
Expand Up @@ -382,3 +382,48 @@

await t.completed
})

test('does not crash when multiple clients are evicted by TTL in one dispatch', (t) => {
const p = tspl(t, { plan: 2 })

const { EventEmitter } = require('node:events')
const { kNeedDrain, kAddClient, kGetDispatcher } = require('../lib/dispatcher/pool-base')

class FakeClient extends EventEmitter {
constructor () {
super()
this.closed = false
this.destroyed = false
this[kNeedDrain] = false
}

close (cb) {
this.closed = true
if (cb) cb()
}

destroy (err, cb) { if (cb) cb() }

Check failure on line 405 in test/round-robin-pool.js

View workflow job for this annotation

GitHub Actions / Lint

Expected error to be handled
dispatch () { return true }
}

const pool = new RoundRobinPool('http://localhost', {
connections: 10,
clientTtl: 1,
factory: () => new FakeClient()
})

// Seed two clients with stale TTLs so the round-robin loop tries to evict
// both in a single dispatch. Before the fix, the stale `clientsLength`
// caused the loop to index past the shrinking array and crash with
// "Cannot read properties of undefined (reading 'ttl')".
const c1 = new FakeClient()
const c2 = new FakeClient()
pool[kAddClient](c1)
pool[kAddClient](c2)
c1.ttl = Date.now() - 1000
c2.ttl = Date.now() - 1000

const dispatcher = pool[kGetDispatcher]()
p.ok(dispatcher, 'dispatch returned a client without crashing')
p.ok(dispatcher instanceof FakeClient)
})
Loading