Skip to content

Commit f50db02

Browse files
committed
fix: don't blow up if you reach max integer requests
1 parent 7cb5e0a commit f50db02

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

lib/LoadBalancer.mjs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ export default class LoadBalancer {
3636
selectRoundRobin(instances) {
3737
if (instances.length === 0) return null
3838

39+
// Reset counter if approaching MAX_SAFE_INTEGER to prevent overflow
40+
if (this.roundRobinIndex >= Number.MAX_SAFE_INTEGER - 1) {
41+
this.roundRobinIndex = 0
42+
}
43+
3944
const selectedInstance = instances[this.roundRobinIndex % instances.length]
4045
this.roundRobinIndex = (this.roundRobinIndex + 1) % instances.length
4146

test/LoadBalancer.test.mjs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,28 @@ describe('LoadBalancer', () => {
7979
assert.strictEqual(instance.instanceId, 'client-1')
8080
}
8181
})
82+
83+
test('should reset counter when approaching MAX_SAFE_INTEGER', () => {
84+
const instances = [
85+
{ instanceId: 'client-1' },
86+
{ instanceId: 'client-2' },
87+
{ instanceId: 'client-3' }
88+
]
89+
90+
// Set counter close to MAX_SAFE_INTEGER
91+
loadBalancer.roundRobinIndex = Number.MAX_SAFE_INTEGER - 1
92+
93+
// Should reset and continue normally
94+
const instance = loadBalancer.selectRoundRobin(instances)
95+
assert(instance)
96+
assert.strictEqual(instance.instanceId, 'client-1') // Starts from beginning after reset
97+
assert.strictEqual(loadBalancer.roundRobinIndex, 1) // Incremented to 1 after selecting index 0
98+
99+
// Next call should work normally
100+
const nextInstance = loadBalancer.selectRoundRobin(instances)
101+
assert.strictEqual(nextInstance.instanceId, 'client-2')
102+
assert.strictEqual(loadBalancer.roundRobinIndex, 2)
103+
})
82104
})
83105

84106
describe('selectRandom', () => {

0 commit comments

Comments
 (0)