X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fpools%2Fabstract-pool.ts;h=e941fabb772690f0797c204226430f113ea97d43;hb=87de9ff55a7ad494b9e9500208b9b7319c094ea6;hp=58fc28ce12d6a56416b6db05cec3e5186c549a14;hpb=6b27d40762317ec8502657663bdc839e358cda03;p=poolifier.git diff --git a/src/pools/abstract-pool.ts b/src/pools/abstract-pool.ts index 58fc28ce..e941fabb 100644 --- a/src/pools/abstract-pool.ts +++ b/src/pools/abstract-pool.ts @@ -1,4 +1,5 @@ import crypto from 'node:crypto' +import { performance } from 'node:perf_hooks' import type { MessageValue, PromiseResponseWrapper } from '../utility-types' import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS, @@ -17,9 +18,10 @@ import { type PoolOptions, type PoolType, PoolTypes, - type TasksQueueOptions + type TasksQueueOptions, + type WorkerType } from './pool' -import type { IWorker, Task, TasksUsage, WorkerNode } from './worker' +import type { IWorker, Task, WorkerNode, WorkerUsage } from './worker' import { WorkerChoiceStrategies, type WorkerChoiceStrategy, @@ -77,9 +79,9 @@ export abstract class AbstractPool< * @param opts - Options for the pool. */ public constructor ( - public readonly numberOfWorkers: number, - public readonly filePath: string, - public readonly opts: PoolOptions + protected readonly numberOfWorkers: number, + protected readonly filePath: string, + protected readonly opts: PoolOptions ) { if (!this.isMain()) { throw new Error('Cannot start a pool from a worker!') @@ -93,12 +95,6 @@ export abstract class AbstractPool< this.enqueueTask = this.enqueueTask.bind(this) this.checkAndEmitEvents = this.checkAndEmitEvents.bind(this) - this.setupHook() - - for (let i = 1; i <= this.numberOfWorkers; i++) { - this.createAndSetupWorker() - } - if (this.opts.enableEvents === true) { this.emitter = new PoolEmitter() } @@ -111,6 +107,12 @@ export abstract class AbstractPool< this.opts.workerChoiceStrategy, this.opts.workerChoiceStrategyOptions ) + + this.setupHook() + + for (let i = 1; i <= this.numberOfWorkers; i++) { + this.createAndSetupWorker() + } } private checkFilePath (filePath: string): void { @@ -210,29 +212,36 @@ export abstract class AbstractPool< } } - /** @inheritDoc */ - public abstract get type (): PoolType - /** @inheritDoc */ public get info (): PoolInfo { return { type: this.type, + worker: this.worker, minSize: this.minSize, maxSize: this.maxSize, workerNodes: this.workerNodes.length, idleWorkerNodes: this.workerNodes.reduce( (accumulator, workerNode) => - workerNode.tasksUsage.running === 0 ? accumulator + 1 : accumulator, + workerNode.workerUsage.tasks.executing === 0 + ? accumulator + 1 + : accumulator, 0 ), busyWorkerNodes: this.workerNodes.reduce( (accumulator, workerNode) => - workerNode.tasksUsage.running > 0 ? accumulator + 1 : accumulator, + workerNode.workerUsage.tasks.executing > 0 + ? accumulator + 1 + : accumulator, 0 ), - runningTasks: this.workerNodes.reduce( + executedTasks: this.workerNodes.reduce( (accumulator, workerNode) => - accumulator + workerNode.tasksUsage.running, + accumulator + workerNode.workerUsage.tasks.executed, + 0 + ), + executingTasks: this.workerNodes.reduce( + (accumulator, workerNode) => + accumulator + workerNode.workerUsage.tasks.executing, 0 ), queuedTasks: this.workerNodes.reduce( @@ -243,10 +252,27 @@ export abstract class AbstractPool< (accumulator, workerNode) => accumulator + workerNode.tasksQueue.maxSize, 0 + ), + failedTasks: this.workerNodes.reduce( + (accumulator, workerNode) => + accumulator + workerNode.workerUsage.tasks.failed, + 0 ) } } + /** + * Pool type. + * + * If it is `'dynamic'`, it provides the `max` property. + */ + protected abstract get type (): PoolType + + /** + * Gets the worker type. + */ + protected abstract get worker (): WorkerType + /** * Pool minimum size. */ @@ -276,27 +302,39 @@ export abstract class AbstractPool< ): void { this.checkValidWorkerChoiceStrategy(workerChoiceStrategy) this.opts.workerChoiceStrategy = workerChoiceStrategy - for (const workerNode of this.workerNodes) { - this.setWorkerNodeTasksUsage(workerNode, { - run: 0, - running: 0, - runTime: 0, - runTimeHistory: new CircularArray(), - avgRunTime: 0, - medRunTime: 0, - waitTime: 0, - waitTimeHistory: new CircularArray(), - avgWaitTime: 0, - medWaitTime: 0, - error: 0 - }) - } this.workerChoiceStrategyContext.setWorkerChoiceStrategy( this.opts.workerChoiceStrategy ) if (workerChoiceStrategyOptions != null) { this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions) } + for (const workerNode of this.workerNodes) { + this.setWorkerNodeTasksUsage(workerNode, { + tasks: { + executed: 0, + executing: 0, + queued: + this.opts.enableTasksQueue === true + ? workerNode.tasksQueue.size + : 0, + failed: 0 + }, + runTime: { + aggregation: 0, + average: 0, + median: 0, + history: new CircularArray() + }, + waitTime: { + aggregation: 0, + average: 0, + median: 0, + history: new CircularArray() + }, + elu: undefined + }) + this.setWorkerStatistics(workerNode.worker) + } } /** @inheritDoc */ @@ -328,7 +366,7 @@ export abstract class AbstractPool< this.checkValidTasksQueueOptions(tasksQueueOptions) this.opts.tasksQueueOptions = this.buildTasksQueueOptions(tasksQueueOptions) - } else { + } else if (this.opts.tasksQueueOptions != null) { delete this.opts.tasksQueueOptions } } @@ -346,7 +384,9 @@ export abstract class AbstractPool< * * The pool filling boolean status. */ - protected abstract get full (): boolean + protected get full (): boolean { + return this.workerNodes.length >= this.maxSize + } /** * Whether the pool is busy or not. @@ -358,20 +398,20 @@ export abstract class AbstractPool< protected internalBusy (): boolean { return ( this.workerNodes.findIndex(workerNode => { - return workerNode.tasksUsage.running === 0 + return workerNode.workerUsage.tasks.executing === 0 }) === -1 ) } /** @inheritDoc */ public async execute (data?: Data, name?: string): Promise { - const submissionTimestamp = performance.now() + const timestamp = performance.now() const workerNodeKey = this.chooseWorkerNode() const submittedTask: Task = { name, // eslint-disable-next-line @typescript-eslint/consistent-type-assertions data: data ?? ({} as Data), - submissionTimestamp, + timestamp, id: crypto.randomUUID() } const res = new Promise((resolve, reject) => { @@ -384,7 +424,7 @@ export abstract class AbstractPool< if ( this.opts.enableTasksQueue === true && (this.busy || - this.workerNodes[workerNodeKey].tasksUsage.running >= + this.workerNodes[workerNodeKey].workerUsage.tasks.executing >= ((this.opts.tasksQueueOptions as TasksQueueOptions) .concurrency as number)) ) { @@ -403,6 +443,7 @@ export abstract class AbstractPool< await Promise.all( this.workerNodes.map(async (workerNode, workerNodeKey) => { this.flushTasksQueue(workerNodeKey) + // FIXME: wait for tasks to be finished await this.destroyWorker(workerNode.worker) }) ) @@ -437,7 +478,11 @@ export abstract class AbstractPool< * @param workerNodeKey - The worker node key. */ protected beforeTaskExecutionHook (workerNodeKey: number): void { - ++this.workerNodes[workerNodeKey].tasksUsage.running + ++this.workerNodes[workerNodeKey].workerUsage.tasks.executing + if (this.opts.enableTasksQueue === true) { + this.workerNodes[workerNodeKey].workerUsage.tasks.queued = + this.tasksQueueSize(workerNodeKey) + } } /** @@ -451,59 +496,94 @@ export abstract class AbstractPool< worker: Worker, message: MessageValue ): void { - const workerTasksUsage = - this.workerNodes[this.getWorkerNodeKey(worker)].tasksUsage - --workerTasksUsage.running - ++workerTasksUsage.run - if (message.error != null) { - ++workerTasksUsage.error + const workerUsage = + this.workerNodes[this.getWorkerNodeKey(worker)].workerUsage + const workerTaskStatistics = workerUsage.tasks + --workerTaskStatistics.executing + ++workerTaskStatistics.executed + if (message.taskError != null) { + ++workerTaskStatistics.failed } - this.updateRunTimeTasksUsage(workerTasksUsage, message) - this.updateWaitTimeTasksUsage(workerTasksUsage, message) + + this.updateRunTimeWorkerUsage(workerUsage, message) + this.updateWaitTimeWorkerUsage(workerUsage, message) + this.updateEluWorkerUsage(workerUsage, message) } - private updateRunTimeTasksUsage ( - workerTasksUsage: TasksUsage, + private updateRunTimeWorkerUsage ( + workerUsage: WorkerUsage, message: MessageValue ): void { - if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) { - workerTasksUsage.runTime += message.runTime ?? 0 + if ( + this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime + ) { + workerUsage.runTime.aggregation += message.taskPerformance?.runTime ?? 0 if ( - this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime && - workerTasksUsage.run !== 0 + this.workerChoiceStrategyContext.getTaskStatisticsRequirements() + .avgRunTime && + workerUsage.tasks.executed !== 0 ) { - workerTasksUsage.avgRunTime = - workerTasksUsage.runTime / workerTasksUsage.run + workerUsage.runTime.average = + workerUsage.runTime.aggregation / workerUsage.tasks.executed } if ( - this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime && - message.runTime != null + this.workerChoiceStrategyContext.getTaskStatisticsRequirements() + .medRunTime && + message.taskPerformance?.runTime != null ) { - workerTasksUsage.runTimeHistory.push(message.runTime) - workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory) + workerUsage.runTime.history.push(message.taskPerformance.runTime) + workerUsage.runTime.median = median(workerUsage.runTime.history) } } } - private updateWaitTimeTasksUsage ( - workerTasksUsage: TasksUsage, + private updateWaitTimeWorkerUsage ( + workerUsage: WorkerUsage, message: MessageValue ): void { - if (this.workerChoiceStrategyContext.getRequiredStatistics().waitTime) { - workerTasksUsage.waitTime += message.waitTime ?? 0 + if ( + this.workerChoiceStrategyContext.getTaskStatisticsRequirements().waitTime + ) { + workerUsage.waitTime.aggregation += message.taskPerformance?.waitTime ?? 0 if ( - this.workerChoiceStrategyContext.getRequiredStatistics().avgWaitTime && - workerTasksUsage.run !== 0 + this.workerChoiceStrategyContext.getTaskStatisticsRequirements() + .avgWaitTime && + workerUsage.tasks.executed !== 0 ) { - workerTasksUsage.avgWaitTime = - workerTasksUsage.waitTime / workerTasksUsage.run + workerUsage.waitTime.average = + workerUsage.waitTime.aggregation / workerUsage.tasks.executed } if ( - this.workerChoiceStrategyContext.getRequiredStatistics().medWaitTime && - message.waitTime != null + this.workerChoiceStrategyContext.getTaskStatisticsRequirements() + .medWaitTime && + message.taskPerformance?.waitTime != null ) { - workerTasksUsage.waitTimeHistory.push(message.waitTime) - workerTasksUsage.medWaitTime = median(workerTasksUsage.waitTimeHistory) + workerUsage.waitTime.history.push(message.taskPerformance.waitTime) + workerUsage.waitTime.median = median(workerUsage.waitTime.history) + } + } + } + + private updateEluWorkerUsage ( + workerTasksUsage: WorkerUsage, + message: MessageValue + ): void { + if (this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu) { + if ( + workerTasksUsage.elu != null && + message.taskPerformance?.elu != null + ) { + workerTasksUsage.elu = { + idle: workerTasksUsage.elu.idle + message.taskPerformance.elu.idle, + active: + workerTasksUsage.elu.active + message.taskPerformance.elu.active, + utilization: + (workerTasksUsage.elu.utilization + + message.taskPerformance.elu.utilization) / + 2 + } + } else if (message.taskPerformance?.elu != null) { + workerTasksUsage.elu = message.taskPerformance.elu } } } @@ -524,10 +604,12 @@ export abstract class AbstractPool< if ( isKillBehavior(KillBehaviors.HARD, message.kill) || (message.kill != null && - this.workerNodes[currentWorkerNodeKey].tasksUsage.running === 0) + this.workerNodes[currentWorkerNodeKey].workerUsage.tasks + .executing === 0) ) { // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime) this.flushTasksQueue(currentWorkerNodeKey) + // FIXME: wait for tasks to be finished void (this.destroyWorker(workerCreated) as Promise) } }) @@ -588,11 +670,11 @@ export abstract class AbstractPool< this.emitter.emit(PoolEvents.error, error) } }) - if (this.opts.restartWorkerOnError === true) { - worker.on('error', () => { + worker.on('error', () => { + if (this.opts.restartWorkerOnError === true) { this.createAndSetupWorker() - }) - } + } + }) worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION) worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION) worker.once('exit', () => { @@ -601,6 +683,8 @@ export abstract class AbstractPool< this.pushWorkerNode(worker) + this.setWorkerStatistics(worker) + this.afterWorkerSetup(worker) return worker @@ -617,13 +701,10 @@ export abstract class AbstractPool< // Task execution response received const promiseResponse = this.promiseResponseMap.get(message.id) if (promiseResponse != null) { - if (message.error != null) { - promiseResponse.reject(message.error) + if (message.taskError != null) { + promiseResponse.reject(message.taskError.message) if (this.emitter != null) { - this.emitter.emit(PoolEvents.taskError, { - error: message.error, - errorData: message.errorData - }) + this.emitter.emit(PoolEvents.taskError, message.taskError) } } else { promiseResponse.resolve(message.data as Response) @@ -660,13 +741,13 @@ export abstract class AbstractPool< * Sets the given worker node its tasks usage in the pool. * * @param workerNode - The worker node. - * @param tasksUsage - The worker node tasks usage. + * @param workerUsage - The worker usage. */ private setWorkerNodeTasksUsage ( workerNode: WorkerNode, - tasksUsage: TasksUsage + workerUsage: WorkerUsage ): void { - workerNode.tasksUsage = tasksUsage + workerNode.workerUsage = workerUsage } /** @@ -678,18 +759,27 @@ export abstract class AbstractPool< private pushWorkerNode (worker: Worker): number { return this.workerNodes.push({ worker, - tasksUsage: { - run: 0, - running: 0, - runTime: 0, - runTimeHistory: new CircularArray(), - avgRunTime: 0, - medRunTime: 0, - waitTime: 0, - waitTimeHistory: new CircularArray(), - avgWaitTime: 0, - medWaitTime: 0, - error: 0 + workerUsage: { + tasks: { + executed: 0, + executing: 0, + queued: 0, + failed: 0 + }, + runTime: { + aggregation: 0, + average: 0, + median: 0, + history: new CircularArray() + }, + + waitTime: { + aggregation: 0, + average: 0, + median: 0, + history: new CircularArray() + }, + elu: undefined }, tasksQueue: new Queue>() }) @@ -700,18 +790,18 @@ export abstract class AbstractPool< * * @param workerNodeKey - The worker node key. * @param worker - The worker. - * @param tasksUsage - The worker tasks usage. + * @param workerUsage - The worker usage. * @param tasksQueue - The worker task queue. */ private setWorkerNode ( workerNodeKey: number, worker: Worker, - tasksUsage: TasksUsage, + workerUsage: WorkerUsage, tasksQueue: Queue> ): void { this.workerNodes[workerNodeKey] = { worker, - tasksUsage, + workerUsage, tasksQueue } } @@ -762,4 +852,19 @@ export abstract class AbstractPool< this.flushTasksQueue(workerNodeKey) } } + + private setWorkerStatistics (worker: Worker): void { + this.sendToWorker(worker, { + statistics: { + runTime: + this.workerChoiceStrategyContext.getTaskStatisticsRequirements() + .runTime, + waitTime: + this.workerChoiceStrategyContext.getTaskStatisticsRequirements() + .waitTime, + elu: this.workerChoiceStrategyContext.getTaskStatisticsRequirements() + .elu + } + }) + } }