perf: remove unneeded class indirection for dynamic pool in worker
[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)
79 this.checkAndEmitBusy.bind(this)
80 this.sendToWorker.bind(this)
81
c97c7edb
S
82 this.setupHook()
83
5c5a1fb7 84 for (let i = 1; i <= this.numberOfWorkers; i++) {
280c2a77 85 this.createAndSetupWorker()
c97c7edb
S
86 }
87
6bd72cd0 88 if (this.opts.enableEvents === true) {
7c0ba920
JB
89 this.emitter = new PoolEmitter()
90 }
a35560ba
S
91 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext(
92 this,
4a6952ff 93 () => {
c923ce56
JB
94 const createdWorker = this.createAndSetupWorker()
95 this.registerWorkerMessageListener(createdWorker, message => {
4a6952ff
JB
96 if (
97 isKillBehavior(KillBehaviors.HARD, message.kill) ||
c923ce56 98 this.getWorkerTasksUsage(createdWorker)?.running === 0
4a6952ff
JB
99 ) {
100 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
c923ce56 101 void this.destroyWorker(createdWorker)
4a6952ff
JB
102 }
103 })
c923ce56 104 return this.getWorkerKey(createdWorker)
4a6952ff 105 },
e843b904 106 this.opts.workerChoiceStrategy
a35560ba 107 )
c97c7edb
S
108 }
109
a35560ba 110 private checkFilePath (filePath: string): void {
ffcbbad8
JB
111 if (
112 filePath == null ||
113 (typeof filePath === 'string' && filePath.trim().length === 0)
114 ) {
c510fea7
APA
115 throw new Error('Please specify a file with a worker implementation')
116 }
117 }
118
8d3782fa
JB
119 private checkNumberOfWorkers (numberOfWorkers: number): void {
120 if (numberOfWorkers == null) {
121 throw new Error(
122 'Cannot instantiate a pool without specifying the number of workers'
123 )
78cea37e 124 } else if (!Number.isSafeInteger(numberOfWorkers)) {
473c717a 125 throw new TypeError(
8d3782fa
JB
126 'Cannot instantiate a pool with a non integer number of workers'
127 )
128 } else if (numberOfWorkers < 0) {
473c717a 129 throw new RangeError(
8d3782fa
JB
130 'Cannot instantiate a pool with a negative number of workers'
131 )
7c0ba920 132 } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) {
8d3782fa
JB
133 throw new Error('Cannot instantiate a fixed pool with no worker')
134 }
135 }
136
7c0ba920 137 private checkPoolOptions (opts: PoolOptions<Worker>): void {
e843b904
JB
138 this.opts.workerChoiceStrategy =
139 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
7c0ba920
JB
140 this.opts.enableEvents = opts.enableEvents ?? true
141 }
142
38e795c1 143 /** {@inheritDoc} */
7c0ba920
JB
144 public abstract get type (): PoolType
145
c2ade475
JB
146 /**
147 * Number of tasks concurrently running.
148 */
149 private get numberOfRunningTasks (): number {
2740a743 150 return this.promiseResponseMap.size
a35560ba
S
151 }
152
ffcbbad8 153 /**
b4e75778 154 * Gets the given worker key.
ffcbbad8
JB
155 *
156 * @param worker - The worker.
7cf00f70 157 * @returns The worker key if the worker is found in the pool, `-1` otherwise.
ffcbbad8 158 */
e65c6cd9
JB
159 private getWorkerKey (worker: Worker): number {
160 return this.workers.findIndex(workerItem => workerItem.worker === worker)
bf9549ae
JB
161 }
162
38e795c1 163 /** {@inheritDoc} */
a35560ba
S
164 public setWorkerChoiceStrategy (
165 workerChoiceStrategy: WorkerChoiceStrategy
166 ): void {
b98ec2e6 167 this.opts.workerChoiceStrategy = workerChoiceStrategy
c923ce56
JB
168 for (const [index, workerItem] of this.workers.entries()) {
169 this.setWorker(index, workerItem.worker, {
ffcbbad8
JB
170 run: 0,
171 running: 0,
172 runTime: 0,
2740a743
JB
173 avgRunTime: 0,
174 error: 0
ffcbbad8 175 })
ea7a90d3 176 }
a35560ba
S
177 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
178 workerChoiceStrategy
179 )
180 }
181
c2ade475
JB
182 /** {@inheritDoc} */
183 public abstract get full (): boolean
184
38e795c1 185 /** {@inheritDoc} */
7c0ba920
JB
186 public abstract get busy (): boolean
187
c2ade475 188 protected internalBusy (): boolean {
7c0ba920
JB
189 return (
190 this.numberOfRunningTasks >= this.numberOfWorkers &&
bf90656c 191 this.findFreeWorkerKey() === -1
7c0ba920
JB
192 )
193 }
194
38e795c1 195 /** {@inheritDoc} */
bf90656c
JB
196 public findFreeWorkerKey (): number {
197 return this.workers.findIndex(workerItem => {
c923ce56
JB
198 return workerItem.tasksUsage.running === 0
199 })
7c0ba920
JB
200 }
201
38e795c1 202 /** {@inheritDoc} */
78cea37e 203 public async execute (data: Data): Promise<Response> {
c923ce56 204 const [workerKey, worker] = this.chooseWorker()
b4e75778 205 const messageId = crypto.randomUUID()
c923ce56 206 const res = this.internalExecute(workerKey, worker, messageId)
14916bf9 207 this.checkAndEmitBusy()
a05c10de 208 this.sendToWorker(worker, {
e5a5c0fc
JB
209 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
210 data: data ?? ({} as Data),
b4e75778 211 id: messageId
a05c10de 212 })
78cea37e 213 // eslint-disable-next-line @typescript-eslint/return-await
280c2a77
S
214 return res
215 }
c97c7edb 216
38e795c1 217 /** {@inheritDoc} */
c97c7edb 218 public async destroy (): Promise<void> {
1fbcaa7c 219 await Promise.all(
e65c6cd9
JB
220 this.workers.map(async workerItem => {
221 await this.destroyWorker(workerItem.worker)
1fbcaa7c
JB
222 })
223 )
c97c7edb
S
224 }
225
4a6952ff 226 /**
675bb809 227 * Shutdowns given worker.
4a6952ff 228 *
38e795c1 229 * @param worker - A worker within `workers`.
4a6952ff
JB
230 */
231 protected abstract destroyWorker (worker: Worker): void | Promise<void>
c97c7edb 232
729c563d 233 /**
280c2a77
S
234 * Setup hook that can be overridden by a Poolifier pool implementation
235 * to run code before workers are created in the abstract constructor.
729c563d 236 */
280c2a77
S
237 protected setupHook (): void {
238 // Can be overridden
239 }
c97c7edb 240
729c563d 241 /**
280c2a77
S
242 * Should return whether the worker is the main worker or not.
243 */
244 protected abstract isMain (): boolean
245
246 /**
bf9549ae
JB
247 * Hook executed before the worker task promise resolution.
248 * Can be overridden.
729c563d 249 *
2740a743 250 * @param workerKey - The worker key.
729c563d 251 */
2740a743
JB
252 protected beforePromiseResponseHook (workerKey: number): void {
253 ++this.workers[workerKey].tasksUsage.running
c97c7edb
S
254 }
255
c01733f1 256 /**
bf9549ae
JB
257 * Hook executed after the worker task promise resolution.
258 * Can be overridden.
c01733f1 259 *
c923ce56 260 * @param worker - The worker.
38e795c1 261 * @param message - The received message.
c01733f1 262 */
2740a743 263 protected afterPromiseResponseHook (
c923ce56 264 worker: Worker,
2740a743 265 message: MessageValue<Response>
bf9549ae 266 ): void {
c923ce56 267 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
3032893a
JB
268 --workerTasksUsage.running
269 ++workerTasksUsage.run
2740a743
JB
270 if (message.error != null) {
271 ++workerTasksUsage.error
272 }
97a2abc3 273 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
3032893a 274 workerTasksUsage.runTime += message.taskRunTime ?? 0
c6bd2650
JB
275 if (
276 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
277 workerTasksUsage.run !== 0
278 ) {
3032893a
JB
279 workerTasksUsage.avgRunTime =
280 workerTasksUsage.runTime / workerTasksUsage.run
281 }
282 }
c01733f1 283 }
284
729c563d
S
285 /**
286 * Removes the given worker from the pool.
287 *
38e795c1 288 * @param worker - The worker that will be removed.
729c563d 289 */
f2fdaa86 290 protected removeWorker (worker: Worker): void {
97a2abc3
JB
291 const workerKey = this.getWorkerKey(worker)
292 this.workers.splice(workerKey, 1)
293 this.workerChoiceStrategyContext.remove(workerKey)
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 *
c923ce56 301 * @returns [worker key, worker].
280c2a77 302 */
c923ce56
JB
303 protected chooseWorker (): [number, Worker] {
304 const workerKey = this.workerChoiceStrategyContext.execute()
305 return [workerKey, this.workers[workerKey].worker]
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
c923ce56 359 this.pushWorker(worker, {
ffcbbad8
JB
360 run: 0,
361 running: 0,
362 runTime: 0,
2740a743
JB
363 avgRunTime: 0,
364 error: 0
ffcbbad8 365 })
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 379 if (message.id !== undefined) {
2740a743
JB
380 const promiseResponse = this.promiseResponseMap.get(message.id)
381 if (promiseResponse !== undefined) {
78cea37e 382 if (message.error != null) {
2740a743 383 promiseResponse.reject(message.error)
a05c10de 384 } else {
2740a743 385 promiseResponse.resolve(message.data as Response)
a05c10de 386 }
c923ce56 387 this.afterPromiseResponseHook(promiseResponse.worker, message)
2740a743 388 this.promiseResponseMap.delete(message.id)
be0676b3
APA
389 }
390 }
391 }
be0676b3 392 }
7c0ba920 393
78cea37e 394 private async internalExecute (
2740a743 395 workerKey: number,
c923ce56 396 worker: Worker,
b4e75778 397 messageId: string
78cea37e 398 ): Promise<Response> {
2740a743 399 this.beforePromiseResponseHook(workerKey)
78cea37e 400 return await new Promise<Response>((resolve, reject) => {
c923ce56 401 this.promiseResponseMap.set(messageId, { resolve, reject, worker })
78cea37e
JB
402 })
403 }
404
7c0ba920 405 private checkAndEmitBusy (): void {
78cea37e 406 if (this.opts.enableEvents === true && this.busy) {
7c0ba920
JB
407 this.emitter?.emit('busy')
408 }
409 }
bf9549ae 410
c923ce56
JB
411 /**
412 * Gets worker tasks usage.
413 *
414 * @param worker - The worker.
415 * @returns The worker tasks usage.
416 */
417 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
3032893a 418 const workerKey = this.getWorkerKey(worker)
e65c6cd9
JB
419 if (workerKey !== -1) {
420 return this.workers[workerKey].tasksUsage
ffcbbad8 421 }
3032893a 422 throw new Error('Worker could not be found in the pool')
a05c10de
JB
423 }
424
425 /**
c923ce56 426 * Pushes the given worker.
ea7a90d3 427 *
38e795c1 428 * @param worker - The worker.
ffcbbad8 429 * @param tasksUsage - The worker tasks usage.
ea7a90d3 430 */
c923ce56 431 private pushWorker (worker: Worker, tasksUsage: TasksUsage): void {
e65c6cd9 432 this.workers.push({
ffcbbad8
JB
433 worker,
434 tasksUsage
ea7a90d3
JB
435 })
436 }
c923ce56
JB
437
438 /**
439 * Sets the given worker.
440 *
441 * @param workerKey - The worker key.
442 * @param worker - The worker.
443 * @param tasksUsage - The worker tasks usage.
444 */
445 private setWorker (
446 workerKey: number,
447 worker: Worker,
448 tasksUsage: TasksUsage
449 ): void {
450 this.workers[workerKey] = {
451 worker,
452 tasksUsage
453 }
454 }
c97c7edb 455}