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