fix: prepare code to fix pool internal IPC for cluster worker
[poolifier.git] / src / pools / selection-strategies / least-busy-worker-choice-strategy.ts
CommitLineData
2fc5cae3
JB
1import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
2import type { IPool } from '../pool'
f06e48d8 3import type { IWorker } from '../worker'
168c526f 4import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
bf90656c
JB
5import type {
6 IWorkerChoiceStrategy,
87de9ff5 7 TaskStatisticsRequirements,
2fc5cae3 8 WorkerChoiceStrategyOptions
bf90656c 9} from './selection-strategies-types'
168c526f
JB
10
11/**
e4543b14 12 * Selects the least busy worker.
168c526f
JB
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.
168c526f 17 */
e4543b14 18export class LeastBusyWorkerChoiceStrategy<
f06e48d8 19 Worker extends IWorker,
b2b1d84e
JB
20 Data = unknown,
21 Response = unknown
bf90656c
JB
22 >
23 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
17393ac8 24 implements IWorkerChoiceStrategy {
afc003b2 25 /** @inheritDoc */
87de9ff5 26 public readonly taskStatisticsRequirements: TaskStatisticsRequirements = {
932fc8be
JB
27 runTime: {
28 aggregate: true,
29 average: false,
30 median: false
31 },
32 waitTime: {
33 aggregate: true,
34 average: false,
35 median: false
36 },
5df69fab
JB
37 elu: {
38 aggregate: false,
39 average: false,
40 median: false
41 }
168c526f
JB
42 }
43
2fc5cae3
JB
44 /** @inheritDoc */
45 public constructor (
46 pool: IPool<Worker, Data, Response>,
47 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
48 ) {
49 super(pool, opts)
932fc8be 50 this.setTaskStatisticsRequirements(this.opts)
2fc5cae3
JB
51 }
52
afc003b2 53 /** @inheritDoc */
168c526f
JB
54 public reset (): boolean {
55 return true
56 }
57
138d29a8
JB
58 /** @inheritDoc */
59 public update (): boolean {
db703c75
JB
60 return true
61 }
62
63 /** @inheritDoc */
64 public choose (): number {
1c6fe997 65 let minTime = Infinity
08f3f44c 66 for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
1c6fe997 67 const workerTime =
932fc8be
JB
68 workerNode.workerUsage.runTime.aggregate +
69 workerNode.workerUsage.waitTime.aggregate
1c6fe997 70 if (workerTime === 0) {
d33be430 71 this.nextWorkerNodeId = workerNodeKey
5ea80606 72 break
1c6fe997
JB
73 } else if (workerTime < minTime) {
74 minTime = workerTime
d33be430 75 this.nextWorkerNodeId = workerNodeKey
168c526f
JB
76 }
77 }
d33be430 78 return this.nextWorkerNodeId
168c526f 79 }
97a2abc3 80
afc003b2 81 /** @inheritDoc */
a4958de2 82 public remove (): boolean {
97a2abc3
JB
83 return true
84 }
168c526f 85}