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 JB |
13 | Worker extends IPoolWorker, |
14 | Data, | |
15 | Response | |
16 | > | |
17 | extends AbstractWorkerChoiceStrategy<Worker, Data, Response> | |
18 | implements IWorkerChoiceStrategy { | |
bdaf31cd | 19 | /** |
ffcbbad8 | 20 | * Id of the next worker. |
bdaf31cd | 21 | */ |
ffcbbad8 | 22 | private nextWorkerId: number = 0 |
bdaf31cd | 23 | |
38e795c1 | 24 | /** {@inheritDoc} */ |
a6f7f1b4 | 25 | public reset (): boolean { |
ffcbbad8 | 26 | this.nextWorkerId = 0 |
ea7a90d3 JB |
27 | return true |
28 | } | |
29 | ||
38e795c1 | 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 JB |
39 | |
40 | /** {@inheritDoc} */ | |
41 | public remove (workerKey: number): boolean { | |
42 | if (this.nextWorkerId === workerKey) { | |
43 | this.nextWorkerId = | |
44 | this.nextWorkerId > this.pool.workers.length - 1 | |
45 | ? this.pool.workers.length - 1 | |
46 | : this.nextWorkerId | |
47 | } | |
48 | return true | |
49 | } | |
bdaf31cd | 50 | } |