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