perf: take into account the number of run tasks in LRU worker choice
[poolifier.git] / src / pools / abstract-pool.ts
CommitLineData
fc3e6586 1import crypto from 'node:crypto'
be0676b3
APA
2import type {
3 MessageValue,
4 PromiseWorkerResponseWrapper
5} from '../utility-types'
ed6dd37f 6import { EMPTY_FUNCTION } from '../utils'
34a0cfab 7import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
bdaf31cd 8import type { PoolOptions } from './pool'
b4904890 9import { PoolEmitter } from './pool'
ffcbbad8 10import type { IPoolInternal, TasksUsage, WorkerType } from './pool-internal'
b4904890 11import { PoolType } from './pool-internal'
ea7a90d3 12import type { IPoolWorker } from './pool-worker'
a35560ba
S
13import {
14 WorkerChoiceStrategies,
63220255 15 type WorkerChoiceStrategy
bdaf31cd
JB
16} from './selection-strategies/selection-strategies-types'
17import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
c97c7edb 18
729c563d 19/**
ea7a90d3 20 * Base class that implements some shared logic for all poolifier pools.
729c563d 21 *
38e795c1
JB
22 * @typeParam Worker - Type of worker which manages this pool.
23 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
24 * @typeParam Response - Type of response of execution. This can only be serializable data.
729c563d 25 */
c97c7edb 26export abstract class AbstractPool<
ea7a90d3 27 Worker extends IPoolWorker,
d3c8a1a8
S
28 Data = unknown,
29 Response = unknown
9b2fdd9f 30> implements IPoolInternal<Worker, Data, Response> {
38e795c1 31 /** {@inheritDoc} */
ffcbbad8
JB
32 public readonly workers: Map<number, WorkerType<Worker>> = new Map<
33 number,
34 WorkerType<Worker>
bf9549ae 35 >()
4a6952ff 36
38e795c1 37 /** {@inheritDoc} */
7c0ba920
JB
38 public readonly emitter?: PoolEmitter
39
ffcbbad8
JB
40 /**
41 * Id of the next worker.
42 */
43 protected nextWorkerId: number = 0
44
be0676b3
APA
45 /**
46 * The promise map.
47 *
ffcbbad8 48 * - `key`: This is the message id of each submitted task.
be0676b3
APA
49 * - `value`: An object that contains the worker, the resolve function and the reject function.
50 *
51 * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
52 */
53 protected promiseMap: Map<
b4e75778 54 string,
78cea37e 55 PromiseWorkerResponseWrapper<Worker, Response>
b4e75778 56 > = new Map<string, PromiseWorkerResponseWrapper<Worker, Response>>()
c97c7edb 57
a35560ba
S
58 /**
59 * Worker choice strategy instance implementing the worker choice algorithm.
60 *
61 * Default to a strategy implementing a round robin algorithm.
62 */
63 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
78cea37e
JB
64 Worker,
65 Data,
66 Response
a35560ba
S
67 >
68
729c563d
S
69 /**
70 * Constructs a new poolifier pool.
71 *
38e795c1
JB
72 * @param numberOfWorkers - Number of workers that this pool should manage.
73 * @param filePath - Path to the worker-file.
74 * @param opts - Options for the pool.
729c563d 75 */
c97c7edb 76 public constructor (
5c5a1fb7 77 public readonly numberOfWorkers: number,
c97c7edb 78 public readonly filePath: string,
1927ee67 79 public readonly opts: PoolOptions<Worker>
c97c7edb 80 ) {
78cea37e 81 if (!this.isMain()) {
c97c7edb
S
82 throw new Error('Cannot start a pool from a worker!')
83 }
8d3782fa 84 this.checkNumberOfWorkers(this.numberOfWorkers)
c510fea7 85 this.checkFilePath(this.filePath)
7c0ba920 86 this.checkPoolOptions(this.opts)
c97c7edb
S
87 this.setupHook()
88
5c5a1fb7 89 for (let i = 1; i <= this.numberOfWorkers; i++) {
280c2a77 90 this.createAndSetupWorker()
c97c7edb
S
91 }
92
6bd72cd0 93 if (this.opts.enableEvents === true) {
7c0ba920
JB
94 this.emitter = new PoolEmitter()
95 }
a35560ba
S
96 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext(
97 this,
4a6952ff
JB
98 () => {
99 const workerCreated = this.createAndSetupWorker()
f3636726 100 this.registerWorkerMessageListener(workerCreated, message => {
4a6952ff
JB
101 if (
102 isKillBehavior(KillBehaviors.HARD, message.kill) ||
bdaf31cd 103 this.getWorkerRunningTasks(workerCreated) === 0
4a6952ff
JB
104 ) {
105 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
a9d9ea34 106 void this.destroyWorker(workerCreated)
4a6952ff
JB
107 }
108 })
109 return workerCreated
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
38e795c1 151 /** {@inheritDoc} */
7c0ba920
JB
152 public get numberOfRunningTasks (): number {
153 return this.promiseMap.size
a35560ba
S
154 }
155
ffcbbad8 156 /**
b4e75778 157 * Gets the given worker key.
ffcbbad8
JB
158 *
159 * @param worker - The worker.
160 * @returns The worker key.
161 */
162 private getWorkerKey (worker: Worker): number | undefined {
163 return [...this.workers].find(([, value]) => value.worker === worker)?.[0]
bf9549ae
JB
164 }
165
38e795c1 166 /** {@inheritDoc} */
bdaf31cd 167 public getWorkerRunningTasks (worker: Worker): number | undefined {
f4ff1ce2
JB
168 return this.getWorkerTasksUsage(worker)?.running
169 }
170
171 /** {@inheritDoc} */
172 public getWorkerRunTasks (worker: Worker): number | undefined {
173 return this.getWorkerTasksUsage(worker)?.run
bdaf31cd
JB
174 }
175
38e795c1 176 /** {@inheritDoc} */
bf9549ae 177 public getWorkerAverageTasksRunTime (worker: Worker): number | undefined {
f4ff1ce2 178 return this.getWorkerTasksUsage(worker)?.avgRunTime
bdaf31cd
JB
179 }
180
38e795c1 181 /** {@inheritDoc} */
a35560ba
S
182 public setWorkerChoiceStrategy (
183 workerChoiceStrategy: WorkerChoiceStrategy
184 ): void {
b98ec2e6 185 this.opts.workerChoiceStrategy = workerChoiceStrategy
ffcbbad8
JB
186 for (const [key, value] of this.workers) {
187 this.setWorker(key, value.worker, {
188 run: 0,
189 running: 0,
190 runTime: 0,
191 avgRunTime: 0
192 })
ea7a90d3 193 }
a35560ba
S
194 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
195 workerChoiceStrategy
196 )
197 }
198
38e795c1 199 /** {@inheritDoc} */
7c0ba920
JB
200 public abstract get busy (): boolean
201
202 protected internalGetBusyStatus (): boolean {
203 return (
204 this.numberOfRunningTasks >= this.numberOfWorkers &&
bdaf31cd 205 this.findFreeWorker() === false
7c0ba920
JB
206 )
207 }
208
38e795c1 209 /** {@inheritDoc} */
bdaf31cd 210 public findFreeWorker (): Worker | false {
ffcbbad8
JB
211 for (const value of this.workers.values()) {
212 if (value.tasksUsage.running === 0) {
bdaf31cd 213 // A worker is free, return the matching worker
ffcbbad8 214 return value.worker
7c0ba920
JB
215 }
216 }
217 return false
218 }
219
38e795c1 220 /** {@inheritDoc} */
78cea37e 221 public async execute (data: Data): Promise<Response> {
280c2a77 222 const worker = this.chooseWorker()
b4e75778
JB
223 const messageId = crypto.randomUUID()
224 const res = this.internalExecute(worker, messageId)
14916bf9 225 this.checkAndEmitBusy()
a05c10de 226 this.sendToWorker(worker, {
e5a5c0fc
JB
227 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
228 data: data ?? ({} as Data),
b4e75778 229 id: messageId
a05c10de 230 })
78cea37e 231 // eslint-disable-next-line @typescript-eslint/return-await
280c2a77
S
232 return res
233 }
c97c7edb 234
38e795c1 235 /** {@inheritDoc} */
c97c7edb 236 public async destroy (): Promise<void> {
1fbcaa7c 237 await Promise.all(
ffcbbad8
JB
238 [...this.workers].map(async ([, value]) => {
239 await this.destroyWorker(value.worker)
1fbcaa7c
JB
240 })
241 )
c97c7edb
S
242 }
243
4a6952ff 244 /**
675bb809 245 * Shutdowns given worker.
4a6952ff 246 *
38e795c1 247 * @param worker - A worker within `workers`.
4a6952ff
JB
248 */
249 protected abstract destroyWorker (worker: Worker): void | Promise<void>
c97c7edb 250
729c563d 251 /**
280c2a77
S
252 * Setup hook that can be overridden by a Poolifier pool implementation
253 * to run code before workers are created in the abstract constructor.
729c563d 254 */
280c2a77
S
255 protected setupHook (): void {
256 // Can be overridden
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 *
38e795c1 268 * @param worker - The worker.
729c563d 269 */
bf9549ae
JB
270 protected beforePromiseWorkerResponseHook (worker: Worker): void {
271 this.increaseWorkerRunningTasks(worker)
c97c7edb
S
272 }
273
c01733f1 274 /**
bf9549ae
JB
275 * Hook executed after the worker task promise resolution.
276 * Can be overridden.
c01733f1 277 *
38e795c1
JB
278 * @param message - The received message.
279 * @param promise - The Promise response.
c01733f1 280 */
bf9549ae
JB
281 protected afterPromiseWorkerResponseHook (
282 message: MessageValue<Response>,
283 promise: PromiseWorkerResponseWrapper<Worker, Response>
284 ): void {
285 this.decreaseWorkerRunningTasks(promise.worker)
286 this.stepWorkerRunTasks(promise.worker, 1)
287 this.updateWorkerTasksRunTime(promise.worker, message.taskRunTime)
c01733f1 288 }
289
729c563d
S
290 /**
291 * Removes the given worker from the pool.
292 *
38e795c1 293 * @param worker - The worker that will be removed.
729c563d 294 */
f2fdaa86 295 protected removeWorker (worker: Worker): void {
ffcbbad8
JB
296 this.workers.delete(this.getWorkerKey(worker) as number)
297 --this.nextWorkerId
f2fdaa86
JB
298 }
299
280c2a77 300 /**
675bb809 301 * Chooses a worker for the next task.
280c2a77
S
302 *
303 * The default implementation uses a round robin algorithm to distribute the load.
304 *
305 * @returns Worker.
306 */
307 protected chooseWorker (): Worker {
a35560ba 308 return this.workerChoiceStrategyContext.execute()
c97c7edb
S
309 }
310
280c2a77 311 /**
675bb809 312 * Sends a message to the given worker.
280c2a77 313 *
38e795c1
JB
314 * @param worker - The worker which should receive the message.
315 * @param message - The message.
280c2a77
S
316 */
317 protected abstract sendToWorker (
318 worker: Worker,
319 message: MessageValue<Data>
320 ): void
321
4a6952ff 322 /**
bdede008 323 * Registers a listener callback on a given worker.
4a6952ff 324 *
38e795c1
JB
325 * @param worker - The worker which should register a listener.
326 * @param listener - The message listener callback.
4a6952ff
JB
327 */
328 protected abstract registerWorkerMessageListener<
4f7fa42a 329 Message extends Data | Response
78cea37e 330 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
c97c7edb 331
729c563d
S
332 /**
333 * Returns a newly created worker.
334 */
280c2a77 335 protected abstract createWorker (): Worker
c97c7edb 336
729c563d
S
337 /**
338 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
339 *
38e795c1 340 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
729c563d 341 *
38e795c1 342 * @param worker - The newly created worker.
729c563d 343 */
280c2a77 344 protected abstract afterWorkerSetup (worker: Worker): void
c97c7edb 345
4a6952ff
JB
346 /**
347 * Creates a new worker for this pool and sets it up completely.
348 *
349 * @returns New, completely set up worker.
350 */
351 protected createAndSetupWorker (): Worker {
bdacc2d2 352 const worker = this.createWorker()
280c2a77 353
35cf1c03 354 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
a35560ba
S
355 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
356 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
357 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
a974afa6
JB
358 worker.once('exit', () => {
359 this.removeWorker(worker)
360 })
280c2a77 361
ffcbbad8
JB
362 this.setWorker(this.nextWorkerId, worker, {
363 run: 0,
364 running: 0,
365 runTime: 0,
366 avgRunTime: 0
367 })
368 ++this.nextWorkerId
280c2a77
S
369
370 this.afterWorkerSetup(worker)
371
c97c7edb
S
372 return worker
373 }
be0676b3
APA
374
375 /**
376 * This function is the listener registered for each worker.
377 *
bdacc2d2 378 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
379 */
380 protected workerListener (): (message: MessageValue<Response>) => void {
4a6952ff 381 return message => {
bdacc2d2
JB
382 if (message.id !== undefined) {
383 const promise = this.promiseMap.get(message.id)
384 if (promise !== undefined) {
78cea37e 385 if (message.error != null) {
a05c10de
JB
386 promise.reject(message.error)
387 } else {
388 promise.resolve(message.data as Response)
389 }
bf9549ae 390 this.afterPromiseWorkerResponseHook(message, promise)
be0676b3
APA
391 this.promiseMap.delete(message.id)
392 }
393 }
394 }
be0676b3 395 }
7c0ba920 396
78cea37e
JB
397 private async internalExecute (
398 worker: Worker,
b4e75778 399 messageId: string
78cea37e
JB
400 ): Promise<Response> {
401 this.beforePromiseWorkerResponseHook(worker)
402 return await new Promise<Response>((resolve, reject) => {
403 this.promiseMap.set(messageId, { resolve, reject, worker })
404 })
405 }
406
7c0ba920 407 private checkAndEmitBusy (): void {
78cea37e 408 if (this.opts.enableEvents === true && this.busy) {
7c0ba920
JB
409 this.emitter?.emit('busy')
410 }
411 }
bf9549ae
JB
412
413 /**
10fcfaf4 414 * Increases the number of tasks that the given worker has applied.
bf9549ae 415 *
38e795c1 416 * @param worker - Worker which running tasks is increased.
bf9549ae
JB
417 */
418 private increaseWorkerRunningTasks (worker: Worker): void {
419 this.stepWorkerRunningTasks(worker, 1)
420 }
421
422 /**
10fcfaf4 423 * Decreases the number of tasks that the given worker has applied.
bf9549ae 424 *
38e795c1 425 * @param worker - Worker which running tasks is decreased.
bf9549ae
JB
426 */
427 private decreaseWorkerRunningTasks (worker: Worker): void {
428 this.stepWorkerRunningTasks(worker, -1)
429 }
430
ffcbbad8 431 /**
b4e75778 432 * Gets tasks usage of the given worker.
ffcbbad8
JB
433 *
434 * @param worker - Worker which tasks usage is returned.
435 */
436 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
437 if (this.checkWorker(worker)) {
438 const workerKey = this.getWorkerKey(worker) as number
439 const workerEntry = this.workers.get(workerKey) as WorkerType<Worker>
440 return workerEntry.tasksUsage
441 }
442 }
443
bf9549ae 444 /**
10fcfaf4 445 * Steps the number of tasks that the given worker has applied.
bf9549ae 446 *
38e795c1
JB
447 * @param worker - Worker which running tasks are stepped.
448 * @param step - Number of running tasks step.
bf9549ae
JB
449 */
450 private stepWorkerRunningTasks (worker: Worker, step: number): void {
ffcbbad8
JB
451 // prettier-ignore
452 (this.getWorkerTasksUsage(worker) as TasksUsage).running += step
bf9549ae
JB
453 }
454
455 /**
10fcfaf4 456 * Steps the number of tasks that the given worker has run.
bf9549ae 457 *
38e795c1
JB
458 * @param worker - Worker which has run tasks.
459 * @param step - Number of run tasks step.
bf9549ae 460 */
10fcfaf4 461 private stepWorkerRunTasks (worker: Worker, step: number): void {
ffcbbad8
JB
462 // prettier-ignore
463 (this.getWorkerTasksUsage(worker) as TasksUsage).run += step
bf9549ae
JB
464 }
465
466 /**
23135a89 467 * Updates tasks runtime for the given worker.
bf9549ae 468 *
38e795c1
JB
469 * @param worker - Worker which run the task.
470 * @param taskRunTime - Worker task runtime.
bf9549ae
JB
471 */
472 private updateWorkerTasksRunTime (
473 worker: Worker,
474 taskRunTime: number | undefined
10fcfaf4
JB
475 ): void {
476 if (
477 this.workerChoiceStrategyContext.getWorkerChoiceStrategy()
ffcbbad8 478 .requiredStatistics.runTime
10fcfaf4 479 ) {
ffcbbad8
JB
480 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
481 workerTasksUsage.runTime += taskRunTime ?? 0
482 if (workerTasksUsage.run !== 0) {
483 workerTasksUsage.avgRunTime =
484 workerTasksUsage.runTime / workerTasksUsage.run
10fcfaf4 485 }
a05c10de
JB
486 }
487 }
488
489 /**
ffcbbad8 490 * Sets the given worker.
ea7a90d3 491 *
ffcbbad8 492 * @param workerKey - The worker key.
38e795c1 493 * @param worker - The worker.
ffcbbad8 494 * @param tasksUsage - The worker tasks usage.
ea7a90d3 495 */
ffcbbad8
JB
496 private setWorker (
497 workerKey: number,
498 worker: Worker,
499 tasksUsage: TasksUsage
500 ): void {
501 this.workers.set(workerKey, {
502 worker,
503 tasksUsage
ea7a90d3
JB
504 })
505 }
506
bf9549ae 507 /**
ffcbbad8 508 * Checks if the given worker is registered in the pool.
ea7a90d3 509 *
ffcbbad8
JB
510 * @param worker - Worker to check.
511 * @returns `true` if the worker is registered in the pool.
ea7a90d3 512 */
ffcbbad8
JB
513 private checkWorker (worker: Worker): boolean {
514 if (this.getWorkerKey(worker) == null) {
515 throw new Error('Worker could not be found in the pool')
516 }
517 return true
ea7a90d3 518 }
c97c7edb 519}