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