Merge pull request #2365 from poolifier/map-execute
[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 * @typeParam Worker - Type of worker which manages the strategy.
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.
14 */
15 export class RoundRobinWorkerChoiceStrategy<
16 Worker extends IWorker,
17 Data = unknown,
18 Response = unknown
19 >
20 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
21 implements IWorkerChoiceStrategy {
22 /** @inheritDoc */
23 public constructor (
24 pool: IPool<Worker, Data, Response>,
25 opts?: WorkerChoiceStrategyOptions
26 ) {
27 super(pool, opts)
28 }
29
30 /** @inheritDoc */
31 public reset (): boolean {
32 this.resetWorkerNodeKeyProperties()
33 return true
34 }
35
36 /** @inheritDoc */
37 public update (): boolean {
38 return true
39 }
40
41 /** @inheritDoc */
42 public choose (): number | undefined {
43 const chosenWorkerNodeKey = this.nextWorkerNodeKey
44 this.setPreviousWorkerNodeKey(chosenWorkerNodeKey)
45 this.roundRobinNextWorkerNodeKey()
46 this.checkNextWorkerNodeKey()
47 return chosenWorkerNodeKey
48 }
49
50 /** @inheritDoc */
51 public remove (workerNodeKey: number): boolean {
52 if (this.pool.workerNodes.length === 0) {
53 this.reset()
54 return true
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 }