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