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 => { | |
a4958de2 | 325 | return workerNode.tasksUsage.running === 0 |
e0ae6100 JB |
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 | } |
b0d6ed8f | 357 | this.workerChoiceStrategyContext.update(workerNodeKey) |
ff733df7 | 358 | this.checkAndEmitEvents() |
78cea37e | 359 | // eslint-disable-next-line @typescript-eslint/return-await |
280c2a77 S |
360 | return res |
361 | } | |
c97c7edb | 362 | |
afc003b2 | 363 | /** @inheritDoc */ |
c97c7edb | 364 | public async destroy (): Promise<void> { |
1fbcaa7c | 365 | await Promise.all( |
875a7c37 JB |
366 | this.workerNodes.map(async (workerNode, workerNodeKey) => { |
367 | this.flushTasksQueue(workerNodeKey) | |
f06e48d8 | 368 | await this.destroyWorker(workerNode.worker) |
1fbcaa7c JB |
369 | }) |
370 | ) | |
c97c7edb S |
371 | } |
372 | ||
4a6952ff | 373 | /** |
f06e48d8 | 374 | * Shutdowns the given worker. |
4a6952ff | 375 | * |
f06e48d8 | 376 | * @param worker - A worker within `workerNodes`. |
4a6952ff JB |
377 | */ |
378 | protected abstract destroyWorker (worker: Worker): void | Promise<void> | |
c97c7edb | 379 | |
729c563d | 380 | /** |
2e81254d | 381 | * Setup hook to execute code before worker node are created in the abstract constructor. |
d99ba5a8 | 382 | * Can be overridden |
afc003b2 JB |
383 | * |
384 | * @virtual | |
729c563d | 385 | */ |
280c2a77 | 386 | protected setupHook (): void { |
d99ba5a8 | 387 | // Intentionally empty |
280c2a77 | 388 | } |
c97c7edb | 389 | |
729c563d | 390 | /** |
280c2a77 S |
391 | * Should return whether the worker is the main worker or not. |
392 | */ | |
393 | protected abstract isMain (): boolean | |
394 | ||
395 | /** | |
2e81254d | 396 | * Hook executed before the worker task execution. |
bf9549ae | 397 | * Can be overridden. |
729c563d | 398 | * |
f06e48d8 | 399 | * @param workerNodeKey - The worker node key. |
729c563d | 400 | */ |
2e81254d | 401 | protected beforeTaskExecutionHook (workerNodeKey: number): void { |
f06e48d8 | 402 | ++this.workerNodes[workerNodeKey].tasksUsage.running |
c97c7edb S |
403 | } |
404 | ||
c01733f1 | 405 | /** |
2e81254d | 406 | * Hook executed after the worker task execution. |
bf9549ae | 407 | * Can be overridden. |
c01733f1 | 408 | * |
c923ce56 | 409 | * @param worker - The worker. |
38e795c1 | 410 | * @param message - The received message. |
c01733f1 | 411 | */ |
2e81254d | 412 | protected afterTaskExecutionHook ( |
c923ce56 | 413 | worker: Worker, |
2740a743 | 414 | message: MessageValue<Response> |
bf9549ae | 415 | ): void { |
a4958de2 JB |
416 | const workerNodeKey = this.getWorkerNodeKey(worker) |
417 | const workerTasksUsage = this.workerNodes[workerNodeKey].tasksUsage | |
3032893a JB |
418 | --workerTasksUsage.running |
419 | ++workerTasksUsage.run | |
2740a743 JB |
420 | if (message.error != null) { |
421 | ++workerTasksUsage.error | |
422 | } | |
97a2abc3 | 423 | if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) { |
aee46736 | 424 | workerTasksUsage.runTime += message.runTime ?? 0 |
c6bd2650 JB |
425 | if ( |
426 | this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime && | |
427 | workerTasksUsage.run !== 0 | |
428 | ) { | |
3032893a JB |
429 | workerTasksUsage.avgRunTime = |
430 | workerTasksUsage.runTime / workerTasksUsage.run | |
431 | } | |
78099a15 JB |
432 | if (this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime) { |
433 | workerTasksUsage.runTimeHistory.push(message.runTime ?? 0) | |
434 | workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory) | |
435 | } | |
3032893a | 436 | } |
c01733f1 | 437 | } |
438 | ||
280c2a77 | 439 | /** |
f06e48d8 | 440 | * Chooses a worker node for the next task. |
280c2a77 | 441 | * |
51fe3d3c | 442 | * The default uses a round robin algorithm to distribute the load. |
280c2a77 | 443 | * |
adc3c320 | 444 | * @returns [worker node key, worker node]. |
280c2a77 | 445 | */ |
adc3c320 | 446 | protected chooseWorkerNode (): [number, WorkerNode<Worker, Data>] { |
f06e48d8 | 447 | let workerNodeKey: number |
0527b6db | 448 | if (this.type === PoolType.DYNAMIC && !this.full && this.internalBusy()) { |
adc3c320 JB |
449 | const workerCreated = this.createAndSetupWorker() |
450 | this.registerWorkerMessageListener(workerCreated, message => { | |
a4958de2 | 451 | const currentWorkerNodeKey = this.getWorkerNodeKey(workerCreated) |
17393ac8 JB |
452 | if ( |
453 | isKillBehavior(KillBehaviors.HARD, message.kill) || | |
d2097c13 | 454 | (message.kill != null && |
a4958de2 | 455 | this.workerNodes[currentWorkerNodeKey].tasksUsage.running === 0) |
17393ac8 | 456 | ) { |
ff733df7 | 457 | // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime) |
a4958de2 | 458 | this.flushTasksQueue(currentWorkerNodeKey) |
7c5a1080 | 459 | void (this.destroyWorker(workerCreated) as Promise<void>) |
17393ac8 JB |
460 | } |
461 | }) | |
adc3c320 | 462 | workerNodeKey = this.getWorkerNodeKey(workerCreated) |
17393ac8 | 463 | } else { |
f06e48d8 | 464 | workerNodeKey = this.workerChoiceStrategyContext.execute() |
17393ac8 | 465 | } |
adc3c320 | 466 | return [workerNodeKey, this.workerNodes[workerNodeKey]] |
c97c7edb S |
467 | } |
468 | ||
280c2a77 | 469 | /** |
675bb809 | 470 | * Sends a message to the given worker. |
280c2a77 | 471 | * |
38e795c1 JB |
472 | * @param worker - The worker which should receive the message. |
473 | * @param message - The message. | |
280c2a77 S |
474 | */ |
475 | protected abstract sendToWorker ( | |
476 | worker: Worker, | |
477 | message: MessageValue<Data> | |
478 | ): void | |
479 | ||
4a6952ff | 480 | /** |
f06e48d8 | 481 | * Registers a listener callback on the given worker. |
4a6952ff | 482 | * |
38e795c1 JB |
483 | * @param worker - The worker which should register a listener. |
484 | * @param listener - The message listener callback. | |
4a6952ff JB |
485 | */ |
486 | protected abstract registerWorkerMessageListener< | |
4f7fa42a | 487 | Message extends Data | Response |
78cea37e | 488 | >(worker: Worker, listener: (message: MessageValue<Message>) => void): void |
c97c7edb | 489 | |
729c563d S |
490 | /** |
491 | * Returns a newly created worker. | |
492 | */ | |
280c2a77 | 493 | protected abstract createWorker (): Worker |
c97c7edb | 494 | |
729c563d | 495 | /** |
f06e48d8 | 496 | * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes. |
729c563d | 497 | * |
38e795c1 | 498 | * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default. |
729c563d | 499 | * |
38e795c1 | 500 | * @param worker - The newly created worker. |
729c563d | 501 | */ |
280c2a77 | 502 | protected abstract afterWorkerSetup (worker: Worker): void |
c97c7edb | 503 | |
4a6952ff | 504 | /** |
f06e48d8 | 505 | * Creates a new worker and sets it up completely in the pool worker nodes. |
4a6952ff JB |
506 | * |
507 | * @returns New, completely set up worker. | |
508 | */ | |
509 | protected createAndSetupWorker (): Worker { | |
bdacc2d2 | 510 | const worker = this.createWorker() |
280c2a77 | 511 | |
35cf1c03 | 512 | worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION) |
a35560ba S |
513 | worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION) |
514 | worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION) | |
515 | worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION) | |
a974afa6 | 516 | worker.once('exit', () => { |
f06e48d8 | 517 | this.removeWorkerNode(worker) |
a974afa6 | 518 | }) |
280c2a77 | 519 | |
f06e48d8 | 520 | this.pushWorkerNode(worker) |
280c2a77 S |
521 | |
522 | this.afterWorkerSetup(worker) | |
523 | ||
c97c7edb S |
524 | return worker |
525 | } | |
be0676b3 APA |
526 | |
527 | /** | |
ff733df7 | 528 | * This function is the listener registered for each worker message. |
be0676b3 | 529 | * |
bdacc2d2 | 530 | * @returns The listener function to execute when a message is received from a worker. |
be0676b3 APA |
531 | */ |
532 | protected workerListener (): (message: MessageValue<Response>) => void { | |
4a6952ff | 533 | return message => { |
b1989cfd | 534 | if (message.id != null) { |
a3445496 | 535 | // Task execution response received |
2740a743 | 536 | const promiseResponse = this.promiseResponseMap.get(message.id) |
b1989cfd | 537 | if (promiseResponse != null) { |
78cea37e | 538 | if (message.error != null) { |
2740a743 | 539 | promiseResponse.reject(message.error) |
a05c10de | 540 | } else { |
2740a743 | 541 | promiseResponse.resolve(message.data as Response) |
a05c10de | 542 | } |
2e81254d | 543 | this.afterTaskExecutionHook(promiseResponse.worker, message) |
2740a743 | 544 | this.promiseResponseMap.delete(message.id) |
ff733df7 JB |
545 | const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker) |
546 | if ( | |
547 | this.opts.enableTasksQueue === true && | |
416fd65c | 548 | this.tasksQueueSize(workerNodeKey) > 0 |
ff733df7 | 549 | ) { |
2e81254d JB |
550 | this.executeTask( |
551 | workerNodeKey, | |
ff733df7 JB |
552 | this.dequeueTask(workerNodeKey) as Task<Data> |
553 | ) | |
554 | } | |
be0676b3 APA |
555 | } |
556 | } | |
557 | } | |
be0676b3 | 558 | } |
7c0ba920 | 559 | |
ff733df7 JB |
560 | private checkAndEmitEvents (): void { |
561 | if (this.opts.enableEvents === true) { | |
562 | if (this.busy) { | |
563 | this.emitter?.emit(PoolEvents.busy) | |
564 | } | |
565 | if (this.type === PoolType.DYNAMIC && this.full) { | |
566 | this.emitter?.emit(PoolEvents.full) | |
567 | } | |
164d950a JB |
568 | } |
569 | } | |
570 | ||
0ebe2a9f JB |
571 | /** |
572 | * Sets the given worker node its tasks usage in the pool. | |
573 | * | |
574 | * @param workerNode - The worker node. | |
575 | * @param tasksUsage - The worker node tasks usage. | |
576 | */ | |
577 | private setWorkerNodeTasksUsage ( | |
578 | workerNode: WorkerNode<Worker, Data>, | |
579 | tasksUsage: TasksUsage | |
580 | ): void { | |
581 | workerNode.tasksUsage = tasksUsage | |
582 | } | |
583 | ||
a05c10de | 584 | /** |
f06e48d8 | 585 | * Pushes the given worker in the pool worker nodes. |
ea7a90d3 | 586 | * |
38e795c1 | 587 | * @param worker - The worker. |
f06e48d8 | 588 | * @returns The worker nodes length. |
ea7a90d3 | 589 | */ |
f06e48d8 JB |
590 | private pushWorkerNode (worker: Worker): number { |
591 | return this.workerNodes.push({ | |
ffcbbad8 | 592 | worker, |
f82cd357 JB |
593 | tasksUsage: { |
594 | run: 0, | |
595 | running: 0, | |
596 | runTime: 0, | |
597 | runTimeHistory: new CircularArray(), | |
598 | avgRunTime: 0, | |
599 | medRunTime: 0, | |
600 | error: 0 | |
601 | }, | |
29ee7e9a | 602 | tasksQueue: new Queue<Task<Data>>() |
ea7a90d3 JB |
603 | }) |
604 | } | |
c923ce56 JB |
605 | |
606 | /** | |
f06e48d8 | 607 | * Sets the given worker in the pool worker nodes. |
c923ce56 | 608 | * |
f06e48d8 | 609 | * @param workerNodeKey - The worker node key. |
c923ce56 JB |
610 | * @param worker - The worker. |
611 | * @param tasksUsage - The worker tasks usage. | |
f06e48d8 | 612 | * @param tasksQueue - The worker task queue. |
c923ce56 | 613 | */ |
f06e48d8 JB |
614 | private setWorkerNode ( |
615 | workerNodeKey: number, | |
c923ce56 | 616 | worker: Worker, |
f06e48d8 | 617 | tasksUsage: TasksUsage, |
29ee7e9a | 618 | tasksQueue: Queue<Task<Data>> |
c923ce56 | 619 | ): void { |
f06e48d8 | 620 | this.workerNodes[workerNodeKey] = { |
c923ce56 | 621 | worker, |
f06e48d8 JB |
622 | tasksUsage, |
623 | tasksQueue | |
c923ce56 JB |
624 | } |
625 | } | |
51fe3d3c JB |
626 | |
627 | /** | |
f06e48d8 | 628 | * Removes the given worker from the pool worker nodes. |
51fe3d3c | 629 | * |
f06e48d8 | 630 | * @param worker - The worker. |
51fe3d3c | 631 | */ |
416fd65c | 632 | private removeWorkerNode (worker: Worker): void { |
f06e48d8 JB |
633 | const workerNodeKey = this.getWorkerNodeKey(worker) |
634 | this.workerNodes.splice(workerNodeKey, 1) | |
635 | this.workerChoiceStrategyContext.remove(workerNodeKey) | |
51fe3d3c | 636 | } |
adc3c320 | 637 | |
2e81254d JB |
638 | private executeTask (workerNodeKey: number, task: Task<Data>): void { |
639 | this.beforeTaskExecutionHook(workerNodeKey) | |
640 | this.sendToWorker(this.workerNodes[workerNodeKey].worker, task) | |
641 | } | |
642 | ||
f9f00b5f | 643 | private enqueueTask (workerNodeKey: number, task: Task<Data>): number { |
29ee7e9a | 644 | return this.workerNodes[workerNodeKey].tasksQueue.enqueue(task) |
adc3c320 JB |
645 | } |
646 | ||
416fd65c | 647 | private dequeueTask (workerNodeKey: number): Task<Data> | undefined { |
29ee7e9a | 648 | return this.workerNodes[workerNodeKey].tasksQueue.dequeue() |
adc3c320 JB |
649 | } |
650 | ||
416fd65c | 651 | private tasksQueueSize (workerNodeKey: number): number { |
4d8bf9e4 | 652 | return this.workerNodes[workerNodeKey].tasksQueue.size |
adc3c320 | 653 | } |
ff733df7 | 654 | |
416fd65c JB |
655 | private flushTasksQueue (workerNodeKey: number): void { |
656 | if (this.tasksQueueSize(workerNodeKey) > 0) { | |
29ee7e9a JB |
657 | for (let i = 0; i < this.tasksQueueSize(workerNodeKey); i++) { |
658 | this.executeTask( | |
659 | workerNodeKey, | |
660 | this.dequeueTask(workerNodeKey) as Task<Data> | |
661 | ) | |
ff733df7 | 662 | } |
ff733df7 JB |
663 | } |
664 | } | |
665 | ||
ef41a6e6 JB |
666 | private flushTasksQueues (): void { |
667 | for (const [workerNodeKey] of this.workerNodes.entries()) { | |
668 | this.flushTasksQueue(workerNodeKey) | |
669 | } | |
670 | } | |
c97c7edb | 671 | } |