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' |
65d7a1c9 | 9 | import { CircularArray } from '../circular-array' |
c4855468 | 10 | import { |
65d7a1c9 | 11 | type IPool, |
7c5a1080 | 12 | PoolEmitter, |
c4855468 | 13 | PoolEvents, |
c4855468 | 14 | type PoolOptions, |
65d7a1c9 JB |
15 | PoolType, |
16 | type TasksQueueOptions | |
c4855468 | 17 | } from './pool' |
f06e48d8 | 18 | import type { IWorker, Task, TasksUsage, WorkerNode } from './worker' |
a35560ba S |
19 | import { |
20 | WorkerChoiceStrategies, | |
a20f0ba5 JB |
21 | type WorkerChoiceStrategy, |
22 | type WorkerChoiceStrategyOptions | |
bdaf31cd JB |
23 | } from './selection-strategies/selection-strategies-types' |
24 | import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context' | |
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 | 71 | * @param numberOfWorkers - Number of workers that this pool should manage. |
029715f0 | 72 | * @param filePath - Path to the worker file. |
38e795c1 | 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 | |
7254e419 JB |
87 | this.chooseWorkerNode = this.chooseWorkerNode.bind(this) |
88 | this.executeTask = this.executeTask.bind(this) | |
89 | this.enqueueTask = this.enqueueTask.bind(this) | |
90 | this.checkAndEmitEvents = 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 | 218 | public setWorkerChoiceStrategy ( |
59219cbb JB |
219 | workerChoiceStrategy: WorkerChoiceStrategy, |
220 | workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions | |
a35560ba | 221 | ): void { |
aee46736 | 222 | this.checkValidWorkerChoiceStrategy(workerChoiceStrategy) |
b98ec2e6 | 223 | this.opts.workerChoiceStrategy = workerChoiceStrategy |
0ebe2a9f | 224 | for (const workerNode of this.workerNodes) { |
f82cd357 JB |
225 | this.setWorkerNodeTasksUsage(workerNode, { |
226 | run: 0, | |
227 | running: 0, | |
228 | runTime: 0, | |
229 | runTimeHistory: new CircularArray(), | |
230 | avgRunTime: 0, | |
231 | medRunTime: 0, | |
232 | error: 0 | |
233 | }) | |
ea7a90d3 | 234 | } |
a35560ba | 235 | this.workerChoiceStrategyContext.setWorkerChoiceStrategy( |
a20f0ba5 JB |
236 | this.opts.workerChoiceStrategy |
237 | ) | |
59219cbb JB |
238 | if (workerChoiceStrategyOptions != null) { |
239 | this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions) | |
240 | } | |
a20f0ba5 JB |
241 | } |
242 | ||
243 | /** @inheritDoc */ | |
244 | public setWorkerChoiceStrategyOptions ( | |
245 | workerChoiceStrategyOptions: WorkerChoiceStrategyOptions | |
246 | ): void { | |
247 | this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions | |
248 | this.workerChoiceStrategyContext.setOptions( | |
249 | this.opts.workerChoiceStrategyOptions | |
a35560ba S |
250 | ) |
251 | } | |
252 | ||
a20f0ba5 | 253 | /** @inheritDoc */ |
8f52842f JB |
254 | public enableTasksQueue ( |
255 | enable: boolean, | |
256 | tasksQueueOptions?: TasksQueueOptions | |
257 | ): void { | |
a20f0ba5 | 258 | if (this.opts.enableTasksQueue === true && !enable) { |
ef41a6e6 | 259 | this.flushTasksQueues() |
a20f0ba5 JB |
260 | } |
261 | this.opts.enableTasksQueue = enable | |
8f52842f | 262 | this.setTasksQueueOptions(tasksQueueOptions as TasksQueueOptions) |
a20f0ba5 JB |
263 | } |
264 | ||
265 | /** @inheritDoc */ | |
8f52842f | 266 | public setTasksQueueOptions (tasksQueueOptions: TasksQueueOptions): void { |
a20f0ba5 | 267 | if (this.opts.enableTasksQueue === true) { |
8f52842f JB |
268 | this.checkValidTasksQueueOptions(tasksQueueOptions) |
269 | this.opts.tasksQueueOptions = | |
270 | this.buildTasksQueueOptions(tasksQueueOptions) | |
a20f0ba5 JB |
271 | } else { |
272 | delete this.opts.tasksQueueOptions | |
273 | } | |
274 | } | |
275 | ||
276 | private buildTasksQueueOptions ( | |
277 | tasksQueueOptions: TasksQueueOptions | |
278 | ): TasksQueueOptions { | |
279 | return { | |
280 | concurrency: tasksQueueOptions?.concurrency ?? 1 | |
281 | } | |
282 | } | |
283 | ||
c319c66b JB |
284 | /** |
285 | * Whether the pool is full or not. | |
286 | * | |
287 | * The pool filling boolean status. | |
288 | */ | |
289 | protected abstract get full (): boolean | |
c2ade475 | 290 | |
c319c66b JB |
291 | /** |
292 | * Whether the pool is busy or not. | |
293 | * | |
294 | * The pool busyness boolean status. | |
295 | */ | |
296 | protected abstract get busy (): boolean | |
7c0ba920 | 297 | |
c2ade475 | 298 | protected internalBusy (): boolean { |
e0ae6100 JB |
299 | return ( |
300 | this.workerNodes.findIndex(workerNode => { | |
301 | return workerNode.tasksUsage?.running === 0 | |
302 | }) === -1 | |
303 | ) | |
cb70b19d JB |
304 | } |
305 | ||
afc003b2 | 306 | /** @inheritDoc */ |
a86b6df1 | 307 | public async execute (data?: Data, name?: string): Promise<Response> { |
adc3c320 JB |
308 | const [workerNodeKey, workerNode] = this.chooseWorkerNode() |
309 | const submittedTask: Task<Data> = { | |
a86b6df1 | 310 | name, |
e5a5c0fc JB |
311 | // eslint-disable-next-line @typescript-eslint/consistent-type-assertions |
312 | data: data ?? ({} as Data), | |
adc3c320 JB |
313 | id: crypto.randomUUID() |
314 | } | |
2e81254d | 315 | const res = new Promise<Response>((resolve, reject) => { |
02706357 | 316 | this.promiseResponseMap.set(submittedTask.id as string, { |
2e81254d JB |
317 | resolve, |
318 | reject, | |
319 | worker: workerNode.worker | |
320 | }) | |
321 | }) | |
ff733df7 JB |
322 | if ( |
323 | this.opts.enableTasksQueue === true && | |
7171d33f | 324 | (this.busy || |
3528c992 | 325 | this.workerNodes[workerNodeKey].tasksUsage.running >= |
7171d33f | 326 | ((this.opts.tasksQueueOptions as TasksQueueOptions) |
3528c992 | 327 | .concurrency as number)) |
ff733df7 | 328 | ) { |
26a929d7 JB |
329 | this.enqueueTask(workerNodeKey, submittedTask) |
330 | } else { | |
2e81254d | 331 | this.executeTask(workerNodeKey, submittedTask) |
adc3c320 | 332 | } |
ff733df7 | 333 | this.checkAndEmitEvents() |
78cea37e | 334 | // eslint-disable-next-line @typescript-eslint/return-await |
280c2a77 S |
335 | return res |
336 | } | |
c97c7edb | 337 | |
afc003b2 | 338 | /** @inheritDoc */ |
c97c7edb | 339 | public async destroy (): Promise<void> { |
1fbcaa7c | 340 | await Promise.all( |
875a7c37 JB |
341 | this.workerNodes.map(async (workerNode, workerNodeKey) => { |
342 | this.flushTasksQueue(workerNodeKey) | |
f06e48d8 | 343 | await this.destroyWorker(workerNode.worker) |
1fbcaa7c JB |
344 | }) |
345 | ) | |
c97c7edb S |
346 | } |
347 | ||
4a6952ff | 348 | /** |
f06e48d8 | 349 | * Shutdowns the given worker. |
4a6952ff | 350 | * |
f06e48d8 | 351 | * @param worker - A worker within `workerNodes`. |
4a6952ff JB |
352 | */ |
353 | protected abstract destroyWorker (worker: Worker): void | Promise<void> | |
c97c7edb | 354 | |
729c563d | 355 | /** |
2e81254d | 356 | * Setup hook to execute code before worker node are created in the abstract constructor. |
d99ba5a8 | 357 | * Can be overridden |
afc003b2 JB |
358 | * |
359 | * @virtual | |
729c563d | 360 | */ |
280c2a77 | 361 | protected setupHook (): void { |
d99ba5a8 | 362 | // Intentionally empty |
280c2a77 | 363 | } |
c97c7edb | 364 | |
729c563d | 365 | /** |
280c2a77 S |
366 | * Should return whether the worker is the main worker or not. |
367 | */ | |
368 | protected abstract isMain (): boolean | |
369 | ||
370 | /** | |
2e81254d | 371 | * Hook executed before the worker task execution. |
bf9549ae | 372 | * Can be overridden. |
729c563d | 373 | * |
f06e48d8 | 374 | * @param workerNodeKey - The worker node key. |
729c563d | 375 | */ |
2e81254d | 376 | protected beforeTaskExecutionHook (workerNodeKey: number): void { |
f06e48d8 | 377 | ++this.workerNodes[workerNodeKey].tasksUsage.running |
c97c7edb S |
378 | } |
379 | ||
c01733f1 | 380 | /** |
2e81254d | 381 | * Hook executed after the worker task execution. |
bf9549ae | 382 | * Can be overridden. |
c01733f1 | 383 | * |
c923ce56 | 384 | * @param worker - The worker. |
38e795c1 | 385 | * @param message - The received message. |
c01733f1 | 386 | */ |
2e81254d | 387 | protected afterTaskExecutionHook ( |
c923ce56 | 388 | worker: Worker, |
2740a743 | 389 | message: MessageValue<Response> |
bf9549ae | 390 | ): void { |
05ca3d0d | 391 | const workerTasksUsage = this.getWorkerTasksUsage(worker) |
3032893a JB |
392 | --workerTasksUsage.running |
393 | ++workerTasksUsage.run | |
2740a743 JB |
394 | if (message.error != null) { |
395 | ++workerTasksUsage.error | |
396 | } | |
97a2abc3 | 397 | if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) { |
aee46736 | 398 | workerTasksUsage.runTime += message.runTime ?? 0 |
c6bd2650 JB |
399 | if ( |
400 | this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime && | |
401 | workerTasksUsage.run !== 0 | |
402 | ) { | |
3032893a JB |
403 | workerTasksUsage.avgRunTime = |
404 | workerTasksUsage.runTime / workerTasksUsage.run | |
405 | } | |
78099a15 JB |
406 | if (this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime) { |
407 | workerTasksUsage.runTimeHistory.push(message.runTime ?? 0) | |
408 | workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory) | |
409 | } | |
3032893a | 410 | } |
c01733f1 | 411 | } |
412 | ||
280c2a77 | 413 | /** |
f06e48d8 | 414 | * Chooses a worker node for the next task. |
280c2a77 | 415 | * |
51fe3d3c | 416 | * The default uses a round robin algorithm to distribute the load. |
280c2a77 | 417 | * |
adc3c320 | 418 | * @returns [worker node key, worker node]. |
280c2a77 | 419 | */ |
adc3c320 | 420 | protected chooseWorkerNode (): [number, WorkerNode<Worker, Data>] { |
f06e48d8 | 421 | let workerNodeKey: number |
0527b6db | 422 | if (this.type === PoolType.DYNAMIC && !this.full && this.internalBusy()) { |
adc3c320 JB |
423 | const workerCreated = this.createAndSetupWorker() |
424 | this.registerWorkerMessageListener(workerCreated, message => { | |
17393ac8 JB |
425 | if ( |
426 | isKillBehavior(KillBehaviors.HARD, message.kill) || | |
d2097c13 | 427 | (message.kill != null && |
adc3c320 | 428 | this.getWorkerTasksUsage(workerCreated)?.running === 0) |
17393ac8 | 429 | ) { |
ff733df7 JB |
430 | // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime) |
431 | this.flushTasksQueueByWorker(workerCreated) | |
7c5a1080 | 432 | void (this.destroyWorker(workerCreated) as Promise<void>) |
17393ac8 JB |
433 | } |
434 | }) | |
adc3c320 | 435 | workerNodeKey = this.getWorkerNodeKey(workerCreated) |
17393ac8 | 436 | } else { |
f06e48d8 | 437 | workerNodeKey = this.workerChoiceStrategyContext.execute() |
17393ac8 | 438 | } |
adc3c320 | 439 | return [workerNodeKey, this.workerNodes[workerNodeKey]] |
c97c7edb S |
440 | } |
441 | ||
280c2a77 | 442 | /** |
675bb809 | 443 | * Sends a message to the given worker. |
280c2a77 | 444 | * |
38e795c1 JB |
445 | * @param worker - The worker which should receive the message. |
446 | * @param message - The message. | |
280c2a77 S |
447 | */ |
448 | protected abstract sendToWorker ( | |
449 | worker: Worker, | |
450 | message: MessageValue<Data> | |
451 | ): void | |
452 | ||
4a6952ff | 453 | /** |
f06e48d8 | 454 | * Registers a listener callback on the given worker. |
4a6952ff | 455 | * |
38e795c1 JB |
456 | * @param worker - The worker which should register a listener. |
457 | * @param listener - The message listener callback. | |
4a6952ff JB |
458 | */ |
459 | protected abstract registerWorkerMessageListener< | |
4f7fa42a | 460 | Message extends Data | Response |
78cea37e | 461 | >(worker: Worker, listener: (message: MessageValue<Message>) => void): void |
c97c7edb | 462 | |
729c563d S |
463 | /** |
464 | * Returns a newly created worker. | |
465 | */ | |
280c2a77 | 466 | protected abstract createWorker (): Worker |
c97c7edb | 467 | |
729c563d | 468 | /** |
f06e48d8 | 469 | * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes. |
729c563d | 470 | * |
38e795c1 | 471 | * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default. |
729c563d | 472 | * |
38e795c1 | 473 | * @param worker - The newly created worker. |
729c563d | 474 | */ |
280c2a77 | 475 | protected abstract afterWorkerSetup (worker: Worker): void |
c97c7edb | 476 | |
4a6952ff | 477 | /** |
f06e48d8 | 478 | * Creates a new worker and sets it up completely in the pool worker nodes. |
4a6952ff JB |
479 | * |
480 | * @returns New, completely set up worker. | |
481 | */ | |
482 | protected createAndSetupWorker (): Worker { | |
bdacc2d2 | 483 | const worker = this.createWorker() |
280c2a77 | 484 | |
35cf1c03 | 485 | worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION) |
a35560ba S |
486 | worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION) |
487 | worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION) | |
488 | worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION) | |
a974afa6 | 489 | worker.once('exit', () => { |
f06e48d8 | 490 | this.removeWorkerNode(worker) |
a974afa6 | 491 | }) |
280c2a77 | 492 | |
f06e48d8 | 493 | this.pushWorkerNode(worker) |
280c2a77 S |
494 | |
495 | this.afterWorkerSetup(worker) | |
496 | ||
c97c7edb S |
497 | return worker |
498 | } | |
be0676b3 APA |
499 | |
500 | /** | |
ff733df7 | 501 | * This function is the listener registered for each worker message. |
be0676b3 | 502 | * |
bdacc2d2 | 503 | * @returns The listener function to execute when a message is received from a worker. |
be0676b3 APA |
504 | */ |
505 | protected workerListener (): (message: MessageValue<Response>) => void { | |
4a6952ff | 506 | return message => { |
b1989cfd | 507 | if (message.id != null) { |
a3445496 | 508 | // Task execution response received |
2740a743 | 509 | const promiseResponse = this.promiseResponseMap.get(message.id) |
b1989cfd | 510 | if (promiseResponse != null) { |
78cea37e | 511 | if (message.error != null) { |
2740a743 | 512 | promiseResponse.reject(message.error) |
a05c10de | 513 | } else { |
2740a743 | 514 | promiseResponse.resolve(message.data as Response) |
a05c10de | 515 | } |
2e81254d | 516 | this.afterTaskExecutionHook(promiseResponse.worker, message) |
2740a743 | 517 | this.promiseResponseMap.delete(message.id) |
ff733df7 JB |
518 | const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker) |
519 | if ( | |
520 | this.opts.enableTasksQueue === true && | |
416fd65c | 521 | this.tasksQueueSize(workerNodeKey) > 0 |
ff733df7 | 522 | ) { |
2e81254d JB |
523 | this.executeTask( |
524 | workerNodeKey, | |
ff733df7 JB |
525 | this.dequeueTask(workerNodeKey) as Task<Data> |
526 | ) | |
527 | } | |
be0676b3 APA |
528 | } |
529 | } | |
530 | } | |
be0676b3 | 531 | } |
7c0ba920 | 532 | |
ff733df7 JB |
533 | private checkAndEmitEvents (): void { |
534 | if (this.opts.enableEvents === true) { | |
535 | if (this.busy) { | |
536 | this.emitter?.emit(PoolEvents.busy) | |
537 | } | |
538 | if (this.type === PoolType.DYNAMIC && this.full) { | |
539 | this.emitter?.emit(PoolEvents.full) | |
540 | } | |
164d950a JB |
541 | } |
542 | } | |
543 | ||
0ebe2a9f JB |
544 | /** |
545 | * Sets the given worker node its tasks usage in the pool. | |
546 | * | |
547 | * @param workerNode - The worker node. | |
548 | * @param tasksUsage - The worker node tasks usage. | |
549 | */ | |
550 | private setWorkerNodeTasksUsage ( | |
551 | workerNode: WorkerNode<Worker, Data>, | |
552 | tasksUsage: TasksUsage | |
553 | ): void { | |
554 | workerNode.tasksUsage = tasksUsage | |
555 | } | |
556 | ||
c923ce56 | 557 | /** |
f06e48d8 | 558 | * Gets the given worker its tasks usage in the pool. |
c923ce56 JB |
559 | * |
560 | * @param worker - The worker. | |
e2473f60 | 561 | * @throws Error if the worker is not found in the pool worker nodes. |
c923ce56 JB |
562 | * @returns The worker tasks usage. |
563 | */ | |
05ca3d0d | 564 | private getWorkerTasksUsage (worker: Worker): TasksUsage { |
f06e48d8 JB |
565 | const workerNodeKey = this.getWorkerNodeKey(worker) |
566 | if (workerNodeKey !== -1) { | |
567 | return this.workerNodes[workerNodeKey].tasksUsage | |
ffcbbad8 | 568 | } |
f06e48d8 | 569 | throw new Error('Worker could not be found in the pool worker nodes') |
a05c10de JB |
570 | } |
571 | ||
572 | /** | |
f06e48d8 | 573 | * Pushes the given worker in the pool worker nodes. |
ea7a90d3 | 574 | * |
38e795c1 | 575 | * @param worker - The worker. |
f06e48d8 | 576 | * @returns The worker nodes length. |
ea7a90d3 | 577 | */ |
f06e48d8 JB |
578 | private pushWorkerNode (worker: Worker): number { |
579 | return this.workerNodes.push({ | |
ffcbbad8 | 580 | worker, |
f82cd357 JB |
581 | tasksUsage: { |
582 | run: 0, | |
583 | running: 0, | |
584 | runTime: 0, | |
585 | runTimeHistory: new CircularArray(), | |
586 | avgRunTime: 0, | |
587 | medRunTime: 0, | |
588 | error: 0 | |
589 | }, | |
f06e48d8 | 590 | tasksQueue: [] |
ea7a90d3 JB |
591 | }) |
592 | } | |
c923ce56 JB |
593 | |
594 | /** | |
f06e48d8 | 595 | * Sets the given worker in the pool worker nodes. |
c923ce56 | 596 | * |
f06e48d8 | 597 | * @param workerNodeKey - The worker node key. |
c923ce56 JB |
598 | * @param worker - The worker. |
599 | * @param tasksUsage - The worker tasks usage. | |
f06e48d8 | 600 | * @param tasksQueue - The worker task queue. |
c923ce56 | 601 | */ |
f06e48d8 JB |
602 | private setWorkerNode ( |
603 | workerNodeKey: number, | |
c923ce56 | 604 | worker: Worker, |
f06e48d8 JB |
605 | tasksUsage: TasksUsage, |
606 | tasksQueue: Array<Task<Data>> | |
c923ce56 | 607 | ): void { |
f06e48d8 | 608 | this.workerNodes[workerNodeKey] = { |
c923ce56 | 609 | worker, |
f06e48d8 JB |
610 | tasksUsage, |
611 | tasksQueue | |
c923ce56 JB |
612 | } |
613 | } | |
51fe3d3c JB |
614 | |
615 | /** | |
f06e48d8 | 616 | * Removes the given worker from the pool worker nodes. |
51fe3d3c | 617 | * |
f06e48d8 | 618 | * @param worker - The worker. |
51fe3d3c | 619 | */ |
416fd65c | 620 | private removeWorkerNode (worker: Worker): void { |
f06e48d8 JB |
621 | const workerNodeKey = this.getWorkerNodeKey(worker) |
622 | this.workerNodes.splice(workerNodeKey, 1) | |
623 | this.workerChoiceStrategyContext.remove(workerNodeKey) | |
51fe3d3c | 624 | } |
adc3c320 | 625 | |
2e81254d JB |
626 | private executeTask (workerNodeKey: number, task: Task<Data>): void { |
627 | this.beforeTaskExecutionHook(workerNodeKey) | |
628 | this.sendToWorker(this.workerNodes[workerNodeKey].worker, task) | |
629 | } | |
630 | ||
f9f00b5f JB |
631 | private enqueueTask (workerNodeKey: number, task: Task<Data>): number { |
632 | return this.workerNodes[workerNodeKey].tasksQueue.push(task) | |
adc3c320 JB |
633 | } |
634 | ||
416fd65c | 635 | private dequeueTask (workerNodeKey: number): Task<Data> | undefined { |
adc3c320 JB |
636 | return this.workerNodes[workerNodeKey].tasksQueue.shift() |
637 | } | |
638 | ||
416fd65c | 639 | private tasksQueueSize (workerNodeKey: number): number { |
adc3c320 JB |
640 | return this.workerNodes[workerNodeKey].tasksQueue.length |
641 | } | |
ff733df7 | 642 | |
416fd65c JB |
643 | private flushTasksQueue (workerNodeKey: number): void { |
644 | if (this.tasksQueueSize(workerNodeKey) > 0) { | |
ff733df7 | 645 | for (const task of this.workerNodes[workerNodeKey].tasksQueue) { |
2e81254d | 646 | this.executeTask(workerNodeKey, task) |
ff733df7 | 647 | } |
ff733df7 JB |
648 | } |
649 | } | |
650 | ||
416fd65c | 651 | private flushTasksQueueByWorker (worker: Worker): void { |
ff733df7 JB |
652 | const workerNodeKey = this.getWorkerNodeKey(worker) |
653 | this.flushTasksQueue(workerNodeKey) | |
654 | } | |
ef41a6e6 JB |
655 | |
656 | private flushTasksQueues (): void { | |
657 | for (const [workerNodeKey] of this.workerNodes.entries()) { | |
658 | this.flushTasksQueue(workerNodeKey) | |
659 | } | |
660 | } | |
c97c7edb | 661 | } |