fix: prepare code to fix pool internal IPC for cluster worker
[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 {
f06e48d8 41 this.nextWorkerNodeId = 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 {
f06e48d8
JB
52 const chosenWorkerNodeKey = this.nextWorkerNodeId
53 this.nextWorkerNodeId =
54 this.nextWorkerNodeId === this.pool.workerNodes.length - 1
bdaf31cd 55 ? 0
f06e48d8
JB
56 : this.nextWorkerNodeId + 1
57 return chosenWorkerNodeKey
bdaf31cd 58 }
97a2abc3 59
afc003b2 60 /** @inheritDoc */
f06e48d8
JB
61 public remove (workerNodeKey: number): boolean {
62 if (this.nextWorkerNodeId === workerNodeKey) {
63 if (this.pool.workerNodes.length === 0) {
64 this.nextWorkerNodeId = 0
97f4fd90
JB
65 } else if (this.nextWorkerNodeId > this.pool.workerNodes.length - 1) {
66 this.nextWorkerNodeId = this.pool.workerNodes.length - 1
78ab2555 67 }
97a2abc3
JB
68 }
69 return true
70 }
bdaf31cd 71}