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