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