39cb3a0803c00183aebd8e67b78b6084655a3ac8
[poolifier.git] / src / pools / selection-strategies / round-robin-worker-choice-strategy.ts
1 import type { IPool } from '../pool.js'
2 import type { IWorker } from '../worker.js'
3 import type {
4 IWorkerChoiceStrategy,
5 WorkerChoiceStrategyOptions,
6 } from './selection-strategies-types.js'
7
8 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy.js'
9
10 /**
11 * Selects the next worker in a round robin fashion.
12 * @typeParam Worker - Type of worker which manages the strategy.
13 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
14 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
15 */
16 export class RoundRobinWorkerChoiceStrategy<
17 Worker extends IWorker,
18 Data = unknown,
19 Response = unknown
20 >
21 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
22 implements IWorkerChoiceStrategy {
23 /** @inheritDoc */
24 public constructor (
25 pool: IPool<Worker, Data, Response>,
26 opts?: WorkerChoiceStrategyOptions
27 ) {
28 super(pool, opts)
29 }
30
31 private roundRobinNextWorkerNodeKey (): number | undefined {
32 this.nextWorkerNodeKey =
33 this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
34 ? 0
35 : (this.nextWorkerNodeKey ?? this.previousWorkerNodeKey) + 1
36 return this.nextWorkerNodeKey
37 }
38
39 /** @inheritDoc */
40 public choose (): number | undefined {
41 const chosenWorkerNodeKey = this.nextWorkerNodeKey
42 this.setPreviousWorkerNodeKey(chosenWorkerNodeKey)
43 this.roundRobinNextWorkerNodeKey()
44 this.checkNextWorkerNodeKey()
45 return chosenWorkerNodeKey
46 }
47
48 /** @inheritDoc */
49 public remove (workerNodeKey: number): boolean {
50 if (this.pool.workerNodes.length === 0) {
51 this.reset()
52 return true
53 }
54 if (
55 this.nextWorkerNodeKey === workerNodeKey &&
56 this.nextWorkerNodeKey > this.pool.workerNodes.length - 1
57 ) {
58 this.nextWorkerNodeKey = this.pool.workerNodes.length - 1
59 }
60 if (
61 this.previousWorkerNodeKey === workerNodeKey &&
62 this.previousWorkerNodeKey > this.pool.workerNodes.length - 1
63 ) {
64 this.previousWorkerNodeKey = this.pool.workerNodes.length - 1
65 }
66 return true
67 }
68
69 /** @inheritDoc */
70 public reset (): boolean {
71 this.resetWorkerNodeKeyProperties()
72 return true
73 }
74
75 /** @inheritDoc */
76 public update (): boolean {
77 return true
78 }
79 }