fix: prepare code to fix pool internal IPC for cluster worker
[poolifier.git] / src / pools / selection-strategies / least-elu-worker-choice-strategy.ts
CommitLineData
058a9457
JB
1import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
2import type { IPool } from '../pool'
3import type { IWorker } from '../worker'
4import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
5import type {
6 IWorkerChoiceStrategy,
05302647 7 TaskStatisticsRequirements,
058a9457
JB
8 WorkerChoiceStrategyOptions
9} from './selection-strategies-types'
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 = {
e460940e
JB
27 runTime: {
28 aggregate: false,
29 average: false,
30 median: false
31 },
32 waitTime: {
33 aggregate: false,
34 average: false,
35 median: false
36 },
5df69fab
JB
37 elu: {
38 aggregate: true,
39 average: false,
40 median: false
41 }
058a9457
JB
42 }
43
44 /** @inheritDoc */
45 public constructor (
46 pool: IPool<Worker, Data, Response>,
47 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
48 ) {
49 super(pool, opts)
e460940e 50 this.setTaskStatisticsRequirements(this.opts)
058a9457
JB
51 }
52
53 /** @inheritDoc */
54 public reset (): boolean {
55 return true
56 }
57
58 /** @inheritDoc */
59 public update (): boolean {
db703c75
JB
60 return true
61 }
62
63 /** @inheritDoc */
64 public choose (): number {
cdb517b3 65 let minWorkerElu = Infinity
058a9457 66 for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
cdb517b3 67 const workerUsage = workerNode.workerUsage
5df69fab 68 const workerElu = workerUsage.elu?.active.aggregate ?? 0
cdb517b3 69 if (workerElu === 0) {
d33be430 70 this.nextWorkerNodeId = workerNodeKey
5ea80606 71 break
cdb517b3
JB
72 } else if (workerElu < minWorkerElu) {
73 minWorkerElu = workerElu
d33be430 74 this.nextWorkerNodeId = workerNodeKey
058a9457
JB
75 }
76 }
d33be430 77 return this.nextWorkerNodeId
058a9457
JB
78 }
79
80 /** @inheritDoc */
81 public remove (): boolean {
82 return true
83 }
84}