1 import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
} from
'../../utils'
2 import type { IPool
} from
'../pool'
3 import type { IWorker
} from
'../worker'
4 import { AbstractWorkerChoiceStrategy
} from
'./abstract-worker-choice-strategy'
7 WorkerChoiceStrategyOptions
8 } from
'./selection-strategies-types'
11 * Selects the next worker in a round robin fashion.
13 * @typeParam Worker - Type of worker which manages the strategy.
14 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
15 * @typeParam Response - Type of execution response. This can only be serializable data.
17 export class RoundRobinWorkerChoiceStrategy
<
18 Worker
extends IWorker
,
22 extends AbstractWorkerChoiceStrategy
<Worker
, Data
, Response
>
23 implements IWorkerChoiceStrategy
{
25 * Id of the next worker node.
27 private nextWorkerNodeId
: number = 0
31 pool
: IPool
<Worker
, Data
, Response
>,
32 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
35 this.checkOptions(this.opts
)
39 public reset (): boolean {
40 this.nextWorkerNodeId
= 0
45 public choose (): number {
46 const chosenWorkerNodeKey
= this.nextWorkerNodeId
47 this.nextWorkerNodeId
=
48 this.nextWorkerNodeId
=== this.pool
.workerNodes
.length
- 1
50 : this.nextWorkerNodeId
+ 1
51 return chosenWorkerNodeKey
55 public remove (workerNodeKey
: number): boolean {
56 if (this.nextWorkerNodeId
=== workerNodeKey
) {
57 if (this.pool
.workerNodes
.length
=== 0) {
58 this.nextWorkerNodeId
= 0
60 this.nextWorkerNodeId
=
61 this.nextWorkerNodeId
> this.pool
.workerNodes
.length
- 1
62 ? this.pool
.workerNodes
.length
- 1
63 : this.nextWorkerNodeId