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