| 1 | import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils' |
| 2 | import type { IPool } from '../pool' |
| 3 | import type { IWorker } from '../worker' |
| 4 | import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy' |
| 5 | import type { |
| 6 | IWorkerChoiceStrategy, |
| 7 | WorkerChoiceStrategyOptions |
| 8 | } from './selection-strategies-types' |
| 9 | |
| 10 | /** |
| 11 | * Selects the next worker in a round robin fashion. |
| 12 | * |
| 13 | * @typeParam Worker - Type of worker which manages the strategy. |
| 14 | * @typeParam Data - Type of data sent to the worker. This can only be serializable data. |
| 15 | * @typeParam Response - Type of execution response. This can only be serializable data. |
| 16 | */ |
| 17 | export class RoundRobinWorkerChoiceStrategy< |
| 18 | Worker extends IWorker, |
| 19 | Data = unknown, |
| 20 | Response = unknown |
| 21 | > |
| 22 | extends AbstractWorkerChoiceStrategy<Worker, Data, Response> |
| 23 | implements IWorkerChoiceStrategy { |
| 24 | /** |
| 25 | * Id of the next worker node. |
| 26 | */ |
| 27 | private nextWorkerNodeId: number = 0 |
| 28 | |
| 29 | /** @inheritDoc */ |
| 30 | public constructor ( |
| 31 | pool: IPool<Worker, Data, Response>, |
| 32 | opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS |
| 33 | ) { |
| 34 | super(pool, opts) |
| 35 | this.setRequiredStatistics(this.opts) |
| 36 | } |
| 37 | |
| 38 | /** @inheritDoc */ |
| 39 | public reset (): boolean { |
| 40 | this.nextWorkerNodeId = 0 |
| 41 | return true |
| 42 | } |
| 43 | |
| 44 | /** @inheritDoc */ |
| 45 | public update (): boolean { |
| 46 | return true |
| 47 | } |
| 48 | |
| 49 | /** @inheritDoc */ |
| 50 | public choose (): number { |
| 51 | const chosenWorkerNodeKey = this.nextWorkerNodeId |
| 52 | this.nextWorkerNodeId = |
| 53 | this.nextWorkerNodeId === this.pool.workerNodes.length - 1 |
| 54 | ? 0 |
| 55 | : this.nextWorkerNodeId + 1 |
| 56 | return chosenWorkerNodeKey |
| 57 | } |
| 58 | |
| 59 | /** @inheritDoc */ |
| 60 | public remove (workerNodeKey: number): boolean { |
| 61 | if (this.nextWorkerNodeId === workerNodeKey) { |
| 62 | if (this.pool.workerNodes.length === 0) { |
| 63 | this.nextWorkerNodeId = 0 |
| 64 | } else if (this.nextWorkerNodeId > this.pool.workerNodes.length - 1) { |
| 65 | this.nextWorkerNodeId = this.pool.workerNodes.length - 1 |
| 66 | } |
| 67 | } |
| 68 | return true |
| 69 | } |
| 70 | } |