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' |
c4855468 JB |
9 | import { |
10 | PoolEvents, | |
11 | type IPool, | |
12 | type PoolOptions, | |
13 | type TasksQueueOptions, | |
14 | PoolType | |
15 | } from './pool' | |
b4904890 | 16 | import { PoolEmitter } from './pool' |
f06e48d8 | 17 | import type { IWorker, Task, TasksUsage, WorkerNode } from './worker' |
a35560ba S |
18 | import { |
19 | WorkerChoiceStrategies, | |
63220255 | 20 | type WorkerChoiceStrategy |
bdaf31cd JB |
21 | } from './selection-strategies/selection-strategies-types' |
22 | import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context' | |
78099a15 | 23 | import { CircularArray } from '../circular-array' |
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 JB |
214 | for (const workerNode of this.workerNodes) { |
215 | this.setWorkerNodeTasksUsage(workerNode, { | |
216 | run: 0, | |
217 | running: 0, | |
218 | runTime: 0, | |
219 | runTimeHistory: new CircularArray(), | |
220 | avgRunTime: 0, | |
221 | medRunTime: 0, | |
222 | error: 0 | |
223 | }) | |
ea7a90d3 | 224 | } |
a35560ba S |
225 | this.workerChoiceStrategyContext.setWorkerChoiceStrategy( |
226 | workerChoiceStrategy | |
227 | ) | |
228 | } | |
229 | ||
c319c66b JB |
230 | /** |
231 | * Whether the pool is full or not. | |
232 | * | |
233 | * The pool filling boolean status. | |
234 | */ | |
235 | protected abstract get full (): boolean | |
c2ade475 | 236 | |
c319c66b JB |
237 | /** |
238 | * Whether the pool is busy or not. | |
239 | * | |
240 | * The pool busyness boolean status. | |
241 | */ | |
242 | protected abstract get busy (): boolean | |
7c0ba920 | 243 | |
c2ade475 | 244 | protected internalBusy (): boolean { |
24990079 | 245 | return this.findFreeWorkerNodeKey() === -1 |
7c0ba920 JB |
246 | } |
247 | ||
afc003b2 | 248 | /** @inheritDoc */ |
f06e48d8 JB |
249 | public findFreeWorkerNodeKey (): number { |
250 | return this.workerNodes.findIndex(workerNode => { | |
251 | return workerNode.tasksUsage?.running === 0 | |
c923ce56 | 252 | }) |
7c0ba920 JB |
253 | } |
254 | ||
afc003b2 | 255 | /** @inheritDoc */ |
78cea37e | 256 | public async execute (data: Data): Promise<Response> { |
adc3c320 JB |
257 | const [workerNodeKey, workerNode] = this.chooseWorkerNode() |
258 | const submittedTask: Task<Data> = { | |
e5a5c0fc JB |
259 | // eslint-disable-next-line @typescript-eslint/consistent-type-assertions |
260 | data: data ?? ({} as Data), | |
adc3c320 JB |
261 | id: crypto.randomUUID() |
262 | } | |
2e81254d | 263 | const res = new Promise<Response>((resolve, reject) => { |
02706357 | 264 | this.promiseResponseMap.set(submittedTask.id as string, { |
2e81254d JB |
265 | resolve, |
266 | reject, | |
267 | worker: workerNode.worker | |
268 | }) | |
269 | }) | |
ff733df7 JB |
270 | if ( |
271 | this.opts.enableTasksQueue === true && | |
7171d33f | 272 | (this.busy || |
3528c992 | 273 | this.workerNodes[workerNodeKey].tasksUsage.running >= |
7171d33f | 274 | ((this.opts.tasksQueueOptions as TasksQueueOptions) |
3528c992 | 275 | .concurrency as number)) |
ff733df7 | 276 | ) { |
26a929d7 JB |
277 | this.enqueueTask(workerNodeKey, submittedTask) |
278 | } else { | |
2e81254d | 279 | this.executeTask(workerNodeKey, submittedTask) |
adc3c320 | 280 | } |
ff733df7 | 281 | this.checkAndEmitEvents() |
78cea37e | 282 | // eslint-disable-next-line @typescript-eslint/return-await |
280c2a77 S |
283 | return res |
284 | } | |
c97c7edb | 285 | |
afc003b2 | 286 | /** @inheritDoc */ |
c97c7edb | 287 | public async destroy (): Promise<void> { |
1fbcaa7c | 288 | await Promise.all( |
875a7c37 JB |
289 | this.workerNodes.map(async (workerNode, workerNodeKey) => { |
290 | this.flushTasksQueue(workerNodeKey) | |
f06e48d8 | 291 | await this.destroyWorker(workerNode.worker) |
1fbcaa7c JB |
292 | }) |
293 | ) | |
c97c7edb S |
294 | } |
295 | ||
4a6952ff | 296 | /** |
f06e48d8 | 297 | * Shutdowns the given worker. |
4a6952ff | 298 | * |
f06e48d8 | 299 | * @param worker - A worker within `workerNodes`. |
4a6952ff JB |
300 | */ |
301 | protected abstract destroyWorker (worker: Worker): void | Promise<void> | |
c97c7edb | 302 | |
729c563d | 303 | /** |
2e81254d | 304 | * Setup hook to execute code before worker node are created in the abstract constructor. |
d99ba5a8 | 305 | * Can be overridden |
afc003b2 JB |
306 | * |
307 | * @virtual | |
729c563d | 308 | */ |
280c2a77 | 309 | protected setupHook (): void { |
d99ba5a8 | 310 | // Intentionally empty |
280c2a77 | 311 | } |
c97c7edb | 312 | |
729c563d | 313 | /** |
280c2a77 S |
314 | * Should return whether the worker is the main worker or not. |
315 | */ | |
316 | protected abstract isMain (): boolean | |
317 | ||
318 | /** | |
2e81254d | 319 | * Hook executed before the worker task execution. |
bf9549ae | 320 | * Can be overridden. |
729c563d | 321 | * |
f06e48d8 | 322 | * @param workerNodeKey - The worker node key. |
729c563d | 323 | */ |
2e81254d | 324 | protected beforeTaskExecutionHook (workerNodeKey: number): void { |
f06e48d8 | 325 | ++this.workerNodes[workerNodeKey].tasksUsage.running |
c97c7edb S |
326 | } |
327 | ||
c01733f1 | 328 | /** |
2e81254d | 329 | * Hook executed after the worker task execution. |
bf9549ae | 330 | * Can be overridden. |
c01733f1 | 331 | * |
c923ce56 | 332 | * @param worker - The worker. |
38e795c1 | 333 | * @param message - The received message. |
c01733f1 | 334 | */ |
2e81254d | 335 | protected afterTaskExecutionHook ( |
c923ce56 | 336 | worker: Worker, |
2740a743 | 337 | message: MessageValue<Response> |
bf9549ae | 338 | ): void { |
c923ce56 | 339 | const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage |
3032893a JB |
340 | --workerTasksUsage.running |
341 | ++workerTasksUsage.run | |
2740a743 JB |
342 | if (message.error != null) { |
343 | ++workerTasksUsage.error | |
344 | } | |
97a2abc3 | 345 | if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) { |
aee46736 | 346 | workerTasksUsage.runTime += message.runTime ?? 0 |
c6bd2650 JB |
347 | if ( |
348 | this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime && | |
349 | workerTasksUsage.run !== 0 | |
350 | ) { | |
3032893a JB |
351 | workerTasksUsage.avgRunTime = |
352 | workerTasksUsage.runTime / workerTasksUsage.run | |
353 | } | |
78099a15 JB |
354 | if (this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime) { |
355 | workerTasksUsage.runTimeHistory.push(message.runTime ?? 0) | |
356 | workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory) | |
357 | } | |
3032893a | 358 | } |
c01733f1 | 359 | } |
360 | ||
280c2a77 | 361 | /** |
f06e48d8 | 362 | * Chooses a worker node for the next task. |
280c2a77 | 363 | * |
51fe3d3c | 364 | * The default uses a round robin algorithm to distribute the load. |
280c2a77 | 365 | * |
adc3c320 | 366 | * @returns [worker node key, worker node]. |
280c2a77 | 367 | */ |
adc3c320 | 368 | protected chooseWorkerNode (): [number, WorkerNode<Worker, Data>] { |
f06e48d8 | 369 | let workerNodeKey: number |
0527b6db | 370 | if (this.type === PoolType.DYNAMIC && !this.full && this.internalBusy()) { |
adc3c320 JB |
371 | const workerCreated = this.createAndSetupWorker() |
372 | this.registerWorkerMessageListener(workerCreated, message => { | |
17393ac8 JB |
373 | if ( |
374 | isKillBehavior(KillBehaviors.HARD, message.kill) || | |
d2097c13 | 375 | (message.kill != null && |
adc3c320 | 376 | this.getWorkerTasksUsage(workerCreated)?.running === 0) |
17393ac8 | 377 | ) { |
ff733df7 JB |
378 | // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime) |
379 | this.flushTasksQueueByWorker(workerCreated) | |
adc3c320 | 380 | void this.destroyWorker(workerCreated) |
17393ac8 JB |
381 | } |
382 | }) | |
adc3c320 | 383 | workerNodeKey = this.getWorkerNodeKey(workerCreated) |
17393ac8 | 384 | } else { |
f06e48d8 | 385 | workerNodeKey = this.workerChoiceStrategyContext.execute() |
17393ac8 | 386 | } |
adc3c320 | 387 | return [workerNodeKey, this.workerNodes[workerNodeKey]] |
c97c7edb S |
388 | } |
389 | ||
280c2a77 | 390 | /** |
675bb809 | 391 | * Sends a message to the given worker. |
280c2a77 | 392 | * |
38e795c1 JB |
393 | * @param worker - The worker which should receive the message. |
394 | * @param message - The message. | |
280c2a77 S |
395 | */ |
396 | protected abstract sendToWorker ( | |
397 | worker: Worker, | |
398 | message: MessageValue<Data> | |
399 | ): void | |
400 | ||
4a6952ff | 401 | /** |
f06e48d8 | 402 | * Registers a listener callback on the given worker. |
4a6952ff | 403 | * |
38e795c1 JB |
404 | * @param worker - The worker which should register a listener. |
405 | * @param listener - The message listener callback. | |
4a6952ff JB |
406 | */ |
407 | protected abstract registerWorkerMessageListener< | |
4f7fa42a | 408 | Message extends Data | Response |
78cea37e | 409 | >(worker: Worker, listener: (message: MessageValue<Message>) => void): void |
c97c7edb | 410 | |
729c563d S |
411 | /** |
412 | * Returns a newly created worker. | |
413 | */ | |
280c2a77 | 414 | protected abstract createWorker (): Worker |
c97c7edb | 415 | |
729c563d | 416 | /** |
f06e48d8 | 417 | * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes. |
729c563d | 418 | * |
38e795c1 | 419 | * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default. |
729c563d | 420 | * |
38e795c1 | 421 | * @param worker - The newly created worker. |
729c563d | 422 | */ |
280c2a77 | 423 | protected abstract afterWorkerSetup (worker: Worker): void |
c97c7edb | 424 | |
4a6952ff | 425 | /** |
f06e48d8 | 426 | * Creates a new worker and sets it up completely in the pool worker nodes. |
4a6952ff JB |
427 | * |
428 | * @returns New, completely set up worker. | |
429 | */ | |
430 | protected createAndSetupWorker (): Worker { | |
bdacc2d2 | 431 | const worker = this.createWorker() |
280c2a77 | 432 | |
35cf1c03 | 433 | worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION) |
a35560ba S |
434 | worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION) |
435 | worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION) | |
436 | worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION) | |
a974afa6 | 437 | worker.once('exit', () => { |
f06e48d8 | 438 | this.removeWorkerNode(worker) |
a974afa6 | 439 | }) |
280c2a77 | 440 | |
f06e48d8 | 441 | this.pushWorkerNode(worker) |
280c2a77 S |
442 | |
443 | this.afterWorkerSetup(worker) | |
444 | ||
c97c7edb S |
445 | return worker |
446 | } | |
be0676b3 APA |
447 | |
448 | /** | |
ff733df7 | 449 | * This function is the listener registered for each worker message. |
be0676b3 | 450 | * |
bdacc2d2 | 451 | * @returns The listener function to execute when a message is received from a worker. |
be0676b3 APA |
452 | */ |
453 | protected workerListener (): (message: MessageValue<Response>) => void { | |
4a6952ff | 454 | return message => { |
b1989cfd | 455 | if (message.id != null) { |
a3445496 | 456 | // Task execution response received |
2740a743 | 457 | const promiseResponse = this.promiseResponseMap.get(message.id) |
b1989cfd | 458 | if (promiseResponse != null) { |
78cea37e | 459 | if (message.error != null) { |
2740a743 | 460 | promiseResponse.reject(message.error) |
a05c10de | 461 | } else { |
2740a743 | 462 | promiseResponse.resolve(message.data as Response) |
a05c10de | 463 | } |
2e81254d | 464 | this.afterTaskExecutionHook(promiseResponse.worker, message) |
2740a743 | 465 | this.promiseResponseMap.delete(message.id) |
ff733df7 JB |
466 | const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker) |
467 | if ( | |
468 | this.opts.enableTasksQueue === true && | |
416fd65c | 469 | this.tasksQueueSize(workerNodeKey) > 0 |
ff733df7 | 470 | ) { |
2e81254d JB |
471 | this.executeTask( |
472 | workerNodeKey, | |
ff733df7 JB |
473 | this.dequeueTask(workerNodeKey) as Task<Data> |
474 | ) | |
475 | } | |
be0676b3 APA |
476 | } |
477 | } | |
478 | } | |
be0676b3 | 479 | } |
7c0ba920 | 480 | |
ff733df7 JB |
481 | private checkAndEmitEvents (): void { |
482 | if (this.opts.enableEvents === true) { | |
483 | if (this.busy) { | |
484 | this.emitter?.emit(PoolEvents.busy) | |
485 | } | |
486 | if (this.type === PoolType.DYNAMIC && this.full) { | |
487 | this.emitter?.emit(PoolEvents.full) | |
488 | } | |
164d950a JB |
489 | } |
490 | } | |
491 | ||
0ebe2a9f JB |
492 | /** |
493 | * Sets the given worker node its tasks usage in the pool. | |
494 | * | |
495 | * @param workerNode - The worker node. | |
496 | * @param tasksUsage - The worker node tasks usage. | |
497 | */ | |
498 | private setWorkerNodeTasksUsage ( | |
499 | workerNode: WorkerNode<Worker, Data>, | |
500 | tasksUsage: TasksUsage | |
501 | ): void { | |
502 | workerNode.tasksUsage = tasksUsage | |
503 | } | |
504 | ||
c923ce56 | 505 | /** |
f06e48d8 | 506 | * Gets the given worker its tasks usage in the pool. |
c923ce56 JB |
507 | * |
508 | * @param worker - The worker. | |
71ebe93b | 509 | * @throws {@link Error} if the worker is not found in the pool worker nodes. |
c923ce56 JB |
510 | * @returns The worker tasks usage. |
511 | */ | |
512 | private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined { | |
f06e48d8 JB |
513 | const workerNodeKey = this.getWorkerNodeKey(worker) |
514 | if (workerNodeKey !== -1) { | |
515 | return this.workerNodes[workerNodeKey].tasksUsage | |
ffcbbad8 | 516 | } |
f06e48d8 | 517 | throw new Error('Worker could not be found in the pool worker nodes') |
a05c10de JB |
518 | } |
519 | ||
520 | /** | |
f06e48d8 | 521 | * Pushes the given worker in the pool worker nodes. |
ea7a90d3 | 522 | * |
38e795c1 | 523 | * @param worker - The worker. |
f06e48d8 | 524 | * @returns The worker nodes length. |
ea7a90d3 | 525 | */ |
f06e48d8 JB |
526 | private pushWorkerNode (worker: Worker): number { |
527 | return this.workerNodes.push({ | |
ffcbbad8 | 528 | worker, |
f06e48d8 JB |
529 | tasksUsage: { |
530 | run: 0, | |
531 | running: 0, | |
532 | runTime: 0, | |
533 | runTimeHistory: new CircularArray(), | |
534 | avgRunTime: 0, | |
535 | medRunTime: 0, | |
536 | error: 0 | |
537 | }, | |
538 | tasksQueue: [] | |
ea7a90d3 JB |
539 | }) |
540 | } | |
c923ce56 JB |
541 | |
542 | /** | |
f06e48d8 | 543 | * Sets the given worker in the pool worker nodes. |
c923ce56 | 544 | * |
f06e48d8 | 545 | * @param workerNodeKey - The worker node key. |
c923ce56 JB |
546 | * @param worker - The worker. |
547 | * @param tasksUsage - The worker tasks usage. | |
f06e48d8 | 548 | * @param tasksQueue - The worker task queue. |
c923ce56 | 549 | */ |
f06e48d8 JB |
550 | private setWorkerNode ( |
551 | workerNodeKey: number, | |
c923ce56 | 552 | worker: Worker, |
f06e48d8 JB |
553 | tasksUsage: TasksUsage, |
554 | tasksQueue: Array<Task<Data>> | |
c923ce56 | 555 | ): void { |
f06e48d8 | 556 | this.workerNodes[workerNodeKey] = { |
c923ce56 | 557 | worker, |
f06e48d8 JB |
558 | tasksUsage, |
559 | tasksQueue | |
c923ce56 JB |
560 | } |
561 | } | |
51fe3d3c JB |
562 | |
563 | /** | |
f06e48d8 | 564 | * Removes the given worker from the pool worker nodes. |
51fe3d3c | 565 | * |
f06e48d8 | 566 | * @param worker - The worker. |
51fe3d3c | 567 | */ |
416fd65c | 568 | private removeWorkerNode (worker: Worker): void { |
f06e48d8 JB |
569 | const workerNodeKey = this.getWorkerNodeKey(worker) |
570 | this.workerNodes.splice(workerNodeKey, 1) | |
571 | this.workerChoiceStrategyContext.remove(workerNodeKey) | |
51fe3d3c | 572 | } |
adc3c320 | 573 | |
2e81254d JB |
574 | private executeTask (workerNodeKey: number, task: Task<Data>): void { |
575 | this.beforeTaskExecutionHook(workerNodeKey) | |
576 | this.sendToWorker(this.workerNodes[workerNodeKey].worker, task) | |
577 | } | |
578 | ||
f9f00b5f JB |
579 | private enqueueTask (workerNodeKey: number, task: Task<Data>): number { |
580 | return this.workerNodes[workerNodeKey].tasksQueue.push(task) | |
adc3c320 JB |
581 | } |
582 | ||
416fd65c | 583 | private dequeueTask (workerNodeKey: number): Task<Data> | undefined { |
adc3c320 JB |
584 | return this.workerNodes[workerNodeKey].tasksQueue.shift() |
585 | } | |
586 | ||
416fd65c | 587 | private tasksQueueSize (workerNodeKey: number): number { |
adc3c320 JB |
588 | return this.workerNodes[workerNodeKey].tasksQueue.length |
589 | } | |
ff733df7 | 590 | |
416fd65c JB |
591 | private flushTasksQueue (workerNodeKey: number): void { |
592 | if (this.tasksQueueSize(workerNodeKey) > 0) { | |
ff733df7 | 593 | for (const task of this.workerNodes[workerNodeKey].tasksQueue) { |
2e81254d | 594 | this.executeTask(workerNodeKey, task) |
ff733df7 | 595 | } |
ff733df7 JB |
596 | } |
597 | } | |
598 | ||
416fd65c | 599 | private flushTasksQueueByWorker (worker: Worker): void { |
ff733df7 JB |
600 | const workerNodeKey = this.getWorkerNodeKey(worker) |
601 | this.flushTasksQueue(workerNodeKey) | |
602 | } | |
c97c7edb | 603 | } |