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