feat: add pool runtime setters
[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
JB
13 * @typeParam Worker - Type of worker which manages the strategy.
14 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
02706357 15 * @typeParam Response - Type of execution response. This can only be serializable 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 {
bdaf31cd 24 /**
f06e48d8 25 * Id of the next worker node.
bdaf31cd 26 */
f06e48d8 27 private nextWorkerNodeId: number = 0
bdaf31cd 28
2fc5cae3
JB
29 /** @inheritDoc */
30 public constructor (
31 pool: IPool<Worker, Data, Response>,
32 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
33 ) {
34 super(pool, opts)
a20f0ba5 35 this.checkOptions(this.opts)
2fc5cae3
JB
36 }
37
afc003b2 38 /** @inheritDoc */
a6f7f1b4 39 public reset (): boolean {
f06e48d8 40 this.nextWorkerNodeId = 0
ea7a90d3
JB
41 return true
42 }
43
afc003b2 44 /** @inheritDoc */
c923ce56 45 public choose (): number {
f06e48d8
JB
46 const chosenWorkerNodeKey = this.nextWorkerNodeId
47 this.nextWorkerNodeId =
48 this.nextWorkerNodeId === this.pool.workerNodes.length - 1
bdaf31cd 49 ? 0
f06e48d8
JB
50 : this.nextWorkerNodeId + 1
51 return chosenWorkerNodeKey
bdaf31cd 52 }
97a2abc3 53
afc003b2 54 /** @inheritDoc */
f06e48d8
JB
55 public remove (workerNodeKey: number): boolean {
56 if (this.nextWorkerNodeId === workerNodeKey) {
57 if (this.pool.workerNodes.length === 0) {
58 this.nextWorkerNodeId = 0
78ab2555 59 } else {
f06e48d8
JB
60 this.nextWorkerNodeId =
61 this.nextWorkerNodeId > this.pool.workerNodes.length - 1
62 ? this.pool.workerNodes.length - 1
63 : this.nextWorkerNodeId
78ab2555 64 }
97a2abc3
JB
65 }
66 return true
67 }
bdaf31cd 68}