6e798fbc4349d98bf5b5761d884013382efa601f
[poolifier.git] / src / pools / selection-strategies / abstract-worker-choice-strategy.ts
1 import { cpus } from 'node:os'
2 import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
3 import type { IPool } from '../pool'
4 import type { IWorker } from '../worker'
5 import type {
6 IWorkerChoiceStrategy,
7 RequiredStatistics,
8 WorkerChoiceStrategyOptions
9 } from './selection-strategies-types'
10
11 /**
12 * Worker choice strategy abstract base class.
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 serializable data.
16 * @typeParam Response - Type of execution response. This can only be serializable data.
17 */
18 export abstract class AbstractWorkerChoiceStrategy<
19 Worker extends IWorker,
20 Data = unknown,
21 Response = unknown
22 > implements IWorkerChoiceStrategy {
23 /**
24 * Toggles finding the last free worker node key.
25 */
26 private toggleFindLastFreeWorkerNodeKey: boolean = false
27 /** @inheritDoc */
28 public readonly requiredStatistics: RequiredStatistics = {
29 runTime: false,
30 avgRunTime: false,
31 medRunTime: false,
32 waitTime: false,
33 avgWaitTime: false,
34 medWaitTime: false
35 }
36
37 /**
38 * Constructs a worker choice strategy bound to the pool.
39 *
40 * @param pool - The pool instance.
41 * @param opts - The worker choice strategy options.
42 */
43 public constructor (
44 protected readonly pool: IPool<Worker, Data, Response>,
45 protected opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
46 ) {
47 this.choose = this.choose.bind(this)
48 }
49
50 protected setRequiredStatistics (opts: WorkerChoiceStrategyOptions): void {
51 if (this.requiredStatistics.avgRunTime && opts.medRunTime === true) {
52 this.requiredStatistics.avgRunTime = false
53 this.requiredStatistics.medRunTime = opts.medRunTime as boolean
54 }
55 if (this.requiredStatistics.medRunTime && opts.medRunTime === false) {
56 this.requiredStatistics.avgRunTime = true
57 this.requiredStatistics.medRunTime = opts.medRunTime as boolean
58 }
59 if (this.requiredStatistics.avgWaitTime && opts.medWaitTime === true) {
60 this.requiredStatistics.avgWaitTime = false
61 this.requiredStatistics.medWaitTime = opts.medWaitTime as boolean
62 }
63 if (this.requiredStatistics.medWaitTime && opts.medWaitTime === false) {
64 this.requiredStatistics.avgWaitTime = true
65 this.requiredStatistics.medWaitTime = opts.medWaitTime as boolean
66 }
67 }
68
69 /** @inheritDoc */
70 public abstract reset (): boolean
71
72 /** @inheritDoc */
73 public abstract update (workerNodeKey: number): boolean
74
75 /** @inheritDoc */
76 public abstract choose (): number
77
78 /** @inheritDoc */
79 public abstract remove (workerNodeKey: number): boolean
80
81 /** @inheritDoc */
82 public setOptions (opts: WorkerChoiceStrategyOptions): void {
83 opts = opts ?? DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
84 this.setRequiredStatistics(opts)
85 this.opts = opts
86 }
87
88 /**
89 * Finds a free worker node key.
90 *
91 * @returns The free worker node key or `-1` if there is no free worker node.
92 */
93 protected findFreeWorkerNodeKey (): number {
94 if (this.toggleFindLastFreeWorkerNodeKey) {
95 this.toggleFindLastFreeWorkerNodeKey = false
96 return this.findLastFreeWorkerNodeKey()
97 }
98 this.toggleFindLastFreeWorkerNodeKey = true
99 return this.findFirstFreeWorkerNodeKey()
100 }
101
102 /**
103 * Gets the worker task runtime.
104 * If the required statistics are `avgRunTime`, the average runtime is returned.
105 * If the required statistics are `medRunTime`, the median runtime is returned.
106 *
107 * @param workerNodeKey - The worker node key.
108 * @returns The worker task runtime.
109 */
110 protected getWorkerTaskRunTime (workerNodeKey: number): number {
111 return this.requiredStatistics.medRunTime
112 ? this.pool.workerNodes[workerNodeKey].tasksUsage.medRunTime
113 : this.pool.workerNodes[workerNodeKey].tasksUsage.avgRunTime
114 }
115
116 /**
117 * Gets the worker task wait time.
118 * If the required statistics are `avgWaitTime`, the average wait time is returned.
119 * If the required statistics are `medWaitTime`, the median wait time is returned.
120 *
121 * @param workerNodeKey - The worker node key.
122 * @returns The worker task wait time.
123 */
124 protected getWorkerWaitTime (workerNodeKey: number): number {
125 return this.requiredStatistics.medWaitTime
126 ? this.pool.workerNodes[workerNodeKey].tasksUsage.medWaitTime
127 : this.pool.workerNodes[workerNodeKey].tasksUsage.avgWaitTime
128 }
129
130 protected computeDefaultWorkerWeight (): number {
131 let cpusCycleTimeWeight = 0
132 for (const cpu of cpus()) {
133 // CPU estimated cycle time
134 const numberOfDigits = cpu.speed.toString().length - 1
135 const cpuCycleTime = 1 / (cpu.speed / Math.pow(10, numberOfDigits))
136 cpusCycleTimeWeight += cpuCycleTime * Math.pow(10, numberOfDigits)
137 }
138 return Math.round(cpusCycleTimeWeight / cpus().length)
139 }
140
141 /**
142 * Finds the first free worker node key based on the number of tasks the worker has applied.
143 *
144 * If a worker is found with `0` running tasks, it is detected as free and its worker node key is returned.
145 *
146 * If no free worker is found, `-1` is returned.
147 *
148 * @returns A worker node key if there is one, `-1` otherwise.
149 */
150 private findFirstFreeWorkerNodeKey (): number {
151 return this.pool.workerNodes.findIndex(workerNode => {
152 return workerNode.tasksUsage.running === 0
153 })
154 }
155
156 /**
157 * Finds the last free worker node key based on the number of tasks the worker has applied.
158 *
159 * If a worker is found with `0` running tasks, it is detected as free and its worker node key is returned.
160 *
161 * If no free worker is found, `-1` is returned.
162 *
163 * @returns A worker node key if there is one, `-1` otherwise.
164 */
165 private findLastFreeWorkerNodeKey (): number {
166 // It requires node >= 18.0.0:
167 // return this.workerNodes.findLastIndex(workerNode => {
168 // return workerNode.tasksUsage.running === 0
169 // })
170 for (
171 let workerNodeKey = this.pool.workerNodes.length - 1;
172 workerNodeKey >= 0;
173 workerNodeKey--
174 ) {
175 if (this.pool.workerNodes[workerNodeKey].tasksUsage.running === 0) {
176 return workerNodeKey
177 }
178 }
179 return -1
180 }
181 }