X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fpools%2Fworker-node.ts;h=1a4df6cd4afd479607a267e0d5ada4744a312e9e;hb=98f60ddd83d32e108adcfddebeb902f0d5a197eb;hp=fbd00096a769d53cd5d3d9415fae64c428cfb3ee;hpb=1f0766e784d0391b6ed084f2fcbc5b7e09d25fa1;p=poolifier.git diff --git a/src/pools/worker-node.ts b/src/pools/worker-node.ts index fbd00096..1a4df6cd 100644 --- a/src/pools/worker-node.ts +++ b/src/pools/worker-node.ts @@ -1,21 +1,27 @@ +import { EventEmitter } from 'node:events' import { MessageChannel } from 'node:worker_threads' -import { CircularArray } from '../circular-array' -import type { Task } from '../utility-types' + +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 { - DEFAULT_TASK_NAME, - EMPTY_FUNCTION, - exponentialDelay, - sleep -} from '../utils' -import { Deque } from '../deque' + 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. @@ -24,65 +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 messageChannel?: MessageChannel - /** @inheritdoc */ public usage: WorkerUsage /** @inheritdoc */ - public tasksQueueBackPressureSize: number + public strategyData?: StrategyData /** @inheritdoc */ - public onBackPressure?: (workerId: number) => void + public messageChannel?: MessageChannel /** @inheritdoc */ - public onEmptyQueue?: (workerId: number) => void - private readonly taskFunctionsUsage: Map + public tasksQueueBackPressureSize: number private readonly tasksQueue: Deque> - private onEmptyQueueCount: number + private onBackPressureStarted: boolean + private readonly taskFunctionsUsage: Map /** * Constructs a new worker node. * - * @param worker - The worker. - * @param workerType - The worker type. - * @param tasksQueueBackPressureSize - The tasks queue back pressure size. + * @param type - The worker type. + * @param filePath - Path to the worker file. + * @param opts - The worker node options. */ - constructor ( - worker: Worker, - workerType: WorkerType, - tasksQueueBackPressureSize: 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 (tasksQueueBackPressureSize == null) { - throw new TypeError( - 'Cannot construct a worker node without a tasks queue back pressure size' - ) - } - if (!Number.isSafeInteger(tasksQueueBackPressureSize)) { - throw new TypeError( - 'Cannot construct a worker node with a tasks queue back pressure 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() - this.taskFunctionsUsage = new Map() + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + this.tasksQueueBackPressureSize = opts.tasksQueueBackPressureSize! this.tasksQueue = new Deque>() - this.tasksQueueBackPressureSize = tasksQueueBackPressureSize - this.onEmptyQueueCount = 0 + this.onBackPressureStarted = false + this.taskFunctionsUsage = new Map() } /** @inheritdoc */ @@ -93,8 +82,10 @@ implements IWorkerNode { /** @inheritdoc */ public enqueueTask (task: Task): number { const tasksQueueSize = this.tasksQueue.push(task) - if (this.onBackPressure != null && this.hasBackPressure()) { - this.onBackPressure(this.info.id as number) + if (this.hasBackPressure() && !this.onBackPressureStarted) { + this.onBackPressureStarted = true + this.emit('backPressure', { workerId: this.info.id }) + this.onBackPressureStarted = false } return tasksQueueSize } @@ -102,28 +93,22 @@ implements IWorkerNode { /** @inheritdoc */ public unshiftTask (task: Task): number { const tasksQueueSize = this.tasksQueue.unshift(task) - if (this.onBackPressure != null && this.hasBackPressure()) { - this.onBackPressure(this.info.id as number) + 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 { - const task = this.tasksQueue.shift() - if (this.onEmptyQueue != null && this.tasksQueue.size === 0) { - this.startOnEmptyQueue().catch(EMPTY_FUNCTION) - } - return task + return this.tasksQueue.shift() } /** @inheritdoc */ public popTask (): Task | undefined { - const task = this.tasksQueue.pop() - if (this.onEmptyQueue != null && this.tasksQueue.size === 0) { - this.startOnEmptyQueue().catch(EMPTY_FUNCTION) - } - return task + return this.tasksQueue.pop() } /** @inheritdoc */ @@ -143,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)) @@ -177,27 +191,29 @@ implements IWorkerNode { return this.taskFunctionsUsage.get(name) } - private async startOnEmptyQueue (): Promise { - if ( - this.onEmptyQueueCount > 0 && - this.usage.tasks.executing > 0 && - this.tasksQueue.size > 0 - ) { - this.onEmptyQueueCount = 0 - return + /** @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 } - (this.onEmptyQueue as (workerId: number) => void)(this.info.id as number) - ++this.onEmptyQueueCount - await sleep(exponentialDelay(this.onEmptyQueueCount)) - await this.startOnEmptyQueue() } - private initWorkerInfo (worker: Worker, workerType: WorkerType): WorkerInfo { + 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 } } @@ -218,21 +234,22 @@ 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() } } } @@ -244,7 +261,8 @@ implements IWorkerNode { for (const task of this.tasksQueue) { if ( (task.name === DEFAULT_TASK_NAME && - name === (this.info.taskFunctions as string[])[1]) || + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + name === this.info.taskFunctionNames![1]) || (task.name !== DEFAULT_TASK_NAME && name === task.name) ) { ++taskFunctionQueueSize @@ -259,41 +277,24 @@ implements IWorkerNode { get queued (): number { 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 - } - } }