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