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 S |
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< | |
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) | |
79 | this.checkAndEmitBusy.bind(this) | |
80 | this.sendToWorker.bind(this) | |
81 | ||
c97c7edb S |
82 | this.setupHook() |
83 | ||
5c5a1fb7 | 84 | for (let i = 1; i <= this.numberOfWorkers; i++) { |
280c2a77 | 85 | this.createAndSetupWorker() |
c97c7edb S |
86 | } |
87 | ||
6bd72cd0 | 88 | if (this.opts.enableEvents === true) { |
7c0ba920 JB |
89 | this.emitter = new PoolEmitter() |
90 | } | |
d59df138 JB |
91 | this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext< |
92 | Worker, | |
93 | Data, | |
94 | Response | |
95 | >( | |
a35560ba | 96 | this, |
4a6952ff | 97 | () => { |
c923ce56 JB |
98 | const createdWorker = this.createAndSetupWorker() |
99 | this.registerWorkerMessageListener(createdWorker, message => { | |
4a6952ff JB |
100 | if ( |
101 | isKillBehavior(KillBehaviors.HARD, message.kill) || | |
c923ce56 | 102 | this.getWorkerTasksUsage(createdWorker)?.running === 0 |
4a6952ff JB |
103 | ) { |
104 | // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime) | |
c923ce56 | 105 | void this.destroyWorker(createdWorker) |
4a6952ff JB |
106 | } |
107 | }) | |
c923ce56 | 108 | return this.getWorkerKey(createdWorker) |
4a6952ff | 109 | }, |
e843b904 | 110 | this.opts.workerChoiceStrategy |
a35560ba | 111 | ) |
c97c7edb S |
112 | } |
113 | ||
a35560ba | 114 | private checkFilePath (filePath: string): void { |
ffcbbad8 JB |
115 | if ( |
116 | filePath == null || | |
117 | (typeof filePath === 'string' && filePath.trim().length === 0) | |
118 | ) { | |
c510fea7 APA |
119 | throw new Error('Please specify a file with a worker implementation') |
120 | } | |
121 | } | |
122 | ||
8d3782fa JB |
123 | private checkNumberOfWorkers (numberOfWorkers: number): void { |
124 | if (numberOfWorkers == null) { | |
125 | throw new Error( | |
126 | 'Cannot instantiate a pool without specifying the number of workers' | |
127 | ) | |
78cea37e | 128 | } else if (!Number.isSafeInteger(numberOfWorkers)) { |
473c717a | 129 | throw new TypeError( |
8d3782fa JB |
130 | 'Cannot instantiate a pool with a non integer number of workers' |
131 | ) | |
132 | } else if (numberOfWorkers < 0) { | |
473c717a | 133 | throw new RangeError( |
8d3782fa JB |
134 | 'Cannot instantiate a pool with a negative number of workers' |
135 | ) | |
7c0ba920 | 136 | } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) { |
8d3782fa JB |
137 | throw new Error('Cannot instantiate a fixed pool with no worker') |
138 | } | |
139 | } | |
140 | ||
7c0ba920 | 141 | private checkPoolOptions (opts: PoolOptions<Worker>): void { |
e843b904 JB |
142 | this.opts.workerChoiceStrategy = |
143 | opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN | |
7c0ba920 JB |
144 | this.opts.enableEvents = opts.enableEvents ?? true |
145 | } | |
146 | ||
38e795c1 | 147 | /** {@inheritDoc} */ |
7c0ba920 JB |
148 | public abstract get type (): PoolType |
149 | ||
c2ade475 JB |
150 | /** |
151 | * Number of tasks concurrently running. | |
152 | */ | |
153 | private get numberOfRunningTasks (): number { | |
2740a743 | 154 | return this.promiseResponseMap.size |
a35560ba S |
155 | } |
156 | ||
ffcbbad8 | 157 | /** |
b4e75778 | 158 | * Gets the given worker key. |
ffcbbad8 JB |
159 | * |
160 | * @param worker - The worker. | |
7cf00f70 | 161 | * @returns The worker key if the worker is found in the pool, `-1` otherwise. |
ffcbbad8 | 162 | */ |
e65c6cd9 JB |
163 | private getWorkerKey (worker: Worker): number { |
164 | return this.workers.findIndex(workerItem => workerItem.worker === worker) | |
bf9549ae JB |
165 | } |
166 | ||
38e795c1 | 167 | /** {@inheritDoc} */ |
a35560ba S |
168 | public setWorkerChoiceStrategy ( |
169 | workerChoiceStrategy: WorkerChoiceStrategy | |
170 | ): void { | |
b98ec2e6 | 171 | this.opts.workerChoiceStrategy = workerChoiceStrategy |
c923ce56 JB |
172 | for (const [index, workerItem] of this.workers.entries()) { |
173 | this.setWorker(index, workerItem.worker, { | |
ffcbbad8 JB |
174 | run: 0, |
175 | running: 0, | |
176 | runTime: 0, | |
2740a743 JB |
177 | avgRunTime: 0, |
178 | error: 0 | |
ffcbbad8 | 179 | }) |
ea7a90d3 | 180 | } |
a35560ba | 181 | this.workerChoiceStrategyContext.setWorkerChoiceStrategy( |
3300e7bc | 182 | this, |
a35560ba S |
183 | workerChoiceStrategy |
184 | ) | |
185 | } | |
186 | ||
c2ade475 JB |
187 | /** {@inheritDoc} */ |
188 | public abstract get full (): boolean | |
189 | ||
38e795c1 | 190 | /** {@inheritDoc} */ |
7c0ba920 JB |
191 | public abstract get busy (): boolean |
192 | ||
c2ade475 | 193 | protected internalBusy (): boolean { |
7c0ba920 JB |
194 | return ( |
195 | this.numberOfRunningTasks >= this.numberOfWorkers && | |
bf90656c | 196 | this.findFreeWorkerKey() === -1 |
7c0ba920 JB |
197 | ) |
198 | } | |
199 | ||
38e795c1 | 200 | /** {@inheritDoc} */ |
bf90656c JB |
201 | public findFreeWorkerKey (): number { |
202 | return this.workers.findIndex(workerItem => { | |
c923ce56 JB |
203 | return workerItem.tasksUsage.running === 0 |
204 | }) | |
7c0ba920 JB |
205 | } |
206 | ||
38e795c1 | 207 | /** {@inheritDoc} */ |
78cea37e | 208 | public async execute (data: Data): Promise<Response> { |
c923ce56 | 209 | const [workerKey, worker] = this.chooseWorker() |
b4e75778 | 210 | const messageId = crypto.randomUUID() |
c923ce56 | 211 | const res = this.internalExecute(workerKey, worker, messageId) |
14916bf9 | 212 | this.checkAndEmitBusy() |
a05c10de | 213 | this.sendToWorker(worker, { |
e5a5c0fc JB |
214 | // eslint-disable-next-line @typescript-eslint/consistent-type-assertions |
215 | data: data ?? ({} as Data), | |
b4e75778 | 216 | id: messageId |
a05c10de | 217 | }) |
78cea37e | 218 | // eslint-disable-next-line @typescript-eslint/return-await |
280c2a77 S |
219 | return res |
220 | } | |
c97c7edb | 221 | |
38e795c1 | 222 | /** {@inheritDoc} */ |
c97c7edb | 223 | public async destroy (): Promise<void> { |
1fbcaa7c | 224 | await Promise.all( |
e65c6cd9 JB |
225 | this.workers.map(async workerItem => { |
226 | await this.destroyWorker(workerItem.worker) | |
1fbcaa7c JB |
227 | }) |
228 | ) | |
c97c7edb S |
229 | } |
230 | ||
4a6952ff | 231 | /** |
675bb809 | 232 | * Shutdowns given worker. |
4a6952ff | 233 | * |
38e795c1 | 234 | * @param worker - A worker within `workers`. |
4a6952ff JB |
235 | */ |
236 | protected abstract destroyWorker (worker: Worker): void | Promise<void> | |
c97c7edb | 237 | |
729c563d | 238 | /** |
280c2a77 S |
239 | * Setup hook that can be overridden by a Poolifier pool implementation |
240 | * to run code before workers are created in the abstract constructor. | |
729c563d | 241 | */ |
280c2a77 S |
242 | protected setupHook (): void { |
243 | // Can be overridden | |
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) { |
3032893a | 279 | workerTasksUsage.runTime += message.taskRunTime ?? 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 | ||
729c563d S |
290 | /** |
291 | * Removes the given worker from the pool. | |
292 | * | |
38e795c1 | 293 | * @param worker - The worker that will be removed. |
729c563d | 294 | */ |
f2fdaa86 | 295 | protected removeWorker (worker: Worker): void { |
97a2abc3 JB |
296 | const workerKey = this.getWorkerKey(worker) |
297 | this.workers.splice(workerKey, 1) | |
298 | this.workerChoiceStrategyContext.remove(workerKey) | |
f2fdaa86 JB |
299 | } |
300 | ||
280c2a77 | 301 | /** |
675bb809 | 302 | * Chooses a worker for the next task. |
280c2a77 S |
303 | * |
304 | * The default implementation uses a round robin algorithm to distribute the load. | |
305 | * | |
c923ce56 | 306 | * @returns [worker key, worker]. |
280c2a77 | 307 | */ |
c923ce56 JB |
308 | protected chooseWorker (): [number, Worker] { |
309 | const workerKey = this.workerChoiceStrategyContext.execute() | |
310 | return [workerKey, this.workers[workerKey].worker] | |
c97c7edb S |
311 | } |
312 | ||
280c2a77 | 313 | /** |
675bb809 | 314 | * Sends a message to the given worker. |
280c2a77 | 315 | * |
38e795c1 JB |
316 | * @param worker - The worker which should receive the message. |
317 | * @param message - The message. | |
280c2a77 S |
318 | */ |
319 | protected abstract sendToWorker ( | |
320 | worker: Worker, | |
321 | message: MessageValue<Data> | |
322 | ): void | |
323 | ||
4a6952ff | 324 | /** |
bdede008 | 325 | * Registers a listener callback on a given worker. |
4a6952ff | 326 | * |
38e795c1 JB |
327 | * @param worker - The worker which should register a listener. |
328 | * @param listener - The message listener callback. | |
4a6952ff JB |
329 | */ |
330 | protected abstract registerWorkerMessageListener< | |
4f7fa42a | 331 | Message extends Data | Response |
78cea37e | 332 | >(worker: Worker, listener: (message: MessageValue<Message>) => void): void |
c97c7edb | 333 | |
729c563d S |
334 | /** |
335 | * Returns a newly created worker. | |
336 | */ | |
280c2a77 | 337 | protected abstract createWorker (): Worker |
c97c7edb | 338 | |
729c563d S |
339 | /** |
340 | * Function that can be hooked up when a worker has been newly created and moved to the workers registry. | |
341 | * | |
38e795c1 | 342 | * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default. |
729c563d | 343 | * |
38e795c1 | 344 | * @param worker - The newly created worker. |
729c563d | 345 | */ |
280c2a77 | 346 | protected abstract afterWorkerSetup (worker: Worker): void |
c97c7edb | 347 | |
4a6952ff JB |
348 | /** |
349 | * Creates a new worker for this pool and sets it up completely. | |
350 | * | |
351 | * @returns New, completely set up worker. | |
352 | */ | |
353 | protected createAndSetupWorker (): Worker { | |
bdacc2d2 | 354 | const worker = this.createWorker() |
280c2a77 | 355 | |
35cf1c03 | 356 | worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION) |
a35560ba S |
357 | worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION) |
358 | worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION) | |
359 | worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION) | |
a974afa6 JB |
360 | worker.once('exit', () => { |
361 | this.removeWorker(worker) | |
362 | }) | |
280c2a77 | 363 | |
c923ce56 | 364 | this.pushWorker(worker, { |
ffcbbad8 JB |
365 | run: 0, |
366 | running: 0, | |
367 | runTime: 0, | |
2740a743 JB |
368 | avgRunTime: 0, |
369 | error: 0 | |
ffcbbad8 | 370 | }) |
280c2a77 S |
371 | |
372 | this.afterWorkerSetup(worker) | |
373 | ||
c97c7edb S |
374 | return worker |
375 | } | |
be0676b3 APA |
376 | |
377 | /** | |
378 | * This function is the listener registered for each worker. | |
379 | * | |
bdacc2d2 | 380 | * @returns The listener function to execute when a message is received from a worker. |
be0676b3 APA |
381 | */ |
382 | protected workerListener (): (message: MessageValue<Response>) => void { | |
4a6952ff | 383 | return message => { |
bdacc2d2 | 384 | if (message.id !== undefined) { |
2740a743 JB |
385 | const promiseResponse = this.promiseResponseMap.get(message.id) |
386 | if (promiseResponse !== undefined) { | |
78cea37e | 387 | if (message.error != null) { |
2740a743 | 388 | promiseResponse.reject(message.error) |
a05c10de | 389 | } else { |
2740a743 | 390 | promiseResponse.resolve(message.data as Response) |
a05c10de | 391 | } |
c923ce56 | 392 | this.afterPromiseResponseHook(promiseResponse.worker, message) |
2740a743 | 393 | this.promiseResponseMap.delete(message.id) |
be0676b3 APA |
394 | } |
395 | } | |
396 | } | |
be0676b3 | 397 | } |
7c0ba920 | 398 | |
78cea37e | 399 | private async internalExecute ( |
2740a743 | 400 | workerKey: number, |
c923ce56 | 401 | worker: Worker, |
b4e75778 | 402 | messageId: string |
78cea37e | 403 | ): Promise<Response> { |
2740a743 | 404 | this.beforePromiseResponseHook(workerKey) |
78cea37e | 405 | return await new Promise<Response>((resolve, reject) => { |
c923ce56 | 406 | this.promiseResponseMap.set(messageId, { resolve, reject, worker }) |
78cea37e JB |
407 | }) |
408 | } | |
409 | ||
7c0ba920 | 410 | private checkAndEmitBusy (): void { |
78cea37e | 411 | if (this.opts.enableEvents === true && this.busy) { |
7c0ba920 JB |
412 | this.emitter?.emit('busy') |
413 | } | |
414 | } | |
bf9549ae | 415 | |
c923ce56 JB |
416 | /** |
417 | * Gets worker tasks usage. | |
418 | * | |
419 | * @param worker - The worker. | |
420 | * @returns The worker tasks usage. | |
421 | */ | |
422 | private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined { | |
3032893a | 423 | const workerKey = this.getWorkerKey(worker) |
e65c6cd9 JB |
424 | if (workerKey !== -1) { |
425 | return this.workers[workerKey].tasksUsage | |
ffcbbad8 | 426 | } |
3032893a | 427 | throw new Error('Worker could not be found in the pool') |
a05c10de JB |
428 | } |
429 | ||
430 | /** | |
c923ce56 | 431 | * Pushes the given worker. |
ea7a90d3 | 432 | * |
38e795c1 | 433 | * @param worker - The worker. |
ffcbbad8 | 434 | * @param tasksUsage - The worker tasks usage. |
ea7a90d3 | 435 | */ |
c923ce56 | 436 | private pushWorker (worker: Worker, tasksUsage: TasksUsage): void { |
e65c6cd9 | 437 | this.workers.push({ |
ffcbbad8 JB |
438 | worker, |
439 | tasksUsage | |
ea7a90d3 JB |
440 | }) |
441 | } | |
c923ce56 JB |
442 | |
443 | /** | |
444 | * Sets the given worker. | |
445 | * | |
446 | * @param workerKey - The worker key. | |
447 | * @param worker - The worker. | |
448 | * @param tasksUsage - The worker tasks usage. | |
449 | */ | |
450 | private setWorker ( | |
451 | workerKey: number, | |
452 | worker: Worker, | |
453 | tasksUsage: TasksUsage | |
454 | ): void { | |
455 | this.workers[workerKey] = { | |
456 | worker, | |
457 | tasksUsage | |
458 | } | |
459 | } | |
c97c7edb | 460 | } |