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