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