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