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