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