53f3ba4fd36c0ee70f0918889e5a5edd9708645b
[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 }
56 if (
57 this.nextWorkerNodeKey === workerNodeKey &&
58 this.nextWorkerNodeKey > this.pool.workerNodes.length - 1
59 ) {
60 this.nextWorkerNodeKey = this.pool.workerNodes.length - 1
61 }
62 if (
63 this.previousWorkerNodeKey === workerNodeKey &&
64 this.previousWorkerNodeKey > this.pool.workerNodes.length - 1
65 ) {
66 this.previousWorkerNodeKey = this.pool.workerNodes.length - 1
67 }
68 return true
69 }
70
71 private roundRobinNextWorkerNodeKey (): number | undefined {
72 this.nextWorkerNodeKey =
73 this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
74 ? 0
75 : (this.nextWorkerNodeKey ?? this.previousWorkerNodeKey) + 1
76 return this.nextWorkerNodeKey
77 }
78 }