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 | |
9df282a0 | 7 | import { defaultBucketSize } from '../priority-queue.js' |
5c4d16da JB |
8 | import type { |
9 | MessageValue, | |
10 | PromiseResponseWrapper, | |
31847469 | 11 | Task, |
3a502712 | 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 JB |
590 | /** |
591 | * The pool readiness boolean status. | |
592 | */ | |
2431bdb4 | 593 | private get ready (): boolean { |
8e8d9101 JB |
594 | if (this.empty) { |
595 | return false | |
596 | } | |
2431bdb4 | 597 | return ( |
b97d82d8 JB |
598 | this.workerNodes.reduce( |
599 | (accumulator, workerNode) => | |
600 | !workerNode.info.dynamic && workerNode.info.ready | |
601 | ? accumulator + 1 | |
602 | : accumulator, | |
603 | 0 | |
26ce26ca | 604 | ) >= this.minimumNumberOfWorkers |
2431bdb4 JB |
605 | ) |
606 | } | |
607 | ||
8e8d9101 JB |
608 | /** |
609 | * The pool emptiness boolean status. | |
610 | */ | |
611 | protected get empty (): boolean { | |
fb43035c | 612 | return this.minimumNumberOfWorkers === 0 && this.workerNodes.length === 0 |
8e8d9101 JB |
613 | } |
614 | ||
afe0d5bf | 615 | /** |
aa9eede8 | 616 | * The approximate pool utilization. |
afe0d5bf JB |
617 | * @returns The pool utilization. |
618 | */ | |
619 | private get utilization (): number { | |
97dc65d9 JB |
620 | if (this.startTimestamp == null) { |
621 | return 0 | |
622 | } | |
8e5ca040 | 623 | const poolTimeCapacity = |
26ce26ca JB |
624 | (performance.now() - this.startTimestamp) * |
625 | (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers) | |
afe0d5bf JB |
626 | const totalTasksRunTime = this.workerNodes.reduce( |
627 | (accumulator, workerNode) => | |
c63a35a0 | 628 | accumulator + (workerNode.usage.runTime.aggregate ?? 0), |
afe0d5bf JB |
629 | 0 |
630 | ) | |
631 | const totalTasksWaitTime = this.workerNodes.reduce( | |
632 | (accumulator, workerNode) => | |
c63a35a0 | 633 | accumulator + (workerNode.usage.waitTime.aggregate ?? 0), |
afe0d5bf JB |
634 | 0 |
635 | ) | |
8e5ca040 | 636 | return (totalTasksRunTime + totalTasksWaitTime) / poolTimeCapacity |
afe0d5bf JB |
637 | } |
638 | ||
8881ae32 | 639 | /** |
aa9eede8 | 640 | * The pool type. |
8881ae32 JB |
641 | * |
642 | * If it is `'dynamic'`, it provides the `max` property. | |
643 | */ | |
644 | protected abstract get type (): PoolType | |
645 | ||
184855e6 | 646 | /** |
aa9eede8 | 647 | * The worker type. |
184855e6 JB |
648 | */ |
649 | protected abstract get worker (): WorkerType | |
650 | ||
6b813701 JB |
651 | /** |
652 | * Checks if the worker id sent in the received message from a worker is valid. | |
6b813701 JB |
653 | * @param message - The received message. |
654 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid. | |
655 | */ | |
4d159167 | 656 | private checkMessageWorkerId (message: MessageValue<Data | Response>): void { |
310de0aa JB |
657 | if (message.workerId == null) { |
658 | throw new Error('Worker message received without worker id') | |
8e5a7cf9 | 659 | } else if (this.getWorkerNodeKeyByWorkerId(message.workerId) === -1) { |
21f710aa JB |
660 | throw new Error( |
661 | `Worker message received from unknown worker '${message.workerId}'` | |
662 | ) | |
663 | } | |
664 | } | |
665 | ||
aa9eede8 JB |
666 | /** |
667 | * Gets the worker node key given its worker id. | |
aa9eede8 | 668 | * @param workerId - The worker id. |
aad6fb64 | 669 | * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise. |
aa9eede8 | 670 | */ |
72ae84a2 | 671 | private getWorkerNodeKeyByWorkerId (workerId: number | undefined): number { |
aad6fb64 | 672 | return this.workerNodes.findIndex( |
041dc05b | 673 | workerNode => workerNode.info.id === workerId |
aad6fb64 | 674 | ) |
aa9eede8 JB |
675 | } |
676 | ||
afc003b2 | 677 | /** @inheritDoc */ |
a35560ba | 678 | public setWorkerChoiceStrategy ( |
59219cbb JB |
679 | workerChoiceStrategy: WorkerChoiceStrategy, |
680 | workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions | |
a35560ba | 681 | ): void { |
19b8be8b | 682 | let requireSync = false |
bde6b5d7 | 683 | checkValidWorkerChoiceStrategy(workerChoiceStrategy) |
85bbc7ab | 684 | if (workerChoiceStrategyOptions != null) { |
423f3b7a | 685 | requireSync = !this.setWorkerChoiceStrategyOptions( |
19b8be8b JB |
686 | workerChoiceStrategyOptions |
687 | ) | |
85bbc7ab JB |
688 | } |
689 | if (workerChoiceStrategy !== this.opts.workerChoiceStrategy) { | |
690 | this.opts.workerChoiceStrategy = workerChoiceStrategy | |
691 | this.workerChoiceStrategiesContext?.setDefaultWorkerChoiceStrategy( | |
692 | this.opts.workerChoiceStrategy, | |
693 | this.opts.workerChoiceStrategyOptions | |
694 | ) | |
19b8be8b JB |
695 | requireSync = true |
696 | } | |
697 | if (requireSync) { | |
85bbc7ab | 698 | this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies( |
91041638 | 699 | this.getWorkerChoiceStrategies(), |
85bbc7ab JB |
700 | this.opts.workerChoiceStrategyOptions |
701 | ) | |
19b8be8b | 702 | for (const workerNodeKey of this.workerNodes.keys()) { |
85bbc7ab JB |
703 | this.sendStatisticsMessageToWorker(workerNodeKey) |
704 | } | |
59219cbb | 705 | } |
a20f0ba5 JB |
706 | } |
707 | ||
708 | /** @inheritDoc */ | |
709 | public setWorkerChoiceStrategyOptions ( | |
c63a35a0 | 710 | workerChoiceStrategyOptions: WorkerChoiceStrategyOptions | undefined |
19b8be8b | 711 | ): boolean { |
0d80593b | 712 | this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions) |
26ce26ca JB |
713 | if (workerChoiceStrategyOptions != null) { |
714 | this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions | |
19b8be8b JB |
715 | this.workerChoiceStrategiesContext?.setOptions( |
716 | this.opts.workerChoiceStrategyOptions | |
717 | ) | |
718 | this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies( | |
91041638 | 719 | this.getWorkerChoiceStrategies(), |
19b8be8b JB |
720 | this.opts.workerChoiceStrategyOptions |
721 | ) | |
722 | for (const workerNodeKey of this.workerNodes.keys()) { | |
723 | this.sendStatisticsMessageToWorker(workerNodeKey) | |
724 | } | |
725 | return true | |
8990357d | 726 | } |
19b8be8b | 727 | return false |
a35560ba S |
728 | } |
729 | ||
a20f0ba5 | 730 | /** @inheritDoc */ |
8f52842f JB |
731 | public enableTasksQueue ( |
732 | enable: boolean, | |
733 | tasksQueueOptions?: TasksQueueOptions | |
734 | ): void { | |
a20f0ba5 | 735 | if (this.opts.enableTasksQueue === true && !enable) { |
d6ca1416 JB |
736 | this.unsetTaskStealing() |
737 | this.unsetTasksStealingOnBackPressure() | |
ef41a6e6 | 738 | this.flushTasksQueues() |
a20f0ba5 JB |
739 | } |
740 | this.opts.enableTasksQueue = enable | |
c63a35a0 | 741 | this.setTasksQueueOptions(tasksQueueOptions) |
a20f0ba5 JB |
742 | } |
743 | ||
744 | /** @inheritDoc */ | |
c63a35a0 JB |
745 | public setTasksQueueOptions ( |
746 | tasksQueueOptions: TasksQueueOptions | undefined | |
747 | ): void { | |
a20f0ba5 | 748 | if (this.opts.enableTasksQueue === true) { |
bde6b5d7 | 749 | checkValidTasksQueueOptions(tasksQueueOptions) |
8f52842f JB |
750 | this.opts.tasksQueueOptions = |
751 | this.buildTasksQueueOptions(tasksQueueOptions) | |
67f3f2d6 JB |
752 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
753 | this.setTasksQueueSize(this.opts.tasksQueueOptions.size!) | |
d6ca1416 | 754 | if (this.opts.tasksQueueOptions.taskStealing === true) { |
9f99eb9b | 755 | this.unsetTaskStealing() |
d6ca1416 JB |
756 | this.setTaskStealing() |
757 | } else { | |
758 | this.unsetTaskStealing() | |
759 | } | |
760 | if (this.opts.tasksQueueOptions.tasksStealingOnBackPressure === true) { | |
9f99eb9b | 761 | this.unsetTasksStealingOnBackPressure() |
d6ca1416 JB |
762 | this.setTasksStealingOnBackPressure() |
763 | } else { | |
764 | this.unsetTasksStealingOnBackPressure() | |
765 | } | |
5baee0d7 | 766 | } else if (this.opts.tasksQueueOptions != null) { |
a20f0ba5 JB |
767 | delete this.opts.tasksQueueOptions |
768 | } | |
769 | } | |
770 | ||
9b38ab2d | 771 | private buildTasksQueueOptions ( |
c63a35a0 | 772 | tasksQueueOptions: TasksQueueOptions | undefined |
9b38ab2d JB |
773 | ): TasksQueueOptions { |
774 | return { | |
26ce26ca JB |
775 | ...getDefaultTasksQueueOptions( |
776 | this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers | |
777 | ), | |
3a502712 | 778 | ...tasksQueueOptions, |
9b38ab2d JB |
779 | } |
780 | } | |
781 | ||
5b49e864 | 782 | private setTasksQueueSize (size: number): void { |
20c6f652 | 783 | for (const workerNode of this.workerNodes) { |
ff3f866a | 784 | workerNode.tasksQueueBackPressureSize = size |
20c6f652 JB |
785 | } |
786 | } | |
787 | ||
d6ca1416 | 788 | private setTaskStealing (): void { |
19b8be8b | 789 | for (const workerNodeKey of this.workerNodes.keys()) { |
e44639e9 | 790 | this.workerNodes[workerNodeKey].on('idle', this.handleWorkerNodeIdleEvent) |
d6ca1416 JB |
791 | } |
792 | } | |
793 | ||
794 | private unsetTaskStealing (): void { | |
19b8be8b | 795 | for (const workerNodeKey of this.workerNodes.keys()) { |
e1c2dba7 | 796 | this.workerNodes[workerNodeKey].off( |
e44639e9 JB |
797 | 'idle', |
798 | this.handleWorkerNodeIdleEvent | |
9f95d5eb | 799 | ) |
d6ca1416 JB |
800 | } |
801 | } | |
802 | ||
803 | private setTasksStealingOnBackPressure (): void { | |
19b8be8b | 804 | for (const workerNodeKey of this.workerNodes.keys()) { |
e1c2dba7 | 805 | this.workerNodes[workerNodeKey].on( |
b5e75be8 | 806 | 'backPressure', |
e44639e9 | 807 | this.handleWorkerNodeBackPressureEvent |
9f95d5eb | 808 | ) |
d6ca1416 JB |
809 | } |
810 | } | |
811 | ||
812 | private unsetTasksStealingOnBackPressure (): void { | |
19b8be8b | 813 | for (const workerNodeKey of this.workerNodes.keys()) { |
e1c2dba7 | 814 | this.workerNodes[workerNodeKey].off( |
b5e75be8 | 815 | 'backPressure', |
e44639e9 | 816 | this.handleWorkerNodeBackPressureEvent |
9f95d5eb | 817 | ) |
d6ca1416 JB |
818 | } |
819 | } | |
820 | ||
c319c66b JB |
821 | /** |
822 | * Whether the pool is full or not. | |
823 | * | |
824 | * The pool filling boolean status. | |
825 | */ | |
dea903a8 | 826 | protected get full (): boolean { |
26ce26ca JB |
827 | return ( |
828 | this.workerNodes.length >= | |
829 | (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers) | |
830 | ) | |
dea903a8 | 831 | } |
c2ade475 | 832 | |
c319c66b JB |
833 | /** |
834 | * Whether the pool is busy or not. | |
835 | * | |
836 | * The pool busyness boolean status. | |
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( | |
c63a35a0 | 894 | `Task function operation '${message.taskFunctionOperation}' failed on worker ${message.workerId} with error: '${message.workerError?.message}'` |
ae036c3e | 895 | ) |
72ae84a2 | 896 | ) |
ae036c3e JB |
897 | } |
898 | this.deregisterWorkerMessageListener( | |
899 | this.getWorkerNodeKeyByWorkerId(message.workerId), | |
900 | taskFunctionOperationListener | |
72ae84a2 JB |
901 | ) |
902 | } | |
ae036c3e JB |
903 | } |
904 | this.registerWorkerMessageListener( | |
905 | workerNodeKey, | |
906 | taskFunctionOperationListener | |
907 | ) | |
72ae84a2 JB |
908 | this.sendToWorker(workerNodeKey, message) |
909 | }) | |
910 | } | |
911 | ||
912 | private async sendTaskFunctionOperationToWorkers ( | |
adee6053 | 913 | message: MessageValue<Data> |
e81c38f2 JB |
914 | ): Promise<boolean> { |
915 | return await new Promise<boolean>((resolve, reject) => { | |
ae036c3e JB |
916 | const responsesReceived = new Array<MessageValue<Response>>() |
917 | const taskFunctionOperationsListener = ( | |
918 | message: MessageValue<Response> | |
919 | ): void => { | |
920 | this.checkMessageWorkerId(message) | |
921 | if (message.taskFunctionOperationStatus != null) { | |
922 | responsesReceived.push(message) | |
923 | if (responsesReceived.length === this.workerNodes.length) { | |
e81c38f2 | 924 | if ( |
e81c38f2 JB |
925 | responsesReceived.every( |
926 | message => message.taskFunctionOperationStatus === true | |
927 | ) | |
928 | ) { | |
929 | resolve(true) | |
930 | } else if ( | |
e81c38f2 JB |
931 | responsesReceived.some( |
932 | message => message.taskFunctionOperationStatus === false | |
933 | ) | |
934 | ) { | |
b0b55f57 JB |
935 | const errorResponse = responsesReceived.find( |
936 | response => response.taskFunctionOperationStatus === false | |
937 | ) | |
e81c38f2 JB |
938 | reject( |
939 | new Error( | |
b0b55f57 | 940 | `Task function operation '${ |
e81c38f2 | 941 | message.taskFunctionOperation as string |
c63a35a0 JB |
942 | }' failed on worker ${errorResponse?.workerId} with error: '${ |
943 | errorResponse?.workerError?.message | |
b0b55f57 | 944 | }'` |
e81c38f2 JB |
945 | ) |
946 | ) | |
947 | } | |
ae036c3e JB |
948 | this.deregisterWorkerMessageListener( |
949 | this.getWorkerNodeKeyByWorkerId(message.workerId), | |
950 | taskFunctionOperationsListener | |
951 | ) | |
e81c38f2 | 952 | } |
ae036c3e JB |
953 | } |
954 | } | |
19b8be8b | 955 | for (const workerNodeKey of this.workerNodes.keys()) { |
ae036c3e JB |
956 | this.registerWorkerMessageListener( |
957 | workerNodeKey, | |
958 | taskFunctionOperationsListener | |
959 | ) | |
72ae84a2 | 960 | this.sendToWorker(workerNodeKey, message) |
e81c38f2 JB |
961 | } |
962 | }) | |
6703b9f4 JB |
963 | } |
964 | ||
965 | /** @inheritDoc */ | |
966 | public hasTaskFunction (name: string): boolean { | |
85bbc7ab JB |
967 | return this.listTaskFunctionsProperties().some( |
968 | taskFunctionProperties => taskFunctionProperties.name === name | |
969 | ) | |
6703b9f4 JB |
970 | } |
971 | ||
972 | /** @inheritDoc */ | |
e81c38f2 JB |
973 | public async addTaskFunction ( |
974 | name: string, | |
31847469 | 975 | fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response> |
e81c38f2 | 976 | ): Promise<boolean> { |
3feeab69 JB |
977 | if (typeof name !== 'string') { |
978 | throw new TypeError('name argument must be a string') | |
979 | } | |
980 | if (typeof name === 'string' && name.trim().length === 0) { | |
981 | throw new TypeError('name argument must not be an empty string') | |
982 | } | |
31847469 JB |
983 | if (typeof fn === 'function') { |
984 | fn = { taskFunction: fn } satisfies TaskFunctionObject<Data, Response> | |
985 | } | |
986 | if (typeof fn.taskFunction !== 'function') { | |
987 | throw new TypeError('taskFunction property must be a function') | |
3feeab69 | 988 | } |
95d1a734 JB |
989 | checkValidPriority(fn.priority) |
990 | checkValidWorkerChoiceStrategy(fn.strategy) | |
adee6053 | 991 | const opResult = await this.sendTaskFunctionOperationToWorkers({ |
6703b9f4 | 992 | taskFunctionOperation: 'add', |
31847469 | 993 | taskFunctionProperties: buildTaskFunctionProperties(name, fn), |
3a502712 | 994 | taskFunction: fn.taskFunction.toString(), |
6703b9f4 | 995 | }) |
adee6053 | 996 | this.taskFunctions.set(name, fn) |
85bbc7ab | 997 | this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies( |
91041638 | 998 | this.getWorkerChoiceStrategies() |
85bbc7ab | 999 | ) |
9a55fa8c JB |
1000 | for (const workerNodeKey of this.workerNodes.keys()) { |
1001 | this.sendStatisticsMessageToWorker(workerNodeKey) | |
1002 | } | |
adee6053 | 1003 | return opResult |
6703b9f4 JB |
1004 | } |
1005 | ||
1006 | /** @inheritDoc */ | |
e81c38f2 | 1007 | public async removeTaskFunction (name: string): Promise<boolean> { |
9eae3c69 JB |
1008 | if (!this.taskFunctions.has(name)) { |
1009 | throw new Error( | |
16248b23 | 1010 | 'Cannot remove a task function not handled on the pool side' |
9eae3c69 JB |
1011 | ) |
1012 | } | |
adee6053 | 1013 | const opResult = await this.sendTaskFunctionOperationToWorkers({ |
6703b9f4 | 1014 | taskFunctionOperation: 'remove', |
31847469 JB |
1015 | taskFunctionProperties: buildTaskFunctionProperties( |
1016 | name, | |
1017 | this.taskFunctions.get(name) | |
3a502712 | 1018 | ), |
6703b9f4 | 1019 | }) |
9a55fa8c JB |
1020 | for (const workerNode of this.workerNodes) { |
1021 | workerNode.deleteTaskFunctionWorkerUsage(name) | |
1022 | } | |
adee6053 | 1023 | this.taskFunctions.delete(name) |
85bbc7ab | 1024 | this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies( |
91041638 | 1025 | this.getWorkerChoiceStrategies() |
85bbc7ab | 1026 | ) |
9a55fa8c JB |
1027 | for (const workerNodeKey of this.workerNodes.keys()) { |
1028 | this.sendStatisticsMessageToWorker(workerNodeKey) | |
1029 | } | |
adee6053 | 1030 | return opResult |
6703b9f4 JB |
1031 | } |
1032 | ||
90d7d101 | 1033 | /** @inheritDoc */ |
31847469 | 1034 | public listTaskFunctionsProperties (): TaskFunctionProperties[] { |
f2dbbf95 JB |
1035 | for (const workerNode of this.workerNodes) { |
1036 | if ( | |
31847469 JB |
1037 | Array.isArray(workerNode.info.taskFunctionsProperties) && |
1038 | workerNode.info.taskFunctionsProperties.length > 0 | |
f2dbbf95 | 1039 | ) { |
31847469 | 1040 | return workerNode.info.taskFunctionsProperties |
f2dbbf95 | 1041 | } |
90d7d101 | 1042 | } |
f2dbbf95 | 1043 | return [] |
90d7d101 JB |
1044 | } |
1045 | ||
bcfb06ce | 1046 | /** |
91041638 | 1047 | * Gets task function worker choice strategy, if any. |
bcfb06ce JB |
1048 | * @param name - The task function name. |
1049 | * @returns The task function worker choice strategy if the task function worker choice strategy is defined, `undefined` otherwise. | |
1050 | */ | |
91041638 | 1051 | private readonly getTaskFunctionWorkerChoiceStrategy = ( |
bcfb06ce JB |
1052 | name?: string |
1053 | ): WorkerChoiceStrategy | undefined => { | |
91041638 JB |
1054 | name = name ?? DEFAULT_TASK_NAME |
1055 | const taskFunctionsProperties = this.listTaskFunctionsProperties() | |
1056 | if (name === DEFAULT_TASK_NAME) { | |
1057 | name = taskFunctionsProperties[1]?.name | |
bcfb06ce | 1058 | } |
91041638 JB |
1059 | return taskFunctionsProperties.find( |
1060 | (taskFunctionProperties: TaskFunctionProperties) => | |
1061 | taskFunctionProperties.name === name | |
1062 | )?.strategy | |
1063 | } | |
1064 | ||
1065 | /** | |
1066 | * Gets worker node task function worker choice strategy, if any. | |
91041638 JB |
1067 | * @param workerNodeKey - The worker node key. |
1068 | * @param name - The task function name. | |
1069 | * @returns The worker node task function worker choice strategy if the worker node task function worker choice strategy is defined, `undefined` otherwise. | |
1070 | */ | |
1071 | private readonly getWorkerNodeTaskFunctionWorkerChoiceStrategy = ( | |
1072 | workerNodeKey: number, | |
1073 | name?: string | |
1074 | ): WorkerChoiceStrategy | undefined => { | |
1075 | const workerInfo = this.getWorkerInfo(workerNodeKey) | |
1076 | if (workerInfo == null) { | |
1077 | return | |
1078 | } | |
1079 | name = name ?? DEFAULT_TASK_NAME | |
1080 | if (name === DEFAULT_TASK_NAME) { | |
1081 | name = workerInfo.taskFunctionsProperties?.[1]?.name | |
1082 | } | |
1083 | return workerInfo.taskFunctionsProperties?.find( | |
1084 | (taskFunctionProperties: TaskFunctionProperties) => | |
1085 | taskFunctionProperties.name === name | |
1086 | )?.strategy | |
bcfb06ce JB |
1087 | } |
1088 | ||
95d1a734 JB |
1089 | /** |
1090 | * Gets worker node task function priority, if any. | |
95d1a734 JB |
1091 | * @param workerNodeKey - The worker node key. |
1092 | * @param name - The task function name. | |
a20062fa | 1093 | * @returns The worker node task function priority if the worker node task function priority is defined, `undefined` otherwise. |
95d1a734 JB |
1094 | */ |
1095 | private readonly getWorkerNodeTaskFunctionPriority = ( | |
1096 | workerNodeKey: number, | |
1097 | name?: string | |
1098 | ): number | undefined => { | |
91041638 JB |
1099 | const workerInfo = this.getWorkerInfo(workerNodeKey) |
1100 | if (workerInfo == null) { | |
1101 | return | |
95d1a734 | 1102 | } |
91041638 JB |
1103 | name = name ?? DEFAULT_TASK_NAME |
1104 | if (name === DEFAULT_TASK_NAME) { | |
1105 | name = workerInfo.taskFunctionsProperties?.[1]?.name | |
1106 | } | |
1107 | return workerInfo.taskFunctionsProperties?.find( | |
1108 | (taskFunctionProperties: TaskFunctionProperties) => | |
1109 | taskFunctionProperties.name === name | |
1110 | )?.priority | |
95d1a734 JB |
1111 | } |
1112 | ||
85bbc7ab JB |
1113 | /** |
1114 | * Gets the worker choice strategies registered in this pool. | |
85bbc7ab JB |
1115 | * @returns The worker choice strategies. |
1116 | */ | |
91041638 | 1117 | private readonly getWorkerChoiceStrategies = |
85bbc7ab JB |
1118 | (): Set<WorkerChoiceStrategy> => { |
1119 | return new Set([ | |
1120 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
1121 | this.opts.workerChoiceStrategy!, | |
1122 | ...(this.listTaskFunctionsProperties() | |
1123 | .map( | |
1124 | (taskFunctionProperties: TaskFunctionProperties) => | |
1125 | taskFunctionProperties.strategy | |
1126 | ) | |
1127 | .filter( | |
1128 | (strategy: WorkerChoiceStrategy | undefined) => strategy != null | |
3a502712 | 1129 | ) as WorkerChoiceStrategy[]), |
85bbc7ab JB |
1130 | ]) |
1131 | } | |
1132 | ||
6703b9f4 | 1133 | /** @inheritDoc */ |
e81c38f2 | 1134 | public async setDefaultTaskFunction (name: string): Promise<boolean> { |
72ae84a2 | 1135 | return await this.sendTaskFunctionOperationToWorkers({ |
6703b9f4 | 1136 | taskFunctionOperation: 'default', |
31847469 JB |
1137 | taskFunctionProperties: buildTaskFunctionProperties( |
1138 | name, | |
1139 | this.taskFunctions.get(name) | |
3a502712 | 1140 | ), |
6703b9f4 | 1141 | }) |
6703b9f4 JB |
1142 | } |
1143 | ||
375f7504 JB |
1144 | private shallExecuteTask (workerNodeKey: number): boolean { |
1145 | return ( | |
1146 | this.tasksQueueSize(workerNodeKey) === 0 && | |
1147 | this.workerNodes[workerNodeKey].usage.tasks.executing < | |
67f3f2d6 JB |
1148 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1149 | this.opts.tasksQueueOptions!.concurrency! | |
375f7504 JB |
1150 | ) |
1151 | } | |
1152 | ||
afc003b2 | 1153 | /** @inheritDoc */ |
7d91a8cd JB |
1154 | public async execute ( |
1155 | data?: Data, | |
1156 | name?: string, | |
6a3ecc50 | 1157 | transferList?: readonly TransferListItem[] |
7d91a8cd | 1158 | ): Promise<Response> { |
52b71763 | 1159 | return await new Promise<Response>((resolve, reject) => { |
15b176e0 | 1160 | if (!this.started) { |
47352846 | 1161 | reject(new Error('Cannot execute a task on not started pool')) |
9d2d0da1 | 1162 | return |
15b176e0 | 1163 | } |
711623b8 JB |
1164 | if (this.destroying) { |
1165 | reject(new Error('Cannot execute a task on destroying pool')) | |
1166 | return | |
1167 | } | |
7d91a8cd JB |
1168 | if (name != null && typeof name !== 'string') { |
1169 | reject(new TypeError('name argument must be a string')) | |
9d2d0da1 | 1170 | return |
7d91a8cd | 1171 | } |
90d7d101 JB |
1172 | if ( |
1173 | name != null && | |
1174 | typeof name === 'string' && | |
1175 | name.trim().length === 0 | |
1176 | ) { | |
f58b60b9 | 1177 | reject(new TypeError('name argument must not be an empty string')) |
9d2d0da1 | 1178 | return |
90d7d101 | 1179 | } |
b558f6b5 JB |
1180 | if (transferList != null && !Array.isArray(transferList)) { |
1181 | reject(new TypeError('transferList argument must be an array')) | |
9d2d0da1 | 1182 | return |
b558f6b5 JB |
1183 | } |
1184 | const timestamp = performance.now() | |
91041638 | 1185 | const workerNodeKey = this.chooseWorkerNode(name) |
501aea93 | 1186 | const task: Task<Data> = { |
52b71763 | 1187 | name: name ?? DEFAULT_TASK_NAME, |
52b71763 | 1188 | data: data ?? ({} as Data), |
95d1a734 | 1189 | priority: this.getWorkerNodeTaskFunctionPriority(workerNodeKey, name), |
91041638 JB |
1190 | strategy: this.getWorkerNodeTaskFunctionWorkerChoiceStrategy( |
1191 | workerNodeKey, | |
1192 | name | |
1193 | ), | |
7d91a8cd | 1194 | transferList, |
52b71763 | 1195 | timestamp, |
3a502712 | 1196 | taskId: randomUUID(), |
52b71763 | 1197 | } |
67f3f2d6 JB |
1198 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1199 | this.promiseResponseMap.set(task.taskId!, { | |
2e81254d JB |
1200 | resolve, |
1201 | reject, | |
f18fd12b JB |
1202 | workerNodeKey, |
1203 | ...(this.emitter != null && { | |
1204 | asyncResource: new AsyncResource('poolifier:task', { | |
1205 | triggerAsyncId: this.emitter.asyncId, | |
3a502712 JB |
1206 | requireManualDestroy: true, |
1207 | }), | |
1208 | }), | |
2e81254d | 1209 | }) |
52b71763 | 1210 | if ( |
4e377863 JB |
1211 | this.opts.enableTasksQueue === false || |
1212 | (this.opts.enableTasksQueue === true && | |
375f7504 | 1213 | this.shallExecuteTask(workerNodeKey)) |
52b71763 | 1214 | ) { |
501aea93 | 1215 | this.executeTask(workerNodeKey, task) |
4e377863 JB |
1216 | } else { |
1217 | this.enqueueTask(workerNodeKey, task) | |
52b71763 | 1218 | } |
2e81254d | 1219 | }) |
280c2a77 | 1220 | } |
c97c7edb | 1221 | |
60dc0a9c JB |
1222 | /** |
1223 | * Starts the minimum number of workers. | |
ec8ed549 | 1224 | * @param initWorkerNodeUsage - Whether to initialize the worker node usage or not. @defaultValue false |
60dc0a9c | 1225 | */ |
e0843544 | 1226 | private startMinimumNumberOfWorkers (initWorkerNodeUsage = false): void { |
b362a929 | 1227 | this.startingMinimumNumberOfWorkers = true |
60dc0a9c JB |
1228 | while ( |
1229 | this.workerNodes.reduce( | |
1230 | (accumulator, workerNode) => | |
1231 | !workerNode.info.dynamic ? accumulator + 1 : accumulator, | |
1232 | 0 | |
1233 | ) < this.minimumNumberOfWorkers | |
1234 | ) { | |
e0843544 JB |
1235 | const workerNodeKey = this.createAndSetupWorkerNode() |
1236 | initWorkerNodeUsage && | |
1237 | this.initWorkerNodeUsage(this.workerNodes[workerNodeKey]) | |
60dc0a9c | 1238 | } |
b362a929 | 1239 | this.startingMinimumNumberOfWorkers = false |
60dc0a9c JB |
1240 | } |
1241 | ||
47352846 JB |
1242 | /** @inheritdoc */ |
1243 | public start (): void { | |
711623b8 JB |
1244 | if (this.started) { |
1245 | throw new Error('Cannot start an already started pool') | |
1246 | } | |
1247 | if (this.starting) { | |
1248 | throw new Error('Cannot start an already starting pool') | |
1249 | } | |
1250 | if (this.destroying) { | |
1251 | throw new Error('Cannot start a destroying pool') | |
1252 | } | |
47352846 | 1253 | this.starting = true |
60dc0a9c | 1254 | this.startMinimumNumberOfWorkers() |
2008bccd | 1255 | this.startTimestamp = performance.now() |
47352846 JB |
1256 | this.starting = false |
1257 | this.started = true | |
1258 | } | |
1259 | ||
afc003b2 | 1260 | /** @inheritDoc */ |
c97c7edb | 1261 | public async destroy (): Promise<void> { |
711623b8 JB |
1262 | if (!this.started) { |
1263 | throw new Error('Cannot destroy an already destroyed pool') | |
1264 | } | |
1265 | if (this.starting) { | |
1266 | throw new Error('Cannot destroy an starting pool') | |
1267 | } | |
1268 | if (this.destroying) { | |
1269 | throw new Error('Cannot destroy an already destroying pool') | |
1270 | } | |
1271 | this.destroying = true | |
1fbcaa7c | 1272 | await Promise.all( |
533a8e22 | 1273 | this.workerNodes.map(async (_, workerNodeKey) => { |
aa9eede8 | 1274 | await this.destroyWorkerNode(workerNodeKey) |
1fbcaa7c JB |
1275 | }) |
1276 | ) | |
33e6bb4c | 1277 | this.emitter?.emit(PoolEvents.destroy, this.info) |
f80125ca | 1278 | this.emitter?.emitDestroy() |
55082af9 | 1279 | this.readyEventEmitted = false |
2008bccd | 1280 | delete this.startTimestamp |
711623b8 | 1281 | this.destroying = false |
15b176e0 | 1282 | this.started = false |
c97c7edb S |
1283 | } |
1284 | ||
26ce26ca | 1285 | private async sendKillMessageToWorker (workerNodeKey: number): Promise<void> { |
9edb9717 | 1286 | await new Promise<void>((resolve, reject) => { |
c63a35a0 | 1287 | if (this.workerNodes[workerNodeKey] == null) { |
ad3836ed | 1288 | resolve() |
85b2561d JB |
1289 | return |
1290 | } | |
ae036c3e JB |
1291 | const killMessageListener = (message: MessageValue<Response>): void => { |
1292 | this.checkMessageWorkerId(message) | |
1e3214b6 JB |
1293 | if (message.kill === 'success') { |
1294 | resolve() | |
1295 | } else if (message.kill === 'failure') { | |
72ae84a2 JB |
1296 | reject( |
1297 | new Error( | |
c63a35a0 | 1298 | `Kill message handling failed on worker ${message.workerId}` |
72ae84a2 JB |
1299 | ) |
1300 | ) | |
1e3214b6 | 1301 | } |
ae036c3e | 1302 | } |
51d9cfbd | 1303 | // FIXME: should be registered only once |
ae036c3e | 1304 | this.registerWorkerMessageListener(workerNodeKey, killMessageListener) |
72ae84a2 | 1305 | this.sendToWorker(workerNodeKey, { kill: true }) |
1e3214b6 | 1306 | }) |
1e3214b6 JB |
1307 | } |
1308 | ||
4a6952ff | 1309 | /** |
aa9eede8 | 1310 | * Terminates the worker node given its worker node key. |
aa9eede8 | 1311 | * @param workerNodeKey - The worker node key. |
4a6952ff | 1312 | */ |
07e0c9e5 JB |
1313 | protected async destroyWorkerNode (workerNodeKey: number): Promise<void> { |
1314 | this.flagWorkerNodeAsNotReady(workerNodeKey) | |
87347ea8 | 1315 | const flushedTasks = this.flushTasksQueue(workerNodeKey) |
07e0c9e5 | 1316 | const workerNode = this.workerNodes[workerNodeKey] |
32b141fd JB |
1317 | await waitWorkerNodeEvents( |
1318 | workerNode, | |
1319 | 'taskFinished', | |
1320 | flushedTasks, | |
1321 | this.opts.tasksQueueOptions?.tasksFinishedTimeout ?? | |
26ce26ca JB |
1322 | getDefaultTasksQueueOptions( |
1323 | this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers | |
1324 | ).tasksFinishedTimeout | |
32b141fd | 1325 | ) |
07e0c9e5 JB |
1326 | await this.sendKillMessageToWorker(workerNodeKey) |
1327 | await workerNode.terminate() | |
1328 | } | |
c97c7edb | 1329 | |
729c563d | 1330 | /** |
6677a3d3 JB |
1331 | * Setup hook to execute code before worker nodes are created in the abstract constructor. |
1332 | * Can be overridden. | |
729c563d | 1333 | */ |
280c2a77 | 1334 | protected setupHook (): void { |
965df41c | 1335 | /* Intentionally empty */ |
280c2a77 | 1336 | } |
c97c7edb | 1337 | |
729c563d | 1338 | /** |
5bec72fd | 1339 | * Returns whether the worker is the main worker or not. |
5bec72fd | 1340 | * @returns `true` if the worker is the main worker, `false` otherwise. |
280c2a77 S |
1341 | */ |
1342 | protected abstract isMain (): boolean | |
1343 | ||
1344 | /** | |
2e81254d | 1345 | * Hook executed before the worker task execution. |
bf9549ae | 1346 | * Can be overridden. |
f06e48d8 | 1347 | * @param workerNodeKey - The worker node key. |
1c6fe997 | 1348 | * @param task - The task to execute. |
729c563d | 1349 | */ |
1c6fe997 JB |
1350 | protected beforeTaskExecutionHook ( |
1351 | workerNodeKey: number, | |
1352 | task: Task<Data> | |
1353 | ): void { | |
efabc98d | 1354 | if (this.workerNodes[workerNodeKey]?.usage != null) { |
94407def JB |
1355 | const workerUsage = this.workerNodes[workerNodeKey].usage |
1356 | ++workerUsage.tasks.executing | |
c329fd41 | 1357 | updateWaitTimeWorkerUsage( |
bcfb06ce | 1358 | this.workerChoiceStrategiesContext, |
c329fd41 JB |
1359 | workerUsage, |
1360 | task | |
1361 | ) | |
94407def JB |
1362 | } |
1363 | if ( | |
1364 | this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) && | |
67f3f2d6 JB |
1365 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1366 | this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(task.name!) != | |
1367 | null | |
94407def | 1368 | ) { |
67f3f2d6 | 1369 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
db0e38ee | 1370 | const taskFunctionWorkerUsage = this.workerNodes[ |
b558f6b5 | 1371 | workerNodeKey |
67f3f2d6 JB |
1372 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1373 | ].getTaskFunctionWorkerUsage(task.name!)! | |
5623b8d5 | 1374 | ++taskFunctionWorkerUsage.tasks.executing |
c329fd41 | 1375 | updateWaitTimeWorkerUsage( |
bcfb06ce | 1376 | this.workerChoiceStrategiesContext, |
c329fd41 JB |
1377 | taskFunctionWorkerUsage, |
1378 | task | |
1379 | ) | |
b558f6b5 | 1380 | } |
c97c7edb S |
1381 | } |
1382 | ||
c01733f1 | 1383 | /** |
2e81254d | 1384 | * Hook executed after the worker task execution. |
bf9549ae | 1385 | * Can be overridden. |
501aea93 | 1386 | * @param workerNodeKey - The worker node key. |
38e795c1 | 1387 | * @param message - The received message. |
c01733f1 | 1388 | */ |
2e81254d | 1389 | protected afterTaskExecutionHook ( |
501aea93 | 1390 | workerNodeKey: number, |
2740a743 | 1391 | message: MessageValue<Response> |
bf9549ae | 1392 | ): void { |
9a55fa8c | 1393 | let needWorkerChoiceStrategiesUpdate = false |
efabc98d | 1394 | if (this.workerNodes[workerNodeKey]?.usage != null) { |
94407def | 1395 | const workerUsage = this.workerNodes[workerNodeKey].usage |
c329fd41 JB |
1396 | updateTaskStatisticsWorkerUsage(workerUsage, message) |
1397 | updateRunTimeWorkerUsage( | |
bcfb06ce | 1398 | this.workerChoiceStrategiesContext, |
c329fd41 JB |
1399 | workerUsage, |
1400 | message | |
1401 | ) | |
1402 | updateEluWorkerUsage( | |
bcfb06ce | 1403 | this.workerChoiceStrategiesContext, |
c329fd41 JB |
1404 | workerUsage, |
1405 | message | |
1406 | ) | |
9a55fa8c | 1407 | needWorkerChoiceStrategiesUpdate = true |
94407def JB |
1408 | } |
1409 | if ( | |
1410 | this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) && | |
1411 | this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage( | |
67f3f2d6 JB |
1412 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1413 | message.taskPerformance!.name | |
94407def JB |
1414 | ) != null |
1415 | ) { | |
67f3f2d6 | 1416 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
db0e38ee | 1417 | const taskFunctionWorkerUsage = this.workerNodes[ |
b558f6b5 | 1418 | workerNodeKey |
67f3f2d6 JB |
1419 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1420 | ].getTaskFunctionWorkerUsage(message.taskPerformance!.name)! | |
c329fd41 JB |
1421 | updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage, message) |
1422 | updateRunTimeWorkerUsage( | |
bcfb06ce | 1423 | this.workerChoiceStrategiesContext, |
c329fd41 JB |
1424 | taskFunctionWorkerUsage, |
1425 | message | |
1426 | ) | |
1427 | updateEluWorkerUsage( | |
bcfb06ce | 1428 | this.workerChoiceStrategiesContext, |
c329fd41 JB |
1429 | taskFunctionWorkerUsage, |
1430 | message | |
1431 | ) | |
9a55fa8c | 1432 | needWorkerChoiceStrategiesUpdate = true |
c329fd41 | 1433 | } |
9a55fa8c | 1434 | if (needWorkerChoiceStrategiesUpdate) { |
bcfb06ce | 1435 | this.workerChoiceStrategiesContext?.update(workerNodeKey) |
b558f6b5 JB |
1436 | } |
1437 | } | |
1438 | ||
db0e38ee JB |
1439 | /** |
1440 | * Whether the worker node shall update its task function worker usage or not. | |
db0e38ee JB |
1441 | * @param workerNodeKey - The worker node key. |
1442 | * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise. | |
1443 | */ | |
1444 | private shallUpdateTaskFunctionWorkerUsage (workerNodeKey: number): boolean { | |
a5d15204 | 1445 | const workerInfo = this.getWorkerInfo(workerNodeKey) |
b558f6b5 | 1446 | return ( |
1851fed0 | 1447 | workerInfo != null && |
31847469 JB |
1448 | Array.isArray(workerInfo.taskFunctionsProperties) && |
1449 | workerInfo.taskFunctionsProperties.length > 2 | |
b558f6b5 | 1450 | ) |
f1c06930 JB |
1451 | } |
1452 | ||
280c2a77 | 1453 | /** |
91041638 | 1454 | * Chooses a worker node for the next task. |
91041638 | 1455 | * @param name - The task function name. |
db89e3bc | 1456 | * @returns The chosen worker node key. |
280c2a77 | 1457 | */ |
91041638 | 1458 | private chooseWorkerNode (name?: string): number { |
930dcf12 | 1459 | if (this.shallCreateDynamicWorker()) { |
aa9eede8 | 1460 | const workerNodeKey = this.createAndSetupDynamicWorkerNode() |
6c6afb84 | 1461 | if ( |
bcfb06ce JB |
1462 | this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerUsage === |
1463 | true | |
6c6afb84 | 1464 | ) { |
aa9eede8 | 1465 | return workerNodeKey |
6c6afb84 | 1466 | } |
17393ac8 | 1467 | } |
c63a35a0 | 1468 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
91041638 JB |
1469 | return this.workerChoiceStrategiesContext!.execute( |
1470 | this.getTaskFunctionWorkerChoiceStrategy(name) | |
1471 | ) | |
930dcf12 JB |
1472 | } |
1473 | ||
6c6afb84 JB |
1474 | /** |
1475 | * Conditions for dynamic worker creation. | |
6c6afb84 JB |
1476 | * @returns Whether to create a dynamic worker or not. |
1477 | */ | |
9d9fb7b6 | 1478 | protected abstract shallCreateDynamicWorker (): boolean |
c97c7edb | 1479 | |
280c2a77 | 1480 | /** |
aa9eede8 | 1481 | * Sends a message to worker given its worker node key. |
aa9eede8 | 1482 | * @param workerNodeKey - The worker node key. |
38e795c1 | 1483 | * @param message - The message. |
7d91a8cd | 1484 | * @param transferList - The optional array of transferable objects. |
280c2a77 S |
1485 | */ |
1486 | protected abstract sendToWorker ( | |
aa9eede8 | 1487 | workerNodeKey: number, |
7d91a8cd | 1488 | message: MessageValue<Data>, |
6a3ecc50 | 1489 | transferList?: readonly TransferListItem[] |
280c2a77 S |
1490 | ): void |
1491 | ||
e0843544 JB |
1492 | /** |
1493 | * Initializes the worker node usage with sensible default values gathered during runtime. | |
e0843544 JB |
1494 | * @param workerNode - The worker node. |
1495 | */ | |
1496 | private initWorkerNodeUsage (workerNode: IWorkerNode<Worker, Data>): void { | |
1497 | if ( | |
1498 | this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements() | |
1499 | .runTime.aggregate === true | |
1500 | ) { | |
1501 | workerNode.usage.runTime.aggregate = min( | |
1502 | ...this.workerNodes.map( | |
80115618 JB |
1503 | workerNode => |
1504 | workerNode.usage.runTime.aggregate ?? Number.POSITIVE_INFINITY | |
e0843544 JB |
1505 | ) |
1506 | ) | |
1507 | } | |
1508 | if ( | |
1509 | this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements() | |
1510 | .waitTime.aggregate === true | |
1511 | ) { | |
1512 | workerNode.usage.waitTime.aggregate = min( | |
1513 | ...this.workerNodes.map( | |
80115618 JB |
1514 | workerNode => |
1515 | workerNode.usage.waitTime.aggregate ?? Number.POSITIVE_INFINITY | |
e0843544 JB |
1516 | ) |
1517 | ) | |
1518 | } | |
1519 | if ( | |
1520 | this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().elu | |
1521 | .aggregate === true | |
1522 | ) { | |
1523 | workerNode.usage.elu.active.aggregate = min( | |
1524 | ...this.workerNodes.map( | |
80115618 JB |
1525 | workerNode => |
1526 | workerNode.usage.elu.active.aggregate ?? Number.POSITIVE_INFINITY | |
e0843544 JB |
1527 | ) |
1528 | ) | |
1529 | } | |
1530 | } | |
1531 | ||
4a6952ff | 1532 | /** |
aa9eede8 | 1533 | * Creates a new, completely set up worker node. |
aa9eede8 | 1534 | * @returns New, completely set up worker node key. |
4a6952ff | 1535 | */ |
aa9eede8 | 1536 | protected createAndSetupWorkerNode (): number { |
c3719753 JB |
1537 | const workerNode = this.createWorkerNode() |
1538 | workerNode.registerWorkerEventHandler( | |
1539 | 'online', | |
1540 | this.opts.onlineHandler ?? EMPTY_FUNCTION | |
1541 | ) | |
1542 | workerNode.registerWorkerEventHandler( | |
1543 | 'message', | |
1544 | this.opts.messageHandler ?? EMPTY_FUNCTION | |
1545 | ) | |
1546 | workerNode.registerWorkerEventHandler( | |
1547 | 'error', | |
1548 | this.opts.errorHandler ?? EMPTY_FUNCTION | |
1549 | ) | |
b271fce0 | 1550 | workerNode.registerOnceWorkerEventHandler('error', (error: Error) => { |
07e0c9e5 | 1551 | workerNode.info.ready = false |
2a69b8c5 | 1552 | this.emitter?.emit(PoolEvents.error, error) |
15b176e0 | 1553 | if ( |
b6bfca01 | 1554 | this.started && |
711623b8 | 1555 | !this.destroying && |
9b38ab2d | 1556 | this.opts.restartWorkerOnError === true |
15b176e0 | 1557 | ) { |
07e0c9e5 | 1558 | if (workerNode.info.dynamic) { |
aa9eede8 | 1559 | this.createAndSetupDynamicWorkerNode() |
b362a929 | 1560 | } else if (!this.startingMinimumNumberOfWorkers) { |
e0843544 | 1561 | this.startMinimumNumberOfWorkers(true) |
8a1260a3 | 1562 | } |
5baee0d7 | 1563 | } |
3c9123c7 JB |
1564 | if ( |
1565 | this.started && | |
1566 | !this.destroying && | |
1567 | this.opts.enableTasksQueue === true | |
1568 | ) { | |
9974369e | 1569 | this.redistributeQueuedTasks(this.workerNodes.indexOf(workerNode)) |
19dbc45b | 1570 | } |
07f6f7b1 | 1571 | workerNode?.terminate().catch((error: unknown) => { |
07e0c9e5 JB |
1572 | this.emitter?.emit(PoolEvents.error, error) |
1573 | }) | |
5baee0d7 | 1574 | }) |
c3719753 JB |
1575 | workerNode.registerWorkerEventHandler( |
1576 | 'exit', | |
1577 | this.opts.exitHandler ?? EMPTY_FUNCTION | |
1578 | ) | |
1579 | workerNode.registerOnceWorkerEventHandler('exit', () => { | |
9974369e | 1580 | this.removeWorkerNode(workerNode) |
b362a929 JB |
1581 | if ( |
1582 | this.started && | |
1583 | !this.startingMinimumNumberOfWorkers && | |
1584 | !this.destroying | |
1585 | ) { | |
e0843544 | 1586 | this.startMinimumNumberOfWorkers(true) |
60dc0a9c | 1587 | } |
a974afa6 | 1588 | }) |
c3719753 | 1589 | const workerNodeKey = this.addWorkerNode(workerNode) |
aa9eede8 | 1590 | this.afterWorkerNodeSetup(workerNodeKey) |
aa9eede8 | 1591 | return workerNodeKey |
c97c7edb | 1592 | } |
be0676b3 | 1593 | |
930dcf12 | 1594 | /** |
aa9eede8 | 1595 | * Creates a new, completely set up dynamic worker node. |
aa9eede8 | 1596 | * @returns New, completely set up dynamic worker node key. |
930dcf12 | 1597 | */ |
aa9eede8 JB |
1598 | protected createAndSetupDynamicWorkerNode (): number { |
1599 | const workerNodeKey = this.createAndSetupWorkerNode() | |
041dc05b | 1600 | this.registerWorkerMessageListener(workerNodeKey, message => { |
4d159167 | 1601 | this.checkMessageWorkerId(message) |
aa9eede8 JB |
1602 | const localWorkerNodeKey = this.getWorkerNodeKeyByWorkerId( |
1603 | message.workerId | |
aad6fb64 | 1604 | ) |
152e87a8 | 1605 | const workerInfo = this.getWorkerInfo(localWorkerNodeKey) |
2b6b412f | 1606 | const workerUsage = this.workerNodes[localWorkerNodeKey]?.usage |
81c02522 | 1607 | // Kill message received from worker |
930dcf12 JB |
1608 | if ( |
1609 | isKillBehavior(KillBehaviors.HARD, message.kill) || | |
1e3214b6 | 1610 | (isKillBehavior(KillBehaviors.SOFT, message.kill) && |
7b56f532 | 1611 | ((this.opts.enableTasksQueue === false && |
aa9eede8 | 1612 | workerUsage.tasks.executing === 0) || |
7b56f532 | 1613 | (this.opts.enableTasksQueue === true && |
152e87a8 JB |
1614 | workerInfo != null && |
1615 | !workerInfo.stealing && | |
aa9eede8 JB |
1616 | workerUsage.tasks.executing === 0 && |
1617 | this.tasksQueueSize(localWorkerNodeKey) === 0))) | |
930dcf12 | 1618 | ) { |
f3827d5d | 1619 | // Flag the worker node as not ready immediately |
ae3ab61d | 1620 | this.flagWorkerNodeAsNotReady(localWorkerNodeKey) |
07f6f7b1 | 1621 | this.destroyWorkerNode(localWorkerNodeKey).catch((error: unknown) => { |
5270d253 JB |
1622 | this.emitter?.emit(PoolEvents.error, error) |
1623 | }) | |
930dcf12 JB |
1624 | } |
1625 | }) | |
aa9eede8 | 1626 | this.sendToWorker(workerNodeKey, { |
3a502712 | 1627 | checkActive: true, |
21f710aa | 1628 | }) |
72ae84a2 | 1629 | if (this.taskFunctions.size > 0) { |
31847469 | 1630 | for (const [taskFunctionName, taskFunctionObject] of this.taskFunctions) { |
72ae84a2 JB |
1631 | this.sendTaskFunctionOperationToWorker(workerNodeKey, { |
1632 | taskFunctionOperation: 'add', | |
31847469 JB |
1633 | taskFunctionProperties: buildTaskFunctionProperties( |
1634 | taskFunctionName, | |
1635 | taskFunctionObject | |
1636 | ), | |
3a502712 | 1637 | taskFunction: taskFunctionObject.taskFunction.toString(), |
07f6f7b1 | 1638 | }).catch((error: unknown) => { |
72ae84a2 JB |
1639 | this.emitter?.emit(PoolEvents.error, error) |
1640 | }) | |
1641 | } | |
1642 | } | |
e44639e9 JB |
1643 | const workerNode = this.workerNodes[workerNodeKey] |
1644 | workerNode.info.dynamic = true | |
b1aae695 | 1645 | if ( |
bcfb06ce JB |
1646 | this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerReady === |
1647 | true || | |
1648 | this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerUsage === | |
1649 | true | |
b1aae695 | 1650 | ) { |
e44639e9 | 1651 | workerNode.info.ready = true |
b5e113f6 | 1652 | } |
e0843544 | 1653 | this.initWorkerNodeUsage(workerNode) |
33e6bb4c | 1654 | this.checkAndEmitDynamicWorkerCreationEvents() |
aa9eede8 | 1655 | return workerNodeKey |
930dcf12 JB |
1656 | } |
1657 | ||
a2ed5053 | 1658 | /** |
aa9eede8 | 1659 | * Registers a listener callback on the worker given its worker node key. |
aa9eede8 | 1660 | * @param workerNodeKey - The worker node key. |
a2ed5053 JB |
1661 | * @param listener - The message listener callback. |
1662 | */ | |
85aeb3f3 JB |
1663 | protected abstract registerWorkerMessageListener< |
1664 | Message extends Data | Response | |
aa9eede8 JB |
1665 | >( |
1666 | workerNodeKey: number, | |
1667 | listener: (message: MessageValue<Message>) => void | |
1668 | ): void | |
a2ed5053 | 1669 | |
ae036c3e JB |
1670 | /** |
1671 | * Registers once a listener callback on the worker given its worker node key. | |
ae036c3e JB |
1672 | * @param workerNodeKey - The worker node key. |
1673 | * @param listener - The message listener callback. | |
1674 | */ | |
1675 | protected abstract registerOnceWorkerMessageListener< | |
1676 | Message extends Data | Response | |
1677 | >( | |
1678 | workerNodeKey: number, | |
1679 | listener: (message: MessageValue<Message>) => void | |
1680 | ): void | |
1681 | ||
1682 | /** | |
1683 | * Deregisters a listener callback on the worker given its worker node key. | |
ae036c3e JB |
1684 | * @param workerNodeKey - The worker node key. |
1685 | * @param listener - The message listener callback. | |
1686 | */ | |
1687 | protected abstract deregisterWorkerMessageListener< | |
1688 | Message extends Data | Response | |
1689 | >( | |
1690 | workerNodeKey: number, | |
1691 | listener: (message: MessageValue<Message>) => void | |
1692 | ): void | |
1693 | ||
a2ed5053 | 1694 | /** |
aa9eede8 | 1695 | * Method hooked up after a worker node has been newly created. |
a2ed5053 | 1696 | * Can be overridden. |
aa9eede8 | 1697 | * @param workerNodeKey - The newly created worker node key. |
a2ed5053 | 1698 | */ |
aa9eede8 | 1699 | protected afterWorkerNodeSetup (workerNodeKey: number): void { |
a2ed5053 | 1700 | // Listen to worker messages. |
fcd39179 JB |
1701 | this.registerWorkerMessageListener( |
1702 | workerNodeKey, | |
3a776b6d | 1703 | this.workerMessageListener |
fcd39179 | 1704 | ) |
85aeb3f3 | 1705 | // Send the startup message to worker. |
aa9eede8 | 1706 | this.sendStartupMessageToWorker(workerNodeKey) |
9edb9717 JB |
1707 | // Send the statistics message to worker. |
1708 | this.sendStatisticsMessageToWorker(workerNodeKey) | |
72695f86 | 1709 | if (this.opts.enableTasksQueue === true) { |
dbd73092 | 1710 | if (this.opts.tasksQueueOptions?.taskStealing === true) { |
e1c2dba7 | 1711 | this.workerNodes[workerNodeKey].on( |
e44639e9 JB |
1712 | 'idle', |
1713 | this.handleWorkerNodeIdleEvent | |
9f95d5eb | 1714 | ) |
47352846 JB |
1715 | } |
1716 | if (this.opts.tasksQueueOptions?.tasksStealingOnBackPressure === true) { | |
e1c2dba7 | 1717 | this.workerNodes[workerNodeKey].on( |
b5e75be8 | 1718 | 'backPressure', |
e44639e9 | 1719 | this.handleWorkerNodeBackPressureEvent |
9f95d5eb | 1720 | ) |
47352846 | 1721 | } |
72695f86 | 1722 | } |
d2c73f82 JB |
1723 | } |
1724 | ||
85aeb3f3 | 1725 | /** |
aa9eede8 | 1726 | * Sends the startup message to worker given its worker node key. |
aa9eede8 JB |
1727 | * @param workerNodeKey - The worker node key. |
1728 | */ | |
1729 | protected abstract sendStartupMessageToWorker (workerNodeKey: number): void | |
1730 | ||
1731 | /** | |
9edb9717 | 1732 | * Sends the statistics message to worker given its worker node key. |
aa9eede8 | 1733 | * @param workerNodeKey - The worker node key. |
85aeb3f3 | 1734 | */ |
9edb9717 | 1735 | private sendStatisticsMessageToWorker (workerNodeKey: number): void { |
aa9eede8 JB |
1736 | this.sendToWorker(workerNodeKey, { |
1737 | statistics: { | |
1738 | runTime: | |
bcfb06ce | 1739 | this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements() |
f4d0a470 | 1740 | .runTime.aggregate ?? false, |
c63a35a0 | 1741 | elu: |
bcfb06ce | 1742 | this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements() |
3a502712 JB |
1743 | .elu.aggregate ?? false, |
1744 | }, | |
aa9eede8 JB |
1745 | }) |
1746 | } | |
a2ed5053 | 1747 | |
5eb72b9e JB |
1748 | private cannotStealTask (): boolean { |
1749 | return this.workerNodes.length <= 1 || this.info.queuedTasks === 0 | |
1750 | } | |
1751 | ||
42c677c1 JB |
1752 | private handleTask (workerNodeKey: number, task: Task<Data>): void { |
1753 | if (this.shallExecuteTask(workerNodeKey)) { | |
1754 | this.executeTask(workerNodeKey, task) | |
1755 | } else { | |
1756 | this.enqueueTask(workerNodeKey, task) | |
1757 | } | |
1758 | } | |
1759 | ||
2d1d3b2d JB |
1760 | private redistributeQueuedTasks (sourceWorkerNodeKey: number): void { |
1761 | if (sourceWorkerNodeKey === -1 || this.cannotStealTask()) { | |
cb71d660 JB |
1762 | return |
1763 | } | |
2d1d3b2d | 1764 | while (this.tasksQueueSize(sourceWorkerNodeKey) > 0) { |
f201a0cd JB |
1765 | const destinationWorkerNodeKey = this.workerNodes.reduce( |
1766 | (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => { | |
2d1d3b2d JB |
1767 | return sourceWorkerNodeKey !== workerNodeKey && |
1768 | workerNode.info.ready && | |
852ed3e4 JB |
1769 | workerNode.usage.tasks.queued < |
1770 | workerNodes[minWorkerNodeKey].usage.tasks.queued | |
f201a0cd JB |
1771 | ? workerNodeKey |
1772 | : minWorkerNodeKey | |
1773 | }, | |
1774 | 0 | |
1775 | ) | |
42c677c1 JB |
1776 | this.handleTask( |
1777 | destinationWorkerNodeKey, | |
67f3f2d6 | 1778 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2d1d3b2d | 1779 | this.dequeueTask(sourceWorkerNodeKey)! |
42c677c1 | 1780 | ) |
dd951876 JB |
1781 | } |
1782 | } | |
1783 | ||
b1838604 JB |
1784 | private updateTaskStolenStatisticsWorkerUsage ( |
1785 | workerNodeKey: number, | |
b1838604 JB |
1786 | taskName: string |
1787 | ): void { | |
1a880eca | 1788 | const workerNode = this.workerNodes[workerNodeKey] |
efabc98d | 1789 | if (workerNode?.usage != null) { |
b1838604 JB |
1790 | ++workerNode.usage.tasks.stolen |
1791 | } | |
1792 | if ( | |
1793 | this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) && | |
1794 | workerNode.getTaskFunctionWorkerUsage(taskName) != null | |
1795 | ) { | |
8bd0556f JB |
1796 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1797 | ++workerNode.getTaskFunctionWorkerUsage(taskName)!.tasks.stolen | |
b1838604 JB |
1798 | } |
1799 | } | |
1800 | ||
463226a4 | 1801 | private updateTaskSequentiallyStolenStatisticsWorkerUsage ( |
2d1d3b2d JB |
1802 | workerNodeKey: number, |
1803 | taskName: string, | |
8bd0556f | 1804 | previousTaskName?: string |
463226a4 JB |
1805 | ): void { |
1806 | const workerNode = this.workerNodes[workerNodeKey] | |
7aa2f476 | 1807 | if (workerNode?.usage != null) { |
463226a4 JB |
1808 | ++workerNode.usage.tasks.sequentiallyStolen |
1809 | } | |
1810 | if ( | |
1811 | this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) && | |
3b33cd2a JB |
1812 | workerNode.getTaskFunctionWorkerUsage(taskName) != null |
1813 | ) { | |
1814 | const taskFunctionWorkerUsage = | |
1815 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
1816 | workerNode.getTaskFunctionWorkerUsage(taskName)! | |
1817 | if ( | |
1818 | taskFunctionWorkerUsage.tasks.sequentiallyStolen === 0 || | |
8bd0556f JB |
1819 | (previousTaskName != null && |
1820 | previousTaskName === taskName && | |
3b33cd2a JB |
1821 | taskFunctionWorkerUsage.tasks.sequentiallyStolen > 0) |
1822 | ) { | |
1823 | ++taskFunctionWorkerUsage.tasks.sequentiallyStolen | |
1824 | } else if (taskFunctionWorkerUsage.tasks.sequentiallyStolen > 0) { | |
1825 | taskFunctionWorkerUsage.tasks.sequentiallyStolen = 0 | |
1826 | } | |
463226a4 JB |
1827 | } |
1828 | } | |
1829 | ||
1830 | private resetTaskSequentiallyStolenStatisticsWorkerUsage ( | |
2d1d3b2d JB |
1831 | workerNodeKey: number, |
1832 | taskName: string | |
463226a4 JB |
1833 | ): void { |
1834 | const workerNode = this.workerNodes[workerNodeKey] | |
efabc98d | 1835 | if (workerNode?.usage != null) { |
463226a4 JB |
1836 | workerNode.usage.tasks.sequentiallyStolen = 0 |
1837 | } | |
1838 | if ( | |
1839 | this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) && | |
1840 | workerNode.getTaskFunctionWorkerUsage(taskName) != null | |
1841 | ) { | |
8bd0556f JB |
1842 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1843 | workerNode.getTaskFunctionWorkerUsage( | |
1844 | taskName | |
1845 | )!.tasks.sequentiallyStolen = 0 | |
463226a4 JB |
1846 | } |
1847 | } | |
1848 | ||
e44639e9 | 1849 | private readonly handleWorkerNodeIdleEvent = ( |
e1c2dba7 | 1850 | eventDetail: WorkerNodeEventDetail, |
463226a4 | 1851 | previousStolenTask?: Task<Data> |
9f95d5eb | 1852 | ): void => { |
e1c2dba7 | 1853 | const { workerNodeKey } = eventDetail |
463226a4 JB |
1854 | if (workerNodeKey == null) { |
1855 | throw new Error( | |
c63a35a0 | 1856 | "WorkerNode event detail 'workerNodeKey' property must be defined" |
463226a4 JB |
1857 | ) |
1858 | } | |
c63a35a0 | 1859 | const workerInfo = this.getWorkerInfo(workerNodeKey) |
010f158c JB |
1860 | if (workerInfo == null) { |
1861 | throw new Error( | |
1862 | `Worker node with key '${workerNodeKey}' not found in pool` | |
1863 | ) | |
1864 | } | |
5eb72b9e JB |
1865 | if ( |
1866 | this.cannotStealTask() || | |
c63a35a0 JB |
1867 | (this.info.stealingWorkerNodes ?? 0) > |
1868 | Math.floor(this.workerNodes.length / 2) | |
5eb72b9e | 1869 | ) { |
010f158c | 1870 | if (previousStolenTask != null) { |
c63a35a0 | 1871 | workerInfo.stealing = false |
2d1d3b2d JB |
1872 | this.resetTaskSequentiallyStolenStatisticsWorkerUsage( |
1873 | workerNodeKey, | |
1874 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
1875 | previousStolenTask.name! | |
1876 | ) | |
5eb72b9e JB |
1877 | } |
1878 | return | |
1879 | } | |
463226a4 JB |
1880 | const workerNodeTasksUsage = this.workerNodes[workerNodeKey].usage.tasks |
1881 | if ( | |
1882 | previousStolenTask != null && | |
463226a4 JB |
1883 | (workerNodeTasksUsage.executing > 0 || |
1884 | this.tasksQueueSize(workerNodeKey) > 0) | |
1885 | ) { | |
c63a35a0 | 1886 | workerInfo.stealing = false |
2d1d3b2d JB |
1887 | this.resetTaskSequentiallyStolenStatisticsWorkerUsage( |
1888 | workerNodeKey, | |
1889 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
1890 | previousStolenTask.name! | |
1891 | ) | |
463226a4 JB |
1892 | return |
1893 | } | |
c63a35a0 | 1894 | workerInfo.stealing = true |
463226a4 | 1895 | const stolenTask = this.workerNodeStealTask(workerNodeKey) |
8bd0556f | 1896 | if (stolenTask != null) { |
2d1d3b2d JB |
1897 | this.updateTaskSequentiallyStolenStatisticsWorkerUsage( |
1898 | workerNodeKey, | |
67f3f2d6 | 1899 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2d1d3b2d | 1900 | stolenTask.name!, |
8bd0556f | 1901 | previousStolenTask?.name |
2d1d3b2d | 1902 | ) |
f1f77f45 | 1903 | } |
463226a4 JB |
1904 | sleep(exponentialDelay(workerNodeTasksUsage.sequentiallyStolen)) |
1905 | .then(() => { | |
e44639e9 | 1906 | this.handleWorkerNodeIdleEvent(eventDetail, stolenTask) |
463226a4 JB |
1907 | return undefined |
1908 | }) | |
07f6f7b1 | 1909 | .catch((error: unknown) => { |
2e8cfbb7 JB |
1910 | this.emitter?.emit(PoolEvents.error, error) |
1911 | }) | |
463226a4 JB |
1912 | } |
1913 | ||
1914 | private readonly workerNodeStealTask = ( | |
1915 | workerNodeKey: number | |
1916 | ): Task<Data> | undefined => { | |
dd951876 | 1917 | const workerNodes = this.workerNodes |
a6b3272b | 1918 | .slice() |
dd951876 JB |
1919 | .sort( |
1920 | (workerNodeA, workerNodeB) => | |
1921 | workerNodeB.usage.tasks.queued - workerNodeA.usage.tasks.queued | |
1922 | ) | |
f201a0cd | 1923 | const sourceWorkerNode = workerNodes.find( |
463226a4 JB |
1924 | (sourceWorkerNode, sourceWorkerNodeKey) => |
1925 | sourceWorkerNode.info.ready && | |
5eb72b9e | 1926 | !sourceWorkerNode.info.stealing && |
463226a4 JB |
1927 | sourceWorkerNodeKey !== workerNodeKey && |
1928 | sourceWorkerNode.usage.tasks.queued > 0 | |
f201a0cd JB |
1929 | ) |
1930 | if (sourceWorkerNode != null) { | |
67f3f2d6 | 1931 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2eee7220 | 1932 | const task = sourceWorkerNode.dequeueLastPrioritizedTask()! |
42c677c1 | 1933 | this.handleTask(workerNodeKey, task) |
67f3f2d6 JB |
1934 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1935 | this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey, task.name!) | |
463226a4 | 1936 | return task |
72695f86 JB |
1937 | } |
1938 | } | |
1939 | ||
e44639e9 | 1940 | private readonly handleWorkerNodeBackPressureEvent = ( |
e1c2dba7 | 1941 | eventDetail: WorkerNodeEventDetail |
9f95d5eb | 1942 | ): void => { |
5eb72b9e JB |
1943 | if ( |
1944 | this.cannotStealTask() || | |
2eee7220 | 1945 | this.hasBackPressure() || |
c63a35a0 JB |
1946 | (this.info.stealingWorkerNodes ?? 0) > |
1947 | Math.floor(this.workerNodes.length / 2) | |
5eb72b9e | 1948 | ) { |
cb71d660 JB |
1949 | return |
1950 | } | |
f778c355 | 1951 | const sizeOffset = 1 |
67f3f2d6 JB |
1952 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1953 | if (this.opts.tasksQueueOptions!.size! <= sizeOffset) { | |
68dbcdc0 JB |
1954 | return |
1955 | } | |
7b2c5627 | 1956 | const { workerId } = eventDetail |
72695f86 | 1957 | const sourceWorkerNode = |
b5e75be8 | 1958 | this.workerNodes[this.getWorkerNodeKeyByWorkerId(workerId)] |
72695f86 | 1959 | const workerNodes = this.workerNodes |
a6b3272b | 1960 | .slice() |
72695f86 JB |
1961 | .sort( |
1962 | (workerNodeA, workerNodeB) => | |
1963 | workerNodeA.usage.tasks.queued - workerNodeB.usage.tasks.queued | |
1964 | ) | |
1965 | for (const [workerNodeKey, workerNode] of workerNodes.entries()) { | |
1966 | if ( | |
0bc68267 | 1967 | sourceWorkerNode.usage.tasks.queued > 0 && |
a6b3272b | 1968 | workerNode.info.ready && |
5eb72b9e | 1969 | !workerNode.info.stealing && |
b5e75be8 | 1970 | workerNode.info.id !== workerId && |
0bc68267 | 1971 | workerNode.usage.tasks.queued < |
67f3f2d6 JB |
1972 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1973 | this.opts.tasksQueueOptions!.size! - sizeOffset | |
72695f86 | 1974 | ) { |
c63a35a0 | 1975 | const workerInfo = this.getWorkerInfo(workerNodeKey) |
1851fed0 JB |
1976 | if (workerInfo == null) { |
1977 | throw new Error( | |
1978 | `Worker node with key '${workerNodeKey}' not found in pool` | |
1979 | ) | |
1980 | } | |
c63a35a0 | 1981 | workerInfo.stealing = true |
67f3f2d6 | 1982 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2eee7220 | 1983 | const task = sourceWorkerNode.dequeueLastPrioritizedTask()! |
42c677c1 | 1984 | this.handleTask(workerNodeKey, task) |
67f3f2d6 JB |
1985 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
1986 | this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey, task.name!) | |
c63a35a0 | 1987 | workerInfo.stealing = false |
10ecf8fd | 1988 | } |
a2ed5053 JB |
1989 | } |
1990 | } | |
1991 | ||
fcfc3353 JB |
1992 | private setTasksQueuePriority (workerNodeKey: number): void { |
1993 | this.workerNodes[workerNodeKey].setTasksQueuePriority( | |
1994 | this.getTasksQueuePriority() | |
1995 | ) | |
1996 | } | |
1997 | ||
be0676b3 | 1998 | /** |
fcd39179 | 1999 | * This method is the message listener registered on each worker. |
ec8ed549 | 2000 | * @param message - The message received from the worker. |
be0676b3 | 2001 | */ |
3a776b6d JB |
2002 | protected readonly workerMessageListener = ( |
2003 | message: MessageValue<Response> | |
2004 | ): void => { | |
fcd39179 | 2005 | this.checkMessageWorkerId(message) |
31847469 JB |
2006 | const { workerId, ready, taskId, taskFunctionsProperties } = message |
2007 | if (ready != null && taskFunctionsProperties != null) { | |
fcd39179 JB |
2008 | // Worker ready response received from worker |
2009 | this.handleWorkerReadyResponse(message) | |
31847469 JB |
2010 | } else if (taskFunctionsProperties != null) { |
2011 | // Task function properties message received from worker | |
9a55fa8c JB |
2012 | const workerNodeKey = this.getWorkerNodeKeyByWorkerId(workerId) |
2013 | const workerInfo = this.getWorkerInfo(workerNodeKey) | |
1851fed0 | 2014 | if (workerInfo != null) { |
31847469 | 2015 | workerInfo.taskFunctionsProperties = taskFunctionsProperties |
9a55fa8c | 2016 | this.sendStatisticsMessageToWorker(workerNodeKey) |
fcfc3353 | 2017 | this.setTasksQueuePriority(workerNodeKey) |
1851fed0 | 2018 | } |
31847469 JB |
2019 | } else if (taskId != null) { |
2020 | // Task execution response received from worker | |
2021 | this.handleTaskExecutionResponse(message) | |
6b272951 JB |
2022 | } |
2023 | } | |
2024 | ||
8e8d9101 JB |
2025 | private checkAndEmitReadyEvent (): void { |
2026 | if (!this.readyEventEmitted && this.ready) { | |
2027 | this.emitter?.emit(PoolEvents.ready, this.info) | |
2028 | this.readyEventEmitted = true | |
2029 | } | |
2030 | } | |
2031 | ||
10e2aa7e | 2032 | private handleWorkerReadyResponse (message: MessageValue<Response>): void { |
31847469 | 2033 | const { workerId, ready, taskFunctionsProperties } = message |
e44639e9 | 2034 | if (ready == null || !ready) { |
c63a35a0 | 2035 | throw new Error(`Worker ${workerId} failed to initialize`) |
f05ed93c | 2036 | } |
9a55fa8c JB |
2037 | const workerNodeKey = this.getWorkerNodeKeyByWorkerId(workerId) |
2038 | const workerNode = this.workerNodes[workerNodeKey] | |
e44639e9 | 2039 | workerNode.info.ready = ready |
31847469 | 2040 | workerNode.info.taskFunctionsProperties = taskFunctionsProperties |
9a55fa8c | 2041 | this.sendStatisticsMessageToWorker(workerNodeKey) |
fcfc3353 | 2042 | this.setTasksQueuePriority(workerNodeKey) |
8e8d9101 | 2043 | this.checkAndEmitReadyEvent() |
6b272951 JB |
2044 | } |
2045 | ||
2046 | private handleTaskExecutionResponse (message: MessageValue<Response>): void { | |
463226a4 | 2047 | const { workerId, taskId, workerError, data } = message |
67f3f2d6 JB |
2048 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2049 | const promiseResponse = this.promiseResponseMap.get(taskId!) | |
6b272951 | 2050 | if (promiseResponse != null) { |
f18fd12b | 2051 | const { resolve, reject, workerNodeKey, asyncResource } = promiseResponse |
9b358e72 | 2052 | const workerNode = this.workerNodes[workerNodeKey] |
6703b9f4 JB |
2053 | if (workerError != null) { |
2054 | this.emitter?.emit(PoolEvents.taskError, workerError) | |
f18fd12b JB |
2055 | asyncResource != null |
2056 | ? asyncResource.runInAsyncScope( | |
2057 | reject, | |
2058 | this.emitter, | |
2059 | workerError.message | |
2060 | ) | |
2061 | : reject(workerError.message) | |
6b272951 | 2062 | } else { |
f18fd12b JB |
2063 | asyncResource != null |
2064 | ? asyncResource.runInAsyncScope(resolve, this.emitter, data) | |
2065 | : resolve(data as Response) | |
6b272951 | 2066 | } |
f18fd12b | 2067 | asyncResource?.emitDestroy() |
501aea93 | 2068 | this.afterTaskExecutionHook(workerNodeKey, message) |
67f3f2d6 JB |
2069 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2070 | this.promiseResponseMap.delete(taskId!) | |
cdaecaee | 2071 | workerNode?.emit('taskFinished', taskId) |
16d7e943 JB |
2072 | if ( |
2073 | this.opts.enableTasksQueue === true && | |
2074 | !this.destroying && | |
16d7e943 JB |
2075 | workerNode != null |
2076 | ) { | |
9b358e72 | 2077 | const workerNodeTasksUsage = workerNode.usage.tasks |
463226a4 JB |
2078 | if ( |
2079 | this.tasksQueueSize(workerNodeKey) > 0 && | |
2080 | workerNodeTasksUsage.executing < | |
67f3f2d6 JB |
2081 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2082 | this.opts.tasksQueueOptions!.concurrency! | |
463226a4 | 2083 | ) { |
67f3f2d6 JB |
2084 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2085 | this.executeTask(workerNodeKey, this.dequeueTask(workerNodeKey)!) | |
463226a4 JB |
2086 | } |
2087 | if ( | |
2088 | workerNodeTasksUsage.executing === 0 && | |
2089 | this.tasksQueueSize(workerNodeKey) === 0 && | |
2090 | workerNodeTasksUsage.sequentiallyStolen === 0 | |
2091 | ) { | |
e44639e9 | 2092 | workerNode.emit('idle', { |
7f0e1334 | 2093 | workerId, |
3a502712 | 2094 | workerNodeKey, |
e1c2dba7 | 2095 | }) |
463226a4 | 2096 | } |
be0676b3 APA |
2097 | } |
2098 | } | |
be0676b3 | 2099 | } |
7c0ba920 | 2100 | |
a1763c54 | 2101 | private checkAndEmitTaskExecutionEvents (): void { |
33e6bb4c JB |
2102 | if (this.busy) { |
2103 | this.emitter?.emit(PoolEvents.busy, this.info) | |
a1763c54 JB |
2104 | } |
2105 | } | |
2106 | ||
2107 | private checkAndEmitTaskQueuingEvents (): void { | |
2108 | if (this.hasBackPressure()) { | |
2109 | this.emitter?.emit(PoolEvents.backPressure, this.info) | |
164d950a JB |
2110 | } |
2111 | } | |
2112 | ||
d0878034 JB |
2113 | /** |
2114 | * Emits dynamic worker creation events. | |
2115 | */ | |
2116 | protected abstract checkAndEmitDynamicWorkerCreationEvents (): void | |
33e6bb4c | 2117 | |
8a1260a3 | 2118 | /** |
aa9eede8 | 2119 | * Gets the worker information given its worker node key. |
8a1260a3 | 2120 | * @param workerNodeKey - The worker node key. |
3f09ed9f | 2121 | * @returns The worker information. |
8a1260a3 | 2122 | */ |
1851fed0 JB |
2123 | protected getWorkerInfo (workerNodeKey: number): WorkerInfo | undefined { |
2124 | return this.workerNodes[workerNodeKey]?.info | |
e221309a JB |
2125 | } |
2126 | ||
fcfc3353 JB |
2127 | private getTasksQueuePriority (): boolean { |
2128 | return this.listTaskFunctionsProperties().some( | |
2129 | taskFunctionProperties => taskFunctionProperties.priority != null | |
2130 | ) | |
2131 | } | |
2132 | ||
a05c10de | 2133 | /** |
c3719753 | 2134 | * Creates a worker node. |
c3719753 | 2135 | * @returns The created worker node. |
ea7a90d3 | 2136 | */ |
c3719753 | 2137 | private createWorkerNode (): IWorkerNode<Worker, Data> { |
671d5154 | 2138 | const workerNode = new WorkerNode<Worker, Data>( |
c3719753 JB |
2139 | this.worker, |
2140 | this.filePath, | |
2141 | { | |
2142 | env: this.opts.env, | |
2143 | workerOptions: this.opts.workerOptions, | |
2144 | tasksQueueBackPressureSize: | |
32b141fd | 2145 | this.opts.tasksQueueOptions?.size ?? |
26ce26ca JB |
2146 | getDefaultTasksQueueOptions( |
2147 | this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers | |
95d1a734 | 2148 | ).size, |
fcfc3353 | 2149 | tasksQueueBucketSize: defaultBucketSize, |
3a502712 | 2150 | tasksQueuePriority: this.getTasksQueuePriority(), |
c3719753 | 2151 | } |
671d5154 | 2152 | ) |
b97d82d8 | 2153 | // Flag the worker node as ready at pool startup. |
d2c73f82 JB |
2154 | if (this.starting) { |
2155 | workerNode.info.ready = true | |
2156 | } | |
c3719753 JB |
2157 | return workerNode |
2158 | } | |
2159 | ||
2160 | /** | |
2161 | * Adds the given worker node in the pool worker nodes. | |
c3719753 JB |
2162 | * @param workerNode - The worker node. |
2163 | * @returns The added worker node key. | |
2164 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found. | |
2165 | */ | |
2166 | private addWorkerNode (workerNode: IWorkerNode<Worker, Data>): number { | |
aa9eede8 | 2167 | this.workerNodes.push(workerNode) |
c3719753 | 2168 | const workerNodeKey = this.workerNodes.indexOf(workerNode) |
aa9eede8 | 2169 | if (workerNodeKey === -1) { |
86ed0598 | 2170 | throw new Error('Worker added not found in worker nodes') |
aa9eede8 JB |
2171 | } |
2172 | return workerNodeKey | |
ea7a90d3 | 2173 | } |
c923ce56 | 2174 | |
8e8d9101 JB |
2175 | private checkAndEmitEmptyEvent (): void { |
2176 | if (this.empty) { | |
2177 | this.emitter?.emit(PoolEvents.empty, this.info) | |
2178 | this.readyEventEmitted = false | |
2179 | } | |
2180 | } | |
2181 | ||
51fe3d3c | 2182 | /** |
9974369e | 2183 | * Removes the worker node from the pool worker nodes. |
9974369e | 2184 | * @param workerNode - The worker node. |
51fe3d3c | 2185 | */ |
9974369e JB |
2186 | private removeWorkerNode (workerNode: IWorkerNode<Worker, Data>): void { |
2187 | const workerNodeKey = this.workerNodes.indexOf(workerNode) | |
1f68cede JB |
2188 | if (workerNodeKey !== -1) { |
2189 | this.workerNodes.splice(workerNodeKey, 1) | |
bcfb06ce | 2190 | this.workerChoiceStrategiesContext?.remove(workerNodeKey) |
1f68cede | 2191 | } |
8e8d9101 | 2192 | this.checkAndEmitEmptyEvent() |
51fe3d3c | 2193 | } |
adc3c320 | 2194 | |
ae3ab61d | 2195 | protected flagWorkerNodeAsNotReady (workerNodeKey: number): void { |
1851fed0 JB |
2196 | const workerInfo = this.getWorkerInfo(workerNodeKey) |
2197 | if (workerInfo != null) { | |
2198 | workerInfo.ready = false | |
2199 | } | |
ae3ab61d JB |
2200 | } |
2201 | ||
9e844245 JB |
2202 | private hasBackPressure (): boolean { |
2203 | return ( | |
2204 | this.opts.enableTasksQueue === true && | |
2205 | this.workerNodes.findIndex( | |
041dc05b | 2206 | workerNode => !workerNode.hasBackPressure() |
a1763c54 | 2207 | ) === -1 |
9e844245 | 2208 | ) |
e2b31e32 JB |
2209 | } |
2210 | ||
b0a4db63 | 2211 | /** |
aa9eede8 | 2212 | * Executes the given task on the worker given its worker node key. |
aa9eede8 | 2213 | * @param workerNodeKey - The worker node key. |
b0a4db63 JB |
2214 | * @param task - The task to execute. |
2215 | */ | |
2e81254d | 2216 | private executeTask (workerNodeKey: number, task: Task<Data>): void { |
1c6fe997 | 2217 | this.beforeTaskExecutionHook(workerNodeKey, task) |
bbfa38a2 | 2218 | this.sendToWorker(workerNodeKey, task, task.transferList) |
a1763c54 | 2219 | this.checkAndEmitTaskExecutionEvents() |
2e81254d JB |
2220 | } |
2221 | ||
f9f00b5f | 2222 | private enqueueTask (workerNodeKey: number, task: Task<Data>): number { |
a1763c54 JB |
2223 | const tasksQueueSize = this.workerNodes[workerNodeKey].enqueueTask(task) |
2224 | this.checkAndEmitTaskQueuingEvents() | |
2225 | return tasksQueueSize | |
adc3c320 JB |
2226 | } |
2227 | ||
0d4e88b3 JB |
2228 | private dequeueTask (workerNodeKey: number): Task<Data> | undefined { |
2229 | return this.workerNodes[workerNodeKey].dequeueTask() | |
adc3c320 JB |
2230 | } |
2231 | ||
416fd65c | 2232 | private tasksQueueSize (workerNodeKey: number): number { |
4b628b48 | 2233 | return this.workerNodes[workerNodeKey].tasksQueueSize() |
df593701 JB |
2234 | } |
2235 | ||
87347ea8 JB |
2236 | protected flushTasksQueue (workerNodeKey: number): number { |
2237 | let flushedTasks = 0 | |
920278a2 | 2238 | while (this.tasksQueueSize(workerNodeKey) > 0) { |
67f3f2d6 JB |
2239 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
2240 | this.executeTask(workerNodeKey, this.dequeueTask(workerNodeKey)!) | |
87347ea8 | 2241 | ++flushedTasks |
ff733df7 | 2242 | } |
4b628b48 | 2243 | this.workerNodes[workerNodeKey].clearTasksQueue() |
87347ea8 | 2244 | return flushedTasks |
ff733df7 JB |
2245 | } |
2246 | ||
ef41a6e6 | 2247 | private flushTasksQueues (): void { |
19b8be8b | 2248 | for (const workerNodeKey of this.workerNodes.keys()) { |
ef41a6e6 JB |
2249 | this.flushTasksQueue(workerNodeKey) |
2250 | } | |
2251 | } | |
c97c7edb | 2252 | } |