refactor: cleanup variables namespace
[poolifier.git] / src / pools / selection-strategies / least-busy-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'
168c526f 4import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
bf90656c
JB
5import type {
6 IWorkerChoiceStrategy,
87de9ff5 7 TaskStatisticsRequirements,
2fc5cae3 8 WorkerChoiceStrategyOptions
bf90656c 9} from './selection-strategies-types'
168c526f
JB
10
11/**
e4543b14 12 * Selects the least busy worker.
168c526f
JB
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.
02706357 16 * @typeParam Response - Type of execution response. This can only be serializable data.
168c526f 17 */
e4543b14 18export class LeastBusyWorkerChoiceStrategy<
f06e48d8 19 Worker extends IWorker,
b2b1d84e
JB
20 Data = unknown,
21 Response = unknown
bf90656c
JB
22 >
23 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
17393ac8 24 implements IWorkerChoiceStrategy {
afc003b2 25 /** @inheritDoc */
87de9ff5 26 public readonly taskStatisticsRequirements: TaskStatisticsRequirements = {
932fc8be
JB
27 runTime: {
28 aggregate: true,
29 average: false,
30 median: false
31 },
32 waitTime: {
33 aggregate: true,
34 average: false,
35 median: false
36 },
5df69fab
JB
37 elu: {
38 aggregate: false,
39 average: false,
40 median: false
41 }
168c526f
JB
42 }
43
2fc5cae3
JB
44 /** @inheritDoc */
45 public constructor (
46 pool: IPool<Worker, Data, Response>,
47 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
48 ) {
49 super(pool, opts)
932fc8be 50 this.setTaskStatisticsRequirements(this.opts)
2fc5cae3
JB
51 }
52
afc003b2 53 /** @inheritDoc */
168c526f
JB
54 public reset (): boolean {
55 return true
56 }
57
138d29a8
JB
58 /** @inheritDoc */
59 public update (): boolean {
1c6fe997 60 let minTime = Infinity
08f3f44c 61 for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
1c6fe997 62 const workerTime =
932fc8be
JB
63 workerNode.workerUsage.runTime.aggregate +
64 workerNode.workerUsage.waitTime.aggregate
1c6fe997 65 if (workerTime === 0) {
d33be430
JB
66 this.nextWorkerNodeId = workerNodeKey
67 return true
1c6fe997
JB
68 } else if (workerTime < minTime) {
69 minTime = workerTime
d33be430 70 this.nextWorkerNodeId = workerNodeKey
168c526f
JB
71 }
72 }
d33be430
JB
73 return true
74 }
75
76 /** @inheritDoc */
77 public choose (): number {
78 return this.nextWorkerNodeId
168c526f 79 }
97a2abc3 80
afc003b2 81 /** @inheritDoc */
a4958de2 82 public remove (): boolean {
97a2abc3
JB
83 return true
84 }
168c526f 85}