import { MessageChannel } from 'node:worker_threads'
-import { CircularArray } from '../circular-array'
-import type { Task } from '../utility-types'
-import { DEFAULT_TASK_NAME, once } from '../utils'
-import { Deque } from '../deque'
+import { EventEmitter } from 'node:events'
+import { CircularArray } from '../circular-array.js'
+import type { Task } from '../utility-types.js'
+import { DEFAULT_TASK_NAME } from '../utils.js'
+import { Deque } from '../deque.js'
import {
+ type EventHandler,
type IWorker,
type IWorkerNode,
+ type StrategyData,
type WorkerInfo,
+ type WorkerNodeOptions,
type WorkerType,
WorkerTypes,
type WorkerUsage
-} from './worker'
+} from './worker.js'
+import {
+ checkWorkerNodeArguments,
+ createWorker,
+ getWorkerId,
+ getWorkerType
+} from './utils.js'
/**
* Worker node.
* @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
*/
export class WorkerNode<Worker extends IWorker, Data = unknown>
-implements IWorkerNode<Worker, Data> {
+ extends EventEmitter
+ implements IWorkerNode<Worker, Data> {
/** @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<string, WorkerUsage>
+ public tasksQueueBackPressureSize: number
private readonly tasksQueue: Deque<Task<Data>>
+ private onBackPressureStarted: boolean
+ private readonly taskFunctionsUsage: Map<string, WorkerUsage>
/**
* 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<Worker>(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<string, WorkerUsage>()
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ this.tasksQueueBackPressureSize = opts.tasksQueueBackPressureSize!
this.tasksQueue = new Deque<Task<Data>>()
- this.tasksQueueBackPressureSize = tasksQueueBackPressureSize
+ this.onBackPressureStarted = false
+ this.taskFunctionsUsage = new Map<string, WorkerUsage>()
}
/** @inheritdoc */
/** @inheritdoc */
public enqueueTask (task: Task<Data>): number {
const tasksQueueSize = this.tasksQueue.push(task)
- if (this.onBackPressure != null && this.hasBackPressure()) {
- once(this.onBackPressure, this)(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 unshiftTask (task: Task<Data>): number {
const tasksQueueSize = this.tasksQueue.unshift(task)
- if (this.onBackPressure != null && this.hasBackPressure()) {
- once(this.onBackPressure, this)(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<Data> | undefined {
- const task = this.tasksQueue.shift()
- if (this.onEmptyQueue != null && this.tasksQueue.size === 0) {
- once(this.onEmptyQueue, this)(this.info.id as number)
- }
- return task
+ return this.tasksQueue.shift()
}
/** @inheritdoc */
public popTask (): Task<Data> | undefined {
- const task = this.tasksQueue.pop()
- if (this.onEmptyQueue != null && this.tasksQueue.size === 0) {
- once(this.onEmptyQueue, this)(this.info.id as number)
- }
- return task
+ return this.tasksQueue.pop()
}
/** @inheritdoc */
}
/** @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<void> {
+ const waitWorkerExit = new Promise<void>(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<Worker>
+ ): void {
+ this.worker.on(event, handler)
+ }
+
+ /** @inheritdoc */
+ public registerOnceWorkerEventHandler (
+ event: string,
+ handler: EventHandler<Worker>
+ ): 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))
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
}
}
get maxQueued (): number {
return getTasksQueueMaxSize()
},
+ sequentiallyStolen: 0,
+ stolen: 0,
failed: 0
},
runTime: {
- history: new CircularArray()
+ history: new CircularArray<number>()
},
waitTime: {
- history: new CircularArray()
+ history: new CircularArray<number>()
},
elu: {
idle: {
- history: new CircularArray()
+ history: new CircularArray<number>()
},
active: {
- history: new CircularArray()
+ history: new CircularArray<number>()
}
}
}
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
get queued (): number {
return getTaskFunctionQueueSize()
},
+ sequentiallyStolen: 0,
+ stolen: 0,
failed: 0
},
runTime: {
- history: new CircularArray()
+ history: new CircularArray<number>()
},
waitTime: {
- history: new CircularArray()
+ history: new CircularArray<number>()
},
elu: {
idle: {
- history: new CircularArray()
+ history: new CircularArray<number>()
},
active: {
- history: new CircularArray()
+ history: new CircularArray<number>()
}
}
}
}
-
- /**
- * 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
- }
- }
}