]>
Commit | Line | Data |
---|---|---|
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 | /** @inheritDoc */ | |
32 | public choose (): number | undefined { | |
33 | const chosenWorkerNodeKey = this.nextWorkerNodeKey | |
34 | this.setPreviousWorkerNodeKey(chosenWorkerNodeKey) | |
35 | this.roundRobinNextWorkerNodeKey() | |
36 | this.checkNextWorkerNodeKey() | |
37 | return chosenWorkerNodeKey | |
38 | } | |
39 | ||
40 | /** @inheritDoc */ | |
41 | public remove (workerNodeKey: number): boolean { | |
42 | if (this.pool.workerNodes.length === 0) { | |
43 | this.reset() | |
44 | return true | |
45 | } | |
46 | if ( | |
47 | this.nextWorkerNodeKey === workerNodeKey && | |
48 | this.nextWorkerNodeKey > this.pool.workerNodes.length - 1 | |
49 | ) { | |
50 | this.nextWorkerNodeKey = this.pool.workerNodes.length - 1 | |
51 | } | |
52 | if ( | |
53 | this.previousWorkerNodeKey === workerNodeKey && | |
54 | this.previousWorkerNodeKey > this.pool.workerNodes.length - 1 | |
55 | ) { | |
56 | this.previousWorkerNodeKey = this.pool.workerNodes.length - 1 | |
57 | } | |
58 | return true | |
59 | } | |
60 | ||
61 | /** @inheritDoc */ | |
62 | public reset (): boolean { | |
63 | this.resetWorkerNodeKeyProperties() | |
64 | return true | |
65 | } | |
66 | ||
67 | /** @inheritDoc */ | |
68 | public update (): boolean { | |
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 | } |