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