X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fpools%2Fabstract-pool.ts;h=b95d16b4b80259b5cb89d0e3c7717d31767e4d4c;hb=c319c66bad0611acf6087950a1f8a20f8124167b;hp=363db0e3f9b64ff650a0c351de05135c8de1de96;hpb=fc3e65861bc1939ae047ee1e8e91a1ce577035f4;p=poolifier.git diff --git a/src/pools/abstract-pool.ts b/src/pools/abstract-pool.ts index 363db0e3..b95d16b4 100644 --- a/src/pools/abstract-pool.ts +++ b/src/pools/abstract-pool.ts @@ -1,20 +1,26 @@ import crypto from 'node:crypto' -import type { - MessageValue, - PromiseWorkerResponseWrapper -} from '../utility-types' -import { EMPTY_FUNCTION } from '../utils' +import type { MessageValue, PromiseResponseWrapper } from '../utility-types' +import { + DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS, + EMPTY_FUNCTION, + median +} from '../utils' import { KillBehaviors, isKillBehavior } from '../worker/worker-options' -import type { PoolOptions } from './pool' +import { + PoolEvents, + type IPool, + type PoolOptions, + type TasksQueueOptions, + PoolType +} from './pool' import { PoolEmitter } from './pool' -import type { IPoolInternal, TasksUsage, WorkerType } from './pool-internal' -import { PoolType } from './pool-internal' -import type { IPoolWorker } from './pool-worker' +import type { IWorker, Task, TasksUsage, WorkerNode } from './worker' import { WorkerChoiceStrategies, type WorkerChoiceStrategy } from './selection-strategies/selection-strategies-types' import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context' +import { CircularArray } from '../circular-array' /** * Base class that implements some shared logic for all poolifier pools. @@ -24,41 +30,33 @@ import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choic * @typeParam Response - Type of response of execution. This can only be serializable data. */ export abstract class AbstractPool< - Worker extends IPoolWorker, + Worker extends IWorker, Data = unknown, Response = unknown -> implements IPoolInternal { - /** {@inheritDoc} */ - public readonly workers: Map> = new Map< - number, - WorkerType - >() - - /** {@inheritDoc} */ - public readonly emitter?: PoolEmitter +> implements IPool { + /** @inheritDoc */ + public readonly workerNodes: Array> = [] - /** - * Id of the next worker. - */ - protected nextWorkerId: number = 0 + /** @inheritDoc */ + public readonly emitter?: PoolEmitter /** - * The promise map. + * The execution response promise map. * - * - `key`: This is the message id of each submitted task. - * - `value`: An object that contains the worker, the resolve function and the reject function. + * - `key`: The message id of each submitted task. + * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks. * - * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message. + * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id. */ - protected promiseMap: Map< + protected promiseResponseMap: Map< string, - PromiseWorkerResponseWrapper - > = new Map>() + PromiseResponseWrapper + > = new Map>() /** - * Worker choice strategy instance implementing the worker choice algorithm. + * Worker choice strategy context referencing a worker choice algorithm implementation. * - * Default to a strategy implementing a round robin algorithm. + * Default to a round robin algorithm. */ protected workerChoiceStrategyContext: WorkerChoiceStrategyContext< Worker, @@ -84,6 +82,12 @@ export abstract class AbstractPool< this.checkNumberOfWorkers(this.numberOfWorkers) this.checkFilePath(this.filePath) this.checkPoolOptions(this.opts) + + this.chooseWorkerNode.bind(this) + this.executeTask.bind(this) + this.enqueueTask.bind(this) + this.checkAndEmitEvents.bind(this) + this.setupHook() for (let i = 1; i <= this.numberOfWorkers; i++) { @@ -93,22 +97,14 @@ export abstract class AbstractPool< if (this.opts.enableEvents === true) { this.emitter = new PoolEmitter() } - this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext( + this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext< + Worker, + Data, + Response + >( this, - () => { - const workerCreated = this.createAndSetupWorker() - this.registerWorkerMessageListener(workerCreated, message => { - if ( - isKillBehavior(KillBehaviors.HARD, message.kill) || - this.getWorkerRunningTasks(workerCreated) === 0 - ) { - // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime) - void this.destroyWorker(workerCreated) - } - }) - return workerCreated - }, - this.opts.workerChoiceStrategy + this.opts.workerChoiceStrategy, + this.opts.workerChoiceStrategyOptions ) } @@ -142,50 +138,88 @@ export abstract class AbstractPool< private checkPoolOptions (opts: PoolOptions): void { this.opts.workerChoiceStrategy = opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN + this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy) + this.opts.workerChoiceStrategyOptions = + opts.workerChoiceStrategyOptions ?? DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS this.opts.enableEvents = opts.enableEvents ?? true + this.opts.enableTasksQueue = opts.enableTasksQueue ?? false + if (this.opts.enableTasksQueue) { + if ((opts.tasksQueueOptions?.concurrency as number) <= 0) { + throw new Error( + `Invalid worker tasks concurrency '${ + (opts.tasksQueueOptions as TasksQueueOptions).concurrency as number + }'` + ) + } + this.opts.tasksQueueOptions = { + concurrency: opts.tasksQueueOptions?.concurrency ?? 1 + } + } } - /** {@inheritDoc} */ - public abstract get type (): PoolType - - /** {@inheritDoc} */ - public get numberOfRunningTasks (): number { - return this.promiseMap.size + private checkValidWorkerChoiceStrategy ( + workerChoiceStrategy: WorkerChoiceStrategy + ): void { + if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) { + throw new Error( + `Invalid worker choice strategy '${workerChoiceStrategy}'` + ) + } } + /** @inheritDoc */ + public abstract get type (): PoolType + /** - * Gets the given worker key. - * - * @param worker - The worker. - * @returns The worker key. + * Number of tasks running in the pool. */ - private getWorkerKey (worker: Worker): number | undefined { - return [...this.workers].find(([, value]) => value.worker === worker)?.[0] + private get numberOfRunningTasks (): number { + return this.workerNodes.reduce( + (accumulator, workerNode) => accumulator + workerNode.tasksUsage.running, + 0 + ) } - /** {@inheritDoc} */ - public getWorkerRunningTasks (worker: Worker): number | undefined { - return this.workers.get(this.getWorkerKey(worker) as number)?.tasksUsage - ?.running + /** + * Number of tasks queued in the pool. + */ + private get numberOfQueuedTasks (): number { + if (this.opts.enableTasksQueue === false) { + return 0 + } + return this.workerNodes.reduce( + (accumulator, workerNode) => accumulator + workerNode.tasksQueue.length, + 0 + ) } - /** {@inheritDoc} */ - public getWorkerAverageTasksRunTime (worker: Worker): number | undefined { - return this.workers.get(this.getWorkerKey(worker) as number)?.tasksUsage - ?.avgRunTime + /** + * Gets the given worker its worker node key. + * + * @param worker - The worker. + * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise. + */ + private getWorkerNodeKey (worker: Worker): number { + return this.workerNodes.findIndex( + workerNode => workerNode.worker === worker + ) } - /** {@inheritDoc} */ + /** @inheritDoc */ public setWorkerChoiceStrategy ( workerChoiceStrategy: WorkerChoiceStrategy ): void { + this.checkValidWorkerChoiceStrategy(workerChoiceStrategy) this.opts.workerChoiceStrategy = workerChoiceStrategy - for (const [key, value] of this.workers) { - this.setWorker(key, value.worker, { + for (const workerNode of this.workerNodes) { + this.setWorkerNodeTasksUsage(workerNode, { run: 0, running: 0, runTime: 0, - avgRunTime: 0 + runTimeHistory: new CircularArray(), + avgRunTime: 0, + medRunTime: 0, + error: 0 }) } this.workerChoiceStrategyContext.setWorkerChoiceStrategy( @@ -193,64 +227,87 @@ export abstract class AbstractPool< ) } - /** {@inheritDoc} */ - public abstract get busy (): boolean + /** + * Whether the pool is full or not. + * + * The pool filling boolean status. + */ + protected abstract get full (): boolean - protected internalGetBusyStatus (): boolean { - return ( - this.numberOfRunningTasks >= this.numberOfWorkers && - this.findFreeWorker() === false - ) + /** + * Whether the pool is busy or not. + * + * The pool busyness boolean status. + */ + protected abstract get busy (): boolean + + protected internalBusy (): boolean { + return this.findFreeWorkerNodeKey() === -1 } - /** {@inheritDoc} */ - public findFreeWorker (): Worker | false { - for (const value of this.workers.values()) { - if (value.tasksUsage.running === 0) { - // A worker is free, return the matching worker - return value.worker - } - } - return false + /** @inheritDoc */ + public findFreeWorkerNodeKey (): number { + return this.workerNodes.findIndex(workerNode => { + return workerNode.tasksUsage?.running === 0 + }) } - /** {@inheritDoc} */ + /** @inheritDoc */ public async execute (data: Data): Promise { - const worker = this.chooseWorker() - const messageId = crypto.randomUUID() - const res = this.internalExecute(worker, messageId) - this.checkAndEmitBusy() - this.sendToWorker(worker, { + const [workerNodeKey, workerNode] = this.chooseWorkerNode() + const submittedTask: Task = { // eslint-disable-next-line @typescript-eslint/consistent-type-assertions data: data ?? ({} as Data), - id: messageId + id: crypto.randomUUID() + } + const res = new Promise((resolve, reject) => { + this.promiseResponseMap.set(submittedTask.id, { + resolve, + reject, + worker: workerNode.worker + }) }) + if ( + this.opts.enableTasksQueue === true && + (this.busy || + this.workerNodes[workerNodeKey].tasksUsage.running >= + ((this.opts.tasksQueueOptions as TasksQueueOptions) + .concurrency as number)) + ) { + this.enqueueTask(workerNodeKey, submittedTask) + } else { + this.executeTask(workerNodeKey, submittedTask) + } + this.checkAndEmitEvents() // eslint-disable-next-line @typescript-eslint/return-await return res } - /** {@inheritDoc} */ + /** @inheritDoc */ public async destroy (): Promise { await Promise.all( - [...this.workers].map(async ([, value]) => { - await this.destroyWorker(value.worker) + this.workerNodes.map(async (workerNode, workerNodeKey) => { + this.flushTasksQueue(workerNodeKey) + await this.destroyWorker(workerNode.worker) }) ) } /** - * Shutdowns given worker. + * Shutdowns the given worker. * - * @param worker - A worker within `workers`. + * @param worker - A worker within `workerNodes`. */ protected abstract destroyWorker (worker: Worker): void | Promise /** - * Setup hook that can be overridden by a Poolifier pool implementation - * to run code before workers are created in the abstract constructor. + * Setup hook to execute code before worker node are created in the abstract constructor. + * Can be overridden + * + * @virtual */ protected setupHook (): void { - // Can be overridden + // Intentionally empty } /** @@ -259,50 +316,75 @@ export abstract class AbstractPool< protected abstract isMain (): boolean /** - * Hook executed before the worker task promise resolution. + * Hook executed before the worker task execution. * Can be overridden. * - * @param worker - The worker. + * @param workerNodeKey - The worker node key. */ - protected beforePromiseWorkerResponseHook (worker: Worker): void { - this.increaseWorkerRunningTasks(worker) + protected beforeTaskExecutionHook (workerNodeKey: number): void { + ++this.workerNodes[workerNodeKey].tasksUsage.running } /** - * Hook executed after the worker task promise resolution. + * Hook executed after the worker task execution. * Can be overridden. * + * @param worker - The worker. * @param message - The received message. - * @param promise - The Promise response. */ - protected afterPromiseWorkerResponseHook ( - message: MessageValue, - promise: PromiseWorkerResponseWrapper + protected afterTaskExecutionHook ( + worker: Worker, + message: MessageValue ): void { - this.decreaseWorkerRunningTasks(promise.worker) - this.stepWorkerRunTasks(promise.worker, 1) - this.updateWorkerTasksRunTime(promise.worker, message.taskRunTime) - } - - /** - * Removes the given worker from the pool. - * - * @param worker - The worker that will be removed. - */ - protected removeWorker (worker: Worker): void { - this.workers.delete(this.getWorkerKey(worker) as number) - --this.nextWorkerId + const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage + --workerTasksUsage.running + ++workerTasksUsage.run + if (message.error != null) { + ++workerTasksUsage.error + } + if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) { + workerTasksUsage.runTime += message.runTime ?? 0 + if ( + this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime && + workerTasksUsage.run !== 0 + ) { + workerTasksUsage.avgRunTime = + workerTasksUsage.runTime / workerTasksUsage.run + } + if (this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime) { + workerTasksUsage.runTimeHistory.push(message.runTime ?? 0) + workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory) + } + } } /** - * Chooses a worker for the next task. + * Chooses a worker node for the next task. * - * The default implementation uses a round robin algorithm to distribute the load. + * The default uses a round robin algorithm to distribute the load. * - * @returns Worker. + * @returns [worker node key, worker node]. */ - protected chooseWorker (): Worker { - return this.workerChoiceStrategyContext.execute() + protected chooseWorkerNode (): [number, WorkerNode] { + let workerNodeKey: number + if (this.type === PoolType.DYNAMIC && !this.full && this.internalBusy()) { + const workerCreated = this.createAndSetupWorker() + this.registerWorkerMessageListener(workerCreated, message => { + if ( + isKillBehavior(KillBehaviors.HARD, message.kill) || + (message.kill != null && + this.getWorkerTasksUsage(workerCreated)?.running === 0) + ) { + // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime) + this.flushTasksQueueByWorker(workerCreated) + void this.destroyWorker(workerCreated) + } + }) + workerNodeKey = this.getWorkerNodeKey(workerCreated) + } else { + workerNodeKey = this.workerChoiceStrategyContext.execute() + } + return [workerNodeKey, this.workerNodes[workerNodeKey]] } /** @@ -317,7 +399,7 @@ export abstract class AbstractPool< ): void /** - * Registers a listener callback on a given worker. + * Registers a listener callback on the given worker. * * @param worker - The worker which should register a listener. * @param listener - The message listener callback. @@ -332,7 +414,7 @@ export abstract class AbstractPool< protected abstract createWorker (): Worker /** - * Function that can be hooked up when a worker has been newly created and moved to the workers registry. + * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes. * * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default. * @@ -341,7 +423,7 @@ export abstract class AbstractPool< protected abstract afterWorkerSetup (worker: Worker): void /** - * Creates a new worker for this pool and sets it up completely. + * Creates a new worker and sets it up completely in the pool worker nodes. * * @returns New, completely set up worker. */ @@ -353,16 +435,10 @@ export abstract class AbstractPool< worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION) worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION) worker.once('exit', () => { - this.removeWorker(worker) + this.removeWorkerNode(worker) }) - this.setWorker(this.nextWorkerId, worker, { - run: 0, - running: 0, - runTime: 0, - avgRunTime: 0 - }) - ++this.nextWorkerId + this.pushWorkerNode(worker) this.afterWorkerSetup(worker) @@ -370,147 +446,157 @@ export abstract class AbstractPool< } /** - * This function is the listener registered for each worker. + * This function is the listener registered for each worker message. * * @returns The listener function to execute when a message is received from a worker. */ protected workerListener (): (message: MessageValue) => void { return message => { - if (message.id !== undefined) { - const promise = this.promiseMap.get(message.id) - if (promise !== undefined) { + if (message.id != null) { + // Task execution response received + const promiseResponse = this.promiseResponseMap.get(message.id) + if (promiseResponse != null) { if (message.error != null) { - promise.reject(message.error) + promiseResponse.reject(message.error) } else { - promise.resolve(message.data as Response) + promiseResponse.resolve(message.data as Response) + } + this.afterTaskExecutionHook(promiseResponse.worker, message) + this.promiseResponseMap.delete(message.id) + const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker) + if ( + this.opts.enableTasksQueue === true && + this.tasksQueueSize(workerNodeKey) > 0 + ) { + this.executeTask( + workerNodeKey, + this.dequeueTask(workerNodeKey) as Task + ) } - this.afterPromiseWorkerResponseHook(message, promise) - this.promiseMap.delete(message.id) } } } } - private async internalExecute ( - worker: Worker, - messageId: string - ): Promise { - this.beforePromiseWorkerResponseHook(worker) - return await new Promise((resolve, reject) => { - this.promiseMap.set(messageId, { resolve, reject, worker }) - }) - } - - private checkAndEmitBusy (): void { - if (this.opts.enableEvents === true && this.busy) { - this.emitter?.emit('busy') + private checkAndEmitEvents (): void { + if (this.opts.enableEvents === true) { + if (this.busy) { + this.emitter?.emit(PoolEvents.busy) + } + if (this.type === PoolType.DYNAMIC && this.full) { + this.emitter?.emit(PoolEvents.full) + } } } /** - * Increases the number of tasks that the given worker has applied. + * Sets the given worker node its tasks usage in the pool. * - * @param worker - Worker which running tasks is increased. + * @param workerNode - The worker node. + * @param tasksUsage - The worker node tasks usage. */ - private increaseWorkerRunningTasks (worker: Worker): void { - this.stepWorkerRunningTasks(worker, 1) - } - - /** - * Decreases the number of tasks that the given worker has applied. - * - * @param worker - Worker which running tasks is decreased. - */ - private decreaseWorkerRunningTasks (worker: Worker): void { - this.stepWorkerRunningTasks(worker, -1) + private setWorkerNodeTasksUsage ( + workerNode: WorkerNode, + tasksUsage: TasksUsage + ): void { + workerNode.tasksUsage = tasksUsage } /** - * Gets tasks usage of the given worker. + * Gets the given worker its tasks usage in the pool. * - * @param worker - Worker which tasks usage is returned. + * @param worker - The worker. + * @returns The worker tasks usage. */ private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined { - if (this.checkWorker(worker)) { - const workerKey = this.getWorkerKey(worker) as number - const workerEntry = this.workers.get(workerKey) as WorkerType - return workerEntry.tasksUsage + const workerNodeKey = this.getWorkerNodeKey(worker) + if (workerNodeKey !== -1) { + return this.workerNodes[workerNodeKey].tasksUsage } + throw new Error('Worker could not be found in the pool worker nodes') } /** - * Steps the number of tasks that the given worker has applied. + * Pushes the given worker in the pool worker nodes. * - * @param worker - Worker which running tasks are stepped. - * @param step - Number of running tasks step. - */ - private stepWorkerRunningTasks (worker: Worker, step: number): void { - // prettier-ignore - (this.getWorkerTasksUsage(worker) as TasksUsage).running += step - } - - /** - * Steps the number of tasks that the given worker has run. - * - * @param worker - Worker which has run tasks. - * @param step - Number of run tasks step. + * @param worker - The worker. + * @returns The worker nodes length. */ - private stepWorkerRunTasks (worker: Worker, step: number): void { - // prettier-ignore - (this.getWorkerTasksUsage(worker) as TasksUsage).run += step + private pushWorkerNode (worker: Worker): number { + return this.workerNodes.push({ + worker, + tasksUsage: { + run: 0, + running: 0, + runTime: 0, + runTimeHistory: new CircularArray(), + avgRunTime: 0, + medRunTime: 0, + error: 0 + }, + tasksQueue: [] + }) } /** - * Updates tasks runtime for the given worker. + * Sets the given worker in the pool worker nodes. * - * @param worker - Worker which run the task. - * @param taskRunTime - Worker task runtime. + * @param workerNodeKey - The worker node key. + * @param worker - The worker. + * @param tasksUsage - The worker tasks usage. + * @param tasksQueue - The worker task queue. */ - private updateWorkerTasksRunTime ( + private setWorkerNode ( + workerNodeKey: number, worker: Worker, - taskRunTime: number | undefined + tasksUsage: TasksUsage, + tasksQueue: Array> ): void { - if ( - this.workerChoiceStrategyContext.getWorkerChoiceStrategy() - .requiredStatistics.runTime - ) { - const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage - workerTasksUsage.runTime += taskRunTime ?? 0 - if (workerTasksUsage.run !== 0) { - workerTasksUsage.avgRunTime = - workerTasksUsage.runTime / workerTasksUsage.run - } + this.workerNodes[workerNodeKey] = { + worker, + tasksUsage, + tasksQueue } } /** - * Sets the given worker. + * Removes the given worker from the pool worker nodes. * - * @param workerKey - The worker key. * @param worker - The worker. - * @param tasksUsage - The worker tasks usage. */ - private setWorker ( - workerKey: number, - worker: Worker, - tasksUsage: TasksUsage - ): void { - this.workers.set(workerKey, { - worker, - tasksUsage - }) + private removeWorkerNode (worker: Worker): void { + const workerNodeKey = this.getWorkerNodeKey(worker) + this.workerNodes.splice(workerNodeKey, 1) + this.workerChoiceStrategyContext.remove(workerNodeKey) } - /** - * Checks if the given worker is registered in the pool. - * - * @param worker - Worker to check. - * @returns `true` if the worker is registered in the pool. - */ - private checkWorker (worker: Worker): boolean { - if (this.getWorkerKey(worker) == null) { - throw new Error('Worker could not be found in the pool') + private executeTask (workerNodeKey: number, task: Task): void { + this.beforeTaskExecutionHook(workerNodeKey) + this.sendToWorker(this.workerNodes[workerNodeKey].worker, task) + } + + private enqueueTask (workerNodeKey: number, task: Task): number { + return this.workerNodes[workerNodeKey].tasksQueue.push(task) + } + + private dequeueTask (workerNodeKey: number): Task | undefined { + return this.workerNodes[workerNodeKey].tasksQueue.shift() + } + + private tasksQueueSize (workerNodeKey: number): number { + return this.workerNodes[workerNodeKey].tasksQueue.length + } + + private flushTasksQueue (workerNodeKey: number): void { + if (this.tasksQueueSize(workerNodeKey) > 0) { + for (const task of this.workerNodes[workerNodeKey].tasksQueue) { + this.executeTask(workerNodeKey, task) + } } - return true + } + + private flushTasksQueueByWorker (worker: Worker): void { + const workerNodeKey = this.getWorkerNodeKey(worker) + this.flushTasksQueue(workerNodeKey) } }