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