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