fix: fix race condition in worker choice strategies
[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,
7 WorkerChoiceStrategyOptions
8} from './selection-strategies-types'
bdaf31cd
JB
9
10/**
11 * Selects the next worker in a round robin fashion.
12 *
38e795c1 13 * @typeParam Worker - Type of worker which manages the strategy.
e102732c
JB
14 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
15 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
bdaf31cd
JB
16 */
17export class RoundRobinWorkerChoiceStrategy<
f06e48d8 18 Worker extends IWorker,
b2b1d84e
JB
19 Data = unknown,
20 Response = unknown
bf90656c
JB
21 >
22 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
17393ac8 23 implements IWorkerChoiceStrategy {
2fc5cae3
JB
24 /** @inheritDoc */
25 public constructor (
26 pool: IPool<Worker, Data, Response>,
27 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
28 ) {
29 super(pool, opts)
932fc8be 30 this.setTaskStatisticsRequirements(this.opts)
2fc5cae3
JB
31 }
32
afc003b2 33 /** @inheritDoc */
a6f7f1b4 34 public reset (): boolean {
39a43af7 35 this.resetWorkerNodeKeyProperties()
ea7a90d3
JB
36 return true
37 }
38
138d29a8
JB
39 /** @inheritDoc */
40 public update (): boolean {
41 return true
42 }
43
afc003b2 44 /** @inheritDoc */
b1aae695 45 public choose (): number | undefined {
9b106837 46 const chosenWorkerNodeKey = this.nextWorkerNodeKey
b1aae695 47 this.roundRobinNextWorkerNodeKey()
f06e48d8 48 return chosenWorkerNodeKey
bdaf31cd 49 }
97a2abc3 50
afc003b2 51 /** @inheritDoc */
f06e48d8 52 public remove (workerNodeKey: number): boolean {
9b106837 53 if (this.nextWorkerNodeKey === workerNodeKey) {
f06e48d8 54 if (this.pool.workerNodes.length === 0) {
9b106837
JB
55 this.nextWorkerNodeKey = 0
56 } else if (this.nextWorkerNodeKey > this.pool.workerNodes.length - 1) {
57 this.nextWorkerNodeKey = this.pool.workerNodes.length - 1
78ab2555 58 }
97a2abc3
JB
59 }
60 return true
61 }
9b106837 62
b1aae695 63 private roundRobinNextWorkerNodeKey (): number | undefined {
9b106837
JB
64 this.nextWorkerNodeKey =
65 this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
66 ? 0
7c7bb289 67 : (this.nextWorkerNodeKey ?? this.previousWorkerNodeKey) + 1
20016c79 68 return this.nextWorkerNodeKey
9b106837 69 }
bdaf31cd 70}