fix: ensure worker removal impact is propated to worker choice strategy
[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
4 /**
5 * Selects the next worker in a round robin fashion.
6 *
7 * @typeParam Worker - Type of worker which manages the strategy.
8 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
9 * @typeParam Response - Type of response of execution. This can only be serializable data.
10 */
11 export class RoundRobinWorkerChoiceStrategy<
12 Worker extends IPoolWorker,
13 Data,
14 Response
15 > extends AbstractWorkerChoiceStrategy<Worker, Data, Response> {
16 /**
17 * Id of the next worker.
18 */
19 private nextWorkerId: number = 0
20
21 /** {@inheritDoc} */
22 public reset (): boolean {
23 this.nextWorkerId = 0
24 return true
25 }
26
27 /** {@inheritDoc} */
28 public choose (): number {
29 const chosenWorkerKey = this.nextWorkerId
30 this.nextWorkerId =
31 this.nextWorkerId === this.pool.workers.length - 1
32 ? 0
33 : this.nextWorkerId + 1
34 return chosenWorkerKey
35 }
36
37 /** {@inheritDoc} */
38 public remove (workerKey: number): boolean {
39 if (this.nextWorkerId === workerKey) {
40 this.nextWorkerId =
41 this.nextWorkerId > this.pool.workers.length - 1
42 ? this.pool.workers.length - 1
43 : this.nextWorkerId
44 }
45 return true
46 }
47 }