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