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' |
bdaf31cd | 5 | import 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> { |
38e795c1 | 28 | /** {@inheritDoc} */ |
e65c6cd9 | 29 | public readonly workers: Array<WorkerType<Worker>> = [] |
4a6952ff | 30 | |
38e795c1 | 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 | |
96 | >( | |
a35560ba | 97 | this, |
4a6952ff | 98 | () => { |
c923ce56 JB |
99 | const createdWorker = this.createAndSetupWorker() |
100 | this.registerWorkerMessageListener(createdWorker, message => { | |
4a6952ff JB |
101 | if ( |
102 | isKillBehavior(KillBehaviors.HARD, message.kill) || | |
c923ce56 | 103 | this.getWorkerTasksUsage(createdWorker)?.running === 0 |
4a6952ff JB |
104 | ) { |
105 | // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime) | |
c923ce56 | 106 | void this.destroyWorker(createdWorker) |
4a6952ff JB |
107 | } |
108 | }) | |
c923ce56 | 109 | return this.getWorkerKey(createdWorker) |
4a6952ff | 110 | }, |
e843b904 | 111 | this.opts.workerChoiceStrategy |
a35560ba | 112 | ) |
c97c7edb S |
113 | } |
114 | ||
a35560ba | 115 | private checkFilePath (filePath: string): void { |
ffcbbad8 JB |
116 | if ( |
117 | filePath == null || | |
118 | (typeof filePath === 'string' && filePath.trim().length === 0) | |
119 | ) { | |
c510fea7 APA |
120 | throw new Error('Please specify a file with a worker implementation') |
121 | } | |
122 | } | |
123 | ||
8d3782fa JB |
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 | ) | |
78cea37e | 129 | } else if (!Number.isSafeInteger(numberOfWorkers)) { |
473c717a | 130 | throw new TypeError( |
8d3782fa JB |
131 | 'Cannot instantiate a pool with a non integer number of workers' |
132 | ) | |
133 | } else if (numberOfWorkers < 0) { | |
473c717a | 134 | throw new RangeError( |
8d3782fa JB |
135 | 'Cannot instantiate a pool with a negative number of workers' |
136 | ) | |
7c0ba920 | 137 | } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) { |
8d3782fa JB |
138 | throw new Error('Cannot instantiate a fixed pool with no worker') |
139 | } | |
140 | } | |
141 | ||
7c0ba920 | 142 | private checkPoolOptions (opts: PoolOptions<Worker>): void { |
e843b904 JB |
143 | this.opts.workerChoiceStrategy = |
144 | opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN | |
7c0ba920 JB |
145 | this.opts.enableEvents = opts.enableEvents ?? true |
146 | } | |
147 | ||
38e795c1 | 148 | /** {@inheritDoc} */ |
7c0ba920 JB |
149 | public abstract get type (): PoolType |
150 | ||
c2ade475 | 151 | /** |
51fe3d3c | 152 | * Number of tasks concurrently running in the pool. |
c2ade475 JB |
153 | */ |
154 | private get numberOfRunningTasks (): number { | |
2740a743 | 155 | return this.promiseResponseMap.size |
a35560ba S |
156 | } |
157 | ||
ffcbbad8 | 158 | /** |
b4e75778 | 159 | * Gets the given worker key. |
ffcbbad8 JB |
160 | * |
161 | * @param worker - The worker. | |
7cf00f70 | 162 | * @returns The worker key if the worker is found in the pool, `-1` otherwise. |
ffcbbad8 | 163 | */ |
e65c6cd9 JB |
164 | private getWorkerKey (worker: Worker): number { |
165 | return this.workers.findIndex(workerItem => workerItem.worker === worker) | |
bf9549ae JB |
166 | } |
167 | ||
38e795c1 | 168 | /** {@inheritDoc} */ |
a35560ba S |
169 | public setWorkerChoiceStrategy ( |
170 | workerChoiceStrategy: WorkerChoiceStrategy | |
171 | ): void { | |
b98ec2e6 | 172 | this.opts.workerChoiceStrategy = workerChoiceStrategy |
c923ce56 JB |
173 | for (const [index, workerItem] of this.workers.entries()) { |
174 | this.setWorker(index, workerItem.worker, { | |
ffcbbad8 JB |
175 | run: 0, |
176 | running: 0, | |
177 | runTime: 0, | |
2740a743 JB |
178 | avgRunTime: 0, |
179 | error: 0 | |
ffcbbad8 | 180 | }) |
ea7a90d3 | 181 | } |
a35560ba | 182 | this.workerChoiceStrategyContext.setWorkerChoiceStrategy( |
3300e7bc | 183 | this, |
a35560ba S |
184 | workerChoiceStrategy |
185 | ) | |
186 | } | |
187 | ||
c2ade475 JB |
188 | /** {@inheritDoc} */ |
189 | public abstract get full (): boolean | |
190 | ||
38e795c1 | 191 | /** {@inheritDoc} */ |
7c0ba920 JB |
192 | public abstract get busy (): boolean |
193 | ||
c2ade475 | 194 | protected internalBusy (): boolean { |
7c0ba920 JB |
195 | return ( |
196 | this.numberOfRunningTasks >= this.numberOfWorkers && | |
bf90656c | 197 | this.findFreeWorkerKey() === -1 |
7c0ba920 JB |
198 | ) |
199 | } | |
200 | ||
38e795c1 | 201 | /** {@inheritDoc} */ |
bf90656c JB |
202 | public findFreeWorkerKey (): number { |
203 | return this.workers.findIndex(workerItem => { | |
c923ce56 JB |
204 | return workerItem.tasksUsage.running === 0 |
205 | }) | |
7c0ba920 JB |
206 | } |
207 | ||
38e795c1 | 208 | /** {@inheritDoc} */ |
78cea37e | 209 | public async execute (data: Data): Promise<Response> { |
c923ce56 | 210 | const [workerKey, worker] = this.chooseWorker() |
b4e75778 | 211 | const messageId = crypto.randomUUID() |
c923ce56 | 212 | const res = this.internalExecute(workerKey, worker, messageId) |
164d950a | 213 | this.checkAndEmitFull() |
14916bf9 | 214 | this.checkAndEmitBusy() |
a05c10de | 215 | this.sendToWorker(worker, { |
e5a5c0fc JB |
216 | // eslint-disable-next-line @typescript-eslint/consistent-type-assertions |
217 | data: data ?? ({} as Data), | |
b4e75778 | 218 | id: messageId |
a05c10de | 219 | }) |
78cea37e | 220 | // eslint-disable-next-line @typescript-eslint/return-await |
280c2a77 S |
221 | return res |
222 | } | |
c97c7edb | 223 | |
38e795c1 | 224 | /** {@inheritDoc} */ |
c97c7edb | 225 | public async destroy (): Promise<void> { |
1fbcaa7c | 226 | await Promise.all( |
e65c6cd9 JB |
227 | this.workers.map(async workerItem => { |
228 | await this.destroyWorker(workerItem.worker) | |
1fbcaa7c JB |
229 | }) |
230 | ) | |
c97c7edb S |
231 | } |
232 | ||
4a6952ff | 233 | /** |
675bb809 | 234 | * Shutdowns given worker. |
4a6952ff | 235 | * |
38e795c1 | 236 | * @param worker - A worker within `workers`. |
4a6952ff JB |
237 | */ |
238 | protected abstract destroyWorker (worker: Worker): void | Promise<void> | |
c97c7edb | 239 | |
729c563d | 240 | /** |
280c2a77 S |
241 | * Setup hook that can be overridden by a Poolifier pool implementation |
242 | * to run code before workers are created in the abstract constructor. | |
729c563d | 243 | */ |
280c2a77 S |
244 | protected setupHook (): void { |
245 | // Can be overridden | |
246 | } | |
c97c7edb | 247 | |
729c563d | 248 | /** |
280c2a77 S |
249 | * Should return whether the worker is the main worker or not. |
250 | */ | |
251 | protected abstract isMain (): boolean | |
252 | ||
253 | /** | |
bf9549ae JB |
254 | * Hook executed before the worker task promise resolution. |
255 | * Can be overridden. | |
729c563d | 256 | * |
2740a743 | 257 | * @param workerKey - The worker key. |
729c563d | 258 | */ |
2740a743 JB |
259 | protected beforePromiseResponseHook (workerKey: number): void { |
260 | ++this.workers[workerKey].tasksUsage.running | |
c97c7edb S |
261 | } |
262 | ||
c01733f1 | 263 | /** |
bf9549ae JB |
264 | * Hook executed after the worker task promise resolution. |
265 | * Can be overridden. | |
c01733f1 | 266 | * |
c923ce56 | 267 | * @param worker - The worker. |
38e795c1 | 268 | * @param message - The received message. |
c01733f1 | 269 | */ |
2740a743 | 270 | protected afterPromiseResponseHook ( |
c923ce56 | 271 | worker: Worker, |
2740a743 | 272 | message: MessageValue<Response> |
bf9549ae | 273 | ): void { |
c923ce56 | 274 | const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage |
3032893a JB |
275 | --workerTasksUsage.running |
276 | ++workerTasksUsage.run | |
2740a743 JB |
277 | if (message.error != null) { |
278 | ++workerTasksUsage.error | |
279 | } | |
97a2abc3 | 280 | if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) { |
3032893a | 281 | workerTasksUsage.runTime += message.taskRunTime ?? 0 |
c6bd2650 JB |
282 | if ( |
283 | this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime && | |
284 | workerTasksUsage.run !== 0 | |
285 | ) { | |
3032893a JB |
286 | workerTasksUsage.avgRunTime = |
287 | workerTasksUsage.runTime / workerTasksUsage.run | |
288 | } | |
289 | } | |
c01733f1 | 290 | } |
291 | ||
280c2a77 | 292 | /** |
675bb809 | 293 | * Chooses a worker for the next task. |
280c2a77 | 294 | * |
51fe3d3c | 295 | * The default uses a round robin algorithm to distribute the load. |
280c2a77 | 296 | * |
c923ce56 | 297 | * @returns [worker key, worker]. |
280c2a77 | 298 | */ |
c923ce56 JB |
299 | protected chooseWorker (): [number, Worker] { |
300 | const workerKey = this.workerChoiceStrategyContext.execute() | |
301 | return [workerKey, this.workers[workerKey].worker] | |
c97c7edb S |
302 | } |
303 | ||
280c2a77 | 304 | /** |
675bb809 | 305 | * Sends a message to the given worker. |
280c2a77 | 306 | * |
38e795c1 JB |
307 | * @param worker - The worker which should receive the message. |
308 | * @param message - The message. | |
280c2a77 S |
309 | */ |
310 | protected abstract sendToWorker ( | |
311 | worker: Worker, | |
312 | message: MessageValue<Data> | |
313 | ): void | |
314 | ||
4a6952ff | 315 | /** |
bdede008 | 316 | * Registers a listener callback on a given worker. |
4a6952ff | 317 | * |
38e795c1 JB |
318 | * @param worker - The worker which should register a listener. |
319 | * @param listener - The message listener callback. | |
4a6952ff JB |
320 | */ |
321 | protected abstract registerWorkerMessageListener< | |
4f7fa42a | 322 | Message extends Data | Response |
78cea37e | 323 | >(worker: Worker, listener: (message: MessageValue<Message>) => void): void |
c97c7edb | 324 | |
729c563d S |
325 | /** |
326 | * Returns a newly created worker. | |
327 | */ | |
280c2a77 | 328 | protected abstract createWorker (): Worker |
c97c7edb | 329 | |
729c563d S |
330 | /** |
331 | * Function that can be hooked up when a worker has been newly created and moved to the workers registry. | |
332 | * | |
38e795c1 | 333 | * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default. |
729c563d | 334 | * |
38e795c1 | 335 | * @param worker - The newly created worker. |
729c563d | 336 | */ |
280c2a77 | 337 | protected abstract afterWorkerSetup (worker: Worker): void |
c97c7edb | 338 | |
4a6952ff JB |
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 { | |
bdacc2d2 | 345 | const worker = this.createWorker() |
280c2a77 | 346 | |
35cf1c03 | 347 | worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION) |
a35560ba S |
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) | |
a974afa6 JB |
351 | worker.once('exit', () => { |
352 | this.removeWorker(worker) | |
353 | }) | |
280c2a77 | 354 | |
c923ce56 | 355 | this.pushWorker(worker, { |
ffcbbad8 JB |
356 | run: 0, |
357 | running: 0, | |
358 | runTime: 0, | |
2740a743 JB |
359 | avgRunTime: 0, |
360 | error: 0 | |
ffcbbad8 | 361 | }) |
280c2a77 S |
362 | |
363 | this.afterWorkerSetup(worker) | |
364 | ||
c97c7edb S |
365 | return worker |
366 | } | |
be0676b3 APA |
367 | |
368 | /** | |
369 | * This function is the listener registered for each worker. | |
370 | * | |
bdacc2d2 | 371 | * @returns The listener function to execute when a message is received from a worker. |
be0676b3 APA |
372 | */ |
373 | protected workerListener (): (message: MessageValue<Response>) => void { | |
4a6952ff | 374 | return message => { |
bdacc2d2 | 375 | if (message.id !== undefined) { |
2740a743 JB |
376 | const promiseResponse = this.promiseResponseMap.get(message.id) |
377 | if (promiseResponse !== undefined) { | |
78cea37e | 378 | if (message.error != null) { |
2740a743 | 379 | promiseResponse.reject(message.error) |
a05c10de | 380 | } else { |
2740a743 | 381 | promiseResponse.resolve(message.data as Response) |
a05c10de | 382 | } |
c923ce56 | 383 | this.afterPromiseResponseHook(promiseResponse.worker, message) |
2740a743 | 384 | this.promiseResponseMap.delete(message.id) |
be0676b3 APA |
385 | } |
386 | } | |
387 | } | |
be0676b3 | 388 | } |
7c0ba920 | 389 | |
78cea37e | 390 | private async internalExecute ( |
2740a743 | 391 | workerKey: number, |
c923ce56 | 392 | worker: Worker, |
b4e75778 | 393 | messageId: string |
78cea37e | 394 | ): Promise<Response> { |
2740a743 | 395 | this.beforePromiseResponseHook(workerKey) |
78cea37e | 396 | return await new Promise<Response>((resolve, reject) => { |
c923ce56 | 397 | this.promiseResponseMap.set(messageId, { resolve, reject, worker }) |
78cea37e JB |
398 | }) |
399 | } | |
400 | ||
7c0ba920 | 401 | private checkAndEmitBusy (): void { |
78cea37e | 402 | if (this.opts.enableEvents === true && this.busy) { |
7c0ba920 JB |
403 | this.emitter?.emit('busy') |
404 | } | |
405 | } | |
bf9549ae | 406 | |
164d950a JB |
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 | ||
c923ce56 JB |
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 { | |
3032893a | 424 | const workerKey = this.getWorkerKey(worker) |
e65c6cd9 JB |
425 | if (workerKey !== -1) { |
426 | return this.workers[workerKey].tasksUsage | |
ffcbbad8 | 427 | } |
3032893a | 428 | throw new Error('Worker could not be found in the pool') |
a05c10de JB |
429 | } |
430 | ||
431 | /** | |
51fe3d3c | 432 | * Pushes the given worker in the pool. |
ea7a90d3 | 433 | * |
38e795c1 | 434 | * @param worker - The worker. |
ffcbbad8 | 435 | * @param tasksUsage - The worker tasks usage. |
ea7a90d3 | 436 | */ |
c923ce56 | 437 | private pushWorker (worker: Worker, tasksUsage: TasksUsage): void { |
e65c6cd9 | 438 | this.workers.push({ |
ffcbbad8 JB |
439 | worker, |
440 | tasksUsage | |
ea7a90d3 JB |
441 | }) |
442 | } | |
c923ce56 JB |
443 | |
444 | /** | |
51fe3d3c | 445 | * Sets the given worker in the pool. |
c923ce56 JB |
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 | } | |
51fe3d3c JB |
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 | } | |
c97c7edb | 472 | } |