perf: bind to this some methods in the tasks execution code path
[poolifier.git] / src / pools / abstract-pool.ts
1 import crypto from 'node:crypto'
2 import type { MessageValue, PromiseResponseWrapper } from '../utility-types'
3 import { EMPTY_FUNCTION } from '../utils'
4 import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
5 import type { PoolOptions } from './pool'
6 import { PoolEmitter } from './pool'
7 import type { IPoolInternal, TasksUsage, WorkerType } from './pool-internal'
8 import { PoolType } from './pool-internal'
9 import type { IPoolWorker } from './pool-worker'
10 import {
11 WorkerChoiceStrategies,
12 type WorkerChoiceStrategy
13 } from './selection-strategies/selection-strategies-types'
14 import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
15
16 /**
17 * Base class that implements some shared logic for all poolifier pools.
18 *
19 * @typeParam Worker - Type of worker which manages this pool.
20 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
21 * @typeParam Response - Type of response of execution. This can only be serializable data.
22 */
23 export abstract class AbstractPool<
24 Worker extends IPoolWorker,
25 Data = unknown,
26 Response = unknown
27 > implements IPoolInternal<Worker, Data, Response> {
28 /** {@inheritDoc} */
29 public readonly workers: Array<WorkerType<Worker>> = []
30
31 /** {@inheritDoc} */
32 public readonly emitter?: PoolEmitter
33
34 /**
35 * The promise response map.
36 *
37 * - `key`: The message id of each submitted task.
38 * - `value`: An object that contains the worker, the promise resolve and reject callbacks.
39 *
40 * When we receive a message from the worker we get a map entry with the promise resolve/reject bound to the message.
41 */
42 protected promiseResponseMap: Map<
43 string,
44 PromiseResponseWrapper<Worker, Response>
45 > = new Map<string, PromiseResponseWrapper<Worker, Response>>()
46
47 /**
48 * Worker choice strategy instance implementing the worker choice algorithm.
49 *
50 * Default to a strategy implementing a round robin algorithm.
51 */
52 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
53 Worker,
54 Data,
55 Response
56 >
57
58 /**
59 * Constructs a new poolifier pool.
60 *
61 * @param numberOfWorkers - Number of workers that this pool should manage.
62 * @param filePath - Path to the worker-file.
63 * @param opts - Options for the pool.
64 */
65 public constructor (
66 public readonly numberOfWorkers: number,
67 public readonly filePath: string,
68 public readonly opts: PoolOptions<Worker>
69 ) {
70 if (!this.isMain()) {
71 throw new Error('Cannot start a pool from a worker!')
72 }
73 this.checkNumberOfWorkers(this.numberOfWorkers)
74 this.checkFilePath(this.filePath)
75 this.checkPoolOptions(this.opts)
76
77 this.chooseWorker.bind(this)
78 this.internalExecute.bind(this)
79 this.checkAndEmitBusy.bind(this)
80 this.sendToWorker.bind(this)
81
82 this.setupHook()
83
84 for (let i = 1; i <= this.numberOfWorkers; i++) {
85 this.createAndSetupWorker()
86 }
87
88 if (this.opts.enableEvents === true) {
89 this.emitter = new PoolEmitter()
90 }
91 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext(
92 this,
93 () => {
94 const createdWorker = this.createAndSetupWorker()
95 this.registerWorkerMessageListener(createdWorker, message => {
96 if (
97 isKillBehavior(KillBehaviors.HARD, message.kill) ||
98 this.getWorkerTasksUsage(createdWorker)?.running === 0
99 ) {
100 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
101 void this.destroyWorker(createdWorker)
102 }
103 })
104 return this.getWorkerKey(createdWorker)
105 },
106 this.opts.workerChoiceStrategy
107 )
108 }
109
110 private checkFilePath (filePath: string): void {
111 if (
112 filePath == null ||
113 (typeof filePath === 'string' && filePath.trim().length === 0)
114 ) {
115 throw new Error('Please specify a file with a worker implementation')
116 }
117 }
118
119 private checkNumberOfWorkers (numberOfWorkers: number): void {
120 if (numberOfWorkers == null) {
121 throw new Error(
122 'Cannot instantiate a pool without specifying the number of workers'
123 )
124 } else if (!Number.isSafeInteger(numberOfWorkers)) {
125 throw new TypeError(
126 'Cannot instantiate a pool with a non integer number of workers'
127 )
128 } else if (numberOfWorkers < 0) {
129 throw new RangeError(
130 'Cannot instantiate a pool with a negative number of workers'
131 )
132 } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) {
133 throw new Error('Cannot instantiate a fixed pool with no worker')
134 }
135 }
136
137 private checkPoolOptions (opts: PoolOptions<Worker>): void {
138 this.opts.workerChoiceStrategy =
139 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
140 this.opts.enableEvents = opts.enableEvents ?? true
141 }
142
143 /** {@inheritDoc} */
144 public abstract get type (): PoolType
145
146 /** {@inheritDoc} */
147 public get numberOfRunningTasks (): number {
148 return this.promiseResponseMap.size
149 }
150
151 /**
152 * Gets the given worker key.
153 *
154 * @param worker - The worker.
155 * @returns The worker key if the worker is found in the pool, `-1` otherwise.
156 */
157 private getWorkerKey (worker: Worker): number {
158 return this.workers.findIndex(workerItem => workerItem.worker === worker)
159 }
160
161 /** {@inheritDoc} */
162 public setWorkerChoiceStrategy (
163 workerChoiceStrategy: WorkerChoiceStrategy
164 ): void {
165 this.opts.workerChoiceStrategy = workerChoiceStrategy
166 for (const [index, workerItem] of this.workers.entries()) {
167 this.setWorker(index, workerItem.worker, {
168 run: 0,
169 running: 0,
170 runTime: 0,
171 avgRunTime: 0,
172 error: 0
173 })
174 }
175 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
176 workerChoiceStrategy
177 )
178 }
179
180 /** {@inheritDoc} */
181 public abstract get busy (): boolean
182
183 protected internalGetBusyStatus (): boolean {
184 return (
185 this.numberOfRunningTasks >= this.numberOfWorkers &&
186 this.findFreeWorkerKey() === -1
187 )
188 }
189
190 /** {@inheritDoc} */
191 public findFreeWorkerKey (): number {
192 return this.workers.findIndex(workerItem => {
193 return workerItem.tasksUsage.running === 0
194 })
195 }
196
197 /** {@inheritDoc} */
198 public async execute (data: Data): Promise<Response> {
199 const [workerKey, worker] = this.chooseWorker()
200 const messageId = crypto.randomUUID()
201 const res = this.internalExecute(workerKey, worker, messageId)
202 this.checkAndEmitBusy()
203 this.sendToWorker(worker, {
204 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
205 data: data ?? ({} as Data),
206 id: messageId
207 })
208 // eslint-disable-next-line @typescript-eslint/return-await
209 return res
210 }
211
212 /** {@inheritDoc} */
213 public async destroy (): Promise<void> {
214 await Promise.all(
215 this.workers.map(async workerItem => {
216 await this.destroyWorker(workerItem.worker)
217 })
218 )
219 }
220
221 /**
222 * Shutdowns given worker.
223 *
224 * @param worker - A worker within `workers`.
225 */
226 protected abstract destroyWorker (worker: Worker): void | Promise<void>
227
228 /**
229 * Setup hook that can be overridden by a Poolifier pool implementation
230 * to run code before workers are created in the abstract constructor.
231 */
232 protected setupHook (): void {
233 // Can be overridden
234 }
235
236 /**
237 * Should return whether the worker is the main worker or not.
238 */
239 protected abstract isMain (): boolean
240
241 /**
242 * Hook executed before the worker task promise resolution.
243 * Can be overridden.
244 *
245 * @param workerKey - The worker key.
246 */
247 protected beforePromiseResponseHook (workerKey: number): void {
248 ++this.workers[workerKey].tasksUsage.running
249 }
250
251 /**
252 * Hook executed after the worker task promise resolution.
253 * Can be overridden.
254 *
255 * @param worker - The worker.
256 * @param message - The received message.
257 */
258 protected afterPromiseResponseHook (
259 worker: Worker,
260 message: MessageValue<Response>
261 ): void {
262 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
263 --workerTasksUsage.running
264 ++workerTasksUsage.run
265 if (message.error != null) {
266 ++workerTasksUsage.error
267 }
268 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
269 workerTasksUsage.runTime += message.taskRunTime ?? 0
270 if (
271 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
272 workerTasksUsage.run !== 0
273 ) {
274 workerTasksUsage.avgRunTime =
275 workerTasksUsage.runTime / workerTasksUsage.run
276 }
277 }
278 }
279
280 /**
281 * Removes the given worker from the pool.
282 *
283 * @param worker - The worker that will be removed.
284 */
285 protected removeWorker (worker: Worker): void {
286 const workerKey = this.getWorkerKey(worker)
287 this.workers.splice(workerKey, 1)
288 this.workerChoiceStrategyContext.remove(workerKey)
289 }
290
291 /**
292 * Chooses a worker for the next task.
293 *
294 * The default implementation uses a round robin algorithm to distribute the load.
295 *
296 * @returns [worker key, worker].
297 */
298 protected chooseWorker (): [number, Worker] {
299 const workerKey = this.workerChoiceStrategyContext.execute()
300 return [workerKey, this.workers[workerKey].worker]
301 }
302
303 /**
304 * Sends a message to the given worker.
305 *
306 * @param worker - The worker which should receive the message.
307 * @param message - The message.
308 */
309 protected abstract sendToWorker (
310 worker: Worker,
311 message: MessageValue<Data>
312 ): void
313
314 /**
315 * Registers a listener callback on a given worker.
316 *
317 * @param worker - The worker which should register a listener.
318 * @param listener - The message listener callback.
319 */
320 protected abstract registerWorkerMessageListener<
321 Message extends Data | Response
322 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
323
324 /**
325 * Returns a newly created worker.
326 */
327 protected abstract createWorker (): Worker
328
329 /**
330 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
331 *
332 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
333 *
334 * @param worker - The newly created worker.
335 */
336 protected abstract afterWorkerSetup (worker: Worker): void
337
338 /**
339 * Creates a new worker for this pool and sets it up completely.
340 *
341 * @returns New, completely set up worker.
342 */
343 protected createAndSetupWorker (): Worker {
344 const worker = this.createWorker()
345
346 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
347 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
348 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
349 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
350 worker.once('exit', () => {
351 this.removeWorker(worker)
352 })
353
354 this.pushWorker(worker, {
355 run: 0,
356 running: 0,
357 runTime: 0,
358 avgRunTime: 0,
359 error: 0
360 })
361
362 this.afterWorkerSetup(worker)
363
364 return worker
365 }
366
367 /**
368 * This function is the listener registered for each worker.
369 *
370 * @returns The listener function to execute when a message is received from a worker.
371 */
372 protected workerListener (): (message: MessageValue<Response>) => void {
373 return message => {
374 if (message.id !== undefined) {
375 const promiseResponse = this.promiseResponseMap.get(message.id)
376 if (promiseResponse !== undefined) {
377 if (message.error != null) {
378 promiseResponse.reject(message.error)
379 } else {
380 promiseResponse.resolve(message.data as Response)
381 }
382 this.afterPromiseResponseHook(promiseResponse.worker, message)
383 this.promiseResponseMap.delete(message.id)
384 }
385 }
386 }
387 }
388
389 private async internalExecute (
390 workerKey: number,
391 worker: Worker,
392 messageId: string
393 ): Promise<Response> {
394 this.beforePromiseResponseHook(workerKey)
395 return await new Promise<Response>((resolve, reject) => {
396 this.promiseResponseMap.set(messageId, { resolve, reject, worker })
397 })
398 }
399
400 private checkAndEmitBusy (): void {
401 if (this.opts.enableEvents === true && this.busy) {
402 this.emitter?.emit('busy')
403 }
404 }
405
406 /**
407 * Gets worker tasks usage.
408 *
409 * @param worker - The worker.
410 * @returns The worker tasks usage.
411 */
412 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
413 const workerKey = this.getWorkerKey(worker)
414 if (workerKey !== -1) {
415 return this.workers[workerKey].tasksUsage
416 }
417 throw new Error('Worker could not be found in the pool')
418 }
419
420 /**
421 * Pushes the given worker.
422 *
423 * @param worker - The worker.
424 * @param tasksUsage - The worker tasks usage.
425 */
426 private pushWorker (worker: Worker, tasksUsage: TasksUsage): void {
427 this.workers.push({
428 worker,
429 tasksUsage
430 })
431 }
432
433 /**
434 * Sets the given worker.
435 *
436 * @param workerKey - The worker key.
437 * @param worker - The worker.
438 * @param tasksUsage - The worker tasks usage.
439 */
440 private setWorker (
441 workerKey: number,
442 worker: Worker,
443 tasksUsage: TasksUsage
444 ): void {
445 this.workers[workerKey] = {
446 worker,
447 tasksUsage
448 }
449 }
450 }