| 1 | import crypto from 'node:crypto' |
| 2 | import { performance } from 'node:perf_hooks' |
| 3 | import type { MessageValue, PromiseResponseWrapper } from '../utility-types' |
| 4 | import { |
| 5 | DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS, |
| 6 | EMPTY_FUNCTION, |
| 7 | isPlainObject, |
| 8 | median |
| 9 | } from '../utils' |
| 10 | import { KillBehaviors, isKillBehavior } from '../worker/worker-options' |
| 11 | import { CircularArray } from '../circular-array' |
| 12 | import { Queue } from '../queue' |
| 13 | import { |
| 14 | type IPool, |
| 15 | PoolEmitter, |
| 16 | PoolEvents, |
| 17 | type PoolInfo, |
| 18 | type PoolOptions, |
| 19 | type PoolType, |
| 20 | PoolTypes, |
| 21 | type TasksQueueOptions, |
| 22 | type WorkerType |
| 23 | } from './pool' |
| 24 | import type { IWorker, Task, TasksUsage, WorkerNode } from './worker' |
| 25 | import { |
| 26 | WorkerChoiceStrategies, |
| 27 | type WorkerChoiceStrategy, |
| 28 | type WorkerChoiceStrategyOptions |
| 29 | } from './selection-strategies/selection-strategies-types' |
| 30 | import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context' |
| 31 | |
| 32 | /** |
| 33 | * Base class that implements some shared logic for all poolifier pools. |
| 34 | * |
| 35 | * @typeParam Worker - Type of worker which manages this pool. |
| 36 | * @typeParam Data - Type of data sent to the worker. This can only be serializable data. |
| 37 | * @typeParam Response - Type of execution response. This can only be serializable data. |
| 38 | */ |
| 39 | export abstract class AbstractPool< |
| 40 | Worker extends IWorker, |
| 41 | Data = unknown, |
| 42 | Response = unknown |
| 43 | > implements IPool<Worker, Data, Response> { |
| 44 | /** @inheritDoc */ |
| 45 | public readonly workerNodes: Array<WorkerNode<Worker, Data>> = [] |
| 46 | |
| 47 | /** @inheritDoc */ |
| 48 | public readonly emitter?: PoolEmitter |
| 49 | |
| 50 | /** |
| 51 | * The execution response promise map. |
| 52 | * |
| 53 | * - `key`: The message id of each submitted task. |
| 54 | * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks. |
| 55 | * |
| 56 | * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id. |
| 57 | */ |
| 58 | protected promiseResponseMap: Map< |
| 59 | string, |
| 60 | PromiseResponseWrapper<Worker, Response> |
| 61 | > = new Map<string, PromiseResponseWrapper<Worker, Response>>() |
| 62 | |
| 63 | /** |
| 64 | * Worker choice strategy context referencing a worker choice algorithm implementation. |
| 65 | * |
| 66 | * Default to a round robin algorithm. |
| 67 | */ |
| 68 | protected workerChoiceStrategyContext: WorkerChoiceStrategyContext< |
| 69 | Worker, |
| 70 | Data, |
| 71 | Response |
| 72 | > |
| 73 | |
| 74 | /** |
| 75 | * Constructs a new poolifier pool. |
| 76 | * |
| 77 | * @param numberOfWorkers - Number of workers that this pool should manage. |
| 78 | * @param filePath - Path to the worker file. |
| 79 | * @param opts - Options for the pool. |
| 80 | */ |
| 81 | public constructor ( |
| 82 | protected readonly numberOfWorkers: number, |
| 83 | protected readonly filePath: string, |
| 84 | protected readonly opts: PoolOptions<Worker> |
| 85 | ) { |
| 86 | if (!this.isMain()) { |
| 87 | throw new Error('Cannot start a pool from a worker!') |
| 88 | } |
| 89 | this.checkNumberOfWorkers(this.numberOfWorkers) |
| 90 | this.checkFilePath(this.filePath) |
| 91 | this.checkPoolOptions(this.opts) |
| 92 | |
| 93 | this.chooseWorkerNode = this.chooseWorkerNode.bind(this) |
| 94 | this.executeTask = this.executeTask.bind(this) |
| 95 | this.enqueueTask = this.enqueueTask.bind(this) |
| 96 | this.checkAndEmitEvents = this.checkAndEmitEvents.bind(this) |
| 97 | |
| 98 | if (this.opts.enableEvents === true) { |
| 99 | this.emitter = new PoolEmitter() |
| 100 | } |
| 101 | this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext< |
| 102 | Worker, |
| 103 | Data, |
| 104 | Response |
| 105 | >( |
| 106 | this, |
| 107 | this.opts.workerChoiceStrategy, |
| 108 | this.opts.workerChoiceStrategyOptions |
| 109 | ) |
| 110 | |
| 111 | this.setupHook() |
| 112 | |
| 113 | for (let i = 1; i <= this.numberOfWorkers; i++) { |
| 114 | this.createAndSetupWorker() |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | private checkFilePath (filePath: string): void { |
| 119 | if ( |
| 120 | filePath == null || |
| 121 | (typeof filePath === 'string' && filePath.trim().length === 0) |
| 122 | ) { |
| 123 | throw new Error('Please specify a file with a worker implementation') |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | private checkNumberOfWorkers (numberOfWorkers: number): void { |
| 128 | if (numberOfWorkers == null) { |
| 129 | throw new Error( |
| 130 | 'Cannot instantiate a pool without specifying the number of workers' |
| 131 | ) |
| 132 | } else if (!Number.isSafeInteger(numberOfWorkers)) { |
| 133 | throw new TypeError( |
| 134 | 'Cannot instantiate a pool with a non safe integer number of workers' |
| 135 | ) |
| 136 | } else if (numberOfWorkers < 0) { |
| 137 | throw new RangeError( |
| 138 | 'Cannot instantiate a pool with a negative number of workers' |
| 139 | ) |
| 140 | } else if (this.type === PoolTypes.fixed && numberOfWorkers === 0) { |
| 141 | throw new Error('Cannot instantiate a fixed pool with no worker') |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | private checkPoolOptions (opts: PoolOptions<Worker>): void { |
| 146 | if (isPlainObject(opts)) { |
| 147 | this.opts.workerChoiceStrategy = |
| 148 | opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN |
| 149 | this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy) |
| 150 | this.opts.workerChoiceStrategyOptions = |
| 151 | opts.workerChoiceStrategyOptions ?? |
| 152 | DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS |
| 153 | this.checkValidWorkerChoiceStrategyOptions( |
| 154 | this.opts.workerChoiceStrategyOptions |
| 155 | ) |
| 156 | this.opts.restartWorkerOnError = opts.restartWorkerOnError ?? true |
| 157 | this.opts.enableEvents = opts.enableEvents ?? true |
| 158 | this.opts.enableTasksQueue = opts.enableTasksQueue ?? false |
| 159 | if (this.opts.enableTasksQueue) { |
| 160 | this.checkValidTasksQueueOptions( |
| 161 | opts.tasksQueueOptions as TasksQueueOptions |
| 162 | ) |
| 163 | this.opts.tasksQueueOptions = this.buildTasksQueueOptions( |
| 164 | opts.tasksQueueOptions as TasksQueueOptions |
| 165 | ) |
| 166 | } |
| 167 | } else { |
| 168 | throw new TypeError('Invalid pool options: must be a plain object') |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | private checkValidWorkerChoiceStrategy ( |
| 173 | workerChoiceStrategy: WorkerChoiceStrategy |
| 174 | ): void { |
| 175 | if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) { |
| 176 | throw new Error( |
| 177 | `Invalid worker choice strategy '${workerChoiceStrategy}'` |
| 178 | ) |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | private checkValidWorkerChoiceStrategyOptions ( |
| 183 | workerChoiceStrategyOptions: WorkerChoiceStrategyOptions |
| 184 | ): void { |
| 185 | if (!isPlainObject(workerChoiceStrategyOptions)) { |
| 186 | throw new TypeError( |
| 187 | 'Invalid worker choice strategy options: must be a plain object' |
| 188 | ) |
| 189 | } |
| 190 | if ( |
| 191 | workerChoiceStrategyOptions.weights != null && |
| 192 | Object.keys(workerChoiceStrategyOptions.weights).length !== this.maxSize |
| 193 | ) { |
| 194 | throw new Error( |
| 195 | 'Invalid worker choice strategy options: must have a weight for each worker node' |
| 196 | ) |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | private checkValidTasksQueueOptions ( |
| 201 | tasksQueueOptions: TasksQueueOptions |
| 202 | ): void { |
| 203 | if (tasksQueueOptions != null && !isPlainObject(tasksQueueOptions)) { |
| 204 | throw new TypeError('Invalid tasks queue options: must be a plain object') |
| 205 | } |
| 206 | if ((tasksQueueOptions?.concurrency as number) <= 0) { |
| 207 | throw new Error( |
| 208 | `Invalid worker tasks concurrency '${ |
| 209 | tasksQueueOptions.concurrency as number |
| 210 | }'` |
| 211 | ) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | /** @inheritDoc */ |
| 216 | public get info (): PoolInfo { |
| 217 | return { |
| 218 | type: this.type, |
| 219 | worker: this.worker, |
| 220 | minSize: this.minSize, |
| 221 | maxSize: this.maxSize, |
| 222 | workerNodes: this.workerNodes.length, |
| 223 | idleWorkerNodes: this.workerNodes.reduce( |
| 224 | (accumulator, workerNode) => |
| 225 | workerNode.tasksUsage.running === 0 ? accumulator + 1 : accumulator, |
| 226 | 0 |
| 227 | ), |
| 228 | busyWorkerNodes: this.workerNodes.reduce( |
| 229 | (accumulator, workerNode) => |
| 230 | workerNode.tasksUsage.running > 0 ? accumulator + 1 : accumulator, |
| 231 | 0 |
| 232 | ), |
| 233 | runningTasks: this.workerNodes.reduce( |
| 234 | (accumulator, workerNode) => |
| 235 | accumulator + workerNode.tasksUsage.running, |
| 236 | 0 |
| 237 | ), |
| 238 | queuedTasks: this.workerNodes.reduce( |
| 239 | (accumulator, workerNode) => accumulator + workerNode.tasksQueue.size, |
| 240 | 0 |
| 241 | ), |
| 242 | maxQueuedTasks: this.workerNodes.reduce( |
| 243 | (accumulator, workerNode) => |
| 244 | accumulator + workerNode.tasksQueue.maxSize, |
| 245 | 0 |
| 246 | ) |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | /** |
| 251 | * Pool type. |
| 252 | * |
| 253 | * If it is `'dynamic'`, it provides the `max` property. |
| 254 | */ |
| 255 | protected abstract get type (): PoolType |
| 256 | |
| 257 | /** |
| 258 | * Gets the worker type. |
| 259 | */ |
| 260 | protected abstract get worker (): WorkerType |
| 261 | |
| 262 | /** |
| 263 | * Pool minimum size. |
| 264 | */ |
| 265 | protected abstract get minSize (): number |
| 266 | |
| 267 | /** |
| 268 | * Pool maximum size. |
| 269 | */ |
| 270 | protected abstract get maxSize (): number |
| 271 | |
| 272 | /** |
| 273 | * Gets the given worker its worker node key. |
| 274 | * |
| 275 | * @param worker - The worker. |
| 276 | * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise. |
| 277 | */ |
| 278 | private getWorkerNodeKey (worker: Worker): number { |
| 279 | return this.workerNodes.findIndex( |
| 280 | workerNode => workerNode.worker === worker |
| 281 | ) |
| 282 | } |
| 283 | |
| 284 | /** @inheritDoc */ |
| 285 | public setWorkerChoiceStrategy ( |
| 286 | workerChoiceStrategy: WorkerChoiceStrategy, |
| 287 | workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions |
| 288 | ): void { |
| 289 | this.checkValidWorkerChoiceStrategy(workerChoiceStrategy) |
| 290 | this.opts.workerChoiceStrategy = workerChoiceStrategy |
| 291 | this.workerChoiceStrategyContext.setWorkerChoiceStrategy( |
| 292 | this.opts.workerChoiceStrategy |
| 293 | ) |
| 294 | if (workerChoiceStrategyOptions != null) { |
| 295 | this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions) |
| 296 | } |
| 297 | for (const workerNode of this.workerNodes) { |
| 298 | this.setWorkerNodeTasksUsage(workerNode, { |
| 299 | ran: 0, |
| 300 | running: 0, |
| 301 | runTime: 0, |
| 302 | runTimeHistory: new CircularArray(), |
| 303 | avgRunTime: 0, |
| 304 | medRunTime: 0, |
| 305 | waitTime: 0, |
| 306 | waitTimeHistory: new CircularArray(), |
| 307 | avgWaitTime: 0, |
| 308 | medWaitTime: 0, |
| 309 | error: 0, |
| 310 | elu: undefined |
| 311 | }) |
| 312 | this.setWorkerStatistics(workerNode.worker) |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | /** @inheritDoc */ |
| 317 | public setWorkerChoiceStrategyOptions ( |
| 318 | workerChoiceStrategyOptions: WorkerChoiceStrategyOptions |
| 319 | ): void { |
| 320 | this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions) |
| 321 | this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions |
| 322 | this.workerChoiceStrategyContext.setOptions( |
| 323 | this.opts.workerChoiceStrategyOptions |
| 324 | ) |
| 325 | } |
| 326 | |
| 327 | /** @inheritDoc */ |
| 328 | public enableTasksQueue ( |
| 329 | enable: boolean, |
| 330 | tasksQueueOptions?: TasksQueueOptions |
| 331 | ): void { |
| 332 | if (this.opts.enableTasksQueue === true && !enable) { |
| 333 | this.flushTasksQueues() |
| 334 | } |
| 335 | this.opts.enableTasksQueue = enable |
| 336 | this.setTasksQueueOptions(tasksQueueOptions as TasksQueueOptions) |
| 337 | } |
| 338 | |
| 339 | /** @inheritDoc */ |
| 340 | public setTasksQueueOptions (tasksQueueOptions: TasksQueueOptions): void { |
| 341 | if (this.opts.enableTasksQueue === true) { |
| 342 | this.checkValidTasksQueueOptions(tasksQueueOptions) |
| 343 | this.opts.tasksQueueOptions = |
| 344 | this.buildTasksQueueOptions(tasksQueueOptions) |
| 345 | } else if (this.opts.tasksQueueOptions != null) { |
| 346 | delete this.opts.tasksQueueOptions |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | private buildTasksQueueOptions ( |
| 351 | tasksQueueOptions: TasksQueueOptions |
| 352 | ): TasksQueueOptions { |
| 353 | return { |
| 354 | concurrency: tasksQueueOptions?.concurrency ?? 1 |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | /** |
| 359 | * Whether the pool is full or not. |
| 360 | * |
| 361 | * The pool filling boolean status. |
| 362 | */ |
| 363 | protected get full (): boolean { |
| 364 | return this.workerNodes.length >= this.maxSize |
| 365 | } |
| 366 | |
| 367 | /** |
| 368 | * Whether the pool is busy or not. |
| 369 | * |
| 370 | * The pool busyness boolean status. |
| 371 | */ |
| 372 | protected abstract get busy (): boolean |
| 373 | |
| 374 | protected internalBusy (): boolean { |
| 375 | return ( |
| 376 | this.workerNodes.findIndex(workerNode => { |
| 377 | return workerNode.tasksUsage.running === 0 |
| 378 | }) === -1 |
| 379 | ) |
| 380 | } |
| 381 | |
| 382 | /** @inheritDoc */ |
| 383 | public async execute (data?: Data, name?: string): Promise<Response> { |
| 384 | const timestamp = performance.now() |
| 385 | const workerNodeKey = this.chooseWorkerNode() |
| 386 | const submittedTask: Task<Data> = { |
| 387 | name, |
| 388 | // eslint-disable-next-line @typescript-eslint/consistent-type-assertions |
| 389 | data: data ?? ({} as Data), |
| 390 | timestamp, |
| 391 | id: crypto.randomUUID() |
| 392 | } |
| 393 | const res = new Promise<Response>((resolve, reject) => { |
| 394 | this.promiseResponseMap.set(submittedTask.id as string, { |
| 395 | resolve, |
| 396 | reject, |
| 397 | worker: this.workerNodes[workerNodeKey].worker |
| 398 | }) |
| 399 | }) |
| 400 | if ( |
| 401 | this.opts.enableTasksQueue === true && |
| 402 | (this.busy || |
| 403 | this.workerNodes[workerNodeKey].tasksUsage.running >= |
| 404 | ((this.opts.tasksQueueOptions as TasksQueueOptions) |
| 405 | .concurrency as number)) |
| 406 | ) { |
| 407 | this.enqueueTask(workerNodeKey, submittedTask) |
| 408 | } else { |
| 409 | this.executeTask(workerNodeKey, submittedTask) |
| 410 | } |
| 411 | this.workerChoiceStrategyContext.update(workerNodeKey) |
| 412 | this.checkAndEmitEvents() |
| 413 | // eslint-disable-next-line @typescript-eslint/return-await |
| 414 | return res |
| 415 | } |
| 416 | |
| 417 | /** @inheritDoc */ |
| 418 | public async destroy (): Promise<void> { |
| 419 | await Promise.all( |
| 420 | this.workerNodes.map(async (workerNode, workerNodeKey) => { |
| 421 | this.flushTasksQueue(workerNodeKey) |
| 422 | // FIXME: wait for tasks to be finished |
| 423 | await this.destroyWorker(workerNode.worker) |
| 424 | }) |
| 425 | ) |
| 426 | } |
| 427 | |
| 428 | /** |
| 429 | * Shutdowns the given worker. |
| 430 | * |
| 431 | * @param worker - A worker within `workerNodes`. |
| 432 | */ |
| 433 | protected abstract destroyWorker (worker: Worker): void | Promise<void> |
| 434 | |
| 435 | /** |
| 436 | * Setup hook to execute code before worker node are created in the abstract constructor. |
| 437 | * Can be overridden |
| 438 | * |
| 439 | * @virtual |
| 440 | */ |
| 441 | protected setupHook (): void { |
| 442 | // Intentionally empty |
| 443 | } |
| 444 | |
| 445 | /** |
| 446 | * Should return whether the worker is the main worker or not. |
| 447 | */ |
| 448 | protected abstract isMain (): boolean |
| 449 | |
| 450 | /** |
| 451 | * Hook executed before the worker task execution. |
| 452 | * Can be overridden. |
| 453 | * |
| 454 | * @param workerNodeKey - The worker node key. |
| 455 | */ |
| 456 | protected beforeTaskExecutionHook (workerNodeKey: number): void { |
| 457 | ++this.workerNodes[workerNodeKey].tasksUsage.running |
| 458 | } |
| 459 | |
| 460 | /** |
| 461 | * Hook executed after the worker task execution. |
| 462 | * Can be overridden. |
| 463 | * |
| 464 | * @param worker - The worker. |
| 465 | * @param message - The received message. |
| 466 | */ |
| 467 | protected afterTaskExecutionHook ( |
| 468 | worker: Worker, |
| 469 | message: MessageValue<Response> |
| 470 | ): void { |
| 471 | const workerTasksUsage = |
| 472 | this.workerNodes[this.getWorkerNodeKey(worker)].tasksUsage |
| 473 | --workerTasksUsage.running |
| 474 | ++workerTasksUsage.ran |
| 475 | if (message.error != null) { |
| 476 | ++workerTasksUsage.error |
| 477 | } |
| 478 | this.updateRunTimeTasksUsage(workerTasksUsage, message) |
| 479 | this.updateWaitTimeTasksUsage(workerTasksUsage, message) |
| 480 | this.updateEluTasksUsage(workerTasksUsage, message) |
| 481 | } |
| 482 | |
| 483 | private updateRunTimeTasksUsage ( |
| 484 | workerTasksUsage: TasksUsage, |
| 485 | message: MessageValue<Response> |
| 486 | ): void { |
| 487 | if (this.workerChoiceStrategyContext.getTaskStatistics().runTime) { |
| 488 | workerTasksUsage.runTime += message.runTime ?? 0 |
| 489 | if ( |
| 490 | this.workerChoiceStrategyContext.getTaskStatistics().avgRunTime && |
| 491 | workerTasksUsage.ran !== 0 |
| 492 | ) { |
| 493 | workerTasksUsage.avgRunTime = |
| 494 | workerTasksUsage.runTime / workerTasksUsage.ran |
| 495 | } |
| 496 | if ( |
| 497 | this.workerChoiceStrategyContext.getTaskStatistics().medRunTime && |
| 498 | message.runTime != null |
| 499 | ) { |
| 500 | workerTasksUsage.runTimeHistory.push(message.runTime) |
| 501 | workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory) |
| 502 | } |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | private updateWaitTimeTasksUsage ( |
| 507 | workerTasksUsage: TasksUsage, |
| 508 | message: MessageValue<Response> |
| 509 | ): void { |
| 510 | if (this.workerChoiceStrategyContext.getTaskStatistics().waitTime) { |
| 511 | workerTasksUsage.waitTime += message.waitTime ?? 0 |
| 512 | if ( |
| 513 | this.workerChoiceStrategyContext.getTaskStatistics().avgWaitTime && |
| 514 | workerTasksUsage.ran !== 0 |
| 515 | ) { |
| 516 | workerTasksUsage.avgWaitTime = |
| 517 | workerTasksUsage.waitTime / workerTasksUsage.ran |
| 518 | } |
| 519 | if ( |
| 520 | this.workerChoiceStrategyContext.getTaskStatistics().medWaitTime && |
| 521 | message.waitTime != null |
| 522 | ) { |
| 523 | workerTasksUsage.waitTimeHistory.push(message.waitTime) |
| 524 | workerTasksUsage.medWaitTime = median(workerTasksUsage.waitTimeHistory) |
| 525 | } |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | private updateEluTasksUsage ( |
| 530 | workerTasksUsage: TasksUsage, |
| 531 | message: MessageValue<Response> |
| 532 | ): void { |
| 533 | if (this.workerChoiceStrategyContext.getTaskStatistics().elu) { |
| 534 | if (workerTasksUsage.elu != null && message.elu != null) { |
| 535 | workerTasksUsage.elu = { |
| 536 | idle: workerTasksUsage.elu.idle + message.elu.idle, |
| 537 | active: workerTasksUsage.elu.active + message.elu.active, |
| 538 | utilization: |
| 539 | workerTasksUsage.elu.utilization + message.elu.utilization |
| 540 | } |
| 541 | } else if (message.elu != null) { |
| 542 | workerTasksUsage.elu = message.elu |
| 543 | } |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | /** |
| 548 | * Chooses a worker node for the next task. |
| 549 | * |
| 550 | * The default worker choice strategy uses a round robin algorithm to distribute the load. |
| 551 | * |
| 552 | * @returns The worker node key |
| 553 | */ |
| 554 | protected chooseWorkerNode (): number { |
| 555 | let workerNodeKey: number |
| 556 | if (this.type === PoolTypes.dynamic && !this.full && this.internalBusy()) { |
| 557 | const workerCreated = this.createAndSetupWorker() |
| 558 | this.registerWorkerMessageListener(workerCreated, message => { |
| 559 | const currentWorkerNodeKey = this.getWorkerNodeKey(workerCreated) |
| 560 | if ( |
| 561 | isKillBehavior(KillBehaviors.HARD, message.kill) || |
| 562 | (message.kill != null && |
| 563 | this.workerNodes[currentWorkerNodeKey].tasksUsage.running === 0) |
| 564 | ) { |
| 565 | // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime) |
| 566 | this.flushTasksQueue(currentWorkerNodeKey) |
| 567 | // FIXME: wait for tasks to be finished |
| 568 | void (this.destroyWorker(workerCreated) as Promise<void>) |
| 569 | } |
| 570 | }) |
| 571 | workerNodeKey = this.getWorkerNodeKey(workerCreated) |
| 572 | } else { |
| 573 | workerNodeKey = this.workerChoiceStrategyContext.execute() |
| 574 | } |
| 575 | return workerNodeKey |
| 576 | } |
| 577 | |
| 578 | /** |
| 579 | * Sends a message to the given worker. |
| 580 | * |
| 581 | * @param worker - The worker which should receive the message. |
| 582 | * @param message - The message. |
| 583 | */ |
| 584 | protected abstract sendToWorker ( |
| 585 | worker: Worker, |
| 586 | message: MessageValue<Data> |
| 587 | ): void |
| 588 | |
| 589 | /** |
| 590 | * Registers a listener callback on the given worker. |
| 591 | * |
| 592 | * @param worker - The worker which should register a listener. |
| 593 | * @param listener - The message listener callback. |
| 594 | */ |
| 595 | protected abstract registerWorkerMessageListener< |
| 596 | Message extends Data | Response |
| 597 | >(worker: Worker, listener: (message: MessageValue<Message>) => void): void |
| 598 | |
| 599 | /** |
| 600 | * Returns a newly created worker. |
| 601 | */ |
| 602 | protected abstract createWorker (): Worker |
| 603 | |
| 604 | /** |
| 605 | * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes. |
| 606 | * |
| 607 | * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default. |
| 608 | * |
| 609 | * @param worker - The newly created worker. |
| 610 | */ |
| 611 | protected abstract afterWorkerSetup (worker: Worker): void |
| 612 | |
| 613 | /** |
| 614 | * Creates a new worker and sets it up completely in the pool worker nodes. |
| 615 | * |
| 616 | * @returns New, completely set up worker. |
| 617 | */ |
| 618 | protected createAndSetupWorker (): Worker { |
| 619 | const worker = this.createWorker() |
| 620 | |
| 621 | worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION) |
| 622 | worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION) |
| 623 | worker.on('error', error => { |
| 624 | if (this.emitter != null) { |
| 625 | this.emitter.emit(PoolEvents.error, error) |
| 626 | } |
| 627 | }) |
| 628 | worker.on('error', () => { |
| 629 | if (this.opts.restartWorkerOnError === true) { |
| 630 | this.createAndSetupWorker() |
| 631 | } |
| 632 | }) |
| 633 | worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION) |
| 634 | worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION) |
| 635 | worker.once('exit', () => { |
| 636 | this.removeWorkerNode(worker) |
| 637 | }) |
| 638 | |
| 639 | this.pushWorkerNode(worker) |
| 640 | |
| 641 | this.setWorkerStatistics(worker) |
| 642 | |
| 643 | this.afterWorkerSetup(worker) |
| 644 | |
| 645 | return worker |
| 646 | } |
| 647 | |
| 648 | /** |
| 649 | * This function is the listener registered for each worker message. |
| 650 | * |
| 651 | * @returns The listener function to execute when a message is received from a worker. |
| 652 | */ |
| 653 | protected workerListener (): (message: MessageValue<Response>) => void { |
| 654 | return message => { |
| 655 | if (message.id != null) { |
| 656 | // Task execution response received |
| 657 | const promiseResponse = this.promiseResponseMap.get(message.id) |
| 658 | if (promiseResponse != null) { |
| 659 | if (message.error != null) { |
| 660 | promiseResponse.reject(message.error) |
| 661 | if (this.emitter != null) { |
| 662 | this.emitter.emit(PoolEvents.taskError, { |
| 663 | error: message.error, |
| 664 | errorData: message.errorData |
| 665 | }) |
| 666 | } |
| 667 | } else { |
| 668 | promiseResponse.resolve(message.data as Response) |
| 669 | } |
| 670 | this.afterTaskExecutionHook(promiseResponse.worker, message) |
| 671 | this.promiseResponseMap.delete(message.id) |
| 672 | const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker) |
| 673 | if ( |
| 674 | this.opts.enableTasksQueue === true && |
| 675 | this.tasksQueueSize(workerNodeKey) > 0 |
| 676 | ) { |
| 677 | this.executeTask( |
| 678 | workerNodeKey, |
| 679 | this.dequeueTask(workerNodeKey) as Task<Data> |
| 680 | ) |
| 681 | } |
| 682 | } |
| 683 | } |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | private checkAndEmitEvents (): void { |
| 688 | if (this.emitter != null) { |
| 689 | if (this.busy) { |
| 690 | this.emitter?.emit(PoolEvents.busy, this.info) |
| 691 | } |
| 692 | if (this.type === PoolTypes.dynamic && this.full) { |
| 693 | this.emitter?.emit(PoolEvents.full, this.info) |
| 694 | } |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | /** |
| 699 | * Sets the given worker node its tasks usage in the pool. |
| 700 | * |
| 701 | * @param workerNode - The worker node. |
| 702 | * @param tasksUsage - The worker node tasks usage. |
| 703 | */ |
| 704 | private setWorkerNodeTasksUsage ( |
| 705 | workerNode: WorkerNode<Worker, Data>, |
| 706 | tasksUsage: TasksUsage |
| 707 | ): void { |
| 708 | workerNode.tasksUsage = tasksUsage |
| 709 | } |
| 710 | |
| 711 | /** |
| 712 | * Pushes the given worker in the pool worker nodes. |
| 713 | * |
| 714 | * @param worker - The worker. |
| 715 | * @returns The worker nodes length. |
| 716 | */ |
| 717 | private pushWorkerNode (worker: Worker): number { |
| 718 | return this.workerNodes.push({ |
| 719 | worker, |
| 720 | tasksUsage: { |
| 721 | ran: 0, |
| 722 | running: 0, |
| 723 | runTime: 0, |
| 724 | runTimeHistory: new CircularArray(), |
| 725 | avgRunTime: 0, |
| 726 | medRunTime: 0, |
| 727 | waitTime: 0, |
| 728 | waitTimeHistory: new CircularArray(), |
| 729 | avgWaitTime: 0, |
| 730 | medWaitTime: 0, |
| 731 | error: 0, |
| 732 | elu: undefined |
| 733 | }, |
| 734 | tasksQueue: new Queue<Task<Data>>() |
| 735 | }) |
| 736 | } |
| 737 | |
| 738 | /** |
| 739 | * Sets the given worker in the pool worker nodes. |
| 740 | * |
| 741 | * @param workerNodeKey - The worker node key. |
| 742 | * @param worker - The worker. |
| 743 | * @param tasksUsage - The worker tasks usage. |
| 744 | * @param tasksQueue - The worker task queue. |
| 745 | */ |
| 746 | private setWorkerNode ( |
| 747 | workerNodeKey: number, |
| 748 | worker: Worker, |
| 749 | tasksUsage: TasksUsage, |
| 750 | tasksQueue: Queue<Task<Data>> |
| 751 | ): void { |
| 752 | this.workerNodes[workerNodeKey] = { |
| 753 | worker, |
| 754 | tasksUsage, |
| 755 | tasksQueue |
| 756 | } |
| 757 | } |
| 758 | |
| 759 | /** |
| 760 | * Removes the given worker from the pool worker nodes. |
| 761 | * |
| 762 | * @param worker - The worker. |
| 763 | */ |
| 764 | private removeWorkerNode (worker: Worker): void { |
| 765 | const workerNodeKey = this.getWorkerNodeKey(worker) |
| 766 | if (workerNodeKey !== -1) { |
| 767 | this.workerNodes.splice(workerNodeKey, 1) |
| 768 | this.workerChoiceStrategyContext.remove(workerNodeKey) |
| 769 | } |
| 770 | } |
| 771 | |
| 772 | private executeTask (workerNodeKey: number, task: Task<Data>): void { |
| 773 | this.beforeTaskExecutionHook(workerNodeKey) |
| 774 | this.sendToWorker(this.workerNodes[workerNodeKey].worker, task) |
| 775 | } |
| 776 | |
| 777 | private enqueueTask (workerNodeKey: number, task: Task<Data>): number { |
| 778 | return this.workerNodes[workerNodeKey].tasksQueue.enqueue(task) |
| 779 | } |
| 780 | |
| 781 | private dequeueTask (workerNodeKey: number): Task<Data> | undefined { |
| 782 | return this.workerNodes[workerNodeKey].tasksQueue.dequeue() |
| 783 | } |
| 784 | |
| 785 | private tasksQueueSize (workerNodeKey: number): number { |
| 786 | return this.workerNodes[workerNodeKey].tasksQueue.size |
| 787 | } |
| 788 | |
| 789 | private flushTasksQueue (workerNodeKey: number): void { |
| 790 | if (this.tasksQueueSize(workerNodeKey) > 0) { |
| 791 | for (let i = 0; i < this.tasksQueueSize(workerNodeKey); i++) { |
| 792 | this.executeTask( |
| 793 | workerNodeKey, |
| 794 | this.dequeueTask(workerNodeKey) as Task<Data> |
| 795 | ) |
| 796 | } |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | private flushTasksQueues (): void { |
| 801 | for (const [workerNodeKey] of this.workerNodes.entries()) { |
| 802 | this.flushTasksQueue(workerNodeKey) |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | private setWorkerStatistics (worker: Worker): void { |
| 807 | this.sendToWorker(worker, { |
| 808 | statistics: { |
| 809 | runTime: this.workerChoiceStrategyContext.getTaskStatistics().runTime, |
| 810 | waitTime: this.workerChoiceStrategyContext.getTaskStatistics().waitTime, |
| 811 | elu: this.workerChoiceStrategyContext.getTaskStatistics().elu |
| 812 | } |
| 813 | }) |
| 814 | } |
| 815 | } |