c3fe32d144176d88e848a8923fa1eb4b63126f88
[poolifier.git] / src / pools / selection-strategies / least-elu-worker-choice-strategy.ts
1 import { DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS } from '../../utils.js'
2 import type { IPool } from '../pool.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 *
14 * @typeParam Worker - Type of worker which manages the strategy.
15 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
16 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
17 */
18 export class LeastEluWorkerChoiceStrategy<
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 taskStatisticsRequirements: TaskStatisticsRequirements = {
27 runTime: DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS,
28 waitTime: DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS,
29 elu: {
30 aggregate: true,
31 average: false,
32 median: false
33 }
34 }
35
36 /** @inheritDoc */
37 public constructor (
38 pool: IPool<Worker, Data, Response>,
39 opts?: WorkerChoiceStrategyOptions
40 ) {
41 super(pool, opts)
42 this.setTaskStatisticsRequirements(this.opts)
43 }
44
45 /** @inheritDoc */
46 public reset (): boolean {
47 return true
48 }
49
50 /** @inheritDoc */
51 public update (): boolean {
52 return true
53 }
54
55 /** @inheritDoc */
56 public choose (): number | undefined {
57 this.setPreviousWorkerNodeKey(this.nextWorkerNodeKey)
58 this.nextWorkerNodeKey = this.leastEluNextWorkerNodeKey()
59 return this.nextWorkerNodeKey
60 }
61
62 /** @inheritDoc */
63 public remove (): boolean {
64 return true
65 }
66
67 private leastEluNextWorkerNodeKey (): number | undefined {
68 if (this.pool.workerNodes.length === 0) {
69 return undefined
70 }
71 return this.pool.workerNodes.reduce(
72 (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => {
73 return this.isWorkerNodeReady(workerNodeKey) &&
74 (workerNode.usage.elu.active.aggregate ?? 0) <
75 (workerNodes[minWorkerNodeKey].usage.elu.active.aggregate ?? 0)
76 ? workerNodeKey
77 : minWorkerNodeKey
78 },
79 0
80 )
81 }
82 }