refactor: use class property if appropriate
[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> {
38e795c1 28 /** {@inheritDoc} */
e65c6cd9 29 public readonly workers: Array<WorkerType<Worker>> = []
4a6952ff 30
38e795c1 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
S
47 /**
48 * Worker choice strategy instance implementing the worker choice algorithm.
49 *
50 * Default to a strategy implementing a round robin algorithm.
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
7c0ba920
JB
145 this.opts.enableEvents = opts.enableEvents ?? true
146 }
147
38e795c1 148 /** {@inheritDoc} */
7c0ba920
JB
149 public abstract get type (): PoolType
150
c2ade475
JB
151 /**
152 * Number of tasks concurrently running.
153 */
154 private get numberOfRunningTasks (): number {
2740a743 155 return this.promiseResponseMap.size
a35560ba
S
156 }
157
ffcbbad8 158 /**
b4e75778 159 * Gets the given worker key.
ffcbbad8
JB
160 *
161 * @param worker - The worker.
7cf00f70 162 * @returns The worker key if the worker is found in the pool, `-1` otherwise.
ffcbbad8 163 */
e65c6cd9
JB
164 private getWorkerKey (worker: Worker): number {
165 return this.workers.findIndex(workerItem => workerItem.worker === worker)
bf9549ae
JB
166 }
167
38e795c1 168 /** {@inheritDoc} */
a35560ba
S
169 public setWorkerChoiceStrategy (
170 workerChoiceStrategy: WorkerChoiceStrategy
171 ): void {
b98ec2e6 172 this.opts.workerChoiceStrategy = workerChoiceStrategy
c923ce56
JB
173 for (const [index, workerItem] of this.workers.entries()) {
174 this.setWorker(index, workerItem.worker, {
ffcbbad8
JB
175 run: 0,
176 running: 0,
177 runTime: 0,
2740a743
JB
178 avgRunTime: 0,
179 error: 0
ffcbbad8 180 })
ea7a90d3 181 }
a35560ba 182 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
3300e7bc 183 this,
a35560ba
S
184 workerChoiceStrategy
185 )
186 }
187
c2ade475
JB
188 /** {@inheritDoc} */
189 public abstract get full (): boolean
190
38e795c1 191 /** {@inheritDoc} */
7c0ba920
JB
192 public abstract get busy (): boolean
193
c2ade475 194 protected internalBusy (): boolean {
7c0ba920
JB
195 return (
196 this.numberOfRunningTasks >= this.numberOfWorkers &&
bf90656c 197 this.findFreeWorkerKey() === -1
7c0ba920
JB
198 )
199 }
200
38e795c1 201 /** {@inheritDoc} */
bf90656c
JB
202 public findFreeWorkerKey (): number {
203 return this.workers.findIndex(workerItem => {
c923ce56
JB
204 return workerItem.tasksUsage.running === 0
205 })
7c0ba920
JB
206 }
207
38e795c1 208 /** {@inheritDoc} */
78cea37e 209 public async execute (data: Data): Promise<Response> {
c923ce56 210 const [workerKey, worker] = this.chooseWorker()
b4e75778 211 const messageId = crypto.randomUUID()
c923ce56 212 const res = this.internalExecute(workerKey, worker, messageId)
164d950a 213 this.checkAndEmitFull()
14916bf9 214 this.checkAndEmitBusy()
a05c10de 215 this.sendToWorker(worker, {
e5a5c0fc
JB
216 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
217 data: data ?? ({} as Data),
b4e75778 218 id: messageId
a05c10de 219 })
78cea37e 220 // eslint-disable-next-line @typescript-eslint/return-await
280c2a77
S
221 return res
222 }
c97c7edb 223
38e795c1 224 /** {@inheritDoc} */
c97c7edb 225 public async destroy (): Promise<void> {
1fbcaa7c 226 await Promise.all(
e65c6cd9
JB
227 this.workers.map(async workerItem => {
228 await this.destroyWorker(workerItem.worker)
1fbcaa7c
JB
229 })
230 )
c97c7edb
S
231 }
232
4a6952ff 233 /**
675bb809 234 * Shutdowns given worker.
4a6952ff 235 *
38e795c1 236 * @param worker - A worker within `workers`.
4a6952ff
JB
237 */
238 protected abstract destroyWorker (worker: Worker): void | Promise<void>
c97c7edb 239
729c563d 240 /**
280c2a77
S
241 * Setup hook that can be overridden by a Poolifier pool implementation
242 * to run code before workers are created in the abstract constructor.
729c563d 243 */
280c2a77
S
244 protected setupHook (): void {
245 // Can be overridden
246 }
c97c7edb 247
729c563d 248 /**
280c2a77
S
249 * Should return whether the worker is the main worker or not.
250 */
251 protected abstract isMain (): boolean
252
253 /**
bf9549ae
JB
254 * Hook executed before the worker task promise resolution.
255 * Can be overridden.
729c563d 256 *
2740a743 257 * @param workerKey - The worker key.
729c563d 258 */
2740a743
JB
259 protected beforePromiseResponseHook (workerKey: number): void {
260 ++this.workers[workerKey].tasksUsage.running
c97c7edb
S
261 }
262
c01733f1 263 /**
bf9549ae
JB
264 * Hook executed after the worker task promise resolution.
265 * Can be overridden.
c01733f1 266 *
c923ce56 267 * @param worker - The worker.
38e795c1 268 * @param message - The received message.
c01733f1 269 */
2740a743 270 protected afterPromiseResponseHook (
c923ce56 271 worker: Worker,
2740a743 272 message: MessageValue<Response>
bf9549ae 273 ): void {
c923ce56 274 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
3032893a
JB
275 --workerTasksUsage.running
276 ++workerTasksUsage.run
2740a743
JB
277 if (message.error != null) {
278 ++workerTasksUsage.error
279 }
97a2abc3 280 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
3032893a 281 workerTasksUsage.runTime += message.taskRunTime ?? 0
c6bd2650
JB
282 if (
283 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
284 workerTasksUsage.run !== 0
285 ) {
3032893a
JB
286 workerTasksUsage.avgRunTime =
287 workerTasksUsage.runTime / workerTasksUsage.run
288 }
289 }
c01733f1 290 }
291
729c563d
S
292 /**
293 * Removes the given worker from the pool.
294 *
38e795c1 295 * @param worker - The worker that will be removed.
729c563d 296 */
f2fdaa86 297 protected removeWorker (worker: Worker): void {
97a2abc3
JB
298 const workerKey = this.getWorkerKey(worker)
299 this.workers.splice(workerKey, 1)
300 this.workerChoiceStrategyContext.remove(workerKey)
f2fdaa86
JB
301 }
302
280c2a77 303 /**
675bb809 304 * Chooses a worker for the next task.
280c2a77
S
305 *
306 * The default implementation uses a round robin algorithm to distribute the load.
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.
729c563d 347 */
280c2a77 348 protected abstract afterWorkerSetup (worker: Worker): void
c97c7edb 349
4a6952ff
JB
350 /**
351 * Creates a new worker for this pool and sets it up completely.
352 *
353 * @returns New, completely set up worker.
354 */
355 protected createAndSetupWorker (): Worker {
bdacc2d2 356 const worker = this.createWorker()
280c2a77 357
35cf1c03 358 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
a35560ba
S
359 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
360 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
361 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
a974afa6
JB
362 worker.once('exit', () => {
363 this.removeWorker(worker)
364 })
280c2a77 365
c923ce56 366 this.pushWorker(worker, {
ffcbbad8
JB
367 run: 0,
368 running: 0,
369 runTime: 0,
2740a743
JB
370 avgRunTime: 0,
371 error: 0
ffcbbad8 372 })
280c2a77
S
373
374 this.afterWorkerSetup(worker)
375
c97c7edb
S
376 return worker
377 }
be0676b3
APA
378
379 /**
380 * This function is the listener registered for each worker.
381 *
bdacc2d2 382 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
383 */
384 protected workerListener (): (message: MessageValue<Response>) => void {
4a6952ff 385 return message => {
bdacc2d2 386 if (message.id !== undefined) {
2740a743
JB
387 const promiseResponse = this.promiseResponseMap.get(message.id)
388 if (promiseResponse !== undefined) {
78cea37e 389 if (message.error != null) {
2740a743 390 promiseResponse.reject(message.error)
a05c10de 391 } else {
2740a743 392 promiseResponse.resolve(message.data as Response)
a05c10de 393 }
c923ce56 394 this.afterPromiseResponseHook(promiseResponse.worker, message)
2740a743 395 this.promiseResponseMap.delete(message.id)
be0676b3
APA
396 }
397 }
398 }
be0676b3 399 }
7c0ba920 400
78cea37e 401 private async internalExecute (
2740a743 402 workerKey: number,
c923ce56 403 worker: Worker,
b4e75778 404 messageId: string
78cea37e 405 ): Promise<Response> {
2740a743 406 this.beforePromiseResponseHook(workerKey)
78cea37e 407 return await new Promise<Response>((resolve, reject) => {
c923ce56 408 this.promiseResponseMap.set(messageId, { resolve, reject, worker })
78cea37e
JB
409 })
410 }
411
7c0ba920 412 private checkAndEmitBusy (): void {
78cea37e 413 if (this.opts.enableEvents === true && this.busy) {
7c0ba920
JB
414 this.emitter?.emit('busy')
415 }
416 }
bf9549ae 417
164d950a
JB
418 private checkAndEmitFull (): void {
419 if (
420 this.type === PoolType.DYNAMIC &&
421 this.opts.enableEvents === true &&
422 this.full
423 ) {
424 this.emitter?.emit('full')
425 }
426 }
427
c923ce56
JB
428 /**
429 * Gets worker tasks usage.
430 *
431 * @param worker - The worker.
432 * @returns The worker tasks usage.
433 */
434 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
3032893a 435 const workerKey = this.getWorkerKey(worker)
e65c6cd9
JB
436 if (workerKey !== -1) {
437 return this.workers[workerKey].tasksUsage
ffcbbad8 438 }
3032893a 439 throw new Error('Worker could not be found in the pool')
a05c10de
JB
440 }
441
442 /**
c923ce56 443 * Pushes the given worker.
ea7a90d3 444 *
38e795c1 445 * @param worker - The worker.
ffcbbad8 446 * @param tasksUsage - The worker tasks usage.
ea7a90d3 447 */
c923ce56 448 private pushWorker (worker: Worker, tasksUsage: TasksUsage): void {
e65c6cd9 449 this.workers.push({
ffcbbad8
JB
450 worker,
451 tasksUsage
ea7a90d3
JB
452 })
453 }
c923ce56
JB
454
455 /**
456 * Sets the given worker.
457 *
458 * @param workerKey - The worker key.
459 * @param worker - The worker.
460 * @param tasksUsage - The worker tasks usage.
461 */
462 private setWorker (
463 workerKey: number,
464 worker: Worker,
465 tasksUsage: TasksUsage
466 ): void {
467 this.workers[workerKey] = {
468 worker,
469 tasksUsage
470 }
471 }
c97c7edb 472}