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