Commit | Line | Data |
---|---|---|
ded253e2 | 1 | import { AsyncResource } from 'node:async_hooks' |
2845f2a5 | 2 | import { randomUUID } from 'node:crypto' |
ded253e2 | 3 | import { EventEmitterAsyncResource } from 'node:events' |
62c15a68 | 4 | import { performance } from 'node:perf_hooks' |
ef083f7b | 5 | import type { TransferListItem } from 'node:worker_threads' |
ded253e2 | 6 | |
5c4d16da JB |
7 | import type { |
8 | MessageValue, | |
9 | PromiseResponseWrapper, | |
31847469 JB |
10 | Task, |
11 | TaskFunctionProperties | |
d35e5717 | 12 | } from '../utility-types.js' |
bbeadd16 | 13 | import { |
ded253e2 | 14 | average, |
31847469 | 15 | buildTaskFunctionProperties, |
ff128cc9 | 16 | DEFAULT_TASK_NAME, |
bbeadd16 | 17 | EMPTY_FUNCTION, |
463226a4 | 18 | exponentialDelay, |
59317253 | 19 | isKillBehavior, |
0d80593b | 20 | isPlainObject, |
90d6701c | 21 | max, |
afe0d5bf | 22 | median, |
90d6701c | 23 | min, |
463226a4 JB |
24 | round, |
25 | sleep | |
d35e5717 | 26 | } from '../utils.js' |
31847469 JB |
27 | import type { |
28 | TaskFunction, | |
29 | TaskFunctionObject | |
30 | } from '../worker/task-functions.js' | |
ded253e2 | 31 | import { KillBehaviors } from '../worker/worker-options.js' |
c4855468 | 32 | import { |
65d7a1c9 | 33 | type IPool, |
c4855468 | 34 | PoolEvents, |
6b27d407 | 35 | type PoolInfo, |
c4855468 | 36 | type PoolOptions, |
6b27d407 JB |
37 | type PoolType, |
38 | PoolTypes, | |
4b628b48 | 39 | type TasksQueueOptions |
d35e5717 | 40 | } from './pool.js' |
a35560ba | 41 | import { |
f0d7f803 | 42 | Measurements, |
a35560ba | 43 | WorkerChoiceStrategies, |
a20f0ba5 JB |
44 | type WorkerChoiceStrategy, |
45 | type WorkerChoiceStrategyOptions | |
d35e5717 | 46 | } from './selection-strategies/selection-strategies-types.js' |
bcfb06ce | 47 | import { WorkerChoiceStrategiesContext } from './selection-strategies/worker-choice-strategies-context.js' |
bde6b5d7 JB |
48 | import { |
49 | checkFilePath, | |
95d1a734 | 50 | checkValidPriority, |
bde6b5d7 | 51 | checkValidTasksQueueOptions, |
bfc75cca | 52 | checkValidWorkerChoiceStrategy, |
32b141fd | 53 | getDefaultTasksQueueOptions, |
c329fd41 JB |
54 | updateEluWorkerUsage, |
55 | updateRunTimeWorkerUsage, | |
56 | updateTaskStatisticsWorkerUsage, | |
57 | updateWaitTimeWorkerUsage, | |
87347ea8 | 58 | waitWorkerNodeEvents |
d35e5717 | 59 | } from './utils.js' |
ded253e2 JB |
60 | import { version } from './version.js' |
61 | import type { | |
62 | IWorker, | |
63 | IWorkerNode, | |
64 | WorkerInfo, | |
65 | WorkerNodeEventDetail, | |
66 | WorkerType | |
67 | } from './worker.js' | |
68 | import { WorkerNode } from './worker-node.js' | |
23ccf9d7 | 69 | |
729c563d | 70 | /** |
ea7a90d3 | 71 | * Base class that implements some shared logic for all poolifier pools. |
729c563d | 72 | * |
38e795c1 | 73 | * @typeParam Worker - Type of worker which manages this pool. |
e102732c JB |
74 | * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. |
75 | * @typeParam Response - Type of execution response. This can only be structured-cloneable data. | |
729c563d | 76 | */ |
c97c7edb | 77 | export abstract class AbstractPool< |
f06e48d8 | 78 | Worker extends IWorker, |
d3c8a1a8 S |
79 | Data = unknown, |
80 | Response = unknown | |
c4855468 | 81 | > implements IPool<Worker, Data, Response> { |
afc003b2 | 82 | /** @inheritDoc */ |
4b628b48 | 83 | public readonly workerNodes: Array<IWorkerNode<Worker, Data>> = [] |
4a6952ff | 84 | |
afc003b2 | 85 | /** @inheritDoc */ |
f80125ca | 86 | public emitter?: EventEmitterAsyncResource |
7c0ba920 | 87 | |
be0676b3 | 88 | /** |
419e8121 | 89 | * The task execution response promise map: |
2740a743 | 90 | * - `key`: The message id of each submitted task. |
bcfb06ce | 91 | * - `value`: An object that contains task's worker node key, execution response promise resolve and reject callbacks, async resource. |
be0676b3 | 92 | * |
a3445496 | 93 | * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id. |
be0676b3 | 94 | */ |
84781cd6 JB |
95 | protected promiseResponseMap: Map< |
96 | `${string}-${string}-${string}-${string}-${string}`, | |
97 | PromiseResponseWrapper<Response> | |
98 | > = new Map< | |
99 | `${string}-${string}-${string}-${string}-${string}`, | |
100 | PromiseResponseWrapper<Response> | |
101 | >() | |
c97c7edb | 102 | |
a35560ba | 103 | /** |
bcfb06ce | 104 | * Worker choice strategies context referencing worker choice algorithms implementation. |
a35560ba | 105 | */ |
bcfb06ce | 106 | protected workerChoiceStrategiesContext?: WorkerChoiceStrategiesContext< |
78cea37e JB |
107 | Worker, |
108 | Data, | |
109 | Response | |
a35560ba S |
110 | > |
111 | ||
72ae84a2 JB |
112 | /** |
113 | * The task functions added at runtime map: | |
114 | * - `key`: The task function name. | |
31847469 | 115 | * - `value`: The task function object. |
72ae84a2 | 116 | */ |
31847469 JB |
117 | private readonly taskFunctions: Map< |
118 | string, | |
119 | TaskFunctionObject<Data, Response> | |
120 | > | |
72ae84a2 | 121 | |
15b176e0 JB |
122 | /** |
123 | * Whether the pool is started or not. | |
124 | */ | |
125 | private started: boolean | |
47352846 JB |
126 | /** |
127 | * Whether the pool is starting or not. | |
128 | */ | |
129 | private starting: boolean | |
711623b8 JB |
130 | /** |
131 | * Whether the pool is destroying or not. | |
132 | */ | |
133 | private destroying: boolean | |
b362a929 JB |
134 | /** |
135 | * Whether the minimum number of workers is starting or not. | |
136 | */ | |
137 | private startingMinimumNumberOfWorkers: boolean | |
55082af9 JB |
138 | /** |
139 | * Whether the pool ready event has been emitted or not. | |
140 | */ | |
141 | private readyEventEmitted: boolean | |
afe0d5bf JB |
142 | /** |
143 | * The start timestamp of the pool. | |
144 | */ | |
97dc65d9 | 145 | private startTimestamp?: number |
afe0d5bf | 146 | |
729c563d S |
147 | /** |
148 | * Constructs a new poolifier pool. | |
149 | * | |
00e1bdeb | 150 | * @param minimumNumberOfWorkers - Minimum number of workers that this pool manages. |
029715f0 | 151 | * @param filePath - Path to the worker file. |
38e795c1 | 152 | * @param opts - Options for the pool. |
00e1bdeb | 153 | * @param maximumNumberOfWorkers - Maximum number of workers that this pool manages. |
729c563d | 154 | */ |
c97c7edb | 155 | public constructor ( |
26ce26ca | 156 | protected readonly minimumNumberOfWorkers: number, |
b4213b7f | 157 | protected readonly filePath: string, |
26ce26ca JB |
158 | protected readonly opts: PoolOptions<Worker>, |
159 | protected readonly maximumNumberOfWorkers?: number | |
c97c7edb | 160 | ) { |
78cea37e | 161 | if (!this.isMain()) { |
04f45163 | 162 | throw new Error( |
8c6d4acf | 163 | 'Cannot start a pool from a worker with the same type as the pool' |
04f45163 | 164 | ) |
c97c7edb | 165 | } |
26ce26ca | 166 | this.checkPoolType() |
bde6b5d7 | 167 | checkFilePath(this.filePath) |
26ce26ca | 168 | this.checkMinimumNumberOfWorkers(this.minimumNumberOfWorkers) |
7c0ba920 | 169 | this.checkPoolOptions(this.opts) |
1086026a | 170 | |
7254e419 JB |
171 | this.chooseWorkerNode = this.chooseWorkerNode.bind(this) |
172 | this.executeTask = this.executeTask.bind(this) | |
173 | this.enqueueTask = this.enqueueTask.bind(this) | |
1086026a | 174 | |
6bd72cd0 | 175 | if (this.opts.enableEvents === true) { |
e0843544 | 176 | this.initEventEmitter() |
7c0ba920 | 177 | } |
bcfb06ce | 178 | this.workerChoiceStrategiesContext = new WorkerChoiceStrategiesContext< |
d59df138 JB |
179 | Worker, |
180 | Data, | |
181 | Response | |
da309861 JB |
182 | >( |
183 | this, | |
bcfb06ce JB |
184 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
185 | [this.opts.workerChoiceStrategy!], | |
da309861 JB |
186 | this.opts.workerChoiceStrategyOptions |
187 | ) | |
b6b32453 JB |
188 | |
189 | this.setupHook() | |
190 | ||
31847469 | 191 | this.taskFunctions = new Map<string, TaskFunctionObject<Data, Response>>() |
72ae84a2 | 192 | |
47352846 | 193 | this.started = false |
075e51d1 | 194 | this.starting = false |
711623b8 | 195 | this.destroying = false |
55082af9 | 196 | this.readyEventEmitted = false |
b362a929 | 197 | this.startingMinimumNumberOfWorkers = false |
47352846 JB |
198 | if (this.opts.startWorkers === true) { |
199 | this.start() | |
200 | } | |
c97c7edb S |
201 | } |
202 | ||
26ce26ca JB |
203 | private checkPoolType (): void { |
204 | if (this.type === PoolTypes.fixed && this.maximumNumberOfWorkers != null) { | |
205 | throw new Error( | |
206 | 'Cannot instantiate a fixed pool with a maximum number of workers specified at initialization' | |
207 | ) | |
208 | } | |
209 | } | |
210 | ||
c63a35a0 JB |
211 | private checkMinimumNumberOfWorkers ( |
212 | minimumNumberOfWorkers: number | undefined | |
213 | ): void { | |
af7f2788 | 214 | if (minimumNumberOfWorkers == null) { |
8d3782fa JB |
215 | throw new Error( |
216 | 'Cannot instantiate a pool without specifying the number of workers' | |
217 | ) | |
af7f2788 | 218 | } else if (!Number.isSafeInteger(minimumNumberOfWorkers)) { |
473c717a | 219 | throw new TypeError( |
0d80593b | 220 | 'Cannot instantiate a pool with a non safe integer number of workers' |
8d3782fa | 221 | ) |
af7f2788 | 222 | } else if (minimumNumberOfWorkers < 0) { |
473c717a | 223 | throw new RangeError( |
8d3782fa JB |
224 | 'Cannot instantiate a pool with a negative number of workers' |
225 | ) | |
af7f2788 | 226 | } else if (this.type === PoolTypes.fixed && minimumNumberOfWorkers === 0) { |
2431bdb4 JB |
227 | throw new RangeError('Cannot instantiate a fixed pool with zero worker') |
228 | } | |
229 | } | |
230 | ||
7c0ba920 | 231 | private checkPoolOptions (opts: PoolOptions<Worker>): void { |
0d80593b | 232 | if (isPlainObject(opts)) { |
47352846 | 233 | this.opts.startWorkers = opts.startWorkers ?? true |
c63a35a0 | 234 | checkValidWorkerChoiceStrategy(opts.workerChoiceStrategy) |
0d80593b JB |
235 | this.opts.workerChoiceStrategy = |
236 | opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN | |
2324f8c9 | 237 | this.checkValidWorkerChoiceStrategyOptions( |
c63a35a0 | 238 | opts.workerChoiceStrategyOptions |
2324f8c9 | 239 | ) |
26ce26ca JB |
240 | if (opts.workerChoiceStrategyOptions != null) { |
241 | this.opts.workerChoiceStrategyOptions = opts.workerChoiceStrategyOptions | |
8990357d | 242 | } |
1f68cede | 243 | this.opts.restartWorkerOnError = opts.restartWorkerOnError ?? true |
0d80593b JB |
244 | this.opts.enableEvents = opts.enableEvents ?? true |
245 | this.opts.enableTasksQueue = opts.enableTasksQueue ?? false | |
246 | if (this.opts.enableTasksQueue) { | |
c63a35a0 | 247 | checkValidTasksQueueOptions(opts.tasksQueueOptions) |
0d80593b | 248 | this.opts.tasksQueueOptions = this.buildTasksQueueOptions( |
c63a35a0 | 249 | opts.tasksQueueOptions |
0d80593b JB |
250 | ) |
251 | } | |
252 | } else { | |
253 | throw new TypeError('Invalid pool options: must be a plain object') | |
7171d33f | 254 | } |
aee46736 JB |
255 | } |
256 | ||
0d80593b | 257 | private checkValidWorkerChoiceStrategyOptions ( |
c63a35a0 | 258 | workerChoiceStrategyOptions: WorkerChoiceStrategyOptions | undefined |
0d80593b | 259 | ): void { |
2324f8c9 JB |
260 | if ( |
261 | workerChoiceStrategyOptions != null && | |
262 | !isPlainObject(workerChoiceStrategyOptions) | |
263 | ) { | |
0d80593b JB |
264 | throw new TypeError( |
265 | 'Invalid worker choice strategy options: must be a plain object' | |
266 | ) | |
267 | } | |
49be33fe | 268 | if ( |
2324f8c9 | 269 | workerChoiceStrategyOptions?.weights != null && |
26ce26ca JB |
270 | Object.keys(workerChoiceStrategyOptions.weights).length !== |
271 | (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers) | |
49be33fe JB |
272 | ) { |
273 | throw new Error( | |
274 | 'Invalid worker choice strategy options: must have a weight for each worker node' | |
275 | ) | |
276 | } | |
f0d7f803 | 277 | if ( |
2324f8c9 | 278 | workerChoiceStrategyOptions?.measurement != null && |
f0d7f803 JB |
279 | !Object.values(Measurements).includes( |
280 | workerChoiceStrategyOptions.measurement | |
281 | ) | |
282 | ) { | |
283 | throw new Error( | |
284 | `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'` | |
285 | ) | |
286 | } | |
0d80593b JB |
287 | } |
288 | ||
e0843544 | 289 | private initEventEmitter (): void { |
5b7d00b4 | 290 | this.emitter = new EventEmitterAsyncResource({ |
b5604034 JB |
291 | name: `poolifier:${this.type}-${this.worker}-pool` |
292 | }) | |
293 | } | |
294 | ||
08f3f44c | 295 | /** @inheritDoc */ |
6b27d407 JB |
296 | public get info (): PoolInfo { |
297 | return { | |
23ccf9d7 | 298 | version, |
6b27d407 | 299 | type: this.type, |
184855e6 | 300 | worker: this.worker, |
47352846 | 301 | started: this.started, |
2431bdb4 | 302 | ready: this.ready, |
67f3f2d6 | 303 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
bcfb06ce JB |
304 | defaultStrategy: this.opts.workerChoiceStrategy!, |
305 | strategyRetries: this.workerChoiceStrategiesContext?.retriesCount ?? 0, | |
26ce26ca JB |
306 | minSize: this.minimumNumberOfWorkers, |
307 | maxSize: this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers, | |
bcfb06ce | 308 | ...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements() |
f4d0a470 | 309 | .runTime.aggregate === true && |
bcfb06ce | 310 | this.workerChoiceStrategiesContext.getTaskStatisticsRequirements() |
c63a35a0 JB |
311 | .waitTime.aggregate && { |
312 | utilization: round(this.utilization) | |
313 | }), | |
6b27d407 JB |
314 | workerNodes: this.workerNodes.length, |
315 | idleWorkerNodes: this.workerNodes.reduce( | |
316 | (accumulator, workerNode) => | |
f59e1027 | 317 | workerNode.usage.tasks.executing === 0 |
a4e07f72 JB |
318 | ? accumulator + 1 |
319 | : accumulator, | |
6b27d407 JB |
320 | 0 |
321 | ), | |
5eb72b9e JB |
322 | ...(this.opts.enableTasksQueue === true && { |
323 | stealingWorkerNodes: this.workerNodes.reduce( | |
324 | (accumulator, workerNode) => | |
325 | workerNode.info.stealing ? accumulator + 1 : accumulator, | |
326 | 0 | |
327 | ) | |
328 | }), | |
6b27d407 | 329 | busyWorkerNodes: this.workerNodes.reduce( |
533a8e22 | 330 | (accumulator, _, workerNodeKey) => |
42c677c1 | 331 | this.isWorkerNodeBusy(workerNodeKey) ? accumulator + 1 : accumulator, |
6b27d407 JB |
332 | 0 |
333 | ), | |
a4e07f72 | 334 | executedTasks: this.workerNodes.reduce( |
6b27d407 | 335 | (accumulator, workerNode) => |
f59e1027 | 336 | accumulator + workerNode.usage.tasks.executed, |
a4e07f72 JB |
337 | 0 |
338 | ), | |
339 | executingTasks: this.workerNodes.reduce( | |
340 | (accumulator, workerNode) => | |
f59e1027 | 341 | accumulator + workerNode.usage.tasks.executing, |
6b27d407 JB |
342 | 0 |
343 | ), | |
daf86646 JB |
344 | ...(this.opts.enableTasksQueue === true && { |
345 | queuedTasks: this.workerNodes.reduce( | |
346 | (accumulator, workerNode) => | |
347 | accumulator + workerNode.usage.tasks.queued, | |
348 | 0 | |
349 | ) | |
350 | }), | |
351 | ...(this.opts.enableTasksQueue === true && { | |
352 | maxQueuedTasks: this.workerNodes.reduce( | |
353 | (accumulator, workerNode) => | |
c63a35a0 | 354 | accumulator + (workerNode.usage.tasks.maxQueued ?? 0), |
daf86646 JB |
355 | 0 |
356 | ) | |
357 | }), | |
a1763c54 JB |
358 | ...(this.opts.enableTasksQueue === true && { |
359 | backPressure: this.hasBackPressure() | |
360 | }), | |
68cbdc84 JB |
361 | ...(this.opts.enableTasksQueue === true && { |
362 | stolenTasks: this.workerNodes.reduce( | |
363 | (accumulator, workerNode) => | |
364 | accumulator + workerNode.usage.tasks.stolen, | |
365 | 0 | |
366 | ) | |
367 | }), | |
a4e07f72 JB |
368 | failedTasks: this.workerNodes.reduce( |
369 | (accumulator, workerNode) => | |
f59e1027 | 370 | accumulator + workerNode.usage.tasks.failed, |
a4e07f72 | 371 | 0 |
1dcf8b7b | 372 | ), |
bcfb06ce | 373 | ...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements() |
f4d0a470 | 374 | .runTime.aggregate === true && { |
1dcf8b7b | 375 | runTime: { |
98e72cda | 376 | minimum: round( |
90d6701c | 377 | min( |
98e72cda | 378 | ...this.workerNodes.map( |
c63a35a0 | 379 | workerNode => workerNode.usage.runTime.minimum ?? Infinity |
98e72cda | 380 | ) |
1dcf8b7b JB |
381 | ) |
382 | ), | |
98e72cda | 383 | maximum: round( |
90d6701c | 384 | max( |
98e72cda | 385 | ...this.workerNodes.map( |
c63a35a0 | 386 | workerNode => workerNode.usage.runTime.maximum ?? -Infinity |
98e72cda | 387 | ) |
1dcf8b7b | 388 | ) |
98e72cda | 389 | ), |
bcfb06ce | 390 | ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements() |
3baa0837 JB |
391 | .runTime.average && { |
392 | average: round( | |
393 | average( | |
394 | this.workerNodes.reduce<number[]>( | |
395 | (accumulator, workerNode) => | |
396 | accumulator.concat(workerNode.usage.runTime.history), | |
397 | [] | |
398 | ) | |
98e72cda | 399 | ) |
dc021bcc | 400 | ) |
3baa0837 | 401 | }), |
bcfb06ce | 402 | ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements() |
98e72cda JB |
403 | .runTime.median && { |
404 | median: round( | |
405 | median( | |
3baa0837 JB |
406 | this.workerNodes.reduce<number[]>( |
407 | (accumulator, workerNode) => | |
408 | accumulator.concat(workerNode.usage.runTime.history), | |
409 | [] | |
98e72cda JB |
410 | ) |
411 | ) | |
412 | ) | |
413 | }) | |
1dcf8b7b JB |
414 | } |
415 | }), | |
bcfb06ce | 416 | ...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements() |
f4d0a470 | 417 | .waitTime.aggregate === true && { |
1dcf8b7b | 418 | waitTime: { |
98e72cda | 419 | minimum: round( |
90d6701c | 420 | min( |
98e72cda | 421 | ...this.workerNodes.map( |
c63a35a0 | 422 | workerNode => workerNode.usage.waitTime.minimum ?? Infinity |
98e72cda | 423 | ) |
1dcf8b7b JB |
424 | ) |
425 | ), | |
98e72cda | 426 | maximum: round( |
90d6701c | 427 | max( |
98e72cda | 428 | ...this.workerNodes.map( |
c63a35a0 | 429 | workerNode => workerNode.usage.waitTime.maximum ?? -Infinity |
98e72cda | 430 | ) |
1dcf8b7b | 431 | ) |
98e72cda | 432 | ), |
bcfb06ce | 433 | ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements() |
3baa0837 JB |
434 | .waitTime.average && { |
435 | average: round( | |
436 | average( | |
437 | this.workerNodes.reduce<number[]>( | |
438 | (accumulator, workerNode) => | |
439 | accumulator.concat(workerNode.usage.waitTime.history), | |
440 | [] | |
441 | ) | |
98e72cda | 442 | ) |
dc021bcc | 443 | ) |
3baa0837 | 444 | }), |
bcfb06ce | 445 | ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements() |
98e72cda JB |
446 | .waitTime.median && { |
447 | median: round( | |
448 | median( | |
3baa0837 JB |
449 | this.workerNodes.reduce<number[]>( |
450 | (accumulator, workerNode) => | |
451 | accumulator.concat(workerNode.usage.waitTime.history), | |
452 | [] | |
98e72cda JB |
453 | ) |
454 | ) | |
455 | ) | |
456 | }) | |
1dcf8b7b | 457 | } |
533a8e22 JB |
458 | }), |
459 | ...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements() | |
460 | .elu.aggregate === true && { | |
461 | elu: { | |
462 | idle: { | |
463 | minimum: round( | |
464 | min( | |
465 | ...this.workerNodes.map( | |
466 | workerNode => workerNode.usage.elu.idle.minimum ?? Infinity | |
467 | ) | |
468 | ) | |
469 | ), | |
470 | maximum: round( | |
471 | max( | |
472 | ...this.workerNodes.map( | |
473 | workerNode => workerNode.usage.elu.idle.maximum ?? -Infinity | |
474 | ) | |
475 | ) | |
476 | ), | |
477 | ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements() | |
478 | .elu.average && { | |
479 | average: round( | |
480 | average( | |
481 | this.workerNodes.reduce<number[]>( | |
482 | (accumulator, workerNode) => | |
483 | accumulator.concat(workerNode.usage.elu.idle.history), | |
484 | [] | |
485 | ) | |
486 | ) | |
487 | ) | |
488 | }), | |
489 | ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements() | |
490 | .elu.median && { | |
491 | median: round( | |
492 | median( | |
493 | this.workerNodes.reduce<number[]>( | |
494 | (accumulator, workerNode) => | |
495 | accumulator.concat(workerNode.usage.elu.idle.history), | |
496 | [] | |
497 | ) | |
498 | ) | |
499 | ) | |
500 | }) | |
501 | }, | |
502 | active: { | |
503 | minimum: round( | |
504 | min( | |
505 | ...this.workerNodes.map( | |
506 | workerNode => workerNode.usage.elu.active.minimum ?? Infinity | |
507 | ) | |
508 | ) | |
509 | ), | |
510 | maximum: round( | |
511 | max( | |
512 | ...this.workerNodes.map( | |
513 | workerNode => workerNode.usage.elu.active.maximum ?? -Infinity | |
514 | ) | |
515 | ) | |
516 | ), | |
517 | ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements() | |
518 | .elu.average && { | |
519 | average: round( | |
520 | average( | |
521 | this.workerNodes.reduce<number[]>( | |
522 | (accumulator, workerNode) => | |
523 | accumulator.concat(workerNode.usage.elu.active.history), | |
524 | [] | |
525 | ) | |
526 | ) | |
527 | ) | |
528 | }), | |
529 | ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements() | |
530 | .elu.median && { | |
531 | median: round( | |
532 | median( | |
533 | this.workerNodes.reduce<number[]>( | |
534 | (accumulator, workerNode) => | |
535 | accumulator.concat(workerNode.usage.elu.active.history), | |
536 | [] | |
537 | ) | |
538 | ) | |
539 | ) | |
540 | }) | |
541 | } | |
542 | } | |
1dcf8b7b | 543 | }) |
6b27d407 JB |
544 | } |
545 | } | |
08f3f44c | 546 | |
aa9eede8 JB |
547 | /** |
548 | * The pool readiness boolean status. | |
549 | */ | |
2431bdb4 | 550 | private get ready (): boolean { |
8e8d9101 JB |
551 | if (this.empty) { |
552 | return false | |
553 | } | |
2431bdb4 | 554 | return ( |
b97d82d8 JB |
555 | this.workerNodes.reduce( |
556 | (accumulator, workerNode) => | |
557 | !workerNode.info.dynamic && workerNode.info.ready | |
558 | ? accumulator + 1 | |
559 | : accumulator, | |
560 | 0 | |
26ce26ca | 561 | ) >= this.minimumNumberOfWorkers |
2431bdb4 JB |
562 | ) |
563 | } | |
564 | ||
8e8d9101 JB |
565 | /** |
566 | * The pool emptiness boolean status. | |
567 | */ | |
568 | protected get empty (): boolean { | |
fb43035c | 569 | return this.minimumNumberOfWorkers === 0 && this.workerNodes.length === 0 |
8e8d9101 JB |
570 | } |
571 | ||
afe0d5bf | 572 | /** |
aa9eede8 | 573 | * The approximate pool utilization. |
afe0d5bf JB |
574 | * |
575 | * @returns The pool utilization. | |
576 | */ | |
577 | private get utilization (): number { | |
97dc65d9 JB |
578 | if (this.startTimestamp == null) { |
579 | return 0 | |
580 | } | |
8e5ca040 | 581 | const poolTimeCapacity = |
26ce26ca JB |
582 | (performance.now() - this.startTimestamp) * |
583 | (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers) | |
afe0d5bf JB |
584 | const totalTasksRunTime = this.workerNodes.reduce( |
585 | (accumulator, workerNode) => | |
c63a35a0 | 586 | accumulator + (workerNode.usage.runTime.aggregate ?? 0), |
afe0d5bf JB |
587 | 0 |
588 | ) | |
589 | const totalTasksWaitTime = this.workerNodes.reduce( | |
590 | (accumulator, workerNode) => | |
c63a35a0 | 591 | accumulator + (workerNode.usage.waitTime.aggregate ?? 0), |
afe0d5bf JB |
592 | 0 |
593 | ) | |
8e5ca040 | 594 | return (totalTasksRunTime + totalTasksWaitTime) / poolTimeCapacity |
afe0d5bf JB |
595 | } |
596 | ||
8881ae32 | 597 | /** |
aa9eede8 | 598 | * The pool type. |
8881ae32 JB |
599 | * |
600 | * If it is `'dynamic'`, it provides the `max` property. | |
601 | */ | |
602 | protected abstract get type (): PoolType | |
603 | ||
184855e6 | 604 | /** |
aa9eede8 | 605 | * The worker type. |
184855e6 JB |
606 | */ |
607 | protected abstract get worker (): WorkerType | |
608 | ||
6b813701 JB |
609 | /** |
610 | * Checks if the worker id sent in the received message from a worker is valid. | |
611 | * | |
612 | * @param message - The received message. | |
613 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid. | |
614 | */ | |
4d159167 | 615 | private checkMessageWorkerId (message: MessageValue<Data | Response>): void { |
310de0aa JB |
616 | if (message.workerId == null) { |
617 | throw new Error('Worker message received without worker id') | |
8e5a7cf9 | 618 | } else if (this.getWorkerNodeKeyByWorkerId(message.workerId) === -1) { |
21f710aa JB |
619 | throw new Error( |
620 | `Worker message received from unknown worker '${message.workerId}'` | |
621 | ) | |
622 | } | |
623 | } | |
624 | ||
aa9eede8 JB |
625 | /** |
626 | * Gets the worker node key given its worker id. | |
627 | * | |
628 | * @param workerId - The worker id. | |
aad6fb64 | 629 | * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise. |
aa9eede8 | 630 | */ |
72ae84a2 | 631 | private getWorkerNodeKeyByWorkerId (workerId: number | undefined): number { |
aad6fb64 | 632 | return this.workerNodes.findIndex( |
041dc05b | 633 | workerNode => workerNode.info.id === workerId |
aad6fb64 | 634 | ) |
aa9eede8 JB |
635 | } |
636 | ||
afc003b2 | 637 | /** @inheritDoc */ |
a35560ba | 638 | public setWorkerChoiceStrategy ( |
59219cbb JB |
639 | workerChoiceStrategy: WorkerChoiceStrategy, |
640 | workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions | |
a35560ba | 641 | ): void { |
19b8be8b | 642 | let requireSync = false |
bde6b5d7 | 643 | checkValidWorkerChoiceStrategy(workerChoiceStrategy) |
85bbc7ab | 644 | if (workerChoiceStrategyOptions != null) { |
423f3b7a | 645 | requireSync = !this.setWorkerChoiceStrategyOptions( |
19b8be8b JB |
646 | workerChoiceStrategyOptions |
647 | ) | |
85bbc7ab JB |
648 | } |
649 | if (workerChoiceStrategy !== this.opts.workerChoiceStrategy) { | |
650 | this.opts.workerChoiceStrategy = workerChoiceStrategy | |
651 | this.workerChoiceStrategiesContext?.setDefaultWorkerChoiceStrategy( | |
652 | this.opts.workerChoiceStrategy, | |
653 | this.opts.workerChoiceStrategyOptions | |
654 | ) | |
19b8be8b JB |
655 | requireSync = true |
656 | } | |
657 | if (requireSync) { | |
85bbc7ab | 658 | this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies( |
91041638 | 659 | this.getWorkerChoiceStrategies(), |
85bbc7ab JB |
660 | this.opts.workerChoiceStrategyOptions |
661 | ) | |
19b8be8b | 662 | for (const workerNodeKey of this.workerNodes.keys()) { |
85bbc7ab JB |
663 | this.sendStatisticsMessageToWorker(workerNodeKey) |
664 | } | |
59219cbb | 665 | } |
a20f0ba5 JB |
666 | } |
667 | ||
668 | /** @inheritDoc */ | |
669 | public setWorkerChoiceStrategyOptions ( | |
c63a35a0 | 670 | workerChoiceStrategyOptions: WorkerChoiceStrategyOptions | undefined |
19b8be8b | 671 | ): boolean { |
0d80593b | 672 | this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions) |
26ce26ca JB |
673 | if (workerChoiceStrategyOptions != null) { |
674 | this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions | |
19b8be8b JB |
675 | this.workerChoiceStrategiesContext?.setOptions( |
676 | this.opts.workerChoiceStrategyOptions | |
677 | ) | |
678 | this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies( | |
91041638 | 679 | this.getWorkerChoiceStrategies(), |
19b8be8b JB |
680 | this.opts.workerChoiceStrategyOptions |
681 | ) | |
682 | for (const workerNodeKey of this.workerNodes.keys()) { | |
683 | this.sendStatisticsMessageToWorker(workerNodeKey) | |
684 | } | |
685 | return true | |
8990357d | 686 | } |
19b8be8b | 687 | return false |
a35560ba S |
688 | } |
689 | ||
a20f0ba5 | 690 | /** @inheritDoc */ |
8f52842f JB |
691 | public enableTasksQueue ( |
692 | enable: boolean, | |
693 | tasksQueueOptions?: TasksQueueOptions | |
694 | ): void { | |
a20f0ba5 | 695 | if (this.opts.enableTasksQueue === true && !enable) { |
d6ca1416 JB |
696 | this.unsetTaskStealing() |
697 | this.unsetTasksStealingOnBackPressure() | |
ef41a6e6 | 698 | this.flushTasksQueues() |
a20f0ba5 JB |
699 | } |
700 | this.opts.enableTasksQueue = enable | |
c63a35a0 | 701 | this.setTasksQueueOptions(tasksQueueOptions) |
a20f0ba5 JB |
702 | } |
703 | ||
704 | /** @inheritDoc */ | |
c63a35a0 JB |
705 | public setTasksQueueOptions ( |
706 | tasksQueueOptions: TasksQueueOptions | undefined | |
707 | ): void { | |
a20f0ba5 | 708 | if (this.opts.enableTasksQueue === true) { |
bde6b5d7 | 709 | checkValidTasksQueueOptions(tasksQueueOptions) |
8f52842f JB |
710 | this.opts.tasksQueueOptions = |
711 | this.buildTasksQueueOptions(tasksQueueOptions) | |
67f3f2d6 JB |
712 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
713 | this.setTasksQueueSize(this.opts.tasksQueueOptions.size!) | |
d6ca1416 | 714 | if (this.opts.tasksQueueOptions.taskStealing === true) { |
9f99eb9b | 715 | this.unsetTaskStealing() |
d6ca1416 JB |
716 | this.setTaskStealing() |
717 | } else { | |
718 | this.unsetTaskStealing() | |
719 | } | |
720 | if (this.opts.tasksQueueOptions.tasksStealingOnBackPressure === true) { | |
9f99eb9b | 721 | this.unsetTasksStealingOnBackPressure() |
d6ca1416 JB |
722 | this.setTasksStealingOnBackPressure() |
723 | } else { | |
724 | this.unsetTasksStealingOnBackPressure() | |
725 | } | |
5baee0d7 | 726 | } else if (this.opts.tasksQueueOptions != null) { |
a20f0ba5 JB |
727 | delete this.opts.tasksQueueOptions |
728 | } | |
729 | } | |
730 | ||
9b38ab2d | 731 | private buildTasksQueueOptions ( |
c63a35a0 | 732 | tasksQueueOptions: TasksQueueOptions | undefined |
9b38ab2d JB |
733 | ): TasksQueueOptions { |
734 | return { | |
26ce26ca JB |
735 | ...getDefaultTasksQueueOptions( |
736 | this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers | |
737 | ), | |
9b38ab2d JB |
738 | ...tasksQueueOptions |
739 | } | |
740 | } | |
741 | ||
5b49e864 | 742 | private setTasksQueueSize (size: number): void { |
20c6f652 | 743 | for (const workerNode of this.workerNodes) { |
ff3f866a | 744 | workerNode.tasksQueueBackPressureSize = size |
20c6f652 JB |
745 | } |
746 | } | |
747 | ||
d6ca1416 | 748 | private setTaskStealing (): void { |
19b8be8b | 749 | for (const workerNodeKey of this.workerNodes.keys()) { |
e44639e9 | 750 | this.workerNodes[workerNodeKey].on('idle', this.handleWorkerNodeIdleEvent) |
d6ca1416 JB |
751 | } |
752 | } | |
753 | ||
754 | private unsetTaskStealing (): void { | |
19b8be8b | 755 | for (const workerNodeKey of this.workerNodes.keys()) { |
e1c2dba7 | 756 | this.workerNodes[workerNodeKey].off( |
e44639e9 JB |
757 | 'idle', |
758 | this.handleWorkerNodeIdleEvent | |
9f95d5eb | 759 | ) |
d6ca1416 JB |
760 | } |
761 | } | |
762 | ||
763 | private setTasksStealingOnBackPressure (): void { | |
19b8be8b | 764 | for (const workerNodeKey of this.workerNodes.keys()) { |
e1c2dba7 | 765 | this.workerNodes[workerNodeKey].on( |
b5e75be8 | 766 | 'backPressure', |
e44639e9 | 767 | this.handleWorkerNodeBackPressureEvent |
9f95d5eb | 768 | ) |
d6ca1416 JB |
769 | } |
770 | } | |
771 | ||
772 | private unsetTasksStealingOnBackPressure (): void { | |
19b8be8b | 773 | for (const workerNodeKey of this.workerNodes.keys()) { |
e1c2dba7 | 774 | this.workerNodes[workerNodeKey].off( |
b5e75be8 | 775 | 'backPressure', |
e44639e9 | 776 | this.handleWorkerNodeBackPressureEvent |
9f95d5eb | 777 | ) |
d6ca1416 JB |
778 | } |
779 | } | |
780 | ||
c319c66b JB |
781 | /** |
782 | * Whether the pool is full or not. | |
783 | * | |
784 | * The pool filling boolean status. | |
785 | */ | |
dea903a8 | 786 | protected get full (): boolean { |
26ce26ca JB |
787 | return ( |
788 | this.workerNodes.length >= | |
789 | (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers) | |
790 | ) | |
dea903a8 | 791 | } |
c2ade475 | 792 | |
c319c66b JB |
793 | /** |
794 | * Whether the pool is busy or not. | |
795 | * | |
796 | * The pool busyness boolean status. | |
797 | */ | |
798 | protected abstract get busy (): boolean | |
7c0ba920 | 799 | |
6c6afb84 | 800 | /** |
3d76750a | 801 | * Whether worker nodes are executing concurrently their tasks quota or not. |
6c6afb84 JB |
802 | * |
803 | * @returns Worker nodes busyness boolean status. | |
804 | */ | |
c2ade475 | 805 | protected internalBusy (): boolean { |
3d76750a JB |
806 | if (this.opts.enableTasksQueue === true) { |
807 | return ( | |
808 | this.workerNodes.findIndex( | |
041dc05b | 809 | workerNode => |
3d76750a JB |
810 | workerNode.info.ready && |
811 | workerNode.usage.tasks.executing < | |
67f3f2d6 JB |
812 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
813 | this.opts.tasksQueueOptions!.concurrency! | |
3d76750a JB |
814 | ) === -1 |
815 | ) | |
3d76750a | 816 | } |
419e8121 JB |
817 | return ( |
818 | this.workerNodes.findIndex( | |
819 | workerNode => | |
820 | workerNode.info.ready && workerNode.usage.tasks.executing === 0 | |
821 | ) === -1 | |
822 | ) | |
cb70b19d JB |
823 | } |
824 | ||
42c677c1 JB |
825 | private isWorkerNodeBusy (workerNodeKey: number): boolean { |
826 | if (this.opts.enableTasksQueue === true) { | |
827 | return ( | |
828 | this.workerNodes[workerNodeKey].usage.tasks.executing >= | |
67f3f2d6 JB |
829 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
830 | this.opts.tasksQueueOptions!.concurrency! | |
42c677c1 JB |
831 | ) |
832 | } | |
833 | return this.workerNodes[workerNodeKey].usage.tasks.executing > 0 | |
834 | } | |
835 | ||
e81c38f2 | 836 | private async sendTaskFunctionOperationToWorker ( |
72ae84a2 JB |
837 | workerNodeKey: number, |
838 | message: MessageValue<Data> | |
839 | ): Promise<boolean> { | |
72ae84a2 | 840 | return await new Promise<boolean>((resolve, reject) => { |
ae036c3e JB |
841 | const taskFunctionOperationListener = ( |
842 | message: MessageValue<Response> | |
843 | ): void => { | |
844 | this.checkMessageWorkerId(message) | |
1851fed0 | 845 | const workerId = this.getWorkerInfo(workerNodeKey)?.id |
72ae84a2 | 846 | if ( |
ae036c3e JB |
847 | message.taskFunctionOperationStatus != null && |
848 | message.workerId === workerId | |
72ae84a2 | 849 | ) { |
ae036c3e JB |
850 | if (message.taskFunctionOperationStatus) { |
851 | resolve(true) | |
c63a35a0 | 852 | } else { |
ae036c3e JB |
853 | reject( |
854 | new Error( | |
c63a35a0 | 855 | `Task function operation '${message.taskFunctionOperation}' failed on worker ${message.workerId} with error: '${message.workerError?.message}'` |
ae036c3e | 856 | ) |
72ae84a2 | 857 | ) |
ae036c3e JB |
858 | } |
859 | this.deregisterWorkerMessageListener( | |
860 | this.getWorkerNodeKeyByWorkerId(message.workerId), | |
861 | taskFunctionOperationListener | |
72ae84a2 JB |
862 | ) |
863 | } | |
ae036c3e JB |
864 | } |
865 | this.registerWorkerMessageListener( | |
866 | workerNodeKey, | |
867 | taskFunctionOperationListener | |
868 | ) | |
72ae84a2 JB |
869 | this.sendToWorker(workerNodeKey, message) |
870 | }) | |
871 | } | |
872 | ||
873 | private async sendTaskFunctionOperationToWorkers ( | |
adee6053 | 874 | message: MessageValue<Data> |
e81c38f2 JB |
875 | ): Promise<boolean> { |
876 | return await new Promise<boolean>((resolve, reject) => { | |
ae036c3e JB |
877 | const responsesReceived = new Array<MessageValue<Response>>() |
878 | const taskFunctionOperationsListener = ( | |
879 | message: MessageValue<Response> | |
880 | ): void => { | |
881 | this.checkMessageWorkerId(message) | |
882 | if (message.taskFunctionOperationStatus != null) { | |
883 | responsesReceived.push(message) | |
884 | if (responsesReceived.length === this.workerNodes.length) { | |
e81c38f2 | 885 | if ( |
e81c38f2 JB |
886 | responsesReceived.every( |
887 | message => message.taskFunctionOperationStatus === true | |
888 | ) | |
889 | ) { | |
890 | resolve(true) | |
891 | } else if ( | |
e81c38f2 JB |
892 | responsesReceived.some( |
893 | message => message.taskFunctionOperationStatus === false | |
894 | ) | |
895 | ) { | |
b0b55f57 JB |
896 | const errorResponse = responsesReceived.find( |
897 | response => response.taskFunctionOperationStatus === false | |
898 | ) | |
e81c38f2 JB |
899 | reject( |
900 | new Error( | |
b0b55f57 | 901 | `Task function operation '${ |
e81c38f2 | 902 | message.taskFunctionOperation as string |
c63a35a0 JB |
903 | }' failed on worker ${errorResponse?.workerId} with error: '${ |
904 | errorResponse?.workerError?.message | |
b0b55f57 | 905 | }'` |
e81c38f2 JB |
906 | ) |
907 | ) | |
908 | } | |
ae036c3e JB |
909 | this.deregisterWorkerMessageListener( |
910 | this.getWorkerNodeKeyByWorkerId(message.workerId), | |
911 | taskFunctionOperationsListener | |
912 | ) | |
e81c38f2 | 913 | } |
ae036c3e JB |
914 | } |
915 | } | |
19b8be8b | 916 | for (const workerNodeKey of this.workerNodes.keys()) { |
ae036c3e JB |
917 | this.registerWorkerMessageListener( |
918 | workerNodeKey, | |
919 | taskFunctionOperationsListener | |
920 | ) | |
72ae84a2 | 921 | this.sendToWorker(workerNodeKey, message) |
e81c38f2 JB |
922 | } |
923 | }) | |
6703b9f4 JB |
924 | } |
925 | ||
926 | /** @inheritDoc */ | |
927 | public hasTaskFunction (name: string): boolean { | |
85bbc7ab JB |
928 | return this.listTaskFunctionsProperties().some( |
929 | taskFunctionProperties => taskFunctionProperties.name === name | |
930 | ) | |
6703b9f4 JB |
931 | } |
932 | ||
933 | /** @inheritDoc */ | |
e81c38f2 JB |
934 | public async addTaskFunction ( |
935 | name: string, | |
31847469 | 936 | fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response> |
e81c38f2 | 937 | ): Promise<boolean> { |
3feeab69 JB |
938 | if (typeof name !== 'string') { |
939 | throw new TypeError('name argument must be a string') | |
940 | } | |
941 | if (typeof name === 'string' && name.trim().length === 0) { | |
942 | throw new TypeError('name argument must not be an empty string') | |
943 | } | |
31847469 JB |
944 | if (typeof fn === 'function') { |
945 | fn = { taskFunction: fn } satisfies TaskFunctionObject<Data, Response> | |
946 | } | |
947 | if (typeof fn.taskFunction !== 'function') { | |
948 | throw new TypeError('taskFunction property must be a function') | |
3feeab69 | 949 | } |
95d1a734 JB |
950 | checkValidPriority(fn.priority) |
951 | checkValidWorkerChoiceStrategy(fn.strategy) | |
adee6053 | 952 | const opResult = await this.sendTaskFunctionOperationToWorkers({ |
6703b9f4 | 953 | taskFunctionOperation: 'add', |
31847469 JB |
954 | taskFunctionProperties: buildTaskFunctionProperties(name, fn), |
955 | taskFunction: fn.taskFunction.toString() | |
6703b9f4 | 956 | }) |
adee6053 | 957 | this.taskFunctions.set(name, fn) |
85bbc7ab | 958 | this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies( |
91041638 | 959 | this.getWorkerChoiceStrategies() |
85bbc7ab | 960 | ) |
9a55fa8c JB |
961 | for (const workerNodeKey of this.workerNodes.keys()) { |
962 | this.sendStatisticsMessageToWorker(workerNodeKey) | |
963 | } | |
adee6053 | 964 | return opResult |
6703b9f4 JB |
965 | } |
966 | ||
967 | /** @inheritDoc */ | |
e81c38f2 | 968 | public async removeTaskFunction (name: string): Promise<boolean> { |
9eae3c69 JB |
969 | if (!this.taskFunctions.has(name)) { |
970 | throw new Error( | |
16248b23 | 971 | 'Cannot remove a task function not handled on the pool side' |
9eae3c69 JB |
972 | ) |
973 | } | |
adee6053 | 974 | const opResult = await this.sendTaskFunctionOperationToWorkers({ |
6703b9f4 | 975 | taskFunctionOperation: 'remove', |
31847469 JB |
976 | taskFunctionProperties: buildTaskFunctionProperties( |
977 | name, | |
978 | this.taskFunctions.get(name) | |
979 | ) | |
6703b9f4 | 980 | }) |
9a55fa8c JB |
981 | for (const workerNode of this.workerNodes) { |
982 | workerNode.deleteTaskFunctionWorkerUsage(name) | |
983 | } | |
adee6053 | 984 | this.taskFunctions.delete(name) |
85bbc7ab | 985 | this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies( |
91041638 | 986 | this.getWorkerChoiceStrategies() |
85bbc7ab | 987 | ) |
9a55fa8c JB |
988 | for (const workerNodeKey of this.workerNodes.keys()) { |
989 | this.sendStatisticsMessageToWorker(workerNodeKey) | |
990 | } | |
adee6053 | 991 | return opResult |
6703b9f4 JB |
992 | } |
993 | ||
90d7d101 | 994 | /** @inheritDoc */ |
31847469 | 995 | public listTaskFunctionsProperties (): TaskFunctionProperties[] { |
f2dbbf95 JB |
996 | for (const workerNode of this.workerNodes) { |
997 | if ( | |
31847469 JB |
998 | Array.isArray(workerNode.info.taskFunctionsProperties) && |
999 | workerNode.info.taskFunctionsProperties.length > 0 | |
f2dbbf95 | 1000 | ) { |
31847469 | 1001 | return workerNode.info.taskFunctionsProperties |
f2dbbf95 | 1002 | } |
90d7d101 | 1003 | } |
f2dbbf95 | 1004 | return [] |
90d7d101 JB |
1005 | } |
1006 | ||
bcfb06ce | 1007 | /** |
91041638 | 1008 | * Gets task function worker choice strategy, if any. |
bcfb06ce JB |
1009 | * |
1010 | * @param name - The task function name. | |
1011 | * @returns The task function worker choice strategy if the task function worker choice strategy is defined, `undefined` otherwise. | |
1012 | */ | |
91041638 | 1013 | private readonly getTaskFunctionWorkerChoiceStrategy = ( |
bcfb06ce JB |
1014 | name?: string |
1015 | ): WorkerChoiceStrategy | undefined => { | |
91041638 JB |
1016 | name = name ?? DEFAULT_TASK_NAME |
1017 | const taskFunctionsProperties = this.listTaskFunctionsProperties() | |
1018 | if (name === DEFAULT_TASK_NAME) { | |
1019 | name = taskFunctionsProperties[1]?.name | |
bcfb06ce | 1020 | } |
91041638 JB |
1021 | return taskFunctionsProperties.find( |
1022 | (taskFunctionProperties: TaskFunctionProperties) => | |
1023 | taskFunctionProperties.name === name | |
1024 | )?.strategy | |
1025 | } | |
1026 | ||
1027 | /** | |
1028 | * Gets worker node task function worker choice strategy, if any. | |
1029 | * | |
1030 | * @param workerNodeKey - The worker node key. | |
1031 | * @param name - The task function name. | |
1032 | * @returns The worker node task function worker choice strategy if the worker node task function worker choice strategy is defined, `undefined` otherwise. | |
1033 | */ | |
1034 | private readonly getWorkerNodeTaskFunctionWorkerChoiceStrategy = ( | |
1035 | workerNodeKey: number, | |
1036 | name?: string | |
1037 | ): WorkerChoiceStrategy | undefined => { | |
1038 | const workerInfo = this.getWorkerInfo(workerNodeKey) | |
1039 | if (workerInfo == null) { | |
1040 | return | |
1041 | } | |
1042 | name = name ?? DEFAULT_TASK_NAME | |
1043 | if (name === DEFAULT_TASK_NAME) { | |
1044 | name = workerInfo.taskFunctionsProperties?.[1]?.name | |
1045 | } | |
1046 | return workerInfo.taskFunctionsProperties?.find( | |
1047 | (taskFunctionProperties: TaskFunctionProperties) => | |
1048 | taskFunctionProperties.name === name | |
1049 | )?.strategy | |
bcfb06ce JB |
1050 | } |
1051 | ||
95d1a734 JB |
1052 | /** |
1053 | * Gets worker node task function priority, if any. | |
1054 | * | |
1055 | * @param workerNodeKey - The worker node key. | |
1056 | * @param name - The task function name. | |
a20062fa | 1057 | * @returns The worker node task function priority if the worker node task function priority is defined, `undefined` otherwise. |
95d1a734 JB |
1058 | */ |
1059 | private readonly getWorkerNodeTaskFunctionPriority = ( | |
1060 | workerNodeKey: number, | |
1061 | name?: string | |
1062 | ): number | undefined => { | |
91041638 JB |
1063 | const workerInfo = this.getWorkerInfo(workerNodeKey) |
1064 | if (workerInfo == null) { | |
1065 | return | |
95d1a734 | 1066 | } |
91041638 JB |
1067 | name = name ?? DEFAULT_TASK_NAME |
1068 | if (name === DEFAULT_TASK_NAME) { | |
1069 | name = workerInfo.taskFunctionsProperties?.[1]?.name | |
1070 | } | |
1071 | return workerInfo.taskFunctionsProperties?.find( | |
1072 | (taskFunctionProperties: TaskFunctionProperties) => | |
1073 | taskFunctionProperties.name === name | |
1074 | )?.priority | |
95d1a734 JB |
1075 | } |
1076 | ||
85bbc7ab JB |
1077 | /** |
1078 | * Gets the worker choice strategies registered in this pool. | |
1079 | * | |
1080 | * @returns The worker choice strategies. | |
1081 | */ | |
91041638 | 1082 | private readonly getWorkerChoiceStrategies = |
85bbc7ab JB |
1083 | (): Set<WorkerChoiceStrategy> => { |
1084 | return new Set([ | |
1085 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
1086 | this.opts.workerChoiceStrategy!, | |
1087 | ...(this.listTaskFunctionsProperties() | |
1088 | .map( | |
1089 | (taskFunctionProperties: TaskFunctionProperties) => | |
1090 | taskFunctionProperties.strategy | |
1091 | ) | |
1092 | .filter( | |
1093 | (strategy: WorkerChoiceStrategy | undefined) => strategy != null | |
1094 | ) as WorkerChoiceStrategy[]) | |
1095 | ]) | |
1096 | } | |
1097 | ||
6703b9f4 | 1098 | /** @inheritDoc */ |
e81c38f2 | 1099 | public async setDefaultTaskFunction (name: string): Promise<boolean> { |
72ae84a2 | 1100 | return await this.sendTaskFunctionOperationToWorkers({ |
6703b9f4 | 1101 | taskFunctionOperation: 'default', |
31847469 JB |
1102 | taskFunctionProperties: buildTaskFunctionProperties( |
1103 | name, | |
1104 | this.taskFunctions.get(name) | |
1105 | ) | |
6703b9f4 | 1106 | }) |
6703b9f4 JB |
1107 | } |
1108 | ||
375f7504 JB |
1109 | private shallExecuteTask (workerNodeKey: number): boolean { |
1110 | return ( | |
1111 | this.tasksQueueSize(workerNodeKey) === 0 && | |
1112 | this.workerNodes[workerNodeKey].usage.tasks.executing < | |
67f3f2d6 JB |
1113 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1114 | this.opts.tasksQueueOptions!.concurrency! | |
375f7504 JB |
1115 | ) |
1116 | } | |
1117 | ||
afc003b2 | 1118 | /** @inheritDoc */ |
7d91a8cd JB |
1119 | public async execute ( |
1120 | data?: Data, | |
1121 | name?: string, | |
6a3ecc50 | 1122 | transferList?: readonly TransferListItem[] |
7d91a8cd | 1123 | ): Promise<Response> { |
52b71763 | 1124 | return await new Promise<Response>((resolve, reject) => { |
15b176e0 | 1125 | if (!this.started) { |
47352846 | 1126 | reject(new Error('Cannot execute a task on not started pool')) |
9d2d0da1 | 1127 | return |
15b176e0 | 1128 | } |
711623b8 JB |
1129 | if (this.destroying) { |
1130 | reject(new Error('Cannot execute a task on destroying pool')) | |
1131 | return | |
1132 | } | |
7d91a8cd JB |
1133 | if (name != null && typeof name !== 'string') { |
1134 | reject(new TypeError('name argument must be a string')) | |
9d2d0da1 | 1135 | return |
7d91a8cd | 1136 | } |
90d7d101 JB |
1137 | if ( |
1138 | name != null && | |
1139 | typeof name === 'string' && | |
1140 | name.trim().length === 0 | |
1141 | ) { | |
f58b60b9 | 1142 | reject(new TypeError('name argument must not be an empty string')) |
9d2d0da1 | 1143 | return |
90d7d101 | 1144 | } |
b558f6b5 JB |
1145 | if (transferList != null && !Array.isArray(transferList)) { |
1146 | reject(new TypeError('transferList argument must be an array')) | |
9d2d0da1 | 1147 | return |
b558f6b5 JB |
1148 | } |
1149 | const timestamp = performance.now() | |
91041638 | 1150 | const workerNodeKey = this.chooseWorkerNode(name) |
501aea93 | 1151 | const task: Task<Data> = { |
52b71763 JB |
1152 | name: name ?? DEFAULT_TASK_NAME, |
1153 | // eslint-disable-next-line @typescript-eslint/consistent-type-assertions | |
1154 | data: data ?? ({} as Data), | |
95d1a734 | 1155 | priority: this.getWorkerNodeTaskFunctionPriority(workerNodeKey, name), |
91041638 JB |
1156 | strategy: this.getWorkerNodeTaskFunctionWorkerChoiceStrategy( |
1157 | workerNodeKey, | |
1158 | name | |
1159 | ), | |
7d91a8cd | 1160 | transferList, |
52b71763 | 1161 | timestamp, |
7629bdf1 | 1162 | taskId: randomUUID() |
52b71763 | 1163 | } |
67f3f2d6 JB |
1164 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1165 | this.promiseResponseMap.set(task.taskId!, { | |
2e81254d JB |
1166 | resolve, |
1167 | reject, | |
f18fd12b JB |
1168 | workerNodeKey, |
1169 | ...(this.emitter != null && { | |
1170 | asyncResource: new AsyncResource('poolifier:task', { | |
1171 | triggerAsyncId: this.emitter.asyncId, | |
1172 | requireManualDestroy: true | |
1173 | }) | |
1174 | }) | |
2e81254d | 1175 | }) |
52b71763 | 1176 | if ( |
4e377863 JB |
1177 | this.opts.enableTasksQueue === false || |
1178 | (this.opts.enableTasksQueue === true && | |
375f7504 | 1179 | this.shallExecuteTask(workerNodeKey)) |
52b71763 | 1180 | ) { |
501aea93 | 1181 | this.executeTask(workerNodeKey, task) |
4e377863 JB |
1182 | } else { |
1183 | this.enqueueTask(workerNodeKey, task) | |
52b71763 | 1184 | } |
2e81254d | 1185 | }) |
280c2a77 | 1186 | } |
c97c7edb | 1187 | |
60dc0a9c JB |
1188 | /** |
1189 | * Starts the minimum number of workers. | |
1190 | */ | |
e0843544 | 1191 | private startMinimumNumberOfWorkers (initWorkerNodeUsage = false): void { |
b362a929 | 1192 | this.startingMinimumNumberOfWorkers = true |
60dc0a9c JB |
1193 | while ( |
1194 | this.workerNodes.reduce( | |
1195 | (accumulator, workerNode) => | |
1196 | !workerNode.info.dynamic ? accumulator + 1 : accumulator, | |
1197 | 0 | |
1198 | ) < this.minimumNumberOfWorkers | |
1199 | ) { | |
e0843544 JB |
1200 | const workerNodeKey = this.createAndSetupWorkerNode() |
1201 | initWorkerNodeUsage && | |
1202 | this.initWorkerNodeUsage(this.workerNodes[workerNodeKey]) | |
60dc0a9c | 1203 | } |
b362a929 | 1204 | this.startingMinimumNumberOfWorkers = false |
60dc0a9c JB |
1205 | } |
1206 | ||
47352846 JB |
1207 | /** @inheritdoc */ |
1208 | public start (): void { | |
711623b8 JB |
1209 | if (this.started) { |
1210 | throw new Error('Cannot start an already started pool') | |
1211 | } | |
1212 | if (this.starting) { | |
1213 | throw new Error('Cannot start an already starting pool') | |
1214 | } | |
1215 | if (this.destroying) { | |
1216 | throw new Error('Cannot start a destroying pool') | |
1217 | } | |
47352846 | 1218 | this.starting = true |
60dc0a9c | 1219 | this.startMinimumNumberOfWorkers() |
2008bccd | 1220 | this.startTimestamp = performance.now() |
47352846 JB |
1221 | this.starting = false |
1222 | this.started = true | |
1223 | } | |
1224 | ||
afc003b2 | 1225 | /** @inheritDoc */ |
c97c7edb | 1226 | public async destroy (): Promise<void> { |
711623b8 JB |
1227 | if (!this.started) { |
1228 | throw new Error('Cannot destroy an already destroyed pool') | |
1229 | } | |
1230 | if (this.starting) { | |
1231 | throw new Error('Cannot destroy an starting pool') | |
1232 | } | |
1233 | if (this.destroying) { | |
1234 | throw new Error('Cannot destroy an already destroying pool') | |
1235 | } | |
1236 | this.destroying = true | |
1fbcaa7c | 1237 | await Promise.all( |
533a8e22 | 1238 | this.workerNodes.map(async (_, workerNodeKey) => { |
aa9eede8 | 1239 | await this.destroyWorkerNode(workerNodeKey) |
1fbcaa7c JB |
1240 | }) |
1241 | ) | |
33e6bb4c | 1242 | this.emitter?.emit(PoolEvents.destroy, this.info) |
f80125ca | 1243 | this.emitter?.emitDestroy() |
55082af9 | 1244 | this.readyEventEmitted = false |
2008bccd | 1245 | delete this.startTimestamp |
711623b8 | 1246 | this.destroying = false |
15b176e0 | 1247 | this.started = false |
c97c7edb S |
1248 | } |
1249 | ||
26ce26ca | 1250 | private async sendKillMessageToWorker (workerNodeKey: number): Promise<void> { |
9edb9717 | 1251 | await new Promise<void>((resolve, reject) => { |
c63a35a0 JB |
1252 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
1253 | if (this.workerNodes[workerNodeKey] == null) { | |
ad3836ed | 1254 | resolve() |
85b2561d JB |
1255 | return |
1256 | } | |
ae036c3e JB |
1257 | const killMessageListener = (message: MessageValue<Response>): void => { |
1258 | this.checkMessageWorkerId(message) | |
1e3214b6 JB |
1259 | if (message.kill === 'success') { |
1260 | resolve() | |
1261 | } else if (message.kill === 'failure') { | |
72ae84a2 JB |
1262 | reject( |
1263 | new Error( | |
c63a35a0 | 1264 | `Kill message handling failed on worker ${message.workerId}` |
72ae84a2 JB |
1265 | ) |
1266 | ) | |
1e3214b6 | 1267 | } |
ae036c3e | 1268 | } |
51d9cfbd | 1269 | // FIXME: should be registered only once |
ae036c3e | 1270 | this.registerWorkerMessageListener(workerNodeKey, killMessageListener) |
72ae84a2 | 1271 | this.sendToWorker(workerNodeKey, { kill: true }) |
1e3214b6 | 1272 | }) |
1e3214b6 JB |
1273 | } |
1274 | ||
4a6952ff | 1275 | /** |
aa9eede8 | 1276 | * Terminates the worker node given its worker node key. |
4a6952ff | 1277 | * |
aa9eede8 | 1278 | * @param workerNodeKey - The worker node key. |
4a6952ff | 1279 | */ |
07e0c9e5 JB |
1280 | protected async destroyWorkerNode (workerNodeKey: number): Promise<void> { |
1281 | this.flagWorkerNodeAsNotReady(workerNodeKey) | |
87347ea8 | 1282 | const flushedTasks = this.flushTasksQueue(workerNodeKey) |
07e0c9e5 | 1283 | const workerNode = this.workerNodes[workerNodeKey] |
32b141fd JB |
1284 | await waitWorkerNodeEvents( |
1285 | workerNode, | |
1286 | 'taskFinished', | |
1287 | flushedTasks, | |
1288 | this.opts.tasksQueueOptions?.tasksFinishedTimeout ?? | |
26ce26ca JB |
1289 | getDefaultTasksQueueOptions( |
1290 | this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers | |
1291 | ).tasksFinishedTimeout | |
32b141fd | 1292 | ) |
07e0c9e5 JB |
1293 | await this.sendKillMessageToWorker(workerNodeKey) |
1294 | await workerNode.terminate() | |
1295 | } | |
c97c7edb | 1296 | |
729c563d | 1297 | /** |
6677a3d3 JB |
1298 | * Setup hook to execute code before worker nodes are created in the abstract constructor. |
1299 | * Can be overridden. | |
afc003b2 JB |
1300 | * |
1301 | * @virtual | |
729c563d | 1302 | */ |
280c2a77 | 1303 | protected setupHook (): void { |
965df41c | 1304 | /* Intentionally empty */ |
280c2a77 | 1305 | } |
c97c7edb | 1306 | |
729c563d | 1307 | /** |
5bec72fd JB |
1308 | * Returns whether the worker is the main worker or not. |
1309 | * | |
1310 | * @returns `true` if the worker is the main worker, `false` otherwise. | |
280c2a77 S |
1311 | */ |
1312 | protected abstract isMain (): boolean | |
1313 | ||
1314 | /** | |
2e81254d | 1315 | * Hook executed before the worker task execution. |
bf9549ae | 1316 | * Can be overridden. |
729c563d | 1317 | * |
f06e48d8 | 1318 | * @param workerNodeKey - The worker node key. |
1c6fe997 | 1319 | * @param task - The task to execute. |
729c563d | 1320 | */ |
1c6fe997 JB |
1321 | protected beforeTaskExecutionHook ( |
1322 | workerNodeKey: number, | |
1323 | task: Task<Data> | |
1324 | ): void { | |
c63a35a0 | 1325 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
efabc98d | 1326 | if (this.workerNodes[workerNodeKey]?.usage != null) { |
94407def JB |
1327 | const workerUsage = this.workerNodes[workerNodeKey].usage |
1328 | ++workerUsage.tasks.executing | |
c329fd41 | 1329 | updateWaitTimeWorkerUsage( |
bcfb06ce | 1330 | this.workerChoiceStrategiesContext, |
c329fd41 JB |
1331 | workerUsage, |
1332 | task | |
1333 | ) | |
94407def JB |
1334 | } |
1335 | if ( | |
1336 | this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) && | |
67f3f2d6 JB |
1337 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1338 | this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(task.name!) != | |
1339 | null | |
94407def | 1340 | ) { |
67f3f2d6 | 1341 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
db0e38ee | 1342 | const taskFunctionWorkerUsage = this.workerNodes[ |
b558f6b5 | 1343 | workerNodeKey |
67f3f2d6 JB |
1344 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1345 | ].getTaskFunctionWorkerUsage(task.name!)! | |
5623b8d5 | 1346 | ++taskFunctionWorkerUsage.tasks.executing |
c329fd41 | 1347 | updateWaitTimeWorkerUsage( |
bcfb06ce | 1348 | this.workerChoiceStrategiesContext, |
c329fd41 JB |
1349 | taskFunctionWorkerUsage, |
1350 | task | |
1351 | ) | |
b558f6b5 | 1352 | } |
c97c7edb S |
1353 | } |
1354 | ||
c01733f1 | 1355 | /** |
2e81254d | 1356 | * Hook executed after the worker task execution. |
bf9549ae | 1357 | * Can be overridden. |
c01733f1 | 1358 | * |
501aea93 | 1359 | * @param workerNodeKey - The worker node key. |
38e795c1 | 1360 | * @param message - The received message. |
c01733f1 | 1361 | */ |
2e81254d | 1362 | protected afterTaskExecutionHook ( |
501aea93 | 1363 | workerNodeKey: number, |
2740a743 | 1364 | message: MessageValue<Response> |
bf9549ae | 1365 | ): void { |
9a55fa8c | 1366 | let needWorkerChoiceStrategiesUpdate = false |
c63a35a0 | 1367 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
efabc98d | 1368 | if (this.workerNodes[workerNodeKey]?.usage != null) { |
94407def | 1369 | const workerUsage = this.workerNodes[workerNodeKey].usage |
c329fd41 JB |
1370 | updateTaskStatisticsWorkerUsage(workerUsage, message) |
1371 | updateRunTimeWorkerUsage( | |
bcfb06ce | 1372 | this.workerChoiceStrategiesContext, |
c329fd41 JB |
1373 | workerUsage, |
1374 | message | |
1375 | ) | |
1376 | updateEluWorkerUsage( | |
bcfb06ce | 1377 | this.workerChoiceStrategiesContext, |
c329fd41 JB |
1378 | workerUsage, |
1379 | message | |
1380 | ) | |
9a55fa8c | 1381 | needWorkerChoiceStrategiesUpdate = true |
94407def JB |
1382 | } |
1383 | if ( | |
1384 | this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) && | |
1385 | this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage( | |
67f3f2d6 JB |
1386 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1387 | message.taskPerformance!.name | |
94407def JB |
1388 | ) != null |
1389 | ) { | |
67f3f2d6 | 1390 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
db0e38ee | 1391 | const taskFunctionWorkerUsage = this.workerNodes[ |
b558f6b5 | 1392 | workerNodeKey |
67f3f2d6 JB |
1393 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1394 | ].getTaskFunctionWorkerUsage(message.taskPerformance!.name)! | |
c329fd41 JB |
1395 | updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage, message) |
1396 | updateRunTimeWorkerUsage( | |
bcfb06ce | 1397 | this.workerChoiceStrategiesContext, |
c329fd41 JB |
1398 | taskFunctionWorkerUsage, |
1399 | message | |
1400 | ) | |
1401 | updateEluWorkerUsage( | |
bcfb06ce | 1402 | this.workerChoiceStrategiesContext, |
c329fd41 JB |
1403 | taskFunctionWorkerUsage, |
1404 | message | |
1405 | ) | |
9a55fa8c | 1406 | needWorkerChoiceStrategiesUpdate = true |
c329fd41 | 1407 | } |
9a55fa8c | 1408 | if (needWorkerChoiceStrategiesUpdate) { |
bcfb06ce | 1409 | this.workerChoiceStrategiesContext?.update(workerNodeKey) |
b558f6b5 JB |
1410 | } |
1411 | } | |
1412 | ||
db0e38ee JB |
1413 | /** |
1414 | * Whether the worker node shall update its task function worker usage or not. | |
1415 | * | |
1416 | * @param workerNodeKey - The worker node key. | |
1417 | * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise. | |
1418 | */ | |
1419 | private shallUpdateTaskFunctionWorkerUsage (workerNodeKey: number): boolean { | |
a5d15204 | 1420 | const workerInfo = this.getWorkerInfo(workerNodeKey) |
b558f6b5 | 1421 | return ( |
1851fed0 | 1422 | workerInfo != null && |
31847469 JB |
1423 | Array.isArray(workerInfo.taskFunctionsProperties) && |
1424 | workerInfo.taskFunctionsProperties.length > 2 | |
b558f6b5 | 1425 | ) |
f1c06930 JB |
1426 | } |
1427 | ||
280c2a77 | 1428 | /** |
91041638 | 1429 | * Chooses a worker node for the next task. |
280c2a77 | 1430 | * |
91041638 | 1431 | * @param name - The task function name. |
aa9eede8 | 1432 | * @returns The chosen worker node key |
280c2a77 | 1433 | */ |
91041638 | 1434 | private chooseWorkerNode (name?: string): number { |
930dcf12 | 1435 | if (this.shallCreateDynamicWorker()) { |
aa9eede8 | 1436 | const workerNodeKey = this.createAndSetupDynamicWorkerNode() |
6c6afb84 | 1437 | if ( |
bcfb06ce JB |
1438 | this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerUsage === |
1439 | true | |
6c6afb84 | 1440 | ) { |
aa9eede8 | 1441 | return workerNodeKey |
6c6afb84 | 1442 | } |
17393ac8 | 1443 | } |
c63a35a0 | 1444 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
91041638 JB |
1445 | return this.workerChoiceStrategiesContext!.execute( |
1446 | this.getTaskFunctionWorkerChoiceStrategy(name) | |
1447 | ) | |
930dcf12 JB |
1448 | } |
1449 | ||
6c6afb84 JB |
1450 | /** |
1451 | * Conditions for dynamic worker creation. | |
1452 | * | |
1453 | * @returns Whether to create a dynamic worker or not. | |
1454 | */ | |
9d9fb7b6 | 1455 | protected abstract shallCreateDynamicWorker (): boolean |
c97c7edb | 1456 | |
280c2a77 | 1457 | /** |
aa9eede8 | 1458 | * Sends a message to worker given its worker node key. |
280c2a77 | 1459 | * |
aa9eede8 | 1460 | * @param workerNodeKey - The worker node key. |
38e795c1 | 1461 | * @param message - The message. |
7d91a8cd | 1462 | * @param transferList - The optional array of transferable objects. |
280c2a77 S |
1463 | */ |
1464 | protected abstract sendToWorker ( | |
aa9eede8 | 1465 | workerNodeKey: number, |
7d91a8cd | 1466 | message: MessageValue<Data>, |
6a3ecc50 | 1467 | transferList?: readonly TransferListItem[] |
280c2a77 S |
1468 | ): void |
1469 | ||
e0843544 JB |
1470 | /** |
1471 | * Initializes the worker node usage with sensible default values gathered during runtime. | |
1472 | * | |
1473 | * @param workerNode - The worker node. | |
1474 | */ | |
1475 | private initWorkerNodeUsage (workerNode: IWorkerNode<Worker, Data>): void { | |
1476 | if ( | |
1477 | this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements() | |
1478 | .runTime.aggregate === true | |
1479 | ) { | |
1480 | workerNode.usage.runTime.aggregate = min( | |
1481 | ...this.workerNodes.map( | |
1482 | workerNode => workerNode.usage.runTime.aggregate ?? Infinity | |
1483 | ) | |
1484 | ) | |
1485 | } | |
1486 | if ( | |
1487 | this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements() | |
1488 | .waitTime.aggregate === true | |
1489 | ) { | |
1490 | workerNode.usage.waitTime.aggregate = min( | |
1491 | ...this.workerNodes.map( | |
1492 | workerNode => workerNode.usage.waitTime.aggregate ?? Infinity | |
1493 | ) | |
1494 | ) | |
1495 | } | |
1496 | if ( | |
1497 | this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().elu | |
1498 | .aggregate === true | |
1499 | ) { | |
1500 | workerNode.usage.elu.active.aggregate = min( | |
1501 | ...this.workerNodes.map( | |
1502 | workerNode => workerNode.usage.elu.active.aggregate ?? Infinity | |
1503 | ) | |
1504 | ) | |
1505 | } | |
1506 | } | |
1507 | ||
4a6952ff | 1508 | /** |
aa9eede8 | 1509 | * Creates a new, completely set up worker node. |
4a6952ff | 1510 | * |
aa9eede8 | 1511 | * @returns New, completely set up worker node key. |
4a6952ff | 1512 | */ |
aa9eede8 | 1513 | protected createAndSetupWorkerNode (): number { |
c3719753 JB |
1514 | const workerNode = this.createWorkerNode() |
1515 | workerNode.registerWorkerEventHandler( | |
1516 | 'online', | |
1517 | this.opts.onlineHandler ?? EMPTY_FUNCTION | |
1518 | ) | |
1519 | workerNode.registerWorkerEventHandler( | |
1520 | 'message', | |
1521 | this.opts.messageHandler ?? EMPTY_FUNCTION | |
1522 | ) | |
1523 | workerNode.registerWorkerEventHandler( | |
1524 | 'error', | |
1525 | this.opts.errorHandler ?? EMPTY_FUNCTION | |
1526 | ) | |
b271fce0 | 1527 | workerNode.registerOnceWorkerEventHandler('error', (error: Error) => { |
07e0c9e5 | 1528 | workerNode.info.ready = false |
2a69b8c5 | 1529 | this.emitter?.emit(PoolEvents.error, error) |
15b176e0 | 1530 | if ( |
b6bfca01 | 1531 | this.started && |
711623b8 | 1532 | !this.destroying && |
9b38ab2d | 1533 | this.opts.restartWorkerOnError === true |
15b176e0 | 1534 | ) { |
07e0c9e5 | 1535 | if (workerNode.info.dynamic) { |
aa9eede8 | 1536 | this.createAndSetupDynamicWorkerNode() |
b362a929 | 1537 | } else if (!this.startingMinimumNumberOfWorkers) { |
e0843544 | 1538 | this.startMinimumNumberOfWorkers(true) |
8a1260a3 | 1539 | } |
5baee0d7 | 1540 | } |
3c9123c7 JB |
1541 | if ( |
1542 | this.started && | |
1543 | !this.destroying && | |
1544 | this.opts.enableTasksQueue === true | |
1545 | ) { | |
9974369e | 1546 | this.redistributeQueuedTasks(this.workerNodes.indexOf(workerNode)) |
19dbc45b | 1547 | } |
b4f8aca8 | 1548 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
07f6f7b1 | 1549 | workerNode?.terminate().catch((error: unknown) => { |
07e0c9e5 JB |
1550 | this.emitter?.emit(PoolEvents.error, error) |
1551 | }) | |
5baee0d7 | 1552 | }) |
c3719753 JB |
1553 | workerNode.registerWorkerEventHandler( |
1554 | 'exit', | |
1555 | this.opts.exitHandler ?? EMPTY_FUNCTION | |
1556 | ) | |
1557 | workerNode.registerOnceWorkerEventHandler('exit', () => { | |
9974369e | 1558 | this.removeWorkerNode(workerNode) |
b362a929 JB |
1559 | if ( |
1560 | this.started && | |
1561 | !this.startingMinimumNumberOfWorkers && | |
1562 | !this.destroying | |
1563 | ) { | |
e0843544 | 1564 | this.startMinimumNumberOfWorkers(true) |
60dc0a9c | 1565 | } |
a974afa6 | 1566 | }) |
c3719753 | 1567 | const workerNodeKey = this.addWorkerNode(workerNode) |
aa9eede8 | 1568 | this.afterWorkerNodeSetup(workerNodeKey) |
aa9eede8 | 1569 | return workerNodeKey |
c97c7edb | 1570 | } |
be0676b3 | 1571 | |
930dcf12 | 1572 | /** |
aa9eede8 | 1573 | * Creates a new, completely set up dynamic worker node. |
930dcf12 | 1574 | * |
aa9eede8 | 1575 | * @returns New, completely set up dynamic worker node key. |
930dcf12 | 1576 | */ |
aa9eede8 JB |
1577 | protected createAndSetupDynamicWorkerNode (): number { |
1578 | const workerNodeKey = this.createAndSetupWorkerNode() | |
041dc05b | 1579 | this.registerWorkerMessageListener(workerNodeKey, message => { |
4d159167 | 1580 | this.checkMessageWorkerId(message) |
aa9eede8 JB |
1581 | const localWorkerNodeKey = this.getWorkerNodeKeyByWorkerId( |
1582 | message.workerId | |
aad6fb64 | 1583 | ) |
2b6b412f | 1584 | const workerUsage = this.workerNodes[localWorkerNodeKey]?.usage |
81c02522 | 1585 | // Kill message received from worker |
930dcf12 JB |
1586 | if ( |
1587 | isKillBehavior(KillBehaviors.HARD, message.kill) || | |
1e3214b6 | 1588 | (isKillBehavior(KillBehaviors.SOFT, message.kill) && |
7b56f532 | 1589 | ((this.opts.enableTasksQueue === false && |
aa9eede8 | 1590 | workerUsage.tasks.executing === 0) || |
7b56f532 | 1591 | (this.opts.enableTasksQueue === true && |
aa9eede8 JB |
1592 | workerUsage.tasks.executing === 0 && |
1593 | this.tasksQueueSize(localWorkerNodeKey) === 0))) | |
930dcf12 | 1594 | ) { |
f3827d5d | 1595 | // Flag the worker node as not ready immediately |
ae3ab61d | 1596 | this.flagWorkerNodeAsNotReady(localWorkerNodeKey) |
07f6f7b1 | 1597 | this.destroyWorkerNode(localWorkerNodeKey).catch((error: unknown) => { |
5270d253 JB |
1598 | this.emitter?.emit(PoolEvents.error, error) |
1599 | }) | |
930dcf12 JB |
1600 | } |
1601 | }) | |
aa9eede8 | 1602 | this.sendToWorker(workerNodeKey, { |
e9dd5b66 | 1603 | checkActive: true |
21f710aa | 1604 | }) |
72ae84a2 | 1605 | if (this.taskFunctions.size > 0) { |
31847469 | 1606 | for (const [taskFunctionName, taskFunctionObject] of this.taskFunctions) { |
72ae84a2 JB |
1607 | this.sendTaskFunctionOperationToWorker(workerNodeKey, { |
1608 | taskFunctionOperation: 'add', | |
31847469 JB |
1609 | taskFunctionProperties: buildTaskFunctionProperties( |
1610 | taskFunctionName, | |
1611 | taskFunctionObject | |
1612 | ), | |
1613 | taskFunction: taskFunctionObject.taskFunction.toString() | |
07f6f7b1 | 1614 | }).catch((error: unknown) => { |
72ae84a2 JB |
1615 | this.emitter?.emit(PoolEvents.error, error) |
1616 | }) | |
1617 | } | |
1618 | } | |
e44639e9 JB |
1619 | const workerNode = this.workerNodes[workerNodeKey] |
1620 | workerNode.info.dynamic = true | |
b1aae695 | 1621 | if ( |
bcfb06ce JB |
1622 | this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerReady === |
1623 | true || | |
1624 | this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerUsage === | |
1625 | true | |
b1aae695 | 1626 | ) { |
e44639e9 | 1627 | workerNode.info.ready = true |
b5e113f6 | 1628 | } |
e0843544 | 1629 | this.initWorkerNodeUsage(workerNode) |
33e6bb4c | 1630 | this.checkAndEmitDynamicWorkerCreationEvents() |
aa9eede8 | 1631 | return workerNodeKey |
930dcf12 JB |
1632 | } |
1633 | ||
a2ed5053 | 1634 | /** |
aa9eede8 | 1635 | * Registers a listener callback on the worker given its worker node key. |
a2ed5053 | 1636 | * |
aa9eede8 | 1637 | * @param workerNodeKey - The worker node key. |
a2ed5053 JB |
1638 | * @param listener - The message listener callback. |
1639 | */ | |
85aeb3f3 JB |
1640 | protected abstract registerWorkerMessageListener< |
1641 | Message extends Data | Response | |
aa9eede8 JB |
1642 | >( |
1643 | workerNodeKey: number, | |
1644 | listener: (message: MessageValue<Message>) => void | |
1645 | ): void | |
a2ed5053 | 1646 | |
ae036c3e JB |
1647 | /** |
1648 | * Registers once a listener callback on the worker given its worker node key. | |
1649 | * | |
1650 | * @param workerNodeKey - The worker node key. | |
1651 | * @param listener - The message listener callback. | |
1652 | */ | |
1653 | protected abstract registerOnceWorkerMessageListener< | |
1654 | Message extends Data | Response | |
1655 | >( | |
1656 | workerNodeKey: number, | |
1657 | listener: (message: MessageValue<Message>) => void | |
1658 | ): void | |
1659 | ||
1660 | /** | |
1661 | * Deregisters a listener callback on the worker given its worker node key. | |
1662 | * | |
1663 | * @param workerNodeKey - The worker node key. | |
1664 | * @param listener - The message listener callback. | |
1665 | */ | |
1666 | protected abstract deregisterWorkerMessageListener< | |
1667 | Message extends Data | Response | |
1668 | >( | |
1669 | workerNodeKey: number, | |
1670 | listener: (message: MessageValue<Message>) => void | |
1671 | ): void | |
1672 | ||
a2ed5053 | 1673 | /** |
aa9eede8 | 1674 | * Method hooked up after a worker node has been newly created. |
a2ed5053 JB |
1675 | * Can be overridden. |
1676 | * | |
aa9eede8 | 1677 | * @param workerNodeKey - The newly created worker node key. |
a2ed5053 | 1678 | */ |
aa9eede8 | 1679 | protected afterWorkerNodeSetup (workerNodeKey: number): void { |
a2ed5053 | 1680 | // Listen to worker messages. |
fcd39179 JB |
1681 | this.registerWorkerMessageListener( |
1682 | workerNodeKey, | |
3a776b6d | 1683 | this.workerMessageListener |
fcd39179 | 1684 | ) |
85aeb3f3 | 1685 | // Send the startup message to worker. |
aa9eede8 | 1686 | this.sendStartupMessageToWorker(workerNodeKey) |
9edb9717 JB |
1687 | // Send the statistics message to worker. |
1688 | this.sendStatisticsMessageToWorker(workerNodeKey) | |
72695f86 | 1689 | if (this.opts.enableTasksQueue === true) { |
dbd73092 | 1690 | if (this.opts.tasksQueueOptions?.taskStealing === true) { |
e1c2dba7 | 1691 | this.workerNodes[workerNodeKey].on( |
e44639e9 JB |
1692 | 'idle', |
1693 | this.handleWorkerNodeIdleEvent | |
9f95d5eb | 1694 | ) |
47352846 JB |
1695 | } |
1696 | if (this.opts.tasksQueueOptions?.tasksStealingOnBackPressure === true) { | |
e1c2dba7 | 1697 | this.workerNodes[workerNodeKey].on( |
b5e75be8 | 1698 | 'backPressure', |
e44639e9 | 1699 | this.handleWorkerNodeBackPressureEvent |
9f95d5eb | 1700 | ) |
47352846 | 1701 | } |
72695f86 | 1702 | } |
d2c73f82 JB |
1703 | } |
1704 | ||
85aeb3f3 | 1705 | /** |
aa9eede8 JB |
1706 | * Sends the startup message to worker given its worker node key. |
1707 | * | |
1708 | * @param workerNodeKey - The worker node key. | |
1709 | */ | |
1710 | protected abstract sendStartupMessageToWorker (workerNodeKey: number): void | |
1711 | ||
1712 | /** | |
9edb9717 | 1713 | * Sends the statistics message to worker given its worker node key. |
85aeb3f3 | 1714 | * |
aa9eede8 | 1715 | * @param workerNodeKey - The worker node key. |
85aeb3f3 | 1716 | */ |
9edb9717 | 1717 | private sendStatisticsMessageToWorker (workerNodeKey: number): void { |
aa9eede8 JB |
1718 | this.sendToWorker(workerNodeKey, { |
1719 | statistics: { | |
1720 | runTime: | |
bcfb06ce | 1721 | this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements() |
f4d0a470 | 1722 | .runTime.aggregate ?? false, |
c63a35a0 | 1723 | elu: |
bcfb06ce JB |
1724 | this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements() |
1725 | .elu.aggregate ?? false | |
72ae84a2 | 1726 | } |
aa9eede8 JB |
1727 | }) |
1728 | } | |
a2ed5053 | 1729 | |
5eb72b9e JB |
1730 | private cannotStealTask (): boolean { |
1731 | return this.workerNodes.length <= 1 || this.info.queuedTasks === 0 | |
1732 | } | |
1733 | ||
42c677c1 JB |
1734 | private handleTask (workerNodeKey: number, task: Task<Data>): void { |
1735 | if (this.shallExecuteTask(workerNodeKey)) { | |
1736 | this.executeTask(workerNodeKey, task) | |
1737 | } else { | |
1738 | this.enqueueTask(workerNodeKey, task) | |
1739 | } | |
1740 | } | |
1741 | ||
2d1d3b2d JB |
1742 | private redistributeQueuedTasks (sourceWorkerNodeKey: number): void { |
1743 | if (sourceWorkerNodeKey === -1 || this.cannotStealTask()) { | |
cb71d660 JB |
1744 | return |
1745 | } | |
2d1d3b2d | 1746 | while (this.tasksQueueSize(sourceWorkerNodeKey) > 0) { |
f201a0cd JB |
1747 | const destinationWorkerNodeKey = this.workerNodes.reduce( |
1748 | (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => { | |
2d1d3b2d JB |
1749 | return sourceWorkerNodeKey !== workerNodeKey && |
1750 | workerNode.info.ready && | |
852ed3e4 JB |
1751 | workerNode.usage.tasks.queued < |
1752 | workerNodes[minWorkerNodeKey].usage.tasks.queued | |
f201a0cd JB |
1753 | ? workerNodeKey |
1754 | : minWorkerNodeKey | |
1755 | }, | |
1756 | 0 | |
1757 | ) | |
42c677c1 JB |
1758 | this.handleTask( |
1759 | destinationWorkerNodeKey, | |
67f3f2d6 | 1760 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2d1d3b2d | 1761 | this.dequeueTask(sourceWorkerNodeKey)! |
42c677c1 | 1762 | ) |
dd951876 JB |
1763 | } |
1764 | } | |
1765 | ||
b1838604 JB |
1766 | private updateTaskStolenStatisticsWorkerUsage ( |
1767 | workerNodeKey: number, | |
b1838604 JB |
1768 | taskName: string |
1769 | ): void { | |
1a880eca | 1770 | const workerNode = this.workerNodes[workerNodeKey] |
c63a35a0 | 1771 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
efabc98d | 1772 | if (workerNode?.usage != null) { |
b1838604 JB |
1773 | ++workerNode.usage.tasks.stolen |
1774 | } | |
1775 | if ( | |
1776 | this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) && | |
1777 | workerNode.getTaskFunctionWorkerUsage(taskName) != null | |
1778 | ) { | |
8bd0556f JB |
1779 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1780 | ++workerNode.getTaskFunctionWorkerUsage(taskName)!.tasks.stolen | |
b1838604 JB |
1781 | } |
1782 | } | |
1783 | ||
463226a4 | 1784 | private updateTaskSequentiallyStolenStatisticsWorkerUsage ( |
2d1d3b2d JB |
1785 | workerNodeKey: number, |
1786 | taskName: string, | |
8bd0556f | 1787 | previousTaskName?: string |
463226a4 JB |
1788 | ): void { |
1789 | const workerNode = this.workerNodes[workerNodeKey] | |
c63a35a0 | 1790 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
7aa2f476 | 1791 | if (workerNode?.usage != null) { |
463226a4 JB |
1792 | ++workerNode.usage.tasks.sequentiallyStolen |
1793 | } | |
1794 | if ( | |
1795 | this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) && | |
3b33cd2a JB |
1796 | workerNode.getTaskFunctionWorkerUsage(taskName) != null |
1797 | ) { | |
1798 | const taskFunctionWorkerUsage = | |
1799 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
1800 | workerNode.getTaskFunctionWorkerUsage(taskName)! | |
1801 | if ( | |
1802 | taskFunctionWorkerUsage.tasks.sequentiallyStolen === 0 || | |
8bd0556f JB |
1803 | (previousTaskName != null && |
1804 | previousTaskName === taskName && | |
3b33cd2a JB |
1805 | taskFunctionWorkerUsage.tasks.sequentiallyStolen > 0) |
1806 | ) { | |
1807 | ++taskFunctionWorkerUsage.tasks.sequentiallyStolen | |
1808 | } else if (taskFunctionWorkerUsage.tasks.sequentiallyStolen > 0) { | |
1809 | taskFunctionWorkerUsage.tasks.sequentiallyStolen = 0 | |
1810 | } | |
463226a4 JB |
1811 | } |
1812 | } | |
1813 | ||
1814 | private resetTaskSequentiallyStolenStatisticsWorkerUsage ( | |
2d1d3b2d JB |
1815 | workerNodeKey: number, |
1816 | taskName: string | |
463226a4 JB |
1817 | ): void { |
1818 | const workerNode = this.workerNodes[workerNodeKey] | |
c63a35a0 | 1819 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
efabc98d | 1820 | if (workerNode?.usage != null) { |
463226a4 JB |
1821 | workerNode.usage.tasks.sequentiallyStolen = 0 |
1822 | } | |
1823 | if ( | |
1824 | this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) && | |
1825 | workerNode.getTaskFunctionWorkerUsage(taskName) != null | |
1826 | ) { | |
8bd0556f JB |
1827 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1828 | workerNode.getTaskFunctionWorkerUsage( | |
1829 | taskName | |
1830 | )!.tasks.sequentiallyStolen = 0 | |
463226a4 JB |
1831 | } |
1832 | } | |
1833 | ||
e44639e9 | 1834 | private readonly handleWorkerNodeIdleEvent = ( |
e1c2dba7 | 1835 | eventDetail: WorkerNodeEventDetail, |
463226a4 | 1836 | previousStolenTask?: Task<Data> |
9f95d5eb | 1837 | ): void => { |
e1c2dba7 | 1838 | const { workerNodeKey } = eventDetail |
463226a4 JB |
1839 | if (workerNodeKey == null) { |
1840 | throw new Error( | |
c63a35a0 | 1841 | "WorkerNode event detail 'workerNodeKey' property must be defined" |
463226a4 JB |
1842 | ) |
1843 | } | |
c63a35a0 | 1844 | const workerInfo = this.getWorkerInfo(workerNodeKey) |
010f158c JB |
1845 | if (workerInfo == null) { |
1846 | throw new Error( | |
1847 | `Worker node with key '${workerNodeKey}' not found in pool` | |
1848 | ) | |
1849 | } | |
5eb72b9e JB |
1850 | if ( |
1851 | this.cannotStealTask() || | |
c63a35a0 JB |
1852 | (this.info.stealingWorkerNodes ?? 0) > |
1853 | Math.floor(this.workerNodes.length / 2) | |
5eb72b9e | 1854 | ) { |
010f158c | 1855 | if (previousStolenTask != null) { |
c63a35a0 | 1856 | workerInfo.stealing = false |
2d1d3b2d JB |
1857 | this.resetTaskSequentiallyStolenStatisticsWorkerUsage( |
1858 | workerNodeKey, | |
1859 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
1860 | previousStolenTask.name! | |
1861 | ) | |
5eb72b9e JB |
1862 | } |
1863 | return | |
1864 | } | |
463226a4 JB |
1865 | const workerNodeTasksUsage = this.workerNodes[workerNodeKey].usage.tasks |
1866 | if ( | |
1867 | previousStolenTask != null && | |
463226a4 JB |
1868 | (workerNodeTasksUsage.executing > 0 || |
1869 | this.tasksQueueSize(workerNodeKey) > 0) | |
1870 | ) { | |
c63a35a0 | 1871 | workerInfo.stealing = false |
2d1d3b2d JB |
1872 | this.resetTaskSequentiallyStolenStatisticsWorkerUsage( |
1873 | workerNodeKey, | |
1874 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
1875 | previousStolenTask.name! | |
1876 | ) | |
463226a4 JB |
1877 | return |
1878 | } | |
c63a35a0 | 1879 | workerInfo.stealing = true |
463226a4 | 1880 | const stolenTask = this.workerNodeStealTask(workerNodeKey) |
8bd0556f | 1881 | if (stolenTask != null) { |
2d1d3b2d JB |
1882 | this.updateTaskSequentiallyStolenStatisticsWorkerUsage( |
1883 | workerNodeKey, | |
67f3f2d6 | 1884 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2d1d3b2d | 1885 | stolenTask.name!, |
8bd0556f | 1886 | previousStolenTask?.name |
2d1d3b2d | 1887 | ) |
f1f77f45 | 1888 | } |
463226a4 JB |
1889 | sleep(exponentialDelay(workerNodeTasksUsage.sequentiallyStolen)) |
1890 | .then(() => { | |
e44639e9 | 1891 | this.handleWorkerNodeIdleEvent(eventDetail, stolenTask) |
463226a4 JB |
1892 | return undefined |
1893 | }) | |
07f6f7b1 | 1894 | .catch((error: unknown) => { |
2e8cfbb7 JB |
1895 | this.emitter?.emit(PoolEvents.error, error) |
1896 | }) | |
463226a4 JB |
1897 | } |
1898 | ||
1899 | private readonly workerNodeStealTask = ( | |
1900 | workerNodeKey: number | |
1901 | ): Task<Data> | undefined => { | |
dd951876 | 1902 | const workerNodes = this.workerNodes |
a6b3272b | 1903 | .slice() |
dd951876 JB |
1904 | .sort( |
1905 | (workerNodeA, workerNodeB) => | |
1906 | workerNodeB.usage.tasks.queued - workerNodeA.usage.tasks.queued | |
1907 | ) | |
f201a0cd | 1908 | const sourceWorkerNode = workerNodes.find( |
463226a4 JB |
1909 | (sourceWorkerNode, sourceWorkerNodeKey) => |
1910 | sourceWorkerNode.info.ready && | |
5eb72b9e | 1911 | !sourceWorkerNode.info.stealing && |
463226a4 JB |
1912 | sourceWorkerNodeKey !== workerNodeKey && |
1913 | sourceWorkerNode.usage.tasks.queued > 0 | |
f201a0cd JB |
1914 | ) |
1915 | if (sourceWorkerNode != null) { | |
67f3f2d6 | 1916 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2eee7220 | 1917 | const task = sourceWorkerNode.dequeueLastPrioritizedTask()! |
42c677c1 | 1918 | this.handleTask(workerNodeKey, task) |
67f3f2d6 JB |
1919 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1920 | this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey, task.name!) | |
463226a4 | 1921 | return task |
72695f86 JB |
1922 | } |
1923 | } | |
1924 | ||
e44639e9 | 1925 | private readonly handleWorkerNodeBackPressureEvent = ( |
e1c2dba7 | 1926 | eventDetail: WorkerNodeEventDetail |
9f95d5eb | 1927 | ): void => { |
5eb72b9e JB |
1928 | if ( |
1929 | this.cannotStealTask() || | |
2eee7220 | 1930 | this.hasBackPressure() || |
c63a35a0 JB |
1931 | (this.info.stealingWorkerNodes ?? 0) > |
1932 | Math.floor(this.workerNodes.length / 2) | |
5eb72b9e | 1933 | ) { |
cb71d660 JB |
1934 | return |
1935 | } | |
f778c355 | 1936 | const sizeOffset = 1 |
67f3f2d6 JB |
1937 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1938 | if (this.opts.tasksQueueOptions!.size! <= sizeOffset) { | |
68dbcdc0 JB |
1939 | return |
1940 | } | |
7b2c5627 | 1941 | const { workerId } = eventDetail |
72695f86 | 1942 | const sourceWorkerNode = |
b5e75be8 | 1943 | this.workerNodes[this.getWorkerNodeKeyByWorkerId(workerId)] |
72695f86 | 1944 | const workerNodes = this.workerNodes |
a6b3272b | 1945 | .slice() |
72695f86 JB |
1946 | .sort( |
1947 | (workerNodeA, workerNodeB) => | |
1948 | workerNodeA.usage.tasks.queued - workerNodeB.usage.tasks.queued | |
1949 | ) | |
1950 | for (const [workerNodeKey, workerNode] of workerNodes.entries()) { | |
1951 | if ( | |
0bc68267 | 1952 | sourceWorkerNode.usage.tasks.queued > 0 && |
a6b3272b | 1953 | workerNode.info.ready && |
5eb72b9e | 1954 | !workerNode.info.stealing && |
b5e75be8 | 1955 | workerNode.info.id !== workerId && |
0bc68267 | 1956 | workerNode.usage.tasks.queued < |
67f3f2d6 JB |
1957 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1958 | this.opts.tasksQueueOptions!.size! - sizeOffset | |
72695f86 | 1959 | ) { |
c63a35a0 | 1960 | const workerInfo = this.getWorkerInfo(workerNodeKey) |
1851fed0 JB |
1961 | if (workerInfo == null) { |
1962 | throw new Error( | |
1963 | `Worker node with key '${workerNodeKey}' not found in pool` | |
1964 | ) | |
1965 | } | |
c63a35a0 | 1966 | workerInfo.stealing = true |
67f3f2d6 | 1967 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2eee7220 | 1968 | const task = sourceWorkerNode.dequeueLastPrioritizedTask()! |
42c677c1 | 1969 | this.handleTask(workerNodeKey, task) |
67f3f2d6 JB |
1970 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1971 | this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey, task.name!) | |
c63a35a0 | 1972 | workerInfo.stealing = false |
10ecf8fd | 1973 | } |
a2ed5053 JB |
1974 | } |
1975 | } | |
1976 | ||
be0676b3 | 1977 | /** |
fcd39179 | 1978 | * This method is the message listener registered on each worker. |
be0676b3 | 1979 | */ |
3a776b6d JB |
1980 | protected readonly workerMessageListener = ( |
1981 | message: MessageValue<Response> | |
1982 | ): void => { | |
fcd39179 | 1983 | this.checkMessageWorkerId(message) |
31847469 JB |
1984 | const { workerId, ready, taskId, taskFunctionsProperties } = message |
1985 | if (ready != null && taskFunctionsProperties != null) { | |
fcd39179 JB |
1986 | // Worker ready response received from worker |
1987 | this.handleWorkerReadyResponse(message) | |
31847469 JB |
1988 | } else if (taskFunctionsProperties != null) { |
1989 | // Task function properties message received from worker | |
9a55fa8c JB |
1990 | const workerNodeKey = this.getWorkerNodeKeyByWorkerId(workerId) |
1991 | const workerInfo = this.getWorkerInfo(workerNodeKey) | |
1851fed0 | 1992 | if (workerInfo != null) { |
31847469 | 1993 | workerInfo.taskFunctionsProperties = taskFunctionsProperties |
9a55fa8c | 1994 | this.sendStatisticsMessageToWorker(workerNodeKey) |
1851fed0 | 1995 | } |
31847469 JB |
1996 | } else if (taskId != null) { |
1997 | // Task execution response received from worker | |
1998 | this.handleTaskExecutionResponse(message) | |
6b272951 JB |
1999 | } |
2000 | } | |
2001 | ||
8e8d9101 JB |
2002 | private checkAndEmitReadyEvent (): void { |
2003 | if (!this.readyEventEmitted && this.ready) { | |
2004 | this.emitter?.emit(PoolEvents.ready, this.info) | |
2005 | this.readyEventEmitted = true | |
2006 | } | |
2007 | } | |
2008 | ||
10e2aa7e | 2009 | private handleWorkerReadyResponse (message: MessageValue<Response>): void { |
31847469 | 2010 | const { workerId, ready, taskFunctionsProperties } = message |
e44639e9 | 2011 | if (ready == null || !ready) { |
c63a35a0 | 2012 | throw new Error(`Worker ${workerId} failed to initialize`) |
f05ed93c | 2013 | } |
9a55fa8c JB |
2014 | const workerNodeKey = this.getWorkerNodeKeyByWorkerId(workerId) |
2015 | const workerNode = this.workerNodes[workerNodeKey] | |
e44639e9 | 2016 | workerNode.info.ready = ready |
31847469 | 2017 | workerNode.info.taskFunctionsProperties = taskFunctionsProperties |
9a55fa8c | 2018 | this.sendStatisticsMessageToWorker(workerNodeKey) |
8e8d9101 | 2019 | this.checkAndEmitReadyEvent() |
6b272951 JB |
2020 | } |
2021 | ||
2022 | private handleTaskExecutionResponse (message: MessageValue<Response>): void { | |
463226a4 | 2023 | const { workerId, taskId, workerError, data } = message |
67f3f2d6 JB |
2024 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2025 | const promiseResponse = this.promiseResponseMap.get(taskId!) | |
6b272951 | 2026 | if (promiseResponse != null) { |
f18fd12b | 2027 | const { resolve, reject, workerNodeKey, asyncResource } = promiseResponse |
9b358e72 | 2028 | const workerNode = this.workerNodes[workerNodeKey] |
6703b9f4 JB |
2029 | if (workerError != null) { |
2030 | this.emitter?.emit(PoolEvents.taskError, workerError) | |
f18fd12b JB |
2031 | asyncResource != null |
2032 | ? asyncResource.runInAsyncScope( | |
2033 | reject, | |
2034 | this.emitter, | |
2035 | workerError.message | |
2036 | ) | |
2037 | : reject(workerError.message) | |
6b272951 | 2038 | } else { |
f18fd12b JB |
2039 | asyncResource != null |
2040 | ? asyncResource.runInAsyncScope(resolve, this.emitter, data) | |
2041 | : resolve(data as Response) | |
6b272951 | 2042 | } |
f18fd12b | 2043 | asyncResource?.emitDestroy() |
501aea93 | 2044 | this.afterTaskExecutionHook(workerNodeKey, message) |
67f3f2d6 JB |
2045 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2046 | this.promiseResponseMap.delete(taskId!) | |
cdaecaee JB |
2047 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
2048 | workerNode?.emit('taskFinished', taskId) | |
16d7e943 JB |
2049 | if ( |
2050 | this.opts.enableTasksQueue === true && | |
2051 | !this.destroying && | |
2052 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition | |
2053 | workerNode != null | |
2054 | ) { | |
9b358e72 | 2055 | const workerNodeTasksUsage = workerNode.usage.tasks |
463226a4 JB |
2056 | if ( |
2057 | this.tasksQueueSize(workerNodeKey) > 0 && | |
2058 | workerNodeTasksUsage.executing < | |
67f3f2d6 JB |
2059 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2060 | this.opts.tasksQueueOptions!.concurrency! | |
463226a4 | 2061 | ) { |
67f3f2d6 JB |
2062 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2063 | this.executeTask(workerNodeKey, this.dequeueTask(workerNodeKey)!) | |
463226a4 JB |
2064 | } |
2065 | if ( | |
2066 | workerNodeTasksUsage.executing === 0 && | |
2067 | this.tasksQueueSize(workerNodeKey) === 0 && | |
2068 | workerNodeTasksUsage.sequentiallyStolen === 0 | |
2069 | ) { | |
e44639e9 | 2070 | workerNode.emit('idle', { |
7f0e1334 | 2071 | workerId, |
e1c2dba7 JB |
2072 | workerNodeKey |
2073 | }) | |
463226a4 | 2074 | } |
be0676b3 APA |
2075 | } |
2076 | } | |
be0676b3 | 2077 | } |
7c0ba920 | 2078 | |
a1763c54 | 2079 | private checkAndEmitTaskExecutionEvents (): void { |
33e6bb4c JB |
2080 | if (this.busy) { |
2081 | this.emitter?.emit(PoolEvents.busy, this.info) | |
a1763c54 JB |
2082 | } |
2083 | } | |
2084 | ||
2085 | private checkAndEmitTaskQueuingEvents (): void { | |
2086 | if (this.hasBackPressure()) { | |
2087 | this.emitter?.emit(PoolEvents.backPressure, this.info) | |
164d950a JB |
2088 | } |
2089 | } | |
2090 | ||
d0878034 JB |
2091 | /** |
2092 | * Emits dynamic worker creation events. | |
2093 | */ | |
2094 | protected abstract checkAndEmitDynamicWorkerCreationEvents (): void | |
33e6bb4c | 2095 | |
8a1260a3 | 2096 | /** |
aa9eede8 | 2097 | * Gets the worker information given its worker node key. |
8a1260a3 JB |
2098 | * |
2099 | * @param workerNodeKey - The worker node key. | |
3f09ed9f | 2100 | * @returns The worker information. |
8a1260a3 | 2101 | */ |
1851fed0 JB |
2102 | protected getWorkerInfo (workerNodeKey: number): WorkerInfo | undefined { |
2103 | return this.workerNodes[workerNodeKey]?.info | |
e221309a JB |
2104 | } |
2105 | ||
a05c10de | 2106 | /** |
c3719753 | 2107 | * Creates a worker node. |
ea7a90d3 | 2108 | * |
c3719753 | 2109 | * @returns The created worker node. |
ea7a90d3 | 2110 | */ |
c3719753 | 2111 | private createWorkerNode (): IWorkerNode<Worker, Data> { |
671d5154 | 2112 | const workerNode = new WorkerNode<Worker, Data>( |
c3719753 JB |
2113 | this.worker, |
2114 | this.filePath, | |
2115 | { | |
2116 | env: this.opts.env, | |
2117 | workerOptions: this.opts.workerOptions, | |
2118 | tasksQueueBackPressureSize: | |
32b141fd | 2119 | this.opts.tasksQueueOptions?.size ?? |
26ce26ca JB |
2120 | getDefaultTasksQueueOptions( |
2121 | this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers | |
95d1a734 JB |
2122 | ).size, |
2123 | tasksQueueBucketSize: | |
2124 | (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers) * 2 | |
c3719753 | 2125 | } |
671d5154 | 2126 | ) |
b97d82d8 | 2127 | // Flag the worker node as ready at pool startup. |
d2c73f82 JB |
2128 | if (this.starting) { |
2129 | workerNode.info.ready = true | |
2130 | } | |
c3719753 JB |
2131 | return workerNode |
2132 | } | |
2133 | ||
2134 | /** | |
2135 | * Adds the given worker node in the pool worker nodes. | |
2136 | * | |
2137 | * @param workerNode - The worker node. | |
2138 | * @returns The added worker node key. | |
2139 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found. | |
2140 | */ | |
2141 | private addWorkerNode (workerNode: IWorkerNode<Worker, Data>): number { | |
aa9eede8 | 2142 | this.workerNodes.push(workerNode) |
c3719753 | 2143 | const workerNodeKey = this.workerNodes.indexOf(workerNode) |
aa9eede8 | 2144 | if (workerNodeKey === -1) { |
86ed0598 | 2145 | throw new Error('Worker added not found in worker nodes') |
aa9eede8 JB |
2146 | } |
2147 | return workerNodeKey | |
ea7a90d3 | 2148 | } |
c923ce56 | 2149 | |
8e8d9101 JB |
2150 | private checkAndEmitEmptyEvent (): void { |
2151 | if (this.empty) { | |
2152 | this.emitter?.emit(PoolEvents.empty, this.info) | |
2153 | this.readyEventEmitted = false | |
2154 | } | |
2155 | } | |
2156 | ||
51fe3d3c | 2157 | /** |
9974369e | 2158 | * Removes the worker node from the pool worker nodes. |
51fe3d3c | 2159 | * |
9974369e | 2160 | * @param workerNode - The worker node. |
51fe3d3c | 2161 | */ |
9974369e JB |
2162 | private removeWorkerNode (workerNode: IWorkerNode<Worker, Data>): void { |
2163 | const workerNodeKey = this.workerNodes.indexOf(workerNode) | |
1f68cede JB |
2164 | if (workerNodeKey !== -1) { |
2165 | this.workerNodes.splice(workerNodeKey, 1) | |
bcfb06ce | 2166 | this.workerChoiceStrategiesContext?.remove(workerNodeKey) |
1f68cede | 2167 | } |
8e8d9101 | 2168 | this.checkAndEmitEmptyEvent() |
51fe3d3c | 2169 | } |
adc3c320 | 2170 | |
ae3ab61d | 2171 | protected flagWorkerNodeAsNotReady (workerNodeKey: number): void { |
1851fed0 JB |
2172 | const workerInfo = this.getWorkerInfo(workerNodeKey) |
2173 | if (workerInfo != null) { | |
2174 | workerInfo.ready = false | |
2175 | } | |
ae3ab61d JB |
2176 | } |
2177 | ||
9e844245 JB |
2178 | private hasBackPressure (): boolean { |
2179 | return ( | |
2180 | this.opts.enableTasksQueue === true && | |
2181 | this.workerNodes.findIndex( | |
041dc05b | 2182 | workerNode => !workerNode.hasBackPressure() |
a1763c54 | 2183 | ) === -1 |
9e844245 | 2184 | ) |
e2b31e32 JB |
2185 | } |
2186 | ||
b0a4db63 | 2187 | /** |
aa9eede8 | 2188 | * Executes the given task on the worker given its worker node key. |
b0a4db63 | 2189 | * |
aa9eede8 | 2190 | * @param workerNodeKey - The worker node key. |
b0a4db63 JB |
2191 | * @param task - The task to execute. |
2192 | */ | |
2e81254d | 2193 | private executeTask (workerNodeKey: number, task: Task<Data>): void { |
1c6fe997 | 2194 | this.beforeTaskExecutionHook(workerNodeKey, task) |
bbfa38a2 | 2195 | this.sendToWorker(workerNodeKey, task, task.transferList) |
a1763c54 | 2196 | this.checkAndEmitTaskExecutionEvents() |
2e81254d JB |
2197 | } |
2198 | ||
f9f00b5f | 2199 | private enqueueTask (workerNodeKey: number, task: Task<Data>): number { |
a1763c54 JB |
2200 | const tasksQueueSize = this.workerNodes[workerNodeKey].enqueueTask(task) |
2201 | this.checkAndEmitTaskQueuingEvents() | |
2202 | return tasksQueueSize | |
adc3c320 JB |
2203 | } |
2204 | ||
0d4e88b3 JB |
2205 | private dequeueTask (workerNodeKey: number): Task<Data> | undefined { |
2206 | return this.workerNodes[workerNodeKey].dequeueTask() | |
adc3c320 JB |
2207 | } |
2208 | ||
416fd65c | 2209 | private tasksQueueSize (workerNodeKey: number): number { |
4b628b48 | 2210 | return this.workerNodes[workerNodeKey].tasksQueueSize() |
df593701 JB |
2211 | } |
2212 | ||
87347ea8 JB |
2213 | protected flushTasksQueue (workerNodeKey: number): number { |
2214 | let flushedTasks = 0 | |
920278a2 | 2215 | while (this.tasksQueueSize(workerNodeKey) > 0) { |
67f3f2d6 JB |
2216 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2217 | this.executeTask(workerNodeKey, this.dequeueTask(workerNodeKey)!) | |
87347ea8 | 2218 | ++flushedTasks |
ff733df7 | 2219 | } |
4b628b48 | 2220 | this.workerNodes[workerNodeKey].clearTasksQueue() |
87347ea8 | 2221 | return flushedTasks |
ff733df7 JB |
2222 | } |
2223 | ||
ef41a6e6 | 2224 | private flushTasksQueues (): void { |
19b8be8b | 2225 | for (const workerNodeKey of this.workerNodes.keys()) { |
ef41a6e6 JB |
2226 | this.flushTasksQueue(workerNodeKey) |
2227 | } | |
2228 | } | |
c97c7edb | 2229 | } |