@@ -164,35 +164,14 @@ class BalancedPool extends PoolBase {
164164 throw new BalancedPoolMissingUpstreamError ( )
165165 }
166166
167- const dispatcher = this [ kClients ] . find ( dispatcher => (
168- ! dispatcher [ kNeedDrain ] &&
169- dispatcher . closed !== true &&
170- dispatcher . destroyed !== true
171- ) )
172-
173- if ( ! dispatcher ) {
174- return
175- }
176-
177- const allClientsBusy = this [ kClients ] . map ( pool => pool [ kNeedDrain ] ) . reduce ( ( a , b ) => a && b , true )
178-
179- if ( allClientsBusy ) {
180- return
181- }
182-
183167 let counter = 0
184168
185- let maxWeightIndex = this [ kClients ] . findIndex ( pool => ! pool [ kNeedDrain ] )
169+ let maxWeightIndex = - 1
186170
187171 while ( counter ++ < this [ kClients ] . length ) {
188172 this [ kIndex ] = ( this [ kIndex ] + 1 ) % this [ kClients ] . length
189173 const pool = this [ kClients ] [ this [ kIndex ] ]
190174
191- // find pool index with the largest weight
192- if ( pool [ kWeight ] > this [ kClients ] [ maxWeightIndex ] [ kWeight ] && ! pool [ kNeedDrain ] ) {
193- maxWeightIndex = this [ kIndex ]
194- }
195-
196175 // decrease the current weight every `this[kClients].length`.
197176 if ( this [ kIndex ] === 0 ) {
198177 // Set the current weight to the next lower weight.
@@ -202,11 +181,30 @@ class BalancedPool extends PoolBase {
202181 this [ kCurrentWeight ] = this [ kMaxWeightPerServer ]
203182 }
204183 }
205- if ( pool [ kWeight ] >= this [ kCurrentWeight ] && ( ! pool [ kNeedDrain ] ) ) {
184+
185+ // Skip unavailable pools after updating the current weight for this cycle.
186+ if (
187+ pool [ kNeedDrain ] ||
188+ pool . closed === true ||
189+ pool . destroyed === true
190+ ) {
191+ continue
192+ }
193+
194+ // Track the best fallback if no pool matches the current weight.
195+ if ( maxWeightIndex === - 1 || pool [ kWeight ] > this [ kClients ] [ maxWeightIndex ] [ kWeight ] ) {
196+ maxWeightIndex = this [ kIndex ]
197+ }
198+
199+ if ( pool [ kWeight ] >= this [ kCurrentWeight ] ) {
206200 return pool
207201 }
208202 }
209203
204+ if ( maxWeightIndex === - 1 ) {
205+ return
206+ }
207+
210208 this [ kCurrentWeight ] = this [ kClients ] [ maxWeightIndex ] [ kWeight ]
211209 this [ kIndex ] = maxWeightIndex
212210 return this [ kClients ] [ maxWeightIndex ]
0 commit comments