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