Commit | Line | Data |
---|---|---|
fc3e6586 | 1 | import crypto from 'node:crypto' |
2740a743 | 2 | import type { MessageValue, PromiseResponseWrapper } from '../utility-types' |
bbeadd16 JB |
3 | import { |
4 | DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS, | |
5 | EMPTY_FUNCTION, | |
6 | median | |
7 | } from '../utils' | |
34a0cfab | 8 | import { KillBehaviors, isKillBehavior } from '../worker/worker-options' |
c4855468 JB |
9 | import { |
10 | PoolEvents, | |
11 | type IPool, | |
12 | type PoolOptions, | |
13 | type TasksQueueOptions, | |
14 | PoolType | |
15 | } from './pool' | |
b4904890 | 16 | import { PoolEmitter } from './pool' |
f06e48d8 | 17 | import type { IWorker, Task, TasksUsage, WorkerNode } from './worker' |
a35560ba S |
18 | import { |
19 | WorkerChoiceStrategies, | |
a20f0ba5 JB |
20 | type WorkerChoiceStrategy, |
21 | type WorkerChoiceStrategyOptions | |
bdaf31cd JB |
22 | } from './selection-strategies/selection-strategies-types' |
23 | import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context' | |
f82cd357 | 24 | import { CircularArray } from '../circular-array' |
c97c7edb | 25 | |
729c563d | 26 | /** |
ea7a90d3 | 27 | * Base class that implements some shared logic for all poolifier pools. |
729c563d | 28 | * |
38e795c1 JB |
29 | * @typeParam Worker - Type of worker which manages this pool. |
30 | * @typeParam Data - Type of data sent to the worker. This can only be serializable data. | |
02706357 | 31 | * @typeParam Response - Type of execution response. This can only be serializable data. |
729c563d | 32 | */ |
c97c7edb | 33 | export abstract class AbstractPool< |
f06e48d8 | 34 | Worker extends IWorker, |
d3c8a1a8 S |
35 | Data = unknown, |
36 | Response = unknown | |
c4855468 | 37 | > implements IPool<Worker, Data, Response> { |
afc003b2 | 38 | /** @inheritDoc */ |
f06e48d8 | 39 | public readonly workerNodes: Array<WorkerNode<Worker, Data>> = [] |
4a6952ff | 40 | |
afc003b2 | 41 | /** @inheritDoc */ |
7c0ba920 JB |
42 | public readonly emitter?: PoolEmitter |
43 | ||
be0676b3 | 44 | /** |
a3445496 | 45 | * The execution response promise map. |
be0676b3 | 46 | * |
2740a743 | 47 | * - `key`: The message id of each submitted task. |
a3445496 | 48 | * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks. |
be0676b3 | 49 | * |
a3445496 | 50 | * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id. |
be0676b3 | 51 | */ |
c923ce56 JB |
52 | protected promiseResponseMap: Map< |
53 | string, | |
54 | PromiseResponseWrapper<Worker, Response> | |
55 | > = new Map<string, PromiseResponseWrapper<Worker, Response>>() | |
c97c7edb | 56 | |
a35560ba | 57 | /** |
51fe3d3c | 58 | * Worker choice strategy context referencing a worker choice algorithm implementation. |
a35560ba | 59 | * |
51fe3d3c | 60 | * Default to a round robin algorithm. |
a35560ba S |
61 | */ |
62 | protected workerChoiceStrategyContext: WorkerChoiceStrategyContext< | |
78cea37e JB |
63 | Worker, |
64 | Data, | |
65 | Response | |
a35560ba S |
66 | > |
67 | ||
729c563d S |
68 | /** |
69 | * Constructs a new poolifier pool. | |
70 | * | |
38e795c1 JB |
71 | * @param numberOfWorkers - Number of workers that this pool should manage. |
72 | * @param filePath - Path to the worker-file. | |
73 | * @param opts - Options for the pool. | |
729c563d | 74 | */ |
c97c7edb | 75 | public constructor ( |
5c5a1fb7 | 76 | public readonly numberOfWorkers: number, |
c97c7edb | 77 | public readonly filePath: string, |
1927ee67 | 78 | public readonly opts: PoolOptions<Worker> |
c97c7edb | 79 | ) { |
78cea37e | 80 | if (!this.isMain()) { |
c97c7edb S |
81 | throw new Error('Cannot start a pool from a worker!') |
82 | } | |
8d3782fa | 83 | this.checkNumberOfWorkers(this.numberOfWorkers) |
c510fea7 | 84 | this.checkFilePath(this.filePath) |
7c0ba920 | 85 | this.checkPoolOptions(this.opts) |
1086026a | 86 | |
adc3c320 | 87 | this.chooseWorkerNode.bind(this) |
2e81254d JB |
88 | this.executeTask.bind(this) |
89 | this.enqueueTask.bind(this) | |
ff733df7 | 90 | this.checkAndEmitEvents.bind(this) |
1086026a | 91 | |
c97c7edb S |
92 | this.setupHook() |
93 | ||
5c5a1fb7 | 94 | for (let i = 1; i <= this.numberOfWorkers; i++) { |
280c2a77 | 95 | this.createAndSetupWorker() |
c97c7edb S |
96 | } |
97 | ||
6bd72cd0 | 98 | if (this.opts.enableEvents === true) { |
7c0ba920 JB |
99 | this.emitter = new PoolEmitter() |
100 | } | |
d59df138 JB |
101 | this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext< |
102 | Worker, | |
103 | Data, | |
104 | Response | |
da309861 JB |
105 | >( |
106 | this, | |
107 | this.opts.workerChoiceStrategy, | |
108 | this.opts.workerChoiceStrategyOptions | |
109 | ) | |
c97c7edb S |
110 | } |
111 | ||
a35560ba | 112 | private checkFilePath (filePath: string): void { |
ffcbbad8 JB |
113 | if ( |
114 | filePath == null || | |
115 | (typeof filePath === 'string' && filePath.trim().length === 0) | |
116 | ) { | |
c510fea7 APA |
117 | throw new Error('Please specify a file with a worker implementation') |
118 | } | |
119 | } | |
120 | ||
8d3782fa JB |
121 | private checkNumberOfWorkers (numberOfWorkers: number): void { |
122 | if (numberOfWorkers == null) { | |
123 | throw new Error( | |
124 | 'Cannot instantiate a pool without specifying the number of workers' | |
125 | ) | |
78cea37e | 126 | } else if (!Number.isSafeInteger(numberOfWorkers)) { |
473c717a | 127 | throw new TypeError( |
8d3782fa JB |
128 | 'Cannot instantiate a pool with a non integer number of workers' |
129 | ) | |
130 | } else if (numberOfWorkers < 0) { | |
473c717a | 131 | throw new RangeError( |
8d3782fa JB |
132 | 'Cannot instantiate a pool with a negative number of workers' |
133 | ) | |
7c0ba920 | 134 | } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) { |
8d3782fa JB |
135 | throw new Error('Cannot instantiate a fixed pool with no worker') |
136 | } | |
137 | } | |
138 | ||
7c0ba920 | 139 | private checkPoolOptions (opts: PoolOptions<Worker>): void { |
e843b904 JB |
140 | this.opts.workerChoiceStrategy = |
141 | opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN | |
aee46736 | 142 | this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy) |
da309861 | 143 | this.opts.workerChoiceStrategyOptions = |
bbeadd16 | 144 | opts.workerChoiceStrategyOptions ?? DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS |
aee46736 | 145 | this.opts.enableEvents = opts.enableEvents ?? true |
ff733df7 | 146 | this.opts.enableTasksQueue = opts.enableTasksQueue ?? false |
7171d33f | 147 | if (this.opts.enableTasksQueue) { |
a20f0ba5 JB |
148 | this.checkValidTasksQueueOptions( |
149 | opts.tasksQueueOptions as TasksQueueOptions | |
150 | ) | |
151 | this.opts.tasksQueueOptions = this.buildTasksQueueOptions( | |
152 | opts.tasksQueueOptions as TasksQueueOptions | |
153 | ) | |
7171d33f | 154 | } |
aee46736 JB |
155 | } |
156 | ||
157 | private checkValidWorkerChoiceStrategy ( | |
158 | workerChoiceStrategy: WorkerChoiceStrategy | |
159 | ): void { | |
160 | if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) { | |
b529c323 | 161 | throw new Error( |
aee46736 | 162 | `Invalid worker choice strategy '${workerChoiceStrategy}'` |
b529c323 JB |
163 | ) |
164 | } | |
7c0ba920 JB |
165 | } |
166 | ||
a20f0ba5 JB |
167 | private checkValidTasksQueueOptions ( |
168 | tasksQueueOptions: TasksQueueOptions | |
169 | ): void { | |
170 | if ((tasksQueueOptions?.concurrency as number) <= 0) { | |
171 | throw new Error( | |
172 | `Invalid worker tasks concurrency '${ | |
173 | tasksQueueOptions.concurrency as number | |
174 | }'` | |
175 | ) | |
176 | } | |
177 | } | |
178 | ||
afc003b2 | 179 | /** @inheritDoc */ |
7c0ba920 JB |
180 | public abstract get type (): PoolType |
181 | ||
c2ade475 | 182 | /** |
ff733df7 | 183 | * Number of tasks running in the pool. |
c2ade475 JB |
184 | */ |
185 | private get numberOfRunningTasks (): number { | |
ff733df7 JB |
186 | return this.workerNodes.reduce( |
187 | (accumulator, workerNode) => accumulator + workerNode.tasksUsage.running, | |
188 | 0 | |
189 | ) | |
190 | } | |
191 | ||
192 | /** | |
193 | * Number of tasks queued in the pool. | |
194 | */ | |
195 | private get numberOfQueuedTasks (): number { | |
196 | if (this.opts.enableTasksQueue === false) { | |
197 | return 0 | |
198 | } | |
199 | return this.workerNodes.reduce( | |
200 | (accumulator, workerNode) => accumulator + workerNode.tasksQueue.length, | |
201 | 0 | |
202 | ) | |
a35560ba S |
203 | } |
204 | ||
ffcbbad8 | 205 | /** |
f06e48d8 | 206 | * Gets the given worker its worker node key. |
ffcbbad8 JB |
207 | * |
208 | * @param worker - The worker. | |
f06e48d8 | 209 | * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise. |
ffcbbad8 | 210 | */ |
f06e48d8 JB |
211 | private getWorkerNodeKey (worker: Worker): number { |
212 | return this.workerNodes.findIndex( | |
213 | workerNode => workerNode.worker === worker | |
214 | ) | |
bf9549ae JB |
215 | } |
216 | ||
afc003b2 | 217 | /** @inheritDoc */ |
a35560ba S |
218 | public setWorkerChoiceStrategy ( |
219 | workerChoiceStrategy: WorkerChoiceStrategy | |
220 | ): void { | |
aee46736 | 221 | this.checkValidWorkerChoiceStrategy(workerChoiceStrategy) |
b98ec2e6 | 222 | this.opts.workerChoiceStrategy = workerChoiceStrategy |
0ebe2a9f | 223 | for (const workerNode of this.workerNodes) { |
f82cd357 JB |
224 | this.setWorkerNodeTasksUsage(workerNode, { |
225 | run: 0, | |
226 | running: 0, | |
227 | runTime: 0, | |
228 | runTimeHistory: new CircularArray(), | |
229 | avgRunTime: 0, | |
230 | medRunTime: 0, | |
231 | error: 0 | |
232 | }) | |
ea7a90d3 | 233 | } |
a35560ba | 234 | this.workerChoiceStrategyContext.setWorkerChoiceStrategy( |
a20f0ba5 JB |
235 | this.opts.workerChoiceStrategy |
236 | ) | |
237 | } | |
238 | ||
239 | /** @inheritDoc */ | |
240 | public setWorkerChoiceStrategyOptions ( | |
241 | workerChoiceStrategyOptions: WorkerChoiceStrategyOptions | |
242 | ): void { | |
243 | this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions | |
244 | this.workerChoiceStrategyContext.setOptions( | |
245 | this.opts.workerChoiceStrategyOptions | |
a35560ba S |
246 | ) |
247 | } | |
248 | ||
a20f0ba5 JB |
249 | /** @inheritDoc */ |
250 | public enableTasksQueue (enable: boolean, opts?: TasksQueueOptions): void { | |
251 | if (this.opts.enableTasksQueue === true && !enable) { | |
252 | for (const [workerNodeKey] of this.workerNodes.entries()) { | |
253 | this.flushTasksQueue(workerNodeKey) | |
254 | } | |
255 | } | |
256 | this.opts.enableTasksQueue = enable | |
257 | this.setTasksQueueOptions(opts as TasksQueueOptions) | |
258 | } | |
259 | ||
260 | /** @inheritDoc */ | |
261 | public setTasksQueueOptions (opts: TasksQueueOptions): void { | |
262 | if (this.opts.enableTasksQueue === true) { | |
263 | this.checkValidTasksQueueOptions(opts) | |
264 | this.opts.tasksQueueOptions = this.buildTasksQueueOptions(opts) | |
265 | } else { | |
266 | delete this.opts.tasksQueueOptions | |
267 | } | |
268 | } | |
269 | ||
270 | private buildTasksQueueOptions ( | |
271 | tasksQueueOptions: TasksQueueOptions | |
272 | ): TasksQueueOptions { | |
273 | return { | |
274 | concurrency: tasksQueueOptions?.concurrency ?? 1 | |
275 | } | |
276 | } | |
277 | ||
c319c66b JB |
278 | /** |
279 | * Whether the pool is full or not. | |
280 | * | |
281 | * The pool filling boolean status. | |
282 | */ | |
283 | protected abstract get full (): boolean | |
c2ade475 | 284 | |
c319c66b JB |
285 | /** |
286 | * Whether the pool is busy or not. | |
287 | * | |
288 | * The pool busyness boolean status. | |
289 | */ | |
290 | protected abstract get busy (): boolean | |
7c0ba920 | 291 | |
c2ade475 | 292 | protected internalBusy (): boolean { |
24990079 | 293 | return this.findFreeWorkerNodeKey() === -1 |
7c0ba920 JB |
294 | } |
295 | ||
afc003b2 | 296 | /** @inheritDoc */ |
f06e48d8 JB |
297 | public findFreeWorkerNodeKey (): number { |
298 | return this.workerNodes.findIndex(workerNode => { | |
299 | return workerNode.tasksUsage?.running === 0 | |
c923ce56 | 300 | }) |
7c0ba920 JB |
301 | } |
302 | ||
afc003b2 | 303 | /** @inheritDoc */ |
78cea37e | 304 | public async execute (data: Data): Promise<Response> { |
adc3c320 JB |
305 | const [workerNodeKey, workerNode] = this.chooseWorkerNode() |
306 | const submittedTask: Task<Data> = { | |
e5a5c0fc JB |
307 | // eslint-disable-next-line @typescript-eslint/consistent-type-assertions |
308 | data: data ?? ({} as Data), | |
adc3c320 JB |
309 | id: crypto.randomUUID() |
310 | } | |
2e81254d | 311 | const res = new Promise<Response>((resolve, reject) => { |
02706357 | 312 | this.promiseResponseMap.set(submittedTask.id as string, { |
2e81254d JB |
313 | resolve, |
314 | reject, | |
315 | worker: workerNode.worker | |
316 | }) | |
317 | }) | |
ff733df7 JB |
318 | if ( |
319 | this.opts.enableTasksQueue === true && | |
7171d33f | 320 | (this.busy || |
3528c992 | 321 | this.workerNodes[workerNodeKey].tasksUsage.running >= |
7171d33f | 322 | ((this.opts.tasksQueueOptions as TasksQueueOptions) |
3528c992 | 323 | .concurrency as number)) |
ff733df7 | 324 | ) { |
26a929d7 JB |
325 | this.enqueueTask(workerNodeKey, submittedTask) |
326 | } else { | |
2e81254d | 327 | this.executeTask(workerNodeKey, submittedTask) |
adc3c320 | 328 | } |
ff733df7 | 329 | this.checkAndEmitEvents() |
78cea37e | 330 | // eslint-disable-next-line @typescript-eslint/return-await |
280c2a77 S |
331 | return res |
332 | } | |
c97c7edb | 333 | |
afc003b2 | 334 | /** @inheritDoc */ |
c97c7edb | 335 | public async destroy (): Promise<void> { |
1fbcaa7c | 336 | await Promise.all( |
875a7c37 JB |
337 | this.workerNodes.map(async (workerNode, workerNodeKey) => { |
338 | this.flushTasksQueue(workerNodeKey) | |
f06e48d8 | 339 | await this.destroyWorker(workerNode.worker) |
1fbcaa7c JB |
340 | }) |
341 | ) | |
c97c7edb S |
342 | } |
343 | ||
4a6952ff | 344 | /** |
f06e48d8 | 345 | * Shutdowns the given worker. |
4a6952ff | 346 | * |
f06e48d8 | 347 | * @param worker - A worker within `workerNodes`. |
4a6952ff JB |
348 | */ |
349 | protected abstract destroyWorker (worker: Worker): void | Promise<void> | |
c97c7edb | 350 | |
729c563d | 351 | /** |
2e81254d | 352 | * Setup hook to execute code before worker node are created in the abstract constructor. |
d99ba5a8 | 353 | * Can be overridden |
afc003b2 JB |
354 | * |
355 | * @virtual | |
729c563d | 356 | */ |
280c2a77 | 357 | protected setupHook (): void { |
d99ba5a8 | 358 | // Intentionally empty |
280c2a77 | 359 | } |
c97c7edb | 360 | |
729c563d | 361 | /** |
280c2a77 S |
362 | * Should return whether the worker is the main worker or not. |
363 | */ | |
364 | protected abstract isMain (): boolean | |
365 | ||
366 | /** | |
2e81254d | 367 | * Hook executed before the worker task execution. |
bf9549ae | 368 | * Can be overridden. |
729c563d | 369 | * |
f06e48d8 | 370 | * @param workerNodeKey - The worker node key. |
729c563d | 371 | */ |
2e81254d | 372 | protected beforeTaskExecutionHook (workerNodeKey: number): void { |
f06e48d8 | 373 | ++this.workerNodes[workerNodeKey].tasksUsage.running |
c97c7edb S |
374 | } |
375 | ||
c01733f1 | 376 | /** |
2e81254d | 377 | * Hook executed after the worker task execution. |
bf9549ae | 378 | * Can be overridden. |
c01733f1 | 379 | * |
c923ce56 | 380 | * @param worker - The worker. |
38e795c1 | 381 | * @param message - The received message. |
c01733f1 | 382 | */ |
2e81254d | 383 | protected afterTaskExecutionHook ( |
c923ce56 | 384 | worker: Worker, |
2740a743 | 385 | message: MessageValue<Response> |
bf9549ae | 386 | ): void { |
c923ce56 | 387 | const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage |
3032893a JB |
388 | --workerTasksUsage.running |
389 | ++workerTasksUsage.run | |
2740a743 JB |
390 | if (message.error != null) { |
391 | ++workerTasksUsage.error | |
392 | } | |
97a2abc3 | 393 | if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) { |
aee46736 | 394 | workerTasksUsage.runTime += message.runTime ?? 0 |
c6bd2650 JB |
395 | if ( |
396 | this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime && | |
397 | workerTasksUsage.run !== 0 | |
398 | ) { | |
3032893a JB |
399 | workerTasksUsage.avgRunTime = |
400 | workerTasksUsage.runTime / workerTasksUsage.run | |
401 | } | |
78099a15 JB |
402 | if (this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime) { |
403 | workerTasksUsage.runTimeHistory.push(message.runTime ?? 0) | |
404 | workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory) | |
405 | } | |
3032893a | 406 | } |
c01733f1 | 407 | } |
408 | ||
280c2a77 | 409 | /** |
f06e48d8 | 410 | * Chooses a worker node for the next task. |
280c2a77 | 411 | * |
51fe3d3c | 412 | * The default uses a round robin algorithm to distribute the load. |
280c2a77 | 413 | * |
adc3c320 | 414 | * @returns [worker node key, worker node]. |
280c2a77 | 415 | */ |
adc3c320 | 416 | protected chooseWorkerNode (): [number, WorkerNode<Worker, Data>] { |
f06e48d8 | 417 | let workerNodeKey: number |
0527b6db | 418 | if (this.type === PoolType.DYNAMIC && !this.full && this.internalBusy()) { |
adc3c320 JB |
419 | const workerCreated = this.createAndSetupWorker() |
420 | this.registerWorkerMessageListener(workerCreated, message => { | |
17393ac8 JB |
421 | if ( |
422 | isKillBehavior(KillBehaviors.HARD, message.kill) || | |
d2097c13 | 423 | (message.kill != null && |
adc3c320 | 424 | this.getWorkerTasksUsage(workerCreated)?.running === 0) |
17393ac8 | 425 | ) { |
ff733df7 JB |
426 | // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime) |
427 | this.flushTasksQueueByWorker(workerCreated) | |
adc3c320 | 428 | void this.destroyWorker(workerCreated) |
17393ac8 JB |
429 | } |
430 | }) | |
adc3c320 | 431 | workerNodeKey = this.getWorkerNodeKey(workerCreated) |
17393ac8 | 432 | } else { |
f06e48d8 | 433 | workerNodeKey = this.workerChoiceStrategyContext.execute() |
17393ac8 | 434 | } |
adc3c320 | 435 | return [workerNodeKey, this.workerNodes[workerNodeKey]] |
c97c7edb S |
436 | } |
437 | ||
280c2a77 | 438 | /** |
675bb809 | 439 | * Sends a message to the given worker. |
280c2a77 | 440 | * |
38e795c1 JB |
441 | * @param worker - The worker which should receive the message. |
442 | * @param message - The message. | |
280c2a77 S |
443 | */ |
444 | protected abstract sendToWorker ( | |
445 | worker: Worker, | |
446 | message: MessageValue<Data> | |
447 | ): void | |
448 | ||
4a6952ff | 449 | /** |
f06e48d8 | 450 | * Registers a listener callback on the given worker. |
4a6952ff | 451 | * |
38e795c1 JB |
452 | * @param worker - The worker which should register a listener. |
453 | * @param listener - The message listener callback. | |
4a6952ff JB |
454 | */ |
455 | protected abstract registerWorkerMessageListener< | |
4f7fa42a | 456 | Message extends Data | Response |
78cea37e | 457 | >(worker: Worker, listener: (message: MessageValue<Message>) => void): void |
c97c7edb | 458 | |
729c563d S |
459 | /** |
460 | * Returns a newly created worker. | |
461 | */ | |
280c2a77 | 462 | protected abstract createWorker (): Worker |
c97c7edb | 463 | |
729c563d | 464 | /** |
f06e48d8 | 465 | * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes. |
729c563d | 466 | * |
38e795c1 | 467 | * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default. |
729c563d | 468 | * |
38e795c1 | 469 | * @param worker - The newly created worker. |
729c563d | 470 | */ |
280c2a77 | 471 | protected abstract afterWorkerSetup (worker: Worker): void |
c97c7edb | 472 | |
4a6952ff | 473 | /** |
f06e48d8 | 474 | * Creates a new worker and sets it up completely in the pool worker nodes. |
4a6952ff JB |
475 | * |
476 | * @returns New, completely set up worker. | |
477 | */ | |
478 | protected createAndSetupWorker (): Worker { | |
bdacc2d2 | 479 | const worker = this.createWorker() |
280c2a77 | 480 | |
35cf1c03 | 481 | worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION) |
a35560ba S |
482 | worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION) |
483 | worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION) | |
484 | worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION) | |
a974afa6 | 485 | worker.once('exit', () => { |
f06e48d8 | 486 | this.removeWorkerNode(worker) |
a974afa6 | 487 | }) |
280c2a77 | 488 | |
f06e48d8 | 489 | this.pushWorkerNode(worker) |
280c2a77 S |
490 | |
491 | this.afterWorkerSetup(worker) | |
492 | ||
c97c7edb S |
493 | return worker |
494 | } | |
be0676b3 APA |
495 | |
496 | /** | |
ff733df7 | 497 | * This function is the listener registered for each worker message. |
be0676b3 | 498 | * |
bdacc2d2 | 499 | * @returns The listener function to execute when a message is received from a worker. |
be0676b3 APA |
500 | */ |
501 | protected workerListener (): (message: MessageValue<Response>) => void { | |
4a6952ff | 502 | return message => { |
b1989cfd | 503 | if (message.id != null) { |
a3445496 | 504 | // Task execution response received |
2740a743 | 505 | const promiseResponse = this.promiseResponseMap.get(message.id) |
b1989cfd | 506 | if (promiseResponse != null) { |
78cea37e | 507 | if (message.error != null) { |
2740a743 | 508 | promiseResponse.reject(message.error) |
a05c10de | 509 | } else { |
2740a743 | 510 | promiseResponse.resolve(message.data as Response) |
a05c10de | 511 | } |
2e81254d | 512 | this.afterTaskExecutionHook(promiseResponse.worker, message) |
2740a743 | 513 | this.promiseResponseMap.delete(message.id) |
ff733df7 JB |
514 | const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker) |
515 | if ( | |
516 | this.opts.enableTasksQueue === true && | |
416fd65c | 517 | this.tasksQueueSize(workerNodeKey) > 0 |
ff733df7 | 518 | ) { |
2e81254d JB |
519 | this.executeTask( |
520 | workerNodeKey, | |
ff733df7 JB |
521 | this.dequeueTask(workerNodeKey) as Task<Data> |
522 | ) | |
523 | } | |
be0676b3 APA |
524 | } |
525 | } | |
526 | } | |
be0676b3 | 527 | } |
7c0ba920 | 528 | |
ff733df7 JB |
529 | private checkAndEmitEvents (): void { |
530 | if (this.opts.enableEvents === true) { | |
531 | if (this.busy) { | |
532 | this.emitter?.emit(PoolEvents.busy) | |
533 | } | |
534 | if (this.type === PoolType.DYNAMIC && this.full) { | |
535 | this.emitter?.emit(PoolEvents.full) | |
536 | } | |
164d950a JB |
537 | } |
538 | } | |
539 | ||
0ebe2a9f JB |
540 | /** |
541 | * Sets the given worker node its tasks usage in the pool. | |
542 | * | |
543 | * @param workerNode - The worker node. | |
544 | * @param tasksUsage - The worker node tasks usage. | |
545 | */ | |
546 | private setWorkerNodeTasksUsage ( | |
547 | workerNode: WorkerNode<Worker, Data>, | |
548 | tasksUsage: TasksUsage | |
549 | ): void { | |
550 | workerNode.tasksUsage = tasksUsage | |
551 | } | |
552 | ||
c923ce56 | 553 | /** |
f06e48d8 | 554 | * Gets the given worker its tasks usage in the pool. |
c923ce56 JB |
555 | * |
556 | * @param worker - The worker. | |
71ebe93b | 557 | * @throws {@link Error} if the worker is not found in the pool worker nodes. |
c923ce56 JB |
558 | * @returns The worker tasks usage. |
559 | */ | |
560 | private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined { | |
f06e48d8 JB |
561 | const workerNodeKey = this.getWorkerNodeKey(worker) |
562 | if (workerNodeKey !== -1) { | |
563 | return this.workerNodes[workerNodeKey].tasksUsage | |
ffcbbad8 | 564 | } |
f06e48d8 | 565 | throw new Error('Worker could not be found in the pool worker nodes') |
a05c10de JB |
566 | } |
567 | ||
568 | /** | |
f06e48d8 | 569 | * Pushes the given worker in the pool worker nodes. |
ea7a90d3 | 570 | * |
38e795c1 | 571 | * @param worker - The worker. |
f06e48d8 | 572 | * @returns The worker nodes length. |
ea7a90d3 | 573 | */ |
f06e48d8 JB |
574 | private pushWorkerNode (worker: Worker): number { |
575 | return this.workerNodes.push({ | |
ffcbbad8 | 576 | worker, |
f82cd357 JB |
577 | tasksUsage: { |
578 | run: 0, | |
579 | running: 0, | |
580 | runTime: 0, | |
581 | runTimeHistory: new CircularArray(), | |
582 | avgRunTime: 0, | |
583 | medRunTime: 0, | |
584 | error: 0 | |
585 | }, | |
f06e48d8 | 586 | tasksQueue: [] |
ea7a90d3 JB |
587 | }) |
588 | } | |
c923ce56 JB |
589 | |
590 | /** | |
f06e48d8 | 591 | * Sets the given worker in the pool worker nodes. |
c923ce56 | 592 | * |
f06e48d8 | 593 | * @param workerNodeKey - The worker node key. |
c923ce56 JB |
594 | * @param worker - The worker. |
595 | * @param tasksUsage - The worker tasks usage. | |
f06e48d8 | 596 | * @param tasksQueue - The worker task queue. |
c923ce56 | 597 | */ |
f06e48d8 JB |
598 | private setWorkerNode ( |
599 | workerNodeKey: number, | |
c923ce56 | 600 | worker: Worker, |
f06e48d8 JB |
601 | tasksUsage: TasksUsage, |
602 | tasksQueue: Array<Task<Data>> | |
c923ce56 | 603 | ): void { |
f06e48d8 | 604 | this.workerNodes[workerNodeKey] = { |
c923ce56 | 605 | worker, |
f06e48d8 JB |
606 | tasksUsage, |
607 | tasksQueue | |
c923ce56 JB |
608 | } |
609 | } | |
51fe3d3c JB |
610 | |
611 | /** | |
f06e48d8 | 612 | * Removes the given worker from the pool worker nodes. |
51fe3d3c | 613 | * |
f06e48d8 | 614 | * @param worker - The worker. |
51fe3d3c | 615 | */ |
416fd65c | 616 | private removeWorkerNode (worker: Worker): void { |
f06e48d8 JB |
617 | const workerNodeKey = this.getWorkerNodeKey(worker) |
618 | this.workerNodes.splice(workerNodeKey, 1) | |
619 | this.workerChoiceStrategyContext.remove(workerNodeKey) | |
51fe3d3c | 620 | } |
adc3c320 | 621 | |
2e81254d JB |
622 | private executeTask (workerNodeKey: number, task: Task<Data>): void { |
623 | this.beforeTaskExecutionHook(workerNodeKey) | |
624 | this.sendToWorker(this.workerNodes[workerNodeKey].worker, task) | |
625 | } | |
626 | ||
f9f00b5f JB |
627 | private enqueueTask (workerNodeKey: number, task: Task<Data>): number { |
628 | return this.workerNodes[workerNodeKey].tasksQueue.push(task) | |
adc3c320 JB |
629 | } |
630 | ||
416fd65c | 631 | private dequeueTask (workerNodeKey: number): Task<Data> | undefined { |
adc3c320 JB |
632 | return this.workerNodes[workerNodeKey].tasksQueue.shift() |
633 | } | |
634 | ||
416fd65c | 635 | private tasksQueueSize (workerNodeKey: number): number { |
adc3c320 JB |
636 | return this.workerNodes[workerNodeKey].tasksQueue.length |
637 | } | |
ff733df7 | 638 | |
416fd65c JB |
639 | private flushTasksQueue (workerNodeKey: number): void { |
640 | if (this.tasksQueueSize(workerNodeKey) > 0) { | |
ff733df7 | 641 | for (const task of this.workerNodes[workerNodeKey].tasksQueue) { |
2e81254d | 642 | this.executeTask(workerNodeKey, task) |
ff733df7 | 643 | } |
ff733df7 JB |
644 | } |
645 | } | |
646 | ||
416fd65c | 647 | private flushTasksQueueByWorker (worker: Worker): void { |
ff733df7 JB |
648 | const workerNodeKey = this.getWorkerNodeKey(worker) |
649 | this.flushTasksQueue(workerNodeKey) | |
650 | } | |
c97c7edb | 651 | } |