feat: add worker choice strategies retry mechanism
[poolifier.git] / src / pools / selection-strategies / round-robin-worker-choice-strategy.ts
CommitLineData
2fc5cae3
JB
1import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
2import type { IPool } from '../pool'
f06e48d8 3import type { IWorker } from '../worker'
bdaf31cd 4import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
2fc5cae3
JB
5import type {
6 IWorkerChoiceStrategy,
6c6afb84 7 StrategyPolicy,
2fc5cae3
JB
8 WorkerChoiceStrategyOptions
9} from './selection-strategies-types'
bdaf31cd
JB
10
11/**
12 * Selects the next worker in a round robin fashion.
13 *
38e795c1 14 * @typeParam Worker - Type of worker which manages the strategy.
e102732c
JB
15 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
16 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
bdaf31cd
JB
17 */
18export class RoundRobinWorkerChoiceStrategy<
f06e48d8 19 Worker extends IWorker,
b2b1d84e
JB
20 Data = unknown,
21 Response = unknown
bf90656c
JB
22 >
23 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
17393ac8 24 implements IWorkerChoiceStrategy {
6c6afb84
JB
25 /** @inheritDoc */
26 public readonly strategyPolicy: StrategyPolicy = {
27 useDynamicWorker: true
28 }
29
2fc5cae3
JB
30 /** @inheritDoc */
31 public constructor (
32 pool: IPool<Worker, Data, Response>,
33 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
34 ) {
35 super(pool, opts)
932fc8be 36 this.setTaskStatisticsRequirements(this.opts)
2fc5cae3
JB
37 }
38
afc003b2 39 /** @inheritDoc */
a6f7f1b4 40 public reset (): boolean {
9b106837 41 this.nextWorkerNodeKey = 0
ea7a90d3
JB
42 return true
43 }
44
138d29a8
JB
45 /** @inheritDoc */
46 public update (): boolean {
47 return true
48 }
49
afc003b2 50 /** @inheritDoc */
c923ce56 51 public choose (): number {
9b106837 52 const chosenWorkerNodeKey = this.nextWorkerNodeKey
949194eb
JB
53 do {
54 this.roundRobinNextWorkerNodeKey()
8990357d 55 } while (!this.isWorkerNodeEligible(this.nextWorkerNodeKey))
f06e48d8 56 return chosenWorkerNodeKey
bdaf31cd 57 }
97a2abc3 58
afc003b2 59 /** @inheritDoc */
f06e48d8 60 public remove (workerNodeKey: number): boolean {
9b106837 61 if (this.nextWorkerNodeKey === workerNodeKey) {
f06e48d8 62 if (this.pool.workerNodes.length === 0) {
9b106837
JB
63 this.nextWorkerNodeKey = 0
64 } else if (this.nextWorkerNodeKey > this.pool.workerNodes.length - 1) {
65 this.nextWorkerNodeKey = this.pool.workerNodes.length - 1
78ab2555 66 }
97a2abc3
JB
67 }
68 return true
69 }
9b106837 70
20016c79 71 private roundRobinNextWorkerNodeKey (): number {
9b106837
JB
72 this.nextWorkerNodeKey =
73 this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
74 ? 0
75 : this.nextWorkerNodeKey + 1
20016c79 76 return this.nextWorkerNodeKey
9b106837 77 }
bdaf31cd 78}