fix: fix worker node removal handling in worker choice strategies
[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 { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy.js'
4 import type {
5 IWorkerChoiceStrategy,
6 WorkerChoiceStrategyOptions
7 } from './selection-strategies-types.js'
8
9 /**
10 * Selects the next worker in a round robin fashion.
11 *
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 /** @inheritDoc */
32 public reset (): boolean {
33 this.resetWorkerNodeKeyProperties()
34 return true
35 }
36
37 /** @inheritDoc */
38 public update (): boolean {
39 return true
40 }
41
42 /** @inheritDoc */
43 public choose (): number | undefined {
44 const chosenWorkerNodeKey = this.nextWorkerNodeKey
45 this.setPreviousWorkerNodeKey(chosenWorkerNodeKey)
46 this.roundRobinNextWorkerNodeKey()
47 this.checkNextWorkerNodeKey()
48 return chosenWorkerNodeKey
49 }
50
51 /** @inheritDoc */
52 public remove (workerNodeKey: number): boolean {
53 if (this.pool.workerNodes.length === 0) {
54 this.reset()
55 return true
56 }
57 if (
58 this.nextWorkerNodeKey === workerNodeKey &&
59 this.nextWorkerNodeKey > this.pool.workerNodes.length - 1
60 ) {
61 this.nextWorkerNodeKey = this.pool.workerNodes.length - 1
62 }
63 if (
64 this.previousWorkerNodeKey === workerNodeKey &&
65 this.previousWorkerNodeKey > this.pool.workerNodes.length - 1
66 ) {
67 this.previousWorkerNodeKey = this.pool.workerNodes.length - 1
68 }
69 return true
70 }
71
72 private roundRobinNextWorkerNodeKey (): number | undefined {
73 this.nextWorkerNodeKey =
74 this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
75 ? 0
76 : (this.nextWorkerNodeKey ?? this.previousWorkerNodeKey) + 1
77 return this.nextWorkerNodeKey
78 }
79 }