X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fpools%2Fworker-node.ts;h=1a4df6cd4afd479607a267e0d5ada4744a312e9e;hb=bcf1c155ec2e2d9208c8f818abd031662bd61d7f;hp=6eb2d646bdcaa86f93eb07cf341012463f295a9a;hpb=25926072f5397949802f6af5a2f7d49d6f15cacc;p=poolifier.git diff --git a/src/pools/worker-node.ts b/src/pools/worker-node.ts index 6eb2d646..1a4df6cd 100644 --- a/src/pools/worker-node.ts +++ b/src/pools/worker-node.ts @@ -1,26 +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, + checkWorkerNodeArguments, + createWorker, getWorkerId, - getWorkerType, - sleep -} from '../utils' -import { Deque } from '../deque' + getWorkerType +} from './utils.js' import { + type EventHandler, type IWorker, type IWorkerNode, type StrategyData, type WorkerInfo, - type WorkerNodeEventCallback, + type WorkerNodeOptions, type WorkerType, WorkerTypes, type WorkerUsage -} from './worker' -import { checkWorkerNodeArguments } from './utils' +} from './worker.js' /** * Worker node. @@ -29,7 +30,8 @@ import { checkWorkerNodeArguments } from './utils' * @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 */ @@ -42,33 +44,33 @@ implements IWorkerNode { public messageChannel?: MessageChannel /** @inheritdoc */ public tasksQueueBackPressureSize: number - /** @inheritdoc */ - public onBackPressure?: WorkerNodeEventCallback - /** @inheritdoc */ - public onEmptyQueue?: WorkerNodeEventCallback private readonly tasksQueue: Deque> private onBackPressureStarted: boolean - private onEmptyQueueCount: number private readonly taskFunctionsUsage: Map /** * Constructs a new worker node. * - * @param worker - The worker. - * @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, tasksQueueBackPressureSize: number) { - checkWorkerNodeArguments(worker, tasksQueueBackPressureSize) - this.worker = worker - this.info = this.initWorkerInfo(worker) + 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.tasksQueueBackPressureSize = tasksQueueBackPressureSize + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + this.tasksQueueBackPressureSize = opts.tasksQueueBackPressureSize! this.tasksQueue = new Deque>() this.onBackPressureStarted = false - this.onEmptyQueueCount = 0 this.taskFunctionsUsage = new Map() } @@ -80,13 +82,9 @@ implements IWorkerNode { /** @inheritdoc */ public enqueueTask (task: Task): number { const tasksQueueSize = this.tasksQueue.push(task) - if ( - this.onBackPressure != null && - this.hasBackPressure() && - !this.onBackPressureStarted - ) { + if (this.hasBackPressure() && !this.onBackPressureStarted) { this.onBackPressureStarted = true - this.onBackPressure(this.info.id as number) + this.emit('backPressure', { workerId: this.info.id }) this.onBackPressureStarted = false } return tasksQueueSize @@ -95,13 +93,9 @@ implements IWorkerNode { /** @inheritdoc */ public unshiftTask (task: Task): number { const tasksQueueSize = this.tasksQueue.unshift(task) - if ( - this.onBackPressure != null && - this.hasBackPressure() && - !this.onBackPressureStarted - ) { + if (this.hasBackPressure() && !this.onBackPressureStarted) { this.onBackPressureStarted = true - this.onBackPressure(this.info.id as number) + this.emit('backPressure', { workerId: this.info.id }) this.onBackPressureStarted = false } return tasksQueueSize @@ -109,28 +103,12 @@ implements IWorkerNode { /** @inheritdoc */ public dequeueTask (): Task | undefined { - const task = this.tasksQueue.shift() - if ( - this.onEmptyQueue != null && - this.tasksQueue.size === 0 && - this.onEmptyQueueCount === 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.onEmptyQueueCount === 0 - ) { - this.startOnEmptyQueue().catch(EMPTY_FUNCTION) - } - return task + return this.tasksQueue.pop() } /** @inheritdoc */ @@ -150,14 +128,43 @@ 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 */ @@ -189,26 +196,24 @@ implements IWorkerNode { return this.taskFunctionsUsage.delete(name) } - private async startOnEmptyQueue (): Promise { - if ( - this.onEmptyQueueCount > 0 && - (this.usage.tasks.executing > 0 || this.tasksQueue.size > 0) - ) { - this.onEmptyQueueCount = 0 - return + 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.onEmptyQueueCount - this.onEmptyQueue?.(this.info.id as number) - await sleep(exponentialDelay(this.onEmptyQueueCount)) - await this.startOnEmptyQueue() } private initWorkerInfo (worker: Worker): WorkerInfo { return { id: getWorkerId(worker), - type: getWorkerType(worker) as WorkerType, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + type: getWorkerType(worker)!, dynamic: false, - ready: false + ready: false, + stealing: false } } @@ -229,6 +234,7 @@ implements IWorkerNode { get maxQueued (): number { return getTasksQueueMaxSize() }, + sequentiallyStolen: 0, stolen: 0, failed: 0 }, @@ -255,7 +261,8 @@ implements IWorkerNode { for (const task of this.tasksQueue) { if ( (task.name === DEFAULT_TASK_NAME && - name === (this.info.taskFunctionNames 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 @@ -270,6 +277,7 @@ implements IWorkerNode { get queued (): number { return getTaskFunctionQueueSize() }, + sequentiallyStolen: 0, stolen: 0, failed: 0 },