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