build(ci): refine autofix GH action
[poolifier.git] / src / pools / selection-strategies / round-robin-worker-choice-strategy.ts
CommitLineData
d35e5717
JB
1import type { IPool } from '../pool.js'
2import type { IWorker } from '../worker.js'
3import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy.js'
2fc5cae3
JB
4import type {
5 IWorkerChoiceStrategy,
3a502712 6 WorkerChoiceStrategyOptions,
d35e5717 7} from './selection-strategies-types.js'
bdaf31cd
JB
8
9/**
10 * Selects the next worker in a round robin fashion.
38e795c1 11 * @typeParam Worker - Type of worker which manages the strategy.
e102732c
JB
12 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
13 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
bdaf31cd
JB
14 */
15export class RoundRobinWorkerChoiceStrategy<
f06e48d8 16 Worker extends IWorker,
b2b1d84e
JB
17 Data = unknown,
18 Response = unknown
bf90656c
JB
19 >
20 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
17393ac8 21 implements IWorkerChoiceStrategy {
2fc5cae3
JB
22 /** @inheritDoc */
23 public constructor (
24 pool: IPool<Worker, Data, Response>,
39618ede 25 opts?: WorkerChoiceStrategyOptions
2fc5cae3
JB
26 ) {
27 super(pool, opts)
2fc5cae3
JB
28 }
29
afc003b2 30 /** @inheritDoc */
a6f7f1b4 31 public reset (): boolean {
39a43af7 32 this.resetWorkerNodeKeyProperties()
ea7a90d3
JB
33 return true
34 }
35
138d29a8
JB
36 /** @inheritDoc */
37 public update (): boolean {
38 return true
39 }
40
afc003b2 41 /** @inheritDoc */
b1aae695 42 public choose (): number | undefined {
9b106837 43 const chosenWorkerNodeKey = this.nextWorkerNodeKey
baca80f7 44 this.setPreviousWorkerNodeKey(chosenWorkerNodeKey)
b1aae695 45 this.roundRobinNextWorkerNodeKey()
8e8d9101 46 this.checkNextWorkerNodeKey()
f06e48d8 47 return chosenWorkerNodeKey
bdaf31cd 48 }
97a2abc3 49
afc003b2 50 /** @inheritDoc */
f06e48d8 51 public remove (workerNodeKey: number): boolean {
226b02a3
JB
52 if (this.pool.workerNodes.length === 0) {
53 this.reset()
153179f2 54 return true
226b02a3
JB
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
97a2abc3
JB
67 }
68 return true
69 }
9b106837 70
b1aae695 71 private roundRobinNextWorkerNodeKey (): number | undefined {
a38b62f1
JB
72 this.nextWorkerNodeKey =
73 this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
74 ? 0
75 : (this.nextWorkerNodeKey ?? this.previousWorkerNodeKey) + 1
20016c79 76 return this.nextWorkerNodeKey
9b106837 77 }
bdaf31cd 78}