refactor: move worker choice instance helper into the context class
[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 context referencing a worker choice algorithm implementation.
49 *
50 * Default to 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.checkAndEmitFull.bind(this)
80 this.checkAndEmitBusy.bind(this)
81 this.sendToWorker.bind(this)
82
83 this.setupHook()
84
85 for (let i = 1; i <= this.numberOfWorkers; i++) {
86 this.createAndSetupWorker()
87 }
88
89 if (this.opts.enableEvents === true) {
90 this.emitter = new PoolEmitter()
91 }
92 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
93 Worker,
94 Data,
95 Response
96 >(
97 this,
98 () => {
99 const createdWorker = this.createAndSetupWorker()
100 this.registerWorkerMessageListener(createdWorker, message => {
101 if (
102 isKillBehavior(KillBehaviors.HARD, message.kill) ||
103 this.getWorkerTasksUsage(createdWorker)?.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(createdWorker)
107 }
108 })
109 return this.getWorkerKey(createdWorker)
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 /**
152 * Number of tasks concurrently running in the pool.
153 */
154 private get numberOfRunningTasks (): number {
155 return this.promiseResponseMap.size
156 }
157
158 /**
159 * Gets the given worker key.
160 *
161 * @param worker - The worker.
162 * @returns The worker key if the worker is found in the pool, `-1` otherwise.
163 */
164 private getWorkerKey (worker: Worker): number {
165 return this.workers.findIndex(workerItem => workerItem.worker === worker)
166 }
167
168 /** {@inheritDoc} */
169 public setWorkerChoiceStrategy (
170 workerChoiceStrategy: WorkerChoiceStrategy
171 ): void {
172 this.opts.workerChoiceStrategy = workerChoiceStrategy
173 for (const [index, workerItem] of this.workers.entries()) {
174 this.setWorker(index, workerItem.worker, {
175 run: 0,
176 running: 0,
177 runTime: 0,
178 avgRunTime: 0,
179 error: 0
180 })
181 }
182 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
183 this,
184 workerChoiceStrategy
185 )
186 }
187
188 /** {@inheritDoc} */
189 public abstract get full (): boolean
190
191 /** {@inheritDoc} */
192 public abstract get busy (): boolean
193
194 protected internalBusy (): boolean {
195 return (
196 this.numberOfRunningTasks >= this.numberOfWorkers &&
197 this.findFreeWorkerKey() === -1
198 )
199 }
200
201 /** {@inheritDoc} */
202 public findFreeWorkerKey (): number {
203 return this.workers.findIndex(workerItem => {
204 return workerItem.tasksUsage.running === 0
205 })
206 }
207
208 /** {@inheritDoc} */
209 public async execute (data: Data): Promise<Response> {
210 const [workerKey, worker] = this.chooseWorker()
211 const messageId = crypto.randomUUID()
212 const res = this.internalExecute(workerKey, worker, messageId)
213 this.checkAndEmitFull()
214 this.checkAndEmitBusy()
215 this.sendToWorker(worker, {
216 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
217 data: data ?? ({} as Data),
218 id: messageId
219 })
220 // eslint-disable-next-line @typescript-eslint/return-await
221 return res
222 }
223
224 /** {@inheritDoc} */
225 public async destroy (): Promise<void> {
226 await Promise.all(
227 this.workers.map(async workerItem => {
228 await this.destroyWorker(workerItem.worker)
229 })
230 )
231 }
232
233 /**
234 * Shutdowns given worker.
235 *
236 * @param worker - A worker within `workers`.
237 */
238 protected abstract destroyWorker (worker: Worker): void | Promise<void>
239
240 /**
241 * Setup hook that can be overridden by a Poolifier pool implementation
242 * to run code before workers are created in the abstract constructor.
243 */
244 protected setupHook (): void {
245 // Can be overridden
246 }
247
248 /**
249 * Should return whether the worker is the main worker or not.
250 */
251 protected abstract isMain (): boolean
252
253 /**
254 * Hook executed before the worker task promise resolution.
255 * Can be overridden.
256 *
257 * @param workerKey - The worker key.
258 */
259 protected beforePromiseResponseHook (workerKey: number): void {
260 ++this.workers[workerKey].tasksUsage.running
261 }
262
263 /**
264 * Hook executed after the worker task promise resolution.
265 * Can be overridden.
266 *
267 * @param worker - The worker.
268 * @param message - The received message.
269 */
270 protected afterPromiseResponseHook (
271 worker: Worker,
272 message: MessageValue<Response>
273 ): void {
274 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
275 --workerTasksUsage.running
276 ++workerTasksUsage.run
277 if (message.error != null) {
278 ++workerTasksUsage.error
279 }
280 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
281 workerTasksUsage.runTime += message.taskRunTime ?? 0
282 if (
283 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
284 workerTasksUsage.run !== 0
285 ) {
286 workerTasksUsage.avgRunTime =
287 workerTasksUsage.runTime / workerTasksUsage.run
288 }
289 }
290 }
291
292 /**
293 * Chooses a worker for the next task.
294 *
295 * The default uses a round robin algorithm to distribute the load.
296 *
297 * @returns [worker key, worker].
298 */
299 protected chooseWorker (): [number, Worker] {
300 const workerKey = this.workerChoiceStrategyContext.execute()
301 return [workerKey, this.workers[workerKey].worker]
302 }
303
304 /**
305 * Sends a message to the given worker.
306 *
307 * @param worker - The worker which should receive the message.
308 * @param message - The message.
309 */
310 protected abstract sendToWorker (
311 worker: Worker,
312 message: MessageValue<Data>
313 ): void
314
315 /**
316 * Registers a listener callback on a given worker.
317 *
318 * @param worker - The worker which should register a listener.
319 * @param listener - The message listener callback.
320 */
321 protected abstract registerWorkerMessageListener<
322 Message extends Data | Response
323 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
324
325 /**
326 * Returns a newly created worker.
327 */
328 protected abstract createWorker (): Worker
329
330 /**
331 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
332 *
333 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
334 *
335 * @param worker - The newly created worker.
336 */
337 protected abstract afterWorkerSetup (worker: Worker): void
338
339 /**
340 * Creates a new worker for this pool and sets it up completely.
341 *
342 * @returns New, completely set up worker.
343 */
344 protected createAndSetupWorker (): Worker {
345 const worker = this.createWorker()
346
347 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
348 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
349 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
350 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
351 worker.once('exit', () => {
352 this.removeWorker(worker)
353 })
354
355 this.pushWorker(worker, {
356 run: 0,
357 running: 0,
358 runTime: 0,
359 avgRunTime: 0,
360 error: 0
361 })
362
363 this.afterWorkerSetup(worker)
364
365 return worker
366 }
367
368 /**
369 * This function is the listener registered for each worker.
370 *
371 * @returns The listener function to execute when a message is received from a worker.
372 */
373 protected workerListener (): (message: MessageValue<Response>) => void {
374 return message => {
375 if (message.id !== undefined) {
376 const promiseResponse = this.promiseResponseMap.get(message.id)
377 if (promiseResponse !== undefined) {
378 if (message.error != null) {
379 promiseResponse.reject(message.error)
380 } else {
381 promiseResponse.resolve(message.data as Response)
382 }
383 this.afterPromiseResponseHook(promiseResponse.worker, message)
384 this.promiseResponseMap.delete(message.id)
385 }
386 }
387 }
388 }
389
390 private async internalExecute (
391 workerKey: number,
392 worker: Worker,
393 messageId: string
394 ): Promise<Response> {
395 this.beforePromiseResponseHook(workerKey)
396 return await new Promise<Response>((resolve, reject) => {
397 this.promiseResponseMap.set(messageId, { resolve, reject, worker })
398 })
399 }
400
401 private checkAndEmitBusy (): void {
402 if (this.opts.enableEvents === true && this.busy) {
403 this.emitter?.emit('busy')
404 }
405 }
406
407 private checkAndEmitFull (): void {
408 if (
409 this.type === PoolType.DYNAMIC &&
410 this.opts.enableEvents === true &&
411 this.full
412 ) {
413 this.emitter?.emit('full')
414 }
415 }
416
417 /**
418 * Gets worker tasks usage.
419 *
420 * @param worker - The worker.
421 * @returns The worker tasks usage.
422 */
423 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
424 const workerKey = this.getWorkerKey(worker)
425 if (workerKey !== -1) {
426 return this.workers[workerKey].tasksUsage
427 }
428 throw new Error('Worker could not be found in the pool')
429 }
430
431 /**
432 * Pushes the given worker in the pool.
433 *
434 * @param worker - The worker.
435 * @param tasksUsage - The worker tasks usage.
436 */
437 private pushWorker (worker: Worker, tasksUsage: TasksUsage): void {
438 this.workers.push({
439 worker,
440 tasksUsage
441 })
442 }
443
444 /**
445 * Sets the given worker in the pool.
446 *
447 * @param workerKey - The worker key.
448 * @param worker - The worker.
449 * @param tasksUsage - The worker tasks usage.
450 */
451 private setWorker (
452 workerKey: number,
453 worker: Worker,
454 tasksUsage: TasksUsage
455 ): void {
456 this.workers[workerKey] = {
457 worker,
458 tasksUsage
459 }
460 }
461
462 /**
463 * Removes the given worker from the pool.
464 *
465 * @param worker - The worker that will be removed.
466 */
467 protected removeWorker (worker: Worker): void {
468 const workerKey = this.getWorkerKey(worker)
469 this.workers.splice(workerKey, 1)
470 this.workerChoiceStrategyContext.remove(workerKey)
471 }
472 }