feat: conditional task performance computation at the worker level
[poolifier.git] / src / pools / selection-strategies / round-robin-worker-choice-strategy.ts
CommitLineData
2fc5cae3
JB
1import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
2import type { IPool } from '../pool'
f06e48d8 3import type { IWorker } from '../worker'
bdaf31cd 4import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
2fc5cae3
JB
5import type {
6 IWorkerChoiceStrategy,
7 WorkerChoiceStrategyOptions
8} from './selection-strategies-types'
bdaf31cd
JB
9
10/**
11 * Selects the next worker in a round robin fashion.
12 *
38e795c1
JB
13 * @typeParam Worker - Type of worker which manages the strategy.
14 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
02706357 15 * @typeParam Response - Type of execution response. This can only be serializable data.
bdaf31cd
JB
16 */
17export class RoundRobinWorkerChoiceStrategy<
f06e48d8 18 Worker extends IWorker,
b2b1d84e
JB
19 Data = unknown,
20 Response = unknown
bf90656c
JB
21 >
22 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
17393ac8 23 implements IWorkerChoiceStrategy {
bdaf31cd 24 /**
f06e48d8 25 * Id of the next worker node.
bdaf31cd 26 */
f06e48d8 27 private nextWorkerNodeId: number = 0
bdaf31cd 28
2fc5cae3
JB
29 /** @inheritDoc */
30 public constructor (
31 pool: IPool<Worker, Data, Response>,
32 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
33 ) {
34 super(pool, opts)
b6b32453 35 this.setTaskStatistics(this.opts)
2fc5cae3
JB
36 }
37
afc003b2 38 /** @inheritDoc */
a6f7f1b4 39 public reset (): boolean {
f06e48d8 40 this.nextWorkerNodeId = 0
ea7a90d3
JB
41 return true
42 }
43
138d29a8
JB
44 /** @inheritDoc */
45 public update (): boolean {
46 return true
47 }
48
afc003b2 49 /** @inheritDoc */
c923ce56 50 public choose (): number {
f06e48d8
JB
51 const chosenWorkerNodeKey = this.nextWorkerNodeId
52 this.nextWorkerNodeId =
53 this.nextWorkerNodeId === this.pool.workerNodes.length - 1
bdaf31cd 54 ? 0
f06e48d8
JB
55 : this.nextWorkerNodeId + 1
56 return chosenWorkerNodeKey
bdaf31cd 57 }
97a2abc3 58
afc003b2 59 /** @inheritDoc */
f06e48d8
JB
60 public remove (workerNodeKey: number): boolean {
61 if (this.nextWorkerNodeId === workerNodeKey) {
62 if (this.pool.workerNodes.length === 0) {
63 this.nextWorkerNodeId = 0
97f4fd90
JB
64 } else if (this.nextWorkerNodeId > this.pool.workerNodes.length - 1) {
65 this.nextWorkerNodeId = this.pool.workerNodes.length - 1
78ab2555 66 }
97a2abc3
JB
67 }
68 return true
69 }
bdaf31cd 70}