eda00c7582e305a57c10318d2878c24045fe21fc
[poolifier.git] / src / pools / selection-strategies / round-robin-worker-choice-strategy.ts
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 response of execution. 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 }