refactor: prepare worker choice strategies code for worker readiness
[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 useDynamicWorker: true
28 }
29
30 /** @inheritDoc */
31 public constructor (
32 pool: IPool<Worker, Data, Response>,
33 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
34 ) {
35 super(pool, opts)
36 this.setTaskStatisticsRequirements(this.opts)
37 }
38
39 /** @inheritDoc */
40 public reset (): boolean {
41 this.nextWorkerNodeKey = 0
42 return true
43 }
44
45 /** @inheritDoc */
46 public update (): boolean {
47 return true
48 }
49
50 /** @inheritDoc */
51 public choose (): number {
52 const chosenWorkerNodeKey = this.nextWorkerNodeKey
53 this.roundRobinNextWorkerNodeKey()
54 return chosenWorkerNodeKey
55 }
56
57 /** @inheritDoc */
58 public remove (workerNodeKey: number): boolean {
59 if (this.nextWorkerNodeKey === workerNodeKey) {
60 if (this.pool.workerNodes.length === 0) {
61 this.nextWorkerNodeKey = 0
62 } else if (this.nextWorkerNodeKey > this.pool.workerNodes.length - 1) {
63 this.nextWorkerNodeKey = this.pool.workerNodes.length - 1
64 }
65 }
66 return true
67 }
68
69 private roundRobinNextWorkerNodeKey (): void {
70 this.nextWorkerNodeKey =
71 this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
72 ? 0
73 : this.nextWorkerNodeKey + 1
74 }
75 }