refactor: explicity extends Task for MessageValue type
[poolifier.git] / src / pools / selection-strategies / round-robin-worker-choice-strategy.ts
CommitLineData
f06e48d8 1import type { IWorker } from '../worker'
bdaf31cd 2import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
bf90656c 3import 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.
02706357 10 * @typeParam Response - Type of execution response. This can only be serializable data.
bdaf31cd
JB
11 */
12export class RoundRobinWorkerChoiceStrategy<
f06e48d8 13 Worker extends IWorker,
b2b1d84e
JB
14 Data = unknown,
15 Response = unknown
bf90656c
JB
16 >
17 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
17393ac8 18 implements IWorkerChoiceStrategy {
bdaf31cd 19 /**
f06e48d8 20 * Id of the next worker node.
bdaf31cd 21 */
f06e48d8 22 private nextWorkerNodeId: number = 0
bdaf31cd 23
afc003b2 24 /** @inheritDoc */
a6f7f1b4 25 public reset (): boolean {
f06e48d8 26 this.nextWorkerNodeId = 0
ea7a90d3
JB
27 return true
28 }
29
afc003b2 30 /** @inheritDoc */
c923ce56 31 public choose (): number {
f06e48d8
JB
32 const chosenWorkerNodeKey = this.nextWorkerNodeId
33 this.nextWorkerNodeId =
34 this.nextWorkerNodeId === this.pool.workerNodes.length - 1
bdaf31cd 35 ? 0
f06e48d8
JB
36 : this.nextWorkerNodeId + 1
37 return chosenWorkerNodeKey
bdaf31cd 38 }
97a2abc3 39
afc003b2 40 /** @inheritDoc */
f06e48d8
JB
41 public remove (workerNodeKey: number): boolean {
42 if (this.nextWorkerNodeId === workerNodeKey) {
43 if (this.pool.workerNodes.length === 0) {
44 this.nextWorkerNodeId = 0
78ab2555 45 } else {
f06e48d8
JB
46 this.nextWorkerNodeId =
47 this.nextWorkerNodeId > this.pool.workerNodes.length - 1
48 ? this.pool.workerNodes.length - 1
49 : this.nextWorkerNodeId
78ab2555 50 }
97a2abc3
JB
51 }
52 return true
53 }
bdaf31cd 54}