fix: add missing crypto import
[poolifier.git] / src / pools / abstract-pool.ts
CommitLineData
fc3e6586 1import crypto from 'node:crypto'
be0676b3
APA
2import type {
3 MessageValue,
4 PromiseWorkerResponseWrapper
5} from '../utility-types'
ed6dd37f 6import { EMPTY_FUNCTION } from '../utils'
34a0cfab 7import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
bdaf31cd 8import type { PoolOptions } from './pool'
b4904890 9import { PoolEmitter } from './pool'
ffcbbad8 10import type { IPoolInternal, TasksUsage, WorkerType } from './pool-internal'
b4904890 11import { PoolType } from './pool-internal'
ea7a90d3 12import type { IPoolWorker } from './pool-worker'
a35560ba
S
13import {
14 WorkerChoiceStrategies,
63220255 15 type WorkerChoiceStrategy
bdaf31cd
JB
16} from './selection-strategies/selection-strategies-types'
17import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
c97c7edb 18
729c563d 19/**
ea7a90d3 20 * Base class that implements some shared logic for all poolifier pools.
729c563d 21 *
38e795c1
JB
22 * @typeParam Worker - Type of worker which manages this pool.
23 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
24 * @typeParam Response - Type of response of execution. This can only be serializable data.
729c563d 25 */
c97c7edb 26export abstract class AbstractPool<
ea7a90d3 27 Worker extends IPoolWorker,
d3c8a1a8
S
28 Data = unknown,
29 Response = unknown
9b2fdd9f 30> implements IPoolInternal<Worker, Data, Response> {
38e795c1 31 /** {@inheritDoc} */
ffcbbad8
JB
32 public readonly workers: Map<number, WorkerType<Worker>> = new Map<
33 number,
34 WorkerType<Worker>
bf9549ae 35 >()
4a6952ff 36
38e795c1 37 /** {@inheritDoc} */
7c0ba920
JB
38 public readonly emitter?: PoolEmitter
39
ffcbbad8
JB
40 /**
41 * Id of the next worker.
42 */
43 protected nextWorkerId: number = 0
44
be0676b3
APA
45 /**
46 * The promise map.
47 *
ffcbbad8 48 * - `key`: This is the message id of each submitted task.
be0676b3
APA
49 * - `value`: An object that contains the worker, the resolve function and the reject function.
50 *
51 * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
52 */
53 protected promiseMap: Map<
b4e75778 54 string,
78cea37e 55 PromiseWorkerResponseWrapper<Worker, Response>
b4e75778 56 > = new Map<string, PromiseWorkerResponseWrapper<Worker, Response>>()
c97c7edb 57
a35560ba
S
58 /**
59 * Worker choice strategy instance implementing the worker choice algorithm.
60 *
61 * Default to a strategy implementing a round robin algorithm.
62 */
63 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
78cea37e
JB
64 Worker,
65 Data,
66 Response
a35560ba
S
67 >
68
729c563d
S
69 /**
70 * Constructs a new poolifier pool.
71 *
38e795c1
JB
72 * @param numberOfWorkers - Number of workers that this pool should manage.
73 * @param filePath - Path to the worker-file.
74 * @param opts - Options for the pool.
729c563d 75 */
c97c7edb 76 public constructor (
5c5a1fb7 77 public readonly numberOfWorkers: number,
c97c7edb 78 public readonly filePath: string,
1927ee67 79 public readonly opts: PoolOptions<Worker>
c97c7edb 80 ) {
78cea37e 81 if (!this.isMain()) {
c97c7edb
S
82 throw new Error('Cannot start a pool from a worker!')
83 }
8d3782fa 84 this.checkNumberOfWorkers(this.numberOfWorkers)
c510fea7 85 this.checkFilePath(this.filePath)
7c0ba920 86 this.checkPoolOptions(this.opts)
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 }
a35560ba
S
96 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext(
97 this,
4a6952ff
JB
98 () => {
99 const workerCreated = this.createAndSetupWorker()
f3636726 100 this.registerWorkerMessageListener(workerCreated, message => {
4a6952ff
JB
101 if (
102 isKillBehavior(KillBehaviors.HARD, message.kill) ||
bdaf31cd 103 this.getWorkerRunningTasks(workerCreated) === 0
4a6952ff
JB
104 ) {
105 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
a9d9ea34 106 void this.destroyWorker(workerCreated)
4a6952ff
JB
107 }
108 })
109 return workerCreated
110 },
e843b904 111 this.opts.workerChoiceStrategy
a35560ba 112 )
c97c7edb
S
113 }
114
a35560ba 115 private checkFilePath (filePath: string): void {
ffcbbad8
JB
116 if (
117 filePath == null ||
118 (typeof filePath === 'string' && filePath.trim().length === 0)
119 ) {
c510fea7
APA
120 throw new Error('Please specify a file with a worker implementation')
121 }
122 }
123
8d3782fa
JB
124 private checkNumberOfWorkers (numberOfWorkers: number): void {
125 if (numberOfWorkers == null) {
126 throw new Error(
127 'Cannot instantiate a pool without specifying the number of workers'
128 )
78cea37e 129 } else if (!Number.isSafeInteger(numberOfWorkers)) {
473c717a 130 throw new TypeError(
8d3782fa
JB
131 'Cannot instantiate a pool with a non integer number of workers'
132 )
133 } else if (numberOfWorkers < 0) {
473c717a 134 throw new RangeError(
8d3782fa
JB
135 'Cannot instantiate a pool with a negative number of workers'
136 )
7c0ba920 137 } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) {
8d3782fa
JB
138 throw new Error('Cannot instantiate a fixed pool with no worker')
139 }
140 }
141
7c0ba920 142 private checkPoolOptions (opts: PoolOptions<Worker>): void {
e843b904
JB
143 this.opts.workerChoiceStrategy =
144 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
7c0ba920
JB
145 this.opts.enableEvents = opts.enableEvents ?? true
146 }
147
38e795c1 148 /** {@inheritDoc} */
7c0ba920
JB
149 public abstract get type (): PoolType
150
38e795c1 151 /** {@inheritDoc} */
7c0ba920
JB
152 public get numberOfRunningTasks (): number {
153 return this.promiseMap.size
a35560ba
S
154 }
155
ffcbbad8 156 /**
b4e75778 157 * Gets the given worker key.
ffcbbad8
JB
158 *
159 * @param worker - The worker.
160 * @returns The worker key.
161 */
162 private getWorkerKey (worker: Worker): number | undefined {
163 return [...this.workers].find(([, value]) => value.worker === worker)?.[0]
bf9549ae
JB
164 }
165
38e795c1 166 /** {@inheritDoc} */
bdaf31cd 167 public getWorkerRunningTasks (worker: Worker): number | undefined {
ffcbbad8
JB
168 return this.workers.get(this.getWorkerKey(worker) as number)?.tasksUsage
169 ?.running
bdaf31cd
JB
170 }
171
38e795c1 172 /** {@inheritDoc} */
bf9549ae 173 public getWorkerAverageTasksRunTime (worker: Worker): number | undefined {
ffcbbad8
JB
174 return this.workers.get(this.getWorkerKey(worker) as number)?.tasksUsage
175 ?.avgRunTime
bdaf31cd
JB
176 }
177
38e795c1 178 /** {@inheritDoc} */
a35560ba
S
179 public setWorkerChoiceStrategy (
180 workerChoiceStrategy: WorkerChoiceStrategy
181 ): void {
b98ec2e6 182 this.opts.workerChoiceStrategy = workerChoiceStrategy
ffcbbad8
JB
183 for (const [key, value] of this.workers) {
184 this.setWorker(key, value.worker, {
185 run: 0,
186 running: 0,
187 runTime: 0,
188 avgRunTime: 0
189 })
ea7a90d3 190 }
a35560ba
S
191 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
192 workerChoiceStrategy
193 )
194 }
195
38e795c1 196 /** {@inheritDoc} */
7c0ba920
JB
197 public abstract get busy (): boolean
198
199 protected internalGetBusyStatus (): boolean {
200 return (
201 this.numberOfRunningTasks >= this.numberOfWorkers &&
bdaf31cd 202 this.findFreeWorker() === false
7c0ba920
JB
203 )
204 }
205
38e795c1 206 /** {@inheritDoc} */
bdaf31cd 207 public findFreeWorker (): Worker | false {
ffcbbad8
JB
208 for (const value of this.workers.values()) {
209 if (value.tasksUsage.running === 0) {
bdaf31cd 210 // A worker is free, return the matching worker
ffcbbad8 211 return value.worker
7c0ba920
JB
212 }
213 }
214 return false
215 }
216
38e795c1 217 /** {@inheritDoc} */
78cea37e 218 public async execute (data: Data): Promise<Response> {
280c2a77 219 const worker = this.chooseWorker()
b4e75778
JB
220 const messageId = crypto.randomUUID()
221 const res = this.internalExecute(worker, messageId)
14916bf9 222 this.checkAndEmitBusy()
a05c10de 223 this.sendToWorker(worker, {
e5a5c0fc
JB
224 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
225 data: data ?? ({} as Data),
b4e75778 226 id: messageId
a05c10de 227 })
78cea37e 228 // eslint-disable-next-line @typescript-eslint/return-await
280c2a77
S
229 return res
230 }
c97c7edb 231
38e795c1 232 /** {@inheritDoc} */
c97c7edb 233 public async destroy (): Promise<void> {
1fbcaa7c 234 await Promise.all(
ffcbbad8
JB
235 [...this.workers].map(async ([, value]) => {
236 await this.destroyWorker(value.worker)
1fbcaa7c
JB
237 })
238 )
c97c7edb
S
239 }
240
4a6952ff 241 /**
675bb809 242 * Shutdowns given worker.
4a6952ff 243 *
38e795c1 244 * @param worker - A worker within `workers`.
4a6952ff
JB
245 */
246 protected abstract destroyWorker (worker: Worker): void | Promise<void>
c97c7edb 247
729c563d 248 /**
280c2a77
S
249 * Setup hook that can be overridden by a Poolifier pool implementation
250 * to run code before workers are created in the abstract constructor.
729c563d 251 */
280c2a77
S
252 protected setupHook (): void {
253 // Can be overridden
254 }
c97c7edb 255
729c563d 256 /**
280c2a77
S
257 * Should return whether the worker is the main worker or not.
258 */
259 protected abstract isMain (): boolean
260
261 /**
bf9549ae
JB
262 * Hook executed before the worker task promise resolution.
263 * Can be overridden.
729c563d 264 *
38e795c1 265 * @param worker - The worker.
729c563d 266 */
bf9549ae
JB
267 protected beforePromiseWorkerResponseHook (worker: Worker): void {
268 this.increaseWorkerRunningTasks(worker)
c97c7edb
S
269 }
270
c01733f1 271 /**
bf9549ae
JB
272 * Hook executed after the worker task promise resolution.
273 * Can be overridden.
c01733f1 274 *
38e795c1
JB
275 * @param message - The received message.
276 * @param promise - The Promise response.
c01733f1 277 */
bf9549ae
JB
278 protected afterPromiseWorkerResponseHook (
279 message: MessageValue<Response>,
280 promise: PromiseWorkerResponseWrapper<Worker, Response>
281 ): void {
282 this.decreaseWorkerRunningTasks(promise.worker)
283 this.stepWorkerRunTasks(promise.worker, 1)
284 this.updateWorkerTasksRunTime(promise.worker, message.taskRunTime)
c01733f1 285 }
286
729c563d
S
287 /**
288 * Removes the given worker from the pool.
289 *
38e795c1 290 * @param worker - The worker that will be removed.
729c563d 291 */
f2fdaa86 292 protected removeWorker (worker: Worker): void {
ffcbbad8
JB
293 this.workers.delete(this.getWorkerKey(worker) as number)
294 --this.nextWorkerId
f2fdaa86
JB
295 }
296
280c2a77 297 /**
675bb809 298 * Chooses a worker for the next task.
280c2a77
S
299 *
300 * The default implementation uses a round robin algorithm to distribute the load.
301 *
302 * @returns Worker.
303 */
304 protected chooseWorker (): Worker {
a35560ba 305 return this.workerChoiceStrategyContext.execute()
c97c7edb
S
306 }
307
280c2a77 308 /**
675bb809 309 * Sends a message to the given worker.
280c2a77 310 *
38e795c1
JB
311 * @param worker - The worker which should receive the message.
312 * @param message - The message.
280c2a77
S
313 */
314 protected abstract sendToWorker (
315 worker: Worker,
316 message: MessageValue<Data>
317 ): void
318
4a6952ff 319 /**
bdede008 320 * Registers a listener callback on a given worker.
4a6952ff 321 *
38e795c1
JB
322 * @param worker - The worker which should register a listener.
323 * @param listener - The message listener callback.
4a6952ff
JB
324 */
325 protected abstract registerWorkerMessageListener<
4f7fa42a 326 Message extends Data | Response
78cea37e 327 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
c97c7edb 328
729c563d
S
329 /**
330 * Returns a newly created worker.
331 */
280c2a77 332 protected abstract createWorker (): Worker
c97c7edb 333
729c563d
S
334 /**
335 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
336 *
38e795c1 337 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
729c563d 338 *
38e795c1 339 * @param worker - The newly created worker.
729c563d 340 */
280c2a77 341 protected abstract afterWorkerSetup (worker: Worker): void
c97c7edb 342
4a6952ff
JB
343 /**
344 * Creates a new worker for this pool and sets it up completely.
345 *
346 * @returns New, completely set up worker.
347 */
348 protected createAndSetupWorker (): Worker {
bdacc2d2 349 const worker = this.createWorker()
280c2a77 350
35cf1c03 351 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
a35560ba
S
352 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
353 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
354 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
a974afa6
JB
355 worker.once('exit', () => {
356 this.removeWorker(worker)
357 })
280c2a77 358
ffcbbad8
JB
359 this.setWorker(this.nextWorkerId, worker, {
360 run: 0,
361 running: 0,
362 runTime: 0,
363 avgRunTime: 0
364 })
365 ++this.nextWorkerId
280c2a77
S
366
367 this.afterWorkerSetup(worker)
368
c97c7edb
S
369 return worker
370 }
be0676b3
APA
371
372 /**
373 * This function is the listener registered for each worker.
374 *
bdacc2d2 375 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
376 */
377 protected workerListener (): (message: MessageValue<Response>) => void {
4a6952ff 378 return message => {
bdacc2d2
JB
379 if (message.id !== undefined) {
380 const promise = this.promiseMap.get(message.id)
381 if (promise !== undefined) {
78cea37e 382 if (message.error != null) {
a05c10de
JB
383 promise.reject(message.error)
384 } else {
385 promise.resolve(message.data as Response)
386 }
bf9549ae 387 this.afterPromiseWorkerResponseHook(message, promise)
be0676b3
APA
388 this.promiseMap.delete(message.id)
389 }
390 }
391 }
be0676b3 392 }
7c0ba920 393
78cea37e
JB
394 private async internalExecute (
395 worker: Worker,
b4e75778 396 messageId: string
78cea37e
JB
397 ): Promise<Response> {
398 this.beforePromiseWorkerResponseHook(worker)
399 return await new Promise<Response>((resolve, reject) => {
400 this.promiseMap.set(messageId, { resolve, reject, worker })
401 })
402 }
403
7c0ba920 404 private checkAndEmitBusy (): void {
78cea37e 405 if (this.opts.enableEvents === true && this.busy) {
7c0ba920
JB
406 this.emitter?.emit('busy')
407 }
408 }
bf9549ae
JB
409
410 /**
10fcfaf4 411 * Increases the number of tasks that the given worker has applied.
bf9549ae 412 *
38e795c1 413 * @param worker - Worker which running tasks is increased.
bf9549ae
JB
414 */
415 private increaseWorkerRunningTasks (worker: Worker): void {
416 this.stepWorkerRunningTasks(worker, 1)
417 }
418
419 /**
10fcfaf4 420 * Decreases the number of tasks that the given worker has applied.
bf9549ae 421 *
38e795c1 422 * @param worker - Worker which running tasks is decreased.
bf9549ae
JB
423 */
424 private decreaseWorkerRunningTasks (worker: Worker): void {
425 this.stepWorkerRunningTasks(worker, -1)
426 }
427
ffcbbad8 428 /**
b4e75778 429 * Gets tasks usage of the given worker.
ffcbbad8
JB
430 *
431 * @param worker - Worker which tasks usage is returned.
432 */
433 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
434 if (this.checkWorker(worker)) {
435 const workerKey = this.getWorkerKey(worker) as number
436 const workerEntry = this.workers.get(workerKey) as WorkerType<Worker>
437 return workerEntry.tasksUsage
438 }
439 }
440
bf9549ae 441 /**
10fcfaf4 442 * Steps the number of tasks that the given worker has applied.
bf9549ae 443 *
38e795c1
JB
444 * @param worker - Worker which running tasks are stepped.
445 * @param step - Number of running tasks step.
bf9549ae
JB
446 */
447 private stepWorkerRunningTasks (worker: Worker, step: number): void {
ffcbbad8
JB
448 // prettier-ignore
449 (this.getWorkerTasksUsage(worker) as TasksUsage).running += step
bf9549ae
JB
450 }
451
452 /**
10fcfaf4 453 * Steps the number of tasks that the given worker has run.
bf9549ae 454 *
38e795c1
JB
455 * @param worker - Worker which has run tasks.
456 * @param step - Number of run tasks step.
bf9549ae 457 */
10fcfaf4 458 private stepWorkerRunTasks (worker: Worker, step: number): void {
ffcbbad8
JB
459 // prettier-ignore
460 (this.getWorkerTasksUsage(worker) as TasksUsage).run += step
bf9549ae
JB
461 }
462
463 /**
23135a89 464 * Updates tasks runtime for the given worker.
bf9549ae 465 *
38e795c1
JB
466 * @param worker - Worker which run the task.
467 * @param taskRunTime - Worker task runtime.
bf9549ae
JB
468 */
469 private updateWorkerTasksRunTime (
470 worker: Worker,
471 taskRunTime: number | undefined
10fcfaf4
JB
472 ): void {
473 if (
474 this.workerChoiceStrategyContext.getWorkerChoiceStrategy()
ffcbbad8 475 .requiredStatistics.runTime
10fcfaf4 476 ) {
ffcbbad8
JB
477 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
478 workerTasksUsage.runTime += taskRunTime ?? 0
479 if (workerTasksUsage.run !== 0) {
480 workerTasksUsage.avgRunTime =
481 workerTasksUsage.runTime / workerTasksUsage.run
10fcfaf4 482 }
a05c10de
JB
483 }
484 }
485
486 /**
ffcbbad8 487 * Sets the given worker.
ea7a90d3 488 *
ffcbbad8 489 * @param workerKey - The worker key.
38e795c1 490 * @param worker - The worker.
ffcbbad8 491 * @param tasksUsage - The worker tasks usage.
ea7a90d3 492 */
ffcbbad8
JB
493 private setWorker (
494 workerKey: number,
495 worker: Worker,
496 tasksUsage: TasksUsage
497 ): void {
498 this.workers.set(workerKey, {
499 worker,
500 tasksUsage
ea7a90d3
JB
501 })
502 }
503
bf9549ae 504 /**
ffcbbad8 505 * Checks if the given worker is registered in the pool.
ea7a90d3 506 *
ffcbbad8
JB
507 * @param worker - Worker to check.
508 * @returns `true` if the worker is registered in the pool.
ea7a90d3 509 */
ffcbbad8
JB
510 private checkWorker (worker: Worker): boolean {
511 if (this.getWorkerKey(worker) == null) {
512 throw new Error('Worker could not be found in the pool')
513 }
514 return true
ea7a90d3 515 }
c97c7edb 516}