X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fpools%2Fworker-node.ts;h=1a4df6cd4afd479607a267e0d5ada4744a312e9e;hb=5b95eb9bcafda56ce57003da834cf4e153bb0509;hp=dbbfbe6727f73643037b0ec423b7feb6038f2bdc;hpb=dd92a715bc73ec8d3b9e1123d025b41b020eb81b;p=poolifier.git diff --git a/src/pools/worker-node.ts b/src/pools/worker-node.ts index dbbfbe67..1a4df6cd 100644 --- a/src/pools/worker-node.ts +++ b/src/pools/worker-node.ts @@ -1,16 +1,27 @@ +import { EventEmitter } from 'node:events' import { MessageChannel } from 'node:worker_threads' -import { CircularArray } from '../circular-array' -import { Queue } from '../queue' -import type { Task } from '../utility-types' -import { DEFAULT_TASK_NAME } from '../utils' + +import { CircularArray } from '../circular-array.js' +import { Deque } from '../deque.js' +import type { Task } from '../utility-types.js' +import { DEFAULT_TASK_NAME } from '../utils.js' +import { + checkWorkerNodeArguments, + createWorker, + getWorkerId, + getWorkerType +} from './utils.js' import { + type EventHandler, type IWorker, type IWorkerNode, + type StrategyData, type WorkerInfo, + type WorkerNodeOptions, type WorkerType, WorkerTypes, type WorkerUsage -} from './worker' +} from './worker.js' /** * Worker node. @@ -19,54 +30,48 @@ import { * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. */ export class WorkerNode -implements IWorkerNode { + extends EventEmitter + implements IWorkerNode { /** @inheritdoc */ public readonly worker: Worker /** @inheritdoc */ public readonly info: WorkerInfo /** @inheritdoc */ + public usage: WorkerUsage + /** @inheritdoc */ + public strategyData?: StrategyData + /** @inheritdoc */ public messageChannel?: MessageChannel /** @inheritdoc */ - public usage: WorkerUsage + public tasksQueueBackPressureSize: number + private readonly tasksQueue: Deque> + private onBackPressureStarted: boolean private readonly taskFunctionsUsage: Map - private readonly tasksQueue: Queue> - private readonly tasksQueueBackPressureSize: number /** * Constructs a new worker node. * - * @param worker - The worker. - * @param workerType - The worker type. - * @param poolMaxSize - The pool maximum size. + * @param type - The worker type. + * @param filePath - Path to the worker file. + * @param opts - The worker node options. */ - constructor (worker: Worker, workerType: WorkerType, poolMaxSize: number) { - if (worker == null) { - throw new TypeError('Cannot construct a worker node without a worker') - } - if (workerType == null) { - throw new TypeError( - 'Cannot construct a worker node without a worker type' - ) - } - if (poolMaxSize == null) { - throw new TypeError( - 'Cannot construct a worker node without a pool maximum size' - ) - } - if (!Number.isSafeInteger(poolMaxSize)) { - throw new TypeError( - 'Cannot construct a worker node with a pool maximum size that is not an integer' - ) - } - this.worker = worker - this.info = this.initWorkerInfo(worker, workerType) - if (workerType === WorkerTypes.thread) { + constructor (type: WorkerType, filePath: string, opts: WorkerNodeOptions) { + super() + checkWorkerNodeArguments(type, filePath, opts) + this.worker = createWorker(type, filePath, { + env: opts.env, + workerOptions: opts.workerOptions + }) + this.info = this.initWorkerInfo(this.worker) + this.usage = this.initWorkerUsage() + if (this.info.type === WorkerTypes.thread) { this.messageChannel = new MessageChannel() } - this.usage = this.initWorkerUsage() + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + this.tasksQueueBackPressureSize = opts.tasksQueueBackPressureSize! + this.tasksQueue = new Deque>() + this.onBackPressureStarted = false this.taskFunctionsUsage = new Map() - this.tasksQueue = new Queue>() - this.tasksQueueBackPressureSize = Math.pow(poolMaxSize, 2) } /** @inheritdoc */ @@ -74,23 +79,36 @@ implements IWorkerNode { return this.tasksQueue.size } - /** - * Tasks queue maximum size. - * - * @returns The tasks queue maximum size. - */ - private tasksQueueMaxSize (): number { - return this.tasksQueue.maxSize + /** @inheritdoc */ + public enqueueTask (task: Task): number { + const tasksQueueSize = this.tasksQueue.push(task) + if (this.hasBackPressure() && !this.onBackPressureStarted) { + this.onBackPressureStarted = true + this.emit('backPressure', { workerId: this.info.id }) + this.onBackPressureStarted = false + } + return tasksQueueSize } /** @inheritdoc */ - public enqueueTask (task: Task): number { - return this.tasksQueue.enqueue(task) + public unshiftTask (task: Task): number { + const tasksQueueSize = this.tasksQueue.unshift(task) + if (this.hasBackPressure() && !this.onBackPressureStarted) { + this.onBackPressureStarted = true + this.emit('backPressure', { workerId: this.info.id }) + this.onBackPressureStarted = false + } + return tasksQueueSize } /** @inheritdoc */ public dequeueTask (): Task | undefined { - return this.tasksQueue.dequeue() + return this.tasksQueue.shift() + } + + /** @inheritdoc */ + public popTask (): Task | undefined { + return this.tasksQueue.pop() } /** @inheritdoc */ @@ -110,33 +128,62 @@ implements IWorkerNode { } /** @inheritdoc */ - public closeChannel (): void { - if (this.messageChannel != null) { - this.messageChannel?.port1.unref() - this.messageChannel?.port2.unref() - this.messageChannel?.port1.close() - this.messageChannel?.port2.close() - delete this.messageChannel + public async terminate (): Promise { + const waitWorkerExit = new Promise(resolve => { + this.registerOnceWorkerEventHandler('exit', () => { + resolve() + }) + }) + this.closeMessageChannel() + this.removeAllListeners() + switch (this.info.type) { + case WorkerTypes.thread: + this.worker.unref?.() + await this.worker.terminate?.() + break + case WorkerTypes.cluster: + this.registerOnceWorkerEventHandler('disconnect', () => { + this.worker.kill?.() + }) + this.worker.disconnect?.() + break } + await waitWorkerExit + } + + /** @inheritdoc */ + public registerWorkerEventHandler ( + event: string, + handler: EventHandler + ): void { + this.worker.on(event, handler) + } + + /** @inheritdoc */ + public registerOnceWorkerEventHandler ( + event: string, + handler: EventHandler + ): void { + this.worker.once(event, handler) } /** @inheritdoc */ public getTaskFunctionWorkerUsage (name: string): WorkerUsage | undefined { - if (!Array.isArray(this.info.taskFunctions)) { + if (!Array.isArray(this.info.taskFunctionNames)) { throw new Error( `Cannot get task function worker usage for task function name '${name}' when task function names list is not yet defined` ) } if ( - Array.isArray(this.info.taskFunctions) && - this.info.taskFunctions.length < 3 + Array.isArray(this.info.taskFunctionNames) && + this.info.taskFunctionNames.length < 3 ) { throw new Error( `Cannot get task function worker usage for task function name '${name}' when task function names list has less than 3 elements` ) } if (name === DEFAULT_TASK_NAME) { - name = this.info.taskFunctions[1] + name = this.info.taskFunctionNames[1] } if (!this.taskFunctionsUsage.has(name)) { this.taskFunctionsUsage.set(name, this.initTaskFunctionWorkerUsage(name)) @@ -144,21 +191,38 @@ implements IWorkerNode { return this.taskFunctionsUsage.get(name) } - private initWorkerInfo (worker: Worker, workerType: WorkerType): WorkerInfo { + /** @inheritdoc */ + public deleteTaskFunctionWorkerUsage (name: string): boolean { + return this.taskFunctionsUsage.delete(name) + } + + private closeMessageChannel (): void { + if (this.messageChannel != null) { + this.messageChannel.port1.unref() + this.messageChannel.port2.unref() + this.messageChannel.port1.close() + this.messageChannel.port2.close() + delete this.messageChannel + } + } + + private initWorkerInfo (worker: Worker): WorkerInfo { return { - id: this.getWorkerId(worker, workerType), - type: workerType, + id: getWorkerId(worker), + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + type: getWorkerType(worker)!, dynamic: false, - ready: false + ready: false, + stealing: false } } private initWorkerUsage (): WorkerUsage { const getTasksQueueSize = (): number => { - return this.tasksQueueSize() + return this.tasksQueue.size } const getTasksQueueMaxSize = (): number => { - return this.tasksQueueMaxSize() + return this.tasksQueue.maxSize } return { tasks: { @@ -170,80 +234,67 @@ implements IWorkerNode { get maxQueued (): number { return getTasksQueueMaxSize() }, + sequentiallyStolen: 0, + stolen: 0, failed: 0 }, runTime: { - history: new CircularArray() + history: new CircularArray() }, waitTime: { - history: new CircularArray() + history: new CircularArray() }, elu: { idle: { - history: new CircularArray() + history: new CircularArray() }, active: { - history: new CircularArray() + history: new CircularArray() } } } } private initTaskFunctionWorkerUsage (name: string): WorkerUsage { - const getTaskQueueSize = (): number => { - let taskQueueSize = 0 + const getTaskFunctionQueueSize = (): number => { + let taskFunctionQueueSize = 0 for (const task of this.tasksQueue) { if ( - (name === DEFAULT_TASK_NAME && - task.name === (this.info.taskFunctions as string[])[1]) || - task.name === name + (task.name === DEFAULT_TASK_NAME && + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + name === this.info.taskFunctionNames![1]) || + (task.name !== DEFAULT_TASK_NAME && name === task.name) ) { - ++taskQueueSize + ++taskFunctionQueueSize } } - return taskQueueSize + return taskFunctionQueueSize } return { tasks: { executed: 0, executing: 0, get queued (): number { - return getTaskQueueSize() + return getTaskFunctionQueueSize() }, + sequentiallyStolen: 0, + stolen: 0, failed: 0 }, runTime: { - history: new CircularArray() + history: new CircularArray() }, waitTime: { - history: new CircularArray() + history: new CircularArray() }, elu: { idle: { - history: new CircularArray() + history: new CircularArray() }, active: { - history: new CircularArray() + history: new CircularArray() } } } } - - /** - * Gets the worker id. - * - * @param worker - The worker. - * @param workerType - The worker type. - * @returns The worker id. - */ - private getWorkerId ( - worker: Worker, - workerType: WorkerType - ): number | undefined { - if (workerType === WorkerTypes.thread) { - return worker.threadId - } else if (workerType === WorkerTypes.cluster) { - return worker.id - } - } }