fix: fix worker choice strategy retries mechanism on some edge cases
[poolifier.git] / src / pools / selection-strategies / round-robin-worker-choice-strategy.ts
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'
5 import type {
6 IWorkerChoiceStrategy,
7 StrategyPolicy,
8 WorkerChoiceStrategyOptions
9 } from './selection-strategies-types'
10
11 /**
12 * Selects the next worker in a round robin fashion.
13 *
14 * @typeParam Worker - Type of worker which manages the strategy.
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.
17 */
18 export class RoundRobinWorkerChoiceStrategy<
19 Worker extends IWorker,
20 Data = unknown,
21 Response = unknown
22 >
23 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
24 implements IWorkerChoiceStrategy {
25 /** @inheritDoc */
26 public readonly strategyPolicy: StrategyPolicy = {
27 dynamicWorkerUsage: true,
28 dynamicWorkerReady: true
29 }
30
31 /** @inheritDoc */
32 public constructor (
33 pool: IPool<Worker, Data, Response>,
34 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
35 ) {
36 super(pool, opts)
37 this.setTaskStatisticsRequirements(this.opts)
38 }
39
40 /** @inheritDoc */
41 public reset (): boolean {
42 this.nextWorkerNodeKey = 0
43 return true
44 }
45
46 /** @inheritDoc */
47 public update (): boolean {
48 return true
49 }
50
51 /** @inheritDoc */
52 public choose (): number | undefined {
53 const chosenWorkerNodeKey = this.nextWorkerNodeKey
54 this.roundRobinNextWorkerNodeKey()
55 if (!this.isWorkerNodeEligible(this.nextWorkerNodeKey as number)) {
56 this.nextWorkerNodeKey = undefined
57 }
58 return chosenWorkerNodeKey
59 }
60
61 /** @inheritDoc */
62 public remove (workerNodeKey: number): boolean {
63 if (this.nextWorkerNodeKey === workerNodeKey) {
64 if (this.pool.workerNodes.length === 0) {
65 this.nextWorkerNodeKey = 0
66 } else if (this.nextWorkerNodeKey > this.pool.workerNodes.length - 1) {
67 this.nextWorkerNodeKey = this.pool.workerNodes.length - 1
68 }
69 }
70 return true
71 }
72
73 private roundRobinNextWorkerNodeKey (): number | undefined {
74 this.nextWorkerNodeKey =
75 this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
76 ? 0
77 : (this.nextWorkerNodeKey ?? 0) + 1
78 return this.nextWorkerNodeKey
79 }
80 }