File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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' , ( ) => {
You can’t perform that action at this time.
0 commit comments