import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
import type {
IWorkerChoiceStrategy,
- StrategyPolicy,
WorkerChoiceStrategyOptions
} from './selection-strategies-types'
>
extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
implements IWorkerChoiceStrategy {
- /** @inheritDoc */
- public readonly strategyPolicy: StrategyPolicy = {
- useDynamicWorker: true
- }
-
/** @inheritDoc */
public constructor (
pool: IPool<Worker, Data, Response>,
/** @inheritDoc */
public reset (): boolean {
- this.nextWorkerNodeId = 0
+ this.resetWorkerNodeKeyProperties()
return true
}
}
/** @inheritDoc */
- public choose (): number {
- const chosenWorkerNodeKey = this.nextWorkerNodeId
- this.nextWorkerNodeId =
- this.nextWorkerNodeId === this.pool.workerNodes.length - 1
- ? 0
- : this.nextWorkerNodeId + 1
+ public choose (): number | undefined {
+ const chosenWorkerNodeKey = this.nextWorkerNodeKey
+ this.setPreviousWorkerNodeKey(chosenWorkerNodeKey)
+ this.roundRobinNextWorkerNodeKey()
return chosenWorkerNodeKey
}
/** @inheritDoc */
public remove (workerNodeKey: number): boolean {
- if (this.nextWorkerNodeId === workerNodeKey) {
- if (this.pool.workerNodes.length === 0) {
- this.nextWorkerNodeId = 0
- } else if (this.nextWorkerNodeId > this.pool.workerNodes.length - 1) {
- this.nextWorkerNodeId = this.pool.workerNodes.length - 1
- }
+ if (this.pool.workerNodes.length === 0) {
+ this.reset()
+ }
+ if (
+ this.nextWorkerNodeKey === workerNodeKey &&
+ this.nextWorkerNodeKey > this.pool.workerNodes.length - 1
+ ) {
+ this.nextWorkerNodeKey = this.pool.workerNodes.length - 1
+ }
+ if (
+ this.previousWorkerNodeKey === workerNodeKey &&
+ this.previousWorkerNodeKey > this.pool.workerNodes.length - 1
+ ) {
+ this.previousWorkerNodeKey = this.pool.workerNodes.length - 1
}
return true
}
+
+ private roundRobinNextWorkerNodeKey (): number | undefined {
+ this.nextWorkerNodeKey =
+ this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
+ ? 0
+ : (this.nextWorkerNodeKey ?? this.previousWorkerNodeKey) + 1
+ return this.nextWorkerNodeKey
+ }
}