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 && | |
c923ce56 | 180 | this.findFreeWorkerKey() === false |
7c0ba920 JB |
181 | ) |
182 | } | |
183 | ||
38e795c1 | 184 | /** {@inheritDoc} */ |
c923ce56 JB |
185 | public findFreeWorkerKey (): number | false { |
186 | const freeWorkerKey = this.workers.findIndex(workerItem => { | |
187 | return workerItem.tasksUsage.running === 0 | |
188 | }) | |
189 | return freeWorkerKey !== -1 ? freeWorkerKey : false | |
7c0ba920 JB |
190 | } |
191 | ||
38e795c1 | 192 | /** {@inheritDoc} */ |
78cea37e | 193 | public async execute (data: Data): Promise<Response> { |
c923ce56 | 194 | const [workerKey, worker] = this.chooseWorker() |
b4e75778 | 195 | const messageId = crypto.randomUUID() |
c923ce56 | 196 | const res = this.internalExecute(workerKey, worker, messageId) |
14916bf9 | 197 | this.checkAndEmitBusy() |
a05c10de | 198 | this.sendToWorker(worker, { |
e5a5c0fc JB |
199 | // eslint-disable-next-line @typescript-eslint/consistent-type-assertions |
200 | data: data ?? ({} as Data), | |
b4e75778 | 201 | id: messageId |
a05c10de | 202 | }) |
78cea37e | 203 | // eslint-disable-next-line @typescript-eslint/return-await |
280c2a77 S |
204 | return res |
205 | } | |
c97c7edb | 206 | |
38e795c1 | 207 | /** {@inheritDoc} */ |
c97c7edb | 208 | public async destroy (): Promise<void> { |
1fbcaa7c | 209 | await Promise.all( |
e65c6cd9 JB |
210 | this.workers.map(async workerItem => { |
211 | await this.destroyWorker(workerItem.worker) | |
1fbcaa7c JB |
212 | }) |
213 | ) | |
c97c7edb S |
214 | } |
215 | ||
4a6952ff | 216 | /** |
675bb809 | 217 | * Shutdowns given worker. |
4a6952ff | 218 | * |
38e795c1 | 219 | * @param worker - A worker within `workers`. |
4a6952ff JB |
220 | */ |
221 | protected abstract destroyWorker (worker: Worker): void | Promise<void> | |
c97c7edb | 222 | |
729c563d | 223 | /** |
280c2a77 S |
224 | * Setup hook that can be overridden by a Poolifier pool implementation |
225 | * to run code before workers are created in the abstract constructor. | |
729c563d | 226 | */ |
280c2a77 S |
227 | protected setupHook (): void { |
228 | // Can be overridden | |
229 | } | |
c97c7edb | 230 | |
729c563d | 231 | /** |
280c2a77 S |
232 | * Should return whether the worker is the main worker or not. |
233 | */ | |
234 | protected abstract isMain (): boolean | |
235 | ||
236 | /** | |
bf9549ae JB |
237 | * Hook executed before the worker task promise resolution. |
238 | * Can be overridden. | |
729c563d | 239 | * |
2740a743 | 240 | * @param workerKey - The worker key. |
729c563d | 241 | */ |
2740a743 JB |
242 | protected beforePromiseResponseHook (workerKey: number): void { |
243 | ++this.workers[workerKey].tasksUsage.running | |
c97c7edb S |
244 | } |
245 | ||
c01733f1 | 246 | /** |
bf9549ae JB |
247 | * Hook executed after the worker task promise resolution. |
248 | * Can be overridden. | |
c01733f1 | 249 | * |
c923ce56 | 250 | * @param worker - The worker. |
38e795c1 | 251 | * @param message - The received message. |
c01733f1 | 252 | */ |
2740a743 | 253 | protected afterPromiseResponseHook ( |
c923ce56 | 254 | worker: Worker, |
2740a743 | 255 | message: MessageValue<Response> |
bf9549ae | 256 | ): void { |
c923ce56 | 257 | const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage |
3032893a JB |
258 | --workerTasksUsage.running |
259 | ++workerTasksUsage.run | |
2740a743 JB |
260 | if (message.error != null) { |
261 | ++workerTasksUsage.error | |
262 | } | |
97a2abc3 | 263 | if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) { |
3032893a JB |
264 | workerTasksUsage.runTime += message.taskRunTime ?? 0 |
265 | if (workerTasksUsage.run !== 0) { | |
266 | workerTasksUsage.avgRunTime = | |
267 | workerTasksUsage.runTime / workerTasksUsage.run | |
268 | } | |
269 | } | |
c01733f1 | 270 | } |
271 | ||
729c563d S |
272 | /** |
273 | * Removes the given worker from the pool. | |
274 | * | |
38e795c1 | 275 | * @param worker - The worker that will be removed. |
729c563d | 276 | */ |
f2fdaa86 | 277 | protected removeWorker (worker: Worker): void { |
97a2abc3 JB |
278 | const workerKey = this.getWorkerKey(worker) |
279 | this.workers.splice(workerKey, 1) | |
280 | this.workerChoiceStrategyContext.remove(workerKey) | |
f2fdaa86 JB |
281 | } |
282 | ||
280c2a77 | 283 | /** |
675bb809 | 284 | * Chooses a worker for the next task. |
280c2a77 S |
285 | * |
286 | * The default implementation uses a round robin algorithm to distribute the load. | |
287 | * | |
c923ce56 | 288 | * @returns [worker key, worker]. |
280c2a77 | 289 | */ |
c923ce56 JB |
290 | protected chooseWorker (): [number, Worker] { |
291 | const workerKey = this.workerChoiceStrategyContext.execute() | |
292 | return [workerKey, this.workers[workerKey].worker] | |
c97c7edb S |
293 | } |
294 | ||
280c2a77 | 295 | /** |
675bb809 | 296 | * Sends a message to the given worker. |
280c2a77 | 297 | * |
38e795c1 JB |
298 | * @param worker - The worker which should receive the message. |
299 | * @param message - The message. | |
280c2a77 S |
300 | */ |
301 | protected abstract sendToWorker ( | |
302 | worker: Worker, | |
303 | message: MessageValue<Data> | |
304 | ): void | |
305 | ||
4a6952ff | 306 | /** |
bdede008 | 307 | * Registers a listener callback on a given worker. |
4a6952ff | 308 | * |
38e795c1 JB |
309 | * @param worker - The worker which should register a listener. |
310 | * @param listener - The message listener callback. | |
4a6952ff JB |
311 | */ |
312 | protected abstract registerWorkerMessageListener< | |
4f7fa42a | 313 | Message extends Data | Response |
78cea37e | 314 | >(worker: Worker, listener: (message: MessageValue<Message>) => void): void |
c97c7edb | 315 | |
729c563d S |
316 | /** |
317 | * Returns a newly created worker. | |
318 | */ | |
280c2a77 | 319 | protected abstract createWorker (): Worker |
c97c7edb | 320 | |
729c563d S |
321 | /** |
322 | * Function that can be hooked up when a worker has been newly created and moved to the workers registry. | |
323 | * | |
38e795c1 | 324 | * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default. |
729c563d | 325 | * |
38e795c1 | 326 | * @param worker - The newly created worker. |
729c563d | 327 | */ |
280c2a77 | 328 | protected abstract afterWorkerSetup (worker: Worker): void |
c97c7edb | 329 | |
4a6952ff JB |
330 | /** |
331 | * Creates a new worker for this pool and sets it up completely. | |
332 | * | |
333 | * @returns New, completely set up worker. | |
334 | */ | |
335 | protected createAndSetupWorker (): Worker { | |
bdacc2d2 | 336 | const worker = this.createWorker() |
280c2a77 | 337 | |
35cf1c03 | 338 | worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION) |
a35560ba S |
339 | worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION) |
340 | worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION) | |
341 | worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION) | |
a974afa6 JB |
342 | worker.once('exit', () => { |
343 | this.removeWorker(worker) | |
344 | }) | |
280c2a77 | 345 | |
c923ce56 | 346 | this.pushWorker(worker, { |
ffcbbad8 JB |
347 | run: 0, |
348 | running: 0, | |
349 | runTime: 0, | |
2740a743 JB |
350 | avgRunTime: 0, |
351 | error: 0 | |
ffcbbad8 | 352 | }) |
280c2a77 S |
353 | |
354 | this.afterWorkerSetup(worker) | |
355 | ||
c97c7edb S |
356 | return worker |
357 | } | |
be0676b3 APA |
358 | |
359 | /** | |
360 | * This function is the listener registered for each worker. | |
361 | * | |
bdacc2d2 | 362 | * @returns The listener function to execute when a message is received from a worker. |
be0676b3 APA |
363 | */ |
364 | protected workerListener (): (message: MessageValue<Response>) => void { | |
4a6952ff | 365 | return message => { |
bdacc2d2 | 366 | if (message.id !== undefined) { |
2740a743 JB |
367 | const promiseResponse = this.promiseResponseMap.get(message.id) |
368 | if (promiseResponse !== undefined) { | |
78cea37e | 369 | if (message.error != null) { |
2740a743 | 370 | promiseResponse.reject(message.error) |
a05c10de | 371 | } else { |
2740a743 | 372 | promiseResponse.resolve(message.data as Response) |
a05c10de | 373 | } |
c923ce56 | 374 | this.afterPromiseResponseHook(promiseResponse.worker, message) |
2740a743 | 375 | this.promiseResponseMap.delete(message.id) |
be0676b3 APA |
376 | } |
377 | } | |
378 | } | |
be0676b3 | 379 | } |
7c0ba920 | 380 | |
78cea37e | 381 | private async internalExecute ( |
2740a743 | 382 | workerKey: number, |
c923ce56 | 383 | worker: Worker, |
b4e75778 | 384 | messageId: string |
78cea37e | 385 | ): Promise<Response> { |
2740a743 | 386 | this.beforePromiseResponseHook(workerKey) |
78cea37e | 387 | return await new Promise<Response>((resolve, reject) => { |
c923ce56 | 388 | this.promiseResponseMap.set(messageId, { resolve, reject, worker }) |
78cea37e JB |
389 | }) |
390 | } | |
391 | ||
7c0ba920 | 392 | private checkAndEmitBusy (): void { |
78cea37e | 393 | if (this.opts.enableEvents === true && this.busy) { |
7c0ba920 JB |
394 | this.emitter?.emit('busy') |
395 | } | |
396 | } | |
bf9549ae | 397 | |
c923ce56 JB |
398 | /** |
399 | * Gets worker tasks usage. | |
400 | * | |
401 | * @param worker - The worker. | |
402 | * @returns The worker tasks usage. | |
403 | */ | |
404 | private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined { | |
3032893a | 405 | const workerKey = this.getWorkerKey(worker) |
e65c6cd9 JB |
406 | if (workerKey !== -1) { |
407 | return this.workers[workerKey].tasksUsage | |
ffcbbad8 | 408 | } |
3032893a | 409 | throw new Error('Worker could not be found in the pool') |
a05c10de JB |
410 | } |
411 | ||
412 | /** | |
c923ce56 | 413 | * Pushes the given worker. |
ea7a90d3 | 414 | * |
38e795c1 | 415 | * @param worker - The worker. |
ffcbbad8 | 416 | * @param tasksUsage - The worker tasks usage. |
ea7a90d3 | 417 | */ |
c923ce56 | 418 | private pushWorker (worker: Worker, tasksUsage: TasksUsage): void { |
e65c6cd9 | 419 | this.workers.push({ |
ffcbbad8 JB |
420 | worker, |
421 | tasksUsage | |
ea7a90d3 JB |
422 | }) |
423 | } | |
c923ce56 JB |
424 | |
425 | /** | |
426 | * Sets the given worker. | |
427 | * | |
428 | * @param workerKey - The worker key. | |
429 | * @param worker - The worker. | |
430 | * @param tasksUsage - The worker tasks usage. | |
431 | */ | |
432 | private setWorker ( | |
433 | workerKey: number, | |
434 | worker: Worker, | |
435 | tasksUsage: TasksUsage | |
436 | ): void { | |
437 | this.workers[workerKey] = { | |
438 | worker, | |
439 | tasksUsage | |
440 | } | |
441 | } | |
c97c7edb | 442 | } |