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