build(deps-dev): apply updates
[poolifier.git] / src / pools / selection-strategies / least-elu-worker-choice-strategy.ts
1 import type { IPool } from '../pool.js'
2 import { DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS } from '../utils.js'
3 import type { IWorker } from '../worker.js'
4 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy.js'
5 import type {
6 IWorkerChoiceStrategy,
7 TaskStatisticsRequirements,
8 WorkerChoiceStrategyOptions,
9 } from './selection-strategies-types.js'
10
11 /**
12 * Selects the worker with the least ELU.
13 * @typeParam Worker - Type of worker which manages the strategy.
14 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
15 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
16 */
17 export class LeastEluWorkerChoiceStrategy<
18 Worker extends IWorker,
19 Data = unknown,
20 Response = unknown
21 >
22 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
23 implements IWorkerChoiceStrategy {
24 /** @inheritDoc */
25 public readonly taskStatisticsRequirements: TaskStatisticsRequirements = {
26 runTime: DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS,
27 waitTime: DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS,
28 elu: {
29 aggregate: true,
30 average: false,
31 median: false,
32 },
33 }
34
35 /** @inheritDoc */
36 public constructor (
37 pool: IPool<Worker, Data, Response>,
38 opts?: WorkerChoiceStrategyOptions
39 ) {
40 super(pool, opts)
41 this.setTaskStatisticsRequirements(this.opts)
42 }
43
44 /** @inheritDoc */
45 public reset (): boolean {
46 return true
47 }
48
49 /** @inheritDoc */
50 public update (): boolean {
51 return true
52 }
53
54 /** @inheritDoc */
55 public choose (): number | undefined {
56 this.setPreviousWorkerNodeKey(this.nextWorkerNodeKey)
57 this.nextWorkerNodeKey = this.leastEluNextWorkerNodeKey()
58 return this.nextWorkerNodeKey
59 }
60
61 /** @inheritDoc */
62 public remove (): boolean {
63 return true
64 }
65
66 private leastEluNextWorkerNodeKey (): number | undefined {
67 return this.pool.workerNodes.reduce(
68 (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => {
69 return this.isWorkerNodeReady(workerNodeKey) &&
70 (workerNode.usage.elu.active.aggregate ?? 0) <
71 (workerNodes[minWorkerNodeKey].usage.elu.active.aggregate ?? 0)
72 ? workerNodeKey
73 : minWorkerNodeKey
74 },
75 0
76 )
77 }
78 }