+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 {
type IWorker,
type IWorkerNode,
- type Task,
type WorkerInfo,
type WorkerType,
WorkerTypes,
implements IWorkerNode<Worker, Data> {
public readonly worker: Worker
public readonly info: WorkerInfo
+ public messageChannel?: MessageChannel
public usage: WorkerUsage
private readonly tasksUsage: Map<string, WorkerUsage>
private readonly tasksQueue: Queue<Task<Data>>
constructor (worker: Worker, workerType: WorkerType) {
this.worker = worker
this.info = this.initWorkerInfo(worker, workerType)
+ if (workerType === WorkerTypes.thread) {
+ this.messageChannel = new MessageChannel()
+ }
this.usage = this.initWorkerUsage()
this.tasksUsage = new Map<string, WorkerUsage>()
this.tasksQueue = new Queue<Task<Data>>()
}
/**
- * Worker node tasks queue maximum size.
+ * Tasks queue maximum size.
*
* @returns The tasks queue maximum size.
*/
this.tasksUsage.clear()
}
+ /** @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
+ }
+ }
+
/** @inheritdoc */
public getTaskWorkerUsage (name: string): WorkerUsage | undefined {
+ if (!Array.isArray(this.info.taskFunctions)) {
+ throw new Error(
+ `Cannot get task worker usage for task function name '${name}' when task function names list is not yet defined`
+ )
+ }
+ if (
+ name === DEFAULT_TASK_NAME &&
+ Array.isArray(this.info.taskFunctions) &&
+ this.info.taskFunctions.length > 1
+ ) {
+ name = this.info.taskFunctions[1]
+ }
if (!this.tasksUsage.has(name)) {
this.tasksUsage.set(name, this.initTaskWorkerUsage(name))
}