feat: add pool runtime setters
[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 WorkerChoiceStrategyOptions
8 } from './selection-strategies-types'
9
10 /**
11 * Selects the next worker in a round robin fashion.
12 *
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.
15 * @typeParam Response - Type of execution response. This can only be serializable data.
16 */
17 export class RoundRobinWorkerChoiceStrategy<
18 Worker extends IWorker,
19 Data = unknown,
20 Response = unknown
21 >
22 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
23 implements IWorkerChoiceStrategy {
24 /**
25 * Id of the next worker node.
26 */
27 private nextWorkerNodeId: number = 0
28
29 /** @inheritDoc */
30 public constructor (
31 pool: IPool<Worker, Data, Response>,
32 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
33 ) {
34 super(pool, opts)
35 this.checkOptions(this.opts)
36 }
37
38 /** @inheritDoc */
39 public reset (): boolean {
40 this.nextWorkerNodeId = 0
41 return true
42 }
43
44 /** @inheritDoc */
45 public choose (): number {
46 const chosenWorkerNodeKey = this.nextWorkerNodeId
47 this.nextWorkerNodeId =
48 this.nextWorkerNodeId === this.pool.workerNodes.length - 1
49 ? 0
50 : this.nextWorkerNodeId + 1
51 return chosenWorkerNodeKey
52 }
53
54 /** @inheritDoc */
55 public remove (workerNodeKey: number): boolean {
56 if (this.nextWorkerNodeId === workerNodeKey) {
57 if (this.pool.workerNodes.length === 0) {
58 this.nextWorkerNodeId = 0
59 } else {
60 this.nextWorkerNodeId =
61 this.nextWorkerNodeId > this.pool.workerNodes.length - 1
62 ? this.pool.workerNodes.length - 1
63 : this.nextWorkerNodeId
64 }
65 }
66 return true
67 }
68 }