Commit | Line | Data |
---|---|---|
ea7a90d3 | 1 | import type { IPoolWorker } from '../pool-worker' |
bdaf31cd | 2 | import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy' |
bf90656c | 3 | import type { IWorkerChoiceStrategy } from './selection-strategies-types' |
bdaf31cd JB |
4 | |
5 | /** | |
6 | * Selects the next worker in a round robin fashion. | |
7 | * | |
38e795c1 JB |
8 | * @typeParam Worker - Type of worker which manages the strategy. |
9 | * @typeParam Data - Type of data sent to the worker. This can only be serializable data. | |
10 | * @typeParam Response - Type of response of execution. This can only be serializable data. | |
bdaf31cd JB |
11 | */ |
12 | export class RoundRobinWorkerChoiceStrategy< | |
bf90656c | 13 | Worker extends IPoolWorker, |
b2b1d84e JB |
14 | Data = unknown, |
15 | Response = unknown | |
bf90656c JB |
16 | > |
17 | extends AbstractWorkerChoiceStrategy<Worker, Data, Response> | |
3300e7bc | 18 | implements IWorkerChoiceStrategy<Worker, Data, Response> { |
bdaf31cd | 19 | /** |
ffcbbad8 | 20 | * Id of the next worker. |
bdaf31cd | 21 | */ |
ffcbbad8 | 22 | private nextWorkerId: number = 0 |
bdaf31cd | 23 | |
afc003b2 | 24 | /** @inheritDoc */ |
a6f7f1b4 | 25 | public reset (): boolean { |
ffcbbad8 | 26 | this.nextWorkerId = 0 |
ea7a90d3 JB |
27 | return true |
28 | } | |
29 | ||
afc003b2 | 30 | /** @inheritDoc */ |
c923ce56 JB |
31 | public choose (): number { |
32 | const chosenWorkerKey = this.nextWorkerId | |
ffcbbad8 | 33 | this.nextWorkerId = |
e65c6cd9 | 34 | this.nextWorkerId === this.pool.workers.length - 1 |
bdaf31cd | 35 | ? 0 |
ffcbbad8 | 36 | : this.nextWorkerId + 1 |
c923ce56 | 37 | return chosenWorkerKey |
bdaf31cd | 38 | } |
97a2abc3 | 39 | |
afc003b2 | 40 | /** @inheritDoc */ |
97a2abc3 JB |
41 | public remove (workerKey: number): boolean { |
42 | if (this.nextWorkerId === workerKey) { | |
78ab2555 JB |
43 | if (this.pool.workers.length === 0) { |
44 | this.nextWorkerId = 0 | |
45 | } else { | |
46 | this.nextWorkerId = | |
47 | this.nextWorkerId > this.pool.workers.length - 1 | |
48 | ? this.pool.workers.length - 1 | |
49 | : this.nextWorkerId | |
50 | } | |
97a2abc3 JB |
51 | } |
52 | return true | |
53 | } | |
bdaf31cd | 54 | } |