Merge branch 'master' of github.com:poolifier/poolifier
[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)
c97c7edb
S
76 this.setupHook()
77
5c5a1fb7 78 for (let i = 1; i <= this.numberOfWorkers; i++) {
280c2a77 79 this.createAndSetupWorker()
c97c7edb
S
80 }
81
6bd72cd0 82 if (this.opts.enableEvents === true) {
7c0ba920
JB
83 this.emitter = new PoolEmitter()
84 }
a35560ba
S
85 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext(
86 this,
4a6952ff 87 () => {
c923ce56
JB
88 const createdWorker = this.createAndSetupWorker()
89 this.registerWorkerMessageListener(createdWorker, message => {
4a6952ff
JB
90 if (
91 isKillBehavior(KillBehaviors.HARD, message.kill) ||
c923ce56 92 this.getWorkerTasksUsage(createdWorker)?.running === 0
4a6952ff
JB
93 ) {
94 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
c923ce56 95 void this.destroyWorker(createdWorker)
4a6952ff
JB
96 }
97 })
c923ce56 98 return this.getWorkerKey(createdWorker)
4a6952ff 99 },
e843b904 100 this.opts.workerChoiceStrategy
a35560ba 101 )
c97c7edb
S
102 }
103
a35560ba 104 private checkFilePath (filePath: string): void {
ffcbbad8
JB
105 if (
106 filePath == null ||
107 (typeof filePath === 'string' && filePath.trim().length === 0)
108 ) {
c510fea7
APA
109 throw new Error('Please specify a file with a worker implementation')
110 }
111 }
112
8d3782fa
JB
113 private checkNumberOfWorkers (numberOfWorkers: number): void {
114 if (numberOfWorkers == null) {
115 throw new Error(
116 'Cannot instantiate a pool without specifying the number of workers'
117 )
78cea37e 118 } else if (!Number.isSafeInteger(numberOfWorkers)) {
473c717a 119 throw new TypeError(
8d3782fa
JB
120 'Cannot instantiate a pool with a non integer number of workers'
121 )
122 } else if (numberOfWorkers < 0) {
473c717a 123 throw new RangeError(
8d3782fa
JB
124 'Cannot instantiate a pool with a negative number of workers'
125 )
7c0ba920 126 } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) {
8d3782fa
JB
127 throw new Error('Cannot instantiate a fixed pool with no worker')
128 }
129 }
130
7c0ba920 131 private checkPoolOptions (opts: PoolOptions<Worker>): void {
e843b904
JB
132 this.opts.workerChoiceStrategy =
133 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
7c0ba920
JB
134 this.opts.enableEvents = opts.enableEvents ?? true
135 }
136
38e795c1 137 /** {@inheritDoc} */
7c0ba920
JB
138 public abstract get type (): PoolType
139
38e795c1 140 /** {@inheritDoc} */
7c0ba920 141 public get numberOfRunningTasks (): number {
2740a743 142 return this.promiseResponseMap.size
a35560ba
S
143 }
144
ffcbbad8 145 /**
b4e75778 146 * Gets the given worker key.
ffcbbad8
JB
147 *
148 * @param worker - The worker.
7cf00f70 149 * @returns The worker key if the worker is found in the pool, `-1` otherwise.
ffcbbad8 150 */
e65c6cd9
JB
151 private getWorkerKey (worker: Worker): number {
152 return this.workers.findIndex(workerItem => workerItem.worker === worker)
bf9549ae
JB
153 }
154
38e795c1 155 /** {@inheritDoc} */
a35560ba
S
156 public setWorkerChoiceStrategy (
157 workerChoiceStrategy: WorkerChoiceStrategy
158 ): void {
b98ec2e6 159 this.opts.workerChoiceStrategy = workerChoiceStrategy
c923ce56
JB
160 for (const [index, workerItem] of this.workers.entries()) {
161 this.setWorker(index, workerItem.worker, {
ffcbbad8
JB
162 run: 0,
163 running: 0,
164 runTime: 0,
2740a743
JB
165 avgRunTime: 0,
166 error: 0
ffcbbad8 167 })
ea7a90d3 168 }
a35560ba
S
169 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
170 workerChoiceStrategy
171 )
172 }
173
38e795c1 174 /** {@inheritDoc} */
7c0ba920
JB
175 public abstract get busy (): boolean
176
177 protected internalGetBusyStatus (): boolean {
178 return (
179 this.numberOfRunningTasks >= this.numberOfWorkers &&
bf90656c 180 this.findFreeWorkerKey() === -1
7c0ba920
JB
181 )
182 }
183
38e795c1 184 /** {@inheritDoc} */
bf90656c
JB
185 public findFreeWorkerKey (): number {
186 return this.workers.findIndex(workerItem => {
c923ce56
JB
187 return workerItem.tasksUsage.running === 0
188 })
7c0ba920
JB
189 }
190
38e795c1 191 /** {@inheritDoc} */
78cea37e 192 public async execute (data: Data): Promise<Response> {
c923ce56 193 const [workerKey, worker] = this.chooseWorker()
b4e75778 194 const messageId = crypto.randomUUID()
c923ce56 195 const res = this.internalExecute(workerKey, worker, messageId)
14916bf9 196 this.checkAndEmitBusy()
a05c10de 197 this.sendToWorker(worker, {
e5a5c0fc
JB
198 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
199 data: data ?? ({} as Data),
b4e75778 200 id: messageId
a05c10de 201 })
78cea37e 202 // eslint-disable-next-line @typescript-eslint/return-await
280c2a77
S
203 return res
204 }
c97c7edb 205
38e795c1 206 /** {@inheritDoc} */
c97c7edb 207 public async destroy (): Promise<void> {
1fbcaa7c 208 await Promise.all(
e65c6cd9
JB
209 this.workers.map(async workerItem => {
210 await this.destroyWorker(workerItem.worker)
1fbcaa7c
JB
211 })
212 )
c97c7edb
S
213 }
214
4a6952ff 215 /**
675bb809 216 * Shutdowns given worker.
4a6952ff 217 *
38e795c1 218 * @param worker - A worker within `workers`.
4a6952ff
JB
219 */
220 protected abstract destroyWorker (worker: Worker): void | Promise<void>
c97c7edb 221
729c563d 222 /**
280c2a77
S
223 * Setup hook that can be overridden by a Poolifier pool implementation
224 * to run code before workers are created in the abstract constructor.
729c563d 225 */
280c2a77
S
226 protected setupHook (): void {
227 // Can be overridden
228 }
c97c7edb 229
729c563d 230 /**
280c2a77
S
231 * Should return whether the worker is the main worker or not.
232 */
233 protected abstract isMain (): boolean
234
235 /**
bf9549ae
JB
236 * Hook executed before the worker task promise resolution.
237 * Can be overridden.
729c563d 238 *
2740a743 239 * @param workerKey - The worker key.
729c563d 240 */
2740a743
JB
241 protected beforePromiseResponseHook (workerKey: number): void {
242 ++this.workers[workerKey].tasksUsage.running
c97c7edb
S
243 }
244
c01733f1 245 /**
bf9549ae
JB
246 * Hook executed after the worker task promise resolution.
247 * Can be overridden.
c01733f1 248 *
c923ce56 249 * @param worker - The worker.
38e795c1 250 * @param message - The received message.
c01733f1 251 */
2740a743 252 protected afterPromiseResponseHook (
c923ce56 253 worker: Worker,
2740a743 254 message: MessageValue<Response>
bf9549ae 255 ): void {
c923ce56 256 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
3032893a
JB
257 --workerTasksUsage.running
258 ++workerTasksUsage.run
2740a743
JB
259 if (message.error != null) {
260 ++workerTasksUsage.error
261 }
97a2abc3 262 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
3032893a 263 workerTasksUsage.runTime += message.taskRunTime ?? 0
c6bd2650
JB
264 if (
265 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
266 workerTasksUsage.run !== 0
267 ) {
3032893a
JB
268 workerTasksUsage.avgRunTime =
269 workerTasksUsage.runTime / workerTasksUsage.run
270 }
271 }
c01733f1 272 }
273
729c563d
S
274 /**
275 * Removes the given worker from the pool.
276 *
38e795c1 277 * @param worker - The worker that will be removed.
729c563d 278 */
f2fdaa86 279 protected removeWorker (worker: Worker): void {
97a2abc3
JB
280 const workerKey = this.getWorkerKey(worker)
281 this.workers.splice(workerKey, 1)
282 this.workerChoiceStrategyContext.remove(workerKey)
f2fdaa86
JB
283 }
284
280c2a77 285 /**
675bb809 286 * Chooses a worker for the next task.
280c2a77
S
287 *
288 * The default implementation uses a round robin algorithm to distribute the load.
289 *
c923ce56 290 * @returns [worker key, worker].
280c2a77 291 */
c923ce56
JB
292 protected chooseWorker (): [number, Worker] {
293 const workerKey = this.workerChoiceStrategyContext.execute()
294 return [workerKey, this.workers[workerKey].worker]
c97c7edb
S
295 }
296
280c2a77 297 /**
675bb809 298 * Sends a message to the given worker.
280c2a77 299 *
38e795c1
JB
300 * @param worker - The worker which should receive the message.
301 * @param message - The message.
280c2a77
S
302 */
303 protected abstract sendToWorker (
304 worker: Worker,
305 message: MessageValue<Data>
306 ): void
307
4a6952ff 308 /**
bdede008 309 * Registers a listener callback on a given worker.
4a6952ff 310 *
38e795c1
JB
311 * @param worker - The worker which should register a listener.
312 * @param listener - The message listener callback.
4a6952ff
JB
313 */
314 protected abstract registerWorkerMessageListener<
4f7fa42a 315 Message extends Data | Response
78cea37e 316 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
c97c7edb 317
729c563d
S
318 /**
319 * Returns a newly created worker.
320 */
280c2a77 321 protected abstract createWorker (): Worker
c97c7edb 322
729c563d
S
323 /**
324 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
325 *
38e795c1 326 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
729c563d 327 *
38e795c1 328 * @param worker - The newly created worker.
729c563d 329 */
280c2a77 330 protected abstract afterWorkerSetup (worker: Worker): void
c97c7edb 331
4a6952ff
JB
332 /**
333 * Creates a new worker for this pool and sets it up completely.
334 *
335 * @returns New, completely set up worker.
336 */
337 protected createAndSetupWorker (): Worker {
bdacc2d2 338 const worker = this.createWorker()
280c2a77 339
35cf1c03 340 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
a35560ba
S
341 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
342 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
343 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
a974afa6
JB
344 worker.once('exit', () => {
345 this.removeWorker(worker)
346 })
280c2a77 347
c923ce56 348 this.pushWorker(worker, {
ffcbbad8
JB
349 run: 0,
350 running: 0,
351 runTime: 0,
2740a743
JB
352 avgRunTime: 0,
353 error: 0
ffcbbad8 354 })
280c2a77
S
355
356 this.afterWorkerSetup(worker)
357
c97c7edb
S
358 return worker
359 }
be0676b3
APA
360
361 /**
362 * This function is the listener registered for each worker.
363 *
bdacc2d2 364 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
365 */
366 protected workerListener (): (message: MessageValue<Response>) => void {
4a6952ff 367 return message => {
bdacc2d2 368 if (message.id !== undefined) {
2740a743
JB
369 const promiseResponse = this.promiseResponseMap.get(message.id)
370 if (promiseResponse !== undefined) {
78cea37e 371 if (message.error != null) {
2740a743 372 promiseResponse.reject(message.error)
a05c10de 373 } else {
2740a743 374 promiseResponse.resolve(message.data as Response)
a05c10de 375 }
c923ce56 376 this.afterPromiseResponseHook(promiseResponse.worker, message)
2740a743 377 this.promiseResponseMap.delete(message.id)
be0676b3
APA
378 }
379 }
380 }
be0676b3 381 }
7c0ba920 382
78cea37e 383 private async internalExecute (
2740a743 384 workerKey: number,
c923ce56 385 worker: Worker,
b4e75778 386 messageId: string
78cea37e 387 ): Promise<Response> {
2740a743 388 this.beforePromiseResponseHook(workerKey)
78cea37e 389 return await new Promise<Response>((resolve, reject) => {
c923ce56 390 this.promiseResponseMap.set(messageId, { resolve, reject, worker })
78cea37e
JB
391 })
392 }
393
7c0ba920 394 private checkAndEmitBusy (): void {
78cea37e 395 if (this.opts.enableEvents === true && this.busy) {
7c0ba920
JB
396 this.emitter?.emit('busy')
397 }
398 }
bf9549ae 399
c923ce56
JB
400 /**
401 * Gets worker tasks usage.
402 *
403 * @param worker - The worker.
404 * @returns The worker tasks usage.
405 */
406 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
3032893a 407 const workerKey = this.getWorkerKey(worker)
e65c6cd9
JB
408 if (workerKey !== -1) {
409 return this.workers[workerKey].tasksUsage
ffcbbad8 410 }
3032893a 411 throw new Error('Worker could not be found in the pool')
a05c10de
JB
412 }
413
414 /**
c923ce56 415 * Pushes the given worker.
ea7a90d3 416 *
38e795c1 417 * @param worker - The worker.
ffcbbad8 418 * @param tasksUsage - The worker tasks usage.
ea7a90d3 419 */
c923ce56 420 private pushWorker (worker: Worker, tasksUsage: TasksUsage): void {
e65c6cd9 421 this.workers.push({
ffcbbad8
JB
422 worker,
423 tasksUsage
ea7a90d3
JB
424 })
425 }
c923ce56
JB
426
427 /**
428 * Sets the given worker.
429 *
430 * @param workerKey - The worker key.
431 * @param worker - The worker.
432 * @param tasksUsage - The worker tasks usage.
433 */
434 private setWorker (
435 workerKey: number,
436 worker: Worker,
437 tasksUsage: TasksUsage
438 ): void {
439 this.workers[workerKey] = {
440 worker,
441 tasksUsage
442 }
443 }
c97c7edb 444}