| 1 | import type { IWorker } from '../worker' |
| 2 | import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy' |
| 3 | import type { IWorkerChoiceStrategy } from './selection-strategies-types' |
| 4 | |
| 5 | /** |
| 6 | * Selects the next worker in a round robin fashion. |
| 7 | * |
| 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 execution response. This can only be serializable data. |
| 11 | */ |
| 12 | export class RoundRobinWorkerChoiceStrategy< |
| 13 | Worker extends IWorker, |
| 14 | Data = unknown, |
| 15 | Response = unknown |
| 16 | > |
| 17 | extends AbstractWorkerChoiceStrategy<Worker, Data, Response> |
| 18 | implements IWorkerChoiceStrategy { |
| 19 | /** |
| 20 | * Id of the next worker node. |
| 21 | */ |
| 22 | private nextWorkerNodeId: number = 0 |
| 23 | |
| 24 | /** @inheritDoc */ |
| 25 | public reset (): boolean { |
| 26 | this.nextWorkerNodeId = 0 |
| 27 | return true |
| 28 | } |
| 29 | |
| 30 | /** @inheritDoc */ |
| 31 | public choose (): number { |
| 32 | const chosenWorkerNodeKey = this.nextWorkerNodeId |
| 33 | this.nextWorkerNodeId = |
| 34 | this.nextWorkerNodeId === this.pool.workerNodes.length - 1 |
| 35 | ? 0 |
| 36 | : this.nextWorkerNodeId + 1 |
| 37 | return chosenWorkerNodeKey |
| 38 | } |
| 39 | |
| 40 | /** @inheritDoc */ |
| 41 | public remove (workerNodeKey: number): boolean { |
| 42 | if (this.nextWorkerNodeId === workerNodeKey) { |
| 43 | if (this.pool.workerNodes.length === 0) { |
| 44 | this.nextWorkerNodeId = 0 |
| 45 | } else { |
| 46 | this.nextWorkerNodeId = |
| 47 | this.nextWorkerNodeId > this.pool.workerNodes.length - 1 |
| 48 | ? this.pool.workerNodes.length - 1 |
| 49 | : this.nextWorkerNodeId |
| 50 | } |
| 51 | } |
| 52 | return true |
| 53 | } |
| 54 | } |