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