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