perf: remove unneeded branching in worker choice strategies
[poolifier.git] / src / pools / selection-strategies / least-elu-worker-choice-strategy.ts
CommitLineData
d35e5717 1import type { IPool } from '../pool.js'
e9ed6eee 2import { DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS } from '../utils.js'
d35e5717
JB
3import type { IWorker } from '../worker.js'
4import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy.js'
058a9457
JB
5import type {
6 IWorkerChoiceStrategy,
39618ede
JB
7 TaskStatisticsRequirements,
8 WorkerChoiceStrategyOptions
d35e5717 9} from './selection-strategies-types.js'
058a9457
JB
10
11/**
12 * Selects the worker with the least ELU.
13 *
14 * @typeParam Worker - Type of worker which manages the strategy.
e102732c
JB
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.
058a9457
JB
17 */
18export class LeastEluWorkerChoiceStrategy<
19 Worker extends IWorker,
20 Data = unknown,
21 Response = unknown
22 >
23 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
24 implements IWorkerChoiceStrategy {
25 /** @inheritDoc */
05302647 26 public readonly taskStatisticsRequirements: TaskStatisticsRequirements = {
3c93feb9
JB
27 runTime: DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS,
28 waitTime: DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS,
5df69fab
JB
29 elu: {
30 aggregate: true,
31 average: false,
32 median: false
33 }
058a9457
JB
34 }
35
36 /** @inheritDoc */
37 public constructor (
38 pool: IPool<Worker, Data, Response>,
39618ede 39 opts?: WorkerChoiceStrategyOptions
058a9457
JB
40 ) {
41 super(pool, opts)
e460940e 42 this.setTaskStatisticsRequirements(this.opts)
058a9457
JB
43 }
44
45 /** @inheritDoc */
46 public reset (): boolean {
47 return true
48 }
49
50 /** @inheritDoc */
51 public update (): boolean {
db703c75
JB
52 return true
53 }
54
55 /** @inheritDoc */
b1aae695 56 public choose (): number | undefined {
baca80f7 57 this.setPreviousWorkerNodeKey(this.nextWorkerNodeKey)
fce028d6 58 this.nextWorkerNodeKey = this.leastEluNextWorkerNodeKey()
b1aae695 59 return this.nextWorkerNodeKey
9b106837
JB
60 }
61
62 /** @inheritDoc */
63 public remove (): boolean {
64 return true
65 }
66
b1aae695 67 private leastEluNextWorkerNodeKey (): number | undefined {
f3a91bac
JB
68 return this.pool.workerNodes.reduce(
69 (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => {
ae3ab61d
JB
70 return this.isWorkerNodeReady(workerNodeKey) &&
71 (workerNode.usage.elu.active.aggregate ?? 0) <
72 (workerNodes[minWorkerNodeKey].usage.elu.active.aggregate ?? 0)
f3a91bac
JB
73 ? workerNodeKey
74 : minWorkerNodeKey
75 },
76 0
77 )
058a9457
JB
78 }
79}