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