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