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