chore: generate documentation
[poolifier.git] / src / pools / abstract-pool.ts
CommitLineData
fc3e6586 1import crypto from 'node:crypto'
2740a743 2import type { MessageValue, PromiseResponseWrapper } from '../utility-types'
ed6dd37f 3import { EMPTY_FUNCTION } from '../utils'
34a0cfab 4import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
bdaf31cd 5import type { PoolOptions } from './pool'
b4904890 6import { PoolEmitter } from './pool'
ffcbbad8 7import type { IPoolInternal, TasksUsage, WorkerType } from './pool-internal'
b4904890 8import { PoolType } from './pool-internal'
ea7a90d3 9import type { IPoolWorker } from './pool-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'
c97c7edb 15
729c563d 16/**
ea7a90d3 17 * Base class that implements some shared logic for all poolifier pools.
729c563d 18 *
38e795c1
JB
19 * @typeParam Worker - Type of worker which manages this pool.
20 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
21 * @typeParam Response - Type of response of execution. This can only be serializable data.
729c563d 22 */
c97c7edb 23export abstract class AbstractPool<
ea7a90d3 24 Worker extends IPoolWorker,
d3c8a1a8
S
25 Data = unknown,
26 Response = unknown
9b2fdd9f 27> implements IPoolInternal<Worker, Data, Response> {
afc003b2 28 /** @inheritDoc */
e65c6cd9 29 public readonly workers: Array<WorkerType<Worker>> = []
4a6952ff 30
afc003b2 31 /** @inheritDoc */
7c0ba920
JB
32 public readonly emitter?: PoolEmitter
33
be0676b3 34 /**
2740a743 35 * The promise response map.
be0676b3 36 *
2740a743 37 * - `key`: The message id of each submitted task.
c923ce56 38 * - `value`: An object that contains the worker, the promise resolve and reject callbacks.
be0676b3 39 *
2740a743 40 * When we receive a message from the worker we get a map entry with the promise resolve/reject bound to the message.
be0676b3 41 */
c923ce56
JB
42 protected promiseResponseMap: Map<
43 string,
44 PromiseResponseWrapper<Worker, Response>
45 > = new Map<string, PromiseResponseWrapper<Worker, Response>>()
c97c7edb 46
a35560ba 47 /**
51fe3d3c 48 * Worker choice strategy context referencing a worker choice algorithm implementation.
a35560ba 49 *
51fe3d3c 50 * Default to a round robin algorithm.
a35560ba
S
51 */
52 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
78cea37e
JB
53 Worker,
54 Data,
55 Response
a35560ba
S
56 >
57
729c563d
S
58 /**
59 * Constructs a new poolifier pool.
60 *
38e795c1
JB
61 * @param numberOfWorkers - Number of workers that this pool should manage.
62 * @param filePath - Path to the worker-file.
63 * @param opts - Options for the pool.
729c563d 64 */
c97c7edb 65 public constructor (
5c5a1fb7 66 public readonly numberOfWorkers: number,
c97c7edb 67 public readonly filePath: string,
1927ee67 68 public readonly opts: PoolOptions<Worker>
c97c7edb 69 ) {
78cea37e 70 if (!this.isMain()) {
c97c7edb
S
71 throw new Error('Cannot start a pool from a worker!')
72 }
8d3782fa 73 this.checkNumberOfWorkers(this.numberOfWorkers)
c510fea7 74 this.checkFilePath(this.filePath)
7c0ba920 75 this.checkPoolOptions(this.opts)
1086026a
JB
76
77 this.chooseWorker.bind(this)
78 this.internalExecute.bind(this)
164d950a 79 this.checkAndEmitFull.bind(this)
1086026a
JB
80 this.checkAndEmitBusy.bind(this)
81 this.sendToWorker.bind(this)
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
96 >(
a35560ba 97 this,
4a6952ff 98 () => {
c923ce56
JB
99 const createdWorker = this.createAndSetupWorker()
100 this.registerWorkerMessageListener(createdWorker, message => {
4a6952ff
JB
101 if (
102 isKillBehavior(KillBehaviors.HARD, message.kill) ||
c923ce56 103 this.getWorkerTasksUsage(createdWorker)?.running === 0
4a6952ff
JB
104 ) {
105 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
c923ce56 106 void this.destroyWorker(createdWorker)
4a6952ff
JB
107 }
108 })
c923ce56 109 return this.getWorkerKey(createdWorker)
4a6952ff 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
b529c323
JB
145 if (
146 !Object.values(WorkerChoiceStrategies).includes(
147 this.opts.workerChoiceStrategy
148 )
149 ) {
150 throw new Error(
151 `Invalid worker choice strategy '${this.opts.workerChoiceStrategy}'`
152 )
153 }
7c0ba920
JB
154 this.opts.enableEvents = opts.enableEvents ?? true
155 }
156
afc003b2 157 /** @inheritDoc */
7c0ba920
JB
158 public abstract get type (): PoolType
159
c2ade475 160 /**
51fe3d3c 161 * Number of tasks concurrently running in the pool.
c2ade475
JB
162 */
163 private get numberOfRunningTasks (): number {
2740a743 164 return this.promiseResponseMap.size
a35560ba
S
165 }
166
ffcbbad8 167 /**
b4e75778 168 * Gets the given worker key.
ffcbbad8
JB
169 *
170 * @param worker - The worker.
7cf00f70 171 * @returns The worker key if the worker is found in the pool, `-1` otherwise.
ffcbbad8 172 */
e65c6cd9
JB
173 private getWorkerKey (worker: Worker): number {
174 return this.workers.findIndex(workerItem => workerItem.worker === worker)
bf9549ae
JB
175 }
176
afc003b2 177 /** @inheritDoc */
a35560ba
S
178 public setWorkerChoiceStrategy (
179 workerChoiceStrategy: WorkerChoiceStrategy
180 ): void {
b98ec2e6 181 this.opts.workerChoiceStrategy = workerChoiceStrategy
c923ce56
JB
182 for (const [index, workerItem] of this.workers.entries()) {
183 this.setWorker(index, workerItem.worker, {
ffcbbad8
JB
184 run: 0,
185 running: 0,
186 runTime: 0,
2740a743
JB
187 avgRunTime: 0,
188 error: 0
ffcbbad8 189 })
ea7a90d3 190 }
a35560ba
S
191 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
192 workerChoiceStrategy
193 )
194 }
195
afc003b2 196 /** @inheritDoc */
c2ade475
JB
197 public abstract get full (): boolean
198
afc003b2 199 /** @inheritDoc */
7c0ba920
JB
200 public abstract get busy (): boolean
201
c2ade475 202 protected internalBusy (): boolean {
7c0ba920
JB
203 return (
204 this.numberOfRunningTasks >= this.numberOfWorkers &&
bf90656c 205 this.findFreeWorkerKey() === -1
7c0ba920
JB
206 )
207 }
208
afc003b2 209 /** @inheritDoc */
bf90656c
JB
210 public findFreeWorkerKey (): number {
211 return this.workers.findIndex(workerItem => {
c923ce56
JB
212 return workerItem.tasksUsage.running === 0
213 })
7c0ba920
JB
214 }
215
afc003b2 216 /** @inheritDoc */
78cea37e 217 public async execute (data: Data): Promise<Response> {
c923ce56 218 const [workerKey, worker] = this.chooseWorker()
b4e75778 219 const messageId = crypto.randomUUID()
c923ce56 220 const res = this.internalExecute(workerKey, worker, messageId)
164d950a 221 this.checkAndEmitFull()
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
afc003b2 232 /** @inheritDoc */
c97c7edb 233 public async destroy (): Promise<void> {
1fbcaa7c 234 await Promise.all(
e65c6cd9
JB
235 this.workers.map(async workerItem => {
236 await this.destroyWorker(workerItem.worker)
1fbcaa7c
JB
237 })
238 )
c97c7edb
S
239 }
240
4a6952ff 241 /**
afc003b2 242 * Shutdowns given worker in the pool.
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.
d99ba5a8 251 * Can be overridden
afc003b2
JB
252 *
253 * @virtual
729c563d 254 */
280c2a77 255 protected setupHook (): void {
d99ba5a8 256 // Intentionally empty
280c2a77 257 }
c97c7edb 258
729c563d 259 /**
280c2a77
S
260 * Should return whether the worker is the main worker or not.
261 */
262 protected abstract isMain (): boolean
263
264 /**
bf9549ae
JB
265 * Hook executed before the worker task promise resolution.
266 * Can be overridden.
729c563d 267 *
2740a743 268 * @param workerKey - The worker key.
729c563d 269 */
2740a743
JB
270 protected beforePromiseResponseHook (workerKey: number): void {
271 ++this.workers[workerKey].tasksUsage.running
c97c7edb
S
272 }
273
c01733f1 274 /**
bf9549ae
JB
275 * Hook executed after the worker task promise resolution.
276 * Can be overridden.
c01733f1 277 *
c923ce56 278 * @param worker - The worker.
38e795c1 279 * @param message - The received message.
c01733f1 280 */
2740a743 281 protected afterPromiseResponseHook (
c923ce56 282 worker: Worker,
2740a743 283 message: MessageValue<Response>
bf9549ae 284 ): void {
c923ce56 285 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
3032893a
JB
286 --workerTasksUsage.running
287 ++workerTasksUsage.run
2740a743
JB
288 if (message.error != null) {
289 ++workerTasksUsage.error
290 }
97a2abc3 291 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
3032893a 292 workerTasksUsage.runTime += message.taskRunTime ?? 0
c6bd2650
JB
293 if (
294 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
295 workerTasksUsage.run !== 0
296 ) {
3032893a
JB
297 workerTasksUsage.avgRunTime =
298 workerTasksUsage.runTime / workerTasksUsage.run
299 }
300 }
c01733f1 301 }
302
280c2a77 303 /**
675bb809 304 * Chooses a worker for the next task.
280c2a77 305 *
51fe3d3c 306 * The default uses a round robin algorithm to distribute the load.
280c2a77 307 *
c923ce56 308 * @returns [worker key, worker].
280c2a77 309 */
c923ce56
JB
310 protected chooseWorker (): [number, Worker] {
311 const workerKey = this.workerChoiceStrategyContext.execute()
312 return [workerKey, this.workers[workerKey].worker]
c97c7edb
S
313 }
314
280c2a77 315 /**
675bb809 316 * Sends a message to the given worker.
280c2a77 317 *
38e795c1
JB
318 * @param worker - The worker which should receive the message.
319 * @param message - The message.
280c2a77
S
320 */
321 protected abstract sendToWorker (
322 worker: Worker,
323 message: MessageValue<Data>
324 ): void
325
4a6952ff 326 /**
bdede008 327 * Registers a listener callback on a given worker.
4a6952ff 328 *
38e795c1
JB
329 * @param worker - The worker which should register a listener.
330 * @param listener - The message listener callback.
4a6952ff
JB
331 */
332 protected abstract registerWorkerMessageListener<
4f7fa42a 333 Message extends Data | Response
78cea37e 334 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
c97c7edb 335
729c563d
S
336 /**
337 * Returns a newly created worker.
338 */
280c2a77 339 protected abstract createWorker (): Worker
c97c7edb 340
729c563d
S
341 /**
342 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
343 *
38e795c1 344 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
729c563d 345 *
38e795c1 346 * @param worker - The newly created worker.
afc003b2 347 * @virtual
729c563d 348 */
280c2a77 349 protected abstract afterWorkerSetup (worker: Worker): void
c97c7edb 350
4a6952ff
JB
351 /**
352 * Creates a new worker for this pool and sets it up completely.
353 *
354 * @returns New, completely set up worker.
355 */
356 protected createAndSetupWorker (): Worker {
bdacc2d2 357 const worker = this.createWorker()
280c2a77 358
35cf1c03 359 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
a35560ba
S
360 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
361 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
362 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
a974afa6
JB
363 worker.once('exit', () => {
364 this.removeWorker(worker)
365 })
280c2a77 366
c923ce56 367 this.pushWorker(worker, {
ffcbbad8
JB
368 run: 0,
369 running: 0,
370 runTime: 0,
2740a743
JB
371 avgRunTime: 0,
372 error: 0
ffcbbad8 373 })
280c2a77
S
374
375 this.afterWorkerSetup(worker)
376
c97c7edb
S
377 return worker
378 }
be0676b3
APA
379
380 /**
381 * This function is the listener registered for each worker.
382 *
bdacc2d2 383 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
384 */
385 protected workerListener (): (message: MessageValue<Response>) => void {
4a6952ff 386 return message => {
b1989cfd 387 if (message.id != null) {
2740a743 388 const promiseResponse = this.promiseResponseMap.get(message.id)
b1989cfd 389 if (promiseResponse != null) {
78cea37e 390 if (message.error != null) {
2740a743 391 promiseResponse.reject(message.error)
a05c10de 392 } else {
2740a743 393 promiseResponse.resolve(message.data as Response)
a05c10de 394 }
c923ce56 395 this.afterPromiseResponseHook(promiseResponse.worker, message)
2740a743 396 this.promiseResponseMap.delete(message.id)
be0676b3
APA
397 }
398 }
399 }
be0676b3 400 }
7c0ba920 401
78cea37e 402 private async internalExecute (
2740a743 403 workerKey: number,
c923ce56 404 worker: Worker,
b4e75778 405 messageId: string
78cea37e 406 ): Promise<Response> {
2740a743 407 this.beforePromiseResponseHook(workerKey)
78cea37e 408 return await new Promise<Response>((resolve, reject) => {
c923ce56 409 this.promiseResponseMap.set(messageId, { resolve, reject, worker })
78cea37e
JB
410 })
411 }
412
7c0ba920 413 private checkAndEmitBusy (): void {
78cea37e 414 if (this.opts.enableEvents === true && this.busy) {
7c0ba920
JB
415 this.emitter?.emit('busy')
416 }
417 }
bf9549ae 418
164d950a
JB
419 private checkAndEmitFull (): void {
420 if (
421 this.type === PoolType.DYNAMIC &&
422 this.opts.enableEvents === true &&
423 this.full
424 ) {
425 this.emitter?.emit('full')
426 }
427 }
428
c923ce56 429 /**
afc003b2 430 * Gets the given worker tasks usage in the pool.
c923ce56
JB
431 *
432 * @param worker - The worker.
433 * @returns The worker tasks usage.
434 */
435 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
3032893a 436 const workerKey = this.getWorkerKey(worker)
e65c6cd9
JB
437 if (workerKey !== -1) {
438 return this.workers[workerKey].tasksUsage
ffcbbad8 439 }
3032893a 440 throw new Error('Worker could not be found in the pool')
a05c10de
JB
441 }
442
443 /**
51fe3d3c 444 * Pushes the given worker in the pool.
ea7a90d3 445 *
38e795c1 446 * @param worker - The worker.
ffcbbad8 447 * @param tasksUsage - The worker tasks usage.
ea7a90d3 448 */
c923ce56 449 private pushWorker (worker: Worker, tasksUsage: TasksUsage): void {
e65c6cd9 450 this.workers.push({
ffcbbad8
JB
451 worker,
452 tasksUsage
ea7a90d3
JB
453 })
454 }
c923ce56
JB
455
456 /**
51fe3d3c 457 * Sets the given worker in the pool.
c923ce56
JB
458 *
459 * @param workerKey - The worker key.
460 * @param worker - The worker.
461 * @param tasksUsage - The worker tasks usage.
462 */
463 private setWorker (
464 workerKey: number,
465 worker: Worker,
466 tasksUsage: TasksUsage
467 ): void {
468 this.workers[workerKey] = {
469 worker,
470 tasksUsage
471 }
472 }
51fe3d3c
JB
473
474 /**
475 * Removes the given worker from the pool.
476 *
477 * @param worker - The worker that will be removed.
478 */
479 protected removeWorker (worker: Worker): void {
480 const workerKey = this.getWorkerKey(worker)
481 this.workers.splice(workerKey, 1)
482 this.workerChoiceStrategyContext.remove(workerKey)
483 }
c97c7edb 484}