fix: ensure worker key can't be negative in worker choice strategies
[poolifier.git] / src / pools / selection-strategies / round-robin-worker-choice-strategy.ts
1 import type { IPoolWorker } from '../pool-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 IPoolWorker,
14 Data = unknown,
15 Response = unknown
16 >
17 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
18 implements IWorkerChoiceStrategy<Worker, Data, Response> {
19 /**
20 * Id of the next worker.
21 */
22 private nextWorkerId: number = 0
23
24 /** {@inheritDoc} */
25 public reset (): boolean {
26 this.nextWorkerId = 0
27 return true
28 }
29
30 /** {@inheritDoc} */
31 public choose (): number {
32 const chosenWorkerKey = this.nextWorkerId
33 this.nextWorkerId =
34 this.nextWorkerId === this.pool.workers.length - 1
35 ? 0
36 : this.nextWorkerId + 1
37 return chosenWorkerKey
38 }
39
40 /** {@inheritDoc} */
41 public remove (workerKey: number): boolean {
42 if (this.nextWorkerId === workerKey) {
43 if (this.pool.workers.length === 0) {
44 this.nextWorkerId = 0
45 } else {
46 this.nextWorkerId =
47 this.nextWorkerId > this.pool.workers.length - 1
48 ? this.pool.workers.length - 1
49 : this.nextWorkerId
50 }
51 }
52 return true
53 }
54 }