fix: fix default worker data value
[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'
bf9549ae 9import type { IPoolInternal, TasksUsage } 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} */
4a6952ff
JB
31 public readonly workers: Worker[] = []
32
38e795c1 33 /** {@inheritDoc} */
ea7a90d3 34 public readonly workersTasksUsage: Map<Worker, TasksUsage> = new Map<
78cea37e
JB
35 Worker,
36 TasksUsage
bf9549ae 37 >()
4a6952ff 38
38e795c1 39 /** {@inheritDoc} */
7c0ba920
JB
40 public readonly emitter?: PoolEmitter
41
be0676b3
APA
42 /**
43 * The promise map.
44 *
e088a00c 45 * - `key`: This is the message Id of each submitted task.
be0676b3
APA
46 * - `value`: An object that contains the worker, the resolve function and the reject function.
47 *
48 * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
49 */
50 protected promiseMap: Map<
78cea37e
JB
51 number,
52 PromiseWorkerResponseWrapper<Worker, Response>
be0676b3
APA
53 > = new Map<number, PromiseWorkerResponseWrapper<Worker, Response>>()
54
729c563d 55 /**
e088a00c 56 * Id of the next message.
729c563d 57 */
280c2a77 58 protected nextMessageId: number = 0
c97c7edb 59
a35560ba
S
60 /**
61 * Worker choice strategy instance implementing the worker choice algorithm.
62 *
63 * Default to a strategy implementing a round robin algorithm.
64 */
65 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
78cea37e
JB
66 Worker,
67 Data,
68 Response
a35560ba
S
69 >
70
729c563d
S
71 /**
72 * Constructs a new poolifier pool.
73 *
38e795c1
JB
74 * @param numberOfWorkers - Number of workers that this pool should manage.
75 * @param filePath - Path to the worker-file.
76 * @param opts - Options for the pool.
729c563d 77 */
c97c7edb 78 public constructor (
5c5a1fb7 79 public readonly numberOfWorkers: number,
c97c7edb 80 public readonly filePath: string,
1927ee67 81 public readonly opts: PoolOptions<Worker>
c97c7edb 82 ) {
78cea37e 83 if (!this.isMain()) {
c97c7edb
S
84 throw new Error('Cannot start a pool from a worker!')
85 }
8d3782fa 86 this.checkNumberOfWorkers(this.numberOfWorkers)
c510fea7 87 this.checkFilePath(this.filePath)
7c0ba920 88 this.checkPoolOptions(this.opts)
c97c7edb
S
89 this.setupHook()
90
5c5a1fb7 91 for (let i = 1; i <= this.numberOfWorkers; i++) {
280c2a77 92 this.createAndSetupWorker()
c97c7edb
S
93 }
94
6bd72cd0 95 if (this.opts.enableEvents === true) {
7c0ba920
JB
96 this.emitter = new PoolEmitter()
97 }
a35560ba
S
98 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext(
99 this,
4a6952ff
JB
100 () => {
101 const workerCreated = this.createAndSetupWorker()
f3636726 102 this.registerWorkerMessageListener(workerCreated, message => {
4a6952ff
JB
103 if (
104 isKillBehavior(KillBehaviors.HARD, message.kill) ||
bdaf31cd 105 this.getWorkerRunningTasks(workerCreated) === 0
4a6952ff
JB
106 ) {
107 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
f44936ae 108 void (this.destroyWorker(workerCreated) as Promise<void>)
4a6952ff
JB
109 }
110 })
111 return workerCreated
112 },
e843b904 113 this.opts.workerChoiceStrategy
a35560ba 114 )
c97c7edb
S
115 }
116
a35560ba 117 private checkFilePath (filePath: string): void {
78cea37e 118 if (filePath == null || filePath.length === 0) {
c510fea7
APA
119 throw new Error('Please specify a file with a worker implementation')
120 }
121 }
122
8d3782fa
JB
123 private checkNumberOfWorkers (numberOfWorkers: number): void {
124 if (numberOfWorkers == null) {
125 throw new Error(
126 'Cannot instantiate a pool without specifying the number of workers'
127 )
78cea37e 128 } else if (!Number.isSafeInteger(numberOfWorkers)) {
473c717a 129 throw new TypeError(
8d3782fa
JB
130 'Cannot instantiate a pool with a non integer number of workers'
131 )
132 } else if (numberOfWorkers < 0) {
473c717a 133 throw new RangeError(
8d3782fa
JB
134 'Cannot instantiate a pool with a negative number of workers'
135 )
7c0ba920 136 } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) {
8d3782fa
JB
137 throw new Error('Cannot instantiate a fixed pool with no worker')
138 }
139 }
140
7c0ba920 141 private checkPoolOptions (opts: PoolOptions<Worker>): void {
e843b904
JB
142 this.opts.workerChoiceStrategy =
143 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
7c0ba920
JB
144 this.opts.enableEvents = opts.enableEvents ?? true
145 }
146
38e795c1 147 /** {@inheritDoc} */
7c0ba920
JB
148 public abstract get type (): PoolType
149
38e795c1 150 /** {@inheritDoc} */
7c0ba920
JB
151 public get numberOfRunningTasks (): number {
152 return this.promiseMap.size
a35560ba
S
153 }
154
38e795c1 155 /** {@inheritDoc} */
bf9549ae
JB
156 public getWorkerIndex (worker: Worker): number {
157 return this.workers.indexOf(worker)
158 }
159
38e795c1 160 /** {@inheritDoc} */
bdaf31cd 161 public getWorkerRunningTasks (worker: Worker): number | undefined {
bf9549ae 162 return this.workersTasksUsage.get(worker)?.running
bdaf31cd
JB
163 }
164
38e795c1 165 /** {@inheritDoc} */
bf9549ae
JB
166 public getWorkerAverageTasksRunTime (worker: Worker): number | undefined {
167 return this.workersTasksUsage.get(worker)?.avgRunTime
bdaf31cd
JB
168 }
169
38e795c1 170 /** {@inheritDoc} */
a35560ba
S
171 public setWorkerChoiceStrategy (
172 workerChoiceStrategy: WorkerChoiceStrategy
173 ): void {
b98ec2e6 174 this.opts.workerChoiceStrategy = workerChoiceStrategy
ea7a90d3
JB
175 for (const worker of this.workers) {
176 this.resetWorkerTasksUsage(worker)
177 }
a35560ba
S
178 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
179 workerChoiceStrategy
180 )
181 }
182
38e795c1 183 /** {@inheritDoc} */
7c0ba920
JB
184 public abstract get busy (): boolean
185
186 protected internalGetBusyStatus (): boolean {
187 return (
188 this.numberOfRunningTasks >= this.numberOfWorkers &&
bdaf31cd 189 this.findFreeWorker() === false
7c0ba920
JB
190 )
191 }
192
38e795c1 193 /** {@inheritDoc} */
bdaf31cd
JB
194 public findFreeWorker (): Worker | false {
195 for (const worker of this.workers) {
196 if (this.getWorkerRunningTasks(worker) === 0) {
197 // A worker is free, return the matching worker
198 return worker
7c0ba920
JB
199 }
200 }
201 return false
202 }
203
38e795c1 204 /** {@inheritDoc} */
78cea37e 205 public async execute (data: Data): Promise<Response> {
280c2a77
S
206 // Configure worker to handle message with the specified task
207 const worker = this.chooseWorker()
a05c10de 208 const res = this.internalExecute(worker, this.nextMessageId)
14916bf9 209 this.checkAndEmitBusy()
a05c10de 210 this.sendToWorker(worker, {
e5a5c0fc
JB
211 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
212 data: data ?? ({} as Data),
a05c10de
JB
213 id: this.nextMessageId
214 })
215 ++this.nextMessageId
78cea37e 216 // eslint-disable-next-line @typescript-eslint/return-await
280c2a77
S
217 return res
218 }
c97c7edb 219
38e795c1 220 /** {@inheritDoc} */
c97c7edb 221 public async destroy (): Promise<void> {
1fbcaa7c
JB
222 await Promise.all(
223 this.workers.map(async worker => {
224 await this.destroyWorker(worker)
225 })
226 )
c97c7edb
S
227 }
228
4a6952ff 229 /**
675bb809 230 * Shutdowns given worker.
4a6952ff 231 *
38e795c1 232 * @param worker - A worker within `workers`.
4a6952ff
JB
233 */
234 protected abstract destroyWorker (worker: Worker): void | Promise<void>
c97c7edb 235
729c563d 236 /**
280c2a77
S
237 * Setup hook that can be overridden by a Poolifier pool implementation
238 * to run code before workers are created in the abstract constructor.
729c563d 239 */
280c2a77
S
240 protected setupHook (): void {
241 // Can be overridden
242 }
c97c7edb 243
729c563d 244 /**
280c2a77
S
245 * Should return whether the worker is the main worker or not.
246 */
247 protected abstract isMain (): boolean
248
249 /**
bf9549ae
JB
250 * Hook executed before the worker task promise resolution.
251 * Can be overridden.
729c563d 252 *
38e795c1 253 * @param worker - The worker.
729c563d 254 */
bf9549ae
JB
255 protected beforePromiseWorkerResponseHook (worker: Worker): void {
256 this.increaseWorkerRunningTasks(worker)
c97c7edb
S
257 }
258
c01733f1 259 /**
bf9549ae
JB
260 * Hook executed after the worker task promise resolution.
261 * Can be overridden.
c01733f1 262 *
38e795c1
JB
263 * @param message - The received message.
264 * @param promise - The Promise response.
c01733f1 265 */
bf9549ae
JB
266 protected afterPromiseWorkerResponseHook (
267 message: MessageValue<Response>,
268 promise: PromiseWorkerResponseWrapper<Worker, Response>
269 ): void {
270 this.decreaseWorkerRunningTasks(promise.worker)
271 this.stepWorkerRunTasks(promise.worker, 1)
272 this.updateWorkerTasksRunTime(promise.worker, message.taskRunTime)
c01733f1 273 }
274
729c563d
S
275 /**
276 * Removes the given worker from the pool.
277 *
38e795c1 278 * @param worker - The worker that will be removed.
729c563d 279 */
f2fdaa86
JB
280 protected removeWorker (worker: Worker): void {
281 // Clean worker from data structure
bdaf31cd 282 this.workers.splice(this.getWorkerIndex(worker), 1)
10fcfaf4 283 this.removeWorkerTasksUsage(worker)
f2fdaa86
JB
284 }
285
280c2a77 286 /**
675bb809 287 * Chooses a worker for the next task.
280c2a77
S
288 *
289 * The default implementation uses a round robin algorithm to distribute the load.
290 *
291 * @returns Worker.
292 */
293 protected chooseWorker (): Worker {
a35560ba 294 return this.workerChoiceStrategyContext.execute()
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
c97c7edb 348 this.workers.push(worker)
280c2a77 349
bf9549ae 350 // Init worker tasks usage map
ea7a90d3 351 this.initWorkerTasksUsage(worker)
280c2a77
S
352
353 this.afterWorkerSetup(worker)
354
c97c7edb
S
355 return worker
356 }
be0676b3
APA
357
358 /**
359 * This function is the listener registered for each worker.
360 *
bdacc2d2 361 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
362 */
363 protected workerListener (): (message: MessageValue<Response>) => void {
4a6952ff 364 return message => {
bdacc2d2
JB
365 if (message.id !== undefined) {
366 const promise = this.promiseMap.get(message.id)
367 if (promise !== undefined) {
78cea37e 368 if (message.error != null) {
a05c10de
JB
369 promise.reject(message.error)
370 } else {
371 promise.resolve(message.data as Response)
372 }
bf9549ae 373 this.afterPromiseWorkerResponseHook(message, promise)
be0676b3
APA
374 this.promiseMap.delete(message.id)
375 }
376 }
377 }
be0676b3 378 }
7c0ba920 379
78cea37e
JB
380 private async internalExecute (
381 worker: Worker,
382 messageId: number
383 ): Promise<Response> {
384 this.beforePromiseWorkerResponseHook(worker)
385 return await new Promise<Response>((resolve, reject) => {
386 this.promiseMap.set(messageId, { resolve, reject, worker })
387 })
388 }
389
7c0ba920 390 private checkAndEmitBusy (): void {
78cea37e 391 if (this.opts.enableEvents === true && this.busy) {
7c0ba920
JB
392 this.emitter?.emit('busy')
393 }
394 }
bf9549ae
JB
395
396 /**
10fcfaf4 397 * Increases the number of tasks that the given worker has applied.
bf9549ae 398 *
38e795c1 399 * @param worker - Worker which running tasks is increased.
bf9549ae
JB
400 */
401 private increaseWorkerRunningTasks (worker: Worker): void {
402 this.stepWorkerRunningTasks(worker, 1)
403 }
404
405 /**
10fcfaf4 406 * Decreases the number of tasks that the given worker has applied.
bf9549ae 407 *
38e795c1 408 * @param worker - Worker which running tasks is decreased.
bf9549ae
JB
409 */
410 private decreaseWorkerRunningTasks (worker: Worker): void {
411 this.stepWorkerRunningTasks(worker, -1)
412 }
413
414 /**
10fcfaf4 415 * Steps the number of tasks that the given worker has applied.
bf9549ae 416 *
38e795c1
JB
417 * @param worker - Worker which running tasks are stepped.
418 * @param step - Number of running tasks step.
bf9549ae
JB
419 */
420 private stepWorkerRunningTasks (worker: Worker, step: number): void {
78cea37e 421 if (this.checkWorkerTasksUsage(worker)) {
a05c10de 422 const tasksUsage = this.workersTasksUsage.get(worker) as TasksUsage
bf9549ae
JB
423 tasksUsage.running = tasksUsage.running + step
424 this.workersTasksUsage.set(worker, tasksUsage)
bf9549ae
JB
425 }
426 }
427
428 /**
10fcfaf4 429 * Steps the number of tasks that the given worker has run.
bf9549ae 430 *
38e795c1
JB
431 * @param worker - Worker which has run tasks.
432 * @param step - Number of run tasks step.
bf9549ae 433 */
10fcfaf4 434 private stepWorkerRunTasks (worker: Worker, step: number): void {
78cea37e 435 if (this.checkWorkerTasksUsage(worker)) {
a05c10de 436 const tasksUsage = this.workersTasksUsage.get(worker) as TasksUsage
bf9549ae
JB
437 tasksUsage.run = tasksUsage.run + step
438 this.workersTasksUsage.set(worker, tasksUsage)
bf9549ae
JB
439 }
440 }
441
442 /**
23135a89 443 * Updates tasks runtime for the given worker.
bf9549ae 444 *
38e795c1
JB
445 * @param worker - Worker which run the task.
446 * @param taskRunTime - Worker task runtime.
bf9549ae
JB
447 */
448 private updateWorkerTasksRunTime (
449 worker: Worker,
450 taskRunTime: number | undefined
10fcfaf4
JB
451 ): void {
452 if (
453 this.workerChoiceStrategyContext.getWorkerChoiceStrategy()
78cea37e
JB
454 .requiredStatistics.runTime &&
455 this.checkWorkerTasksUsage(worker)
10fcfaf4 456 ) {
a05c10de
JB
457 const tasksUsage = this.workersTasksUsage.get(worker) as TasksUsage
458 tasksUsage.runTime += taskRunTime ?? 0
459 if (tasksUsage.run !== 0) {
460 tasksUsage.avgRunTime = tasksUsage.runTime / tasksUsage.run
10fcfaf4 461 }
a05c10de
JB
462 this.workersTasksUsage.set(worker, tasksUsage)
463 }
464 }
465
466 /**
467 * Checks if the given worker is registered in the workers tasks usage map.
468 *
38e795c1 469 * @param worker - Worker to check.
a05c10de
JB
470 * @returns `true` if the worker is registered in the workers tasks usage map. `false` otherwise.
471 */
472 private checkWorkerTasksUsage (worker: Worker): boolean {
473 const hasTasksUsage = this.workersTasksUsage.has(worker)
78cea37e 474 if (!hasTasksUsage) {
a05c10de 475 throw new Error('Worker could not be found in workers tasks usage map')
bf9549ae 476 }
a05c10de 477 return hasTasksUsage
bf9549ae
JB
478 }
479
ea7a90d3
JB
480 /**
481 * Initializes tasks usage statistics.
482 *
38e795c1 483 * @param worker - The worker.
ea7a90d3 484 */
e336fea6 485 private initWorkerTasksUsage (worker: Worker): void {
ea7a90d3
JB
486 this.workersTasksUsage.set(worker, {
487 run: 0,
488 running: 0,
489 runTime: 0,
490 avgRunTime: 0
491 })
492 }
493
bf9549ae 494 /**
10fcfaf4 495 * Removes worker tasks usage statistics.
bf9549ae 496 *
38e795c1 497 * @param worker - The worker.
bf9549ae 498 */
10fcfaf4 499 private removeWorkerTasksUsage (worker: Worker): void {
bf9549ae
JB
500 this.workersTasksUsage.delete(worker)
501 }
ea7a90d3
JB
502
503 /**
504 * Resets worker tasks usage statistics.
505 *
38e795c1 506 * @param worker - The worker.
ea7a90d3
JB
507 */
508 private resetWorkerTasksUsage (worker: Worker): void {
509 this.removeWorkerTasksUsage(worker)
510 this.initWorkerTasksUsage(worker)
511 }
c97c7edb 512}