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,
*/
export class WorkerNode<Worker extends IWorker, Data = unknown>
implements IWorkerNode<Worker, Data> {
+ /** @inheritdoc */
public readonly worker: Worker
+ /** @inheritdoc */
public readonly info: WorkerInfo
+ /** @inheritdoc */
+ public messageChannel?: MessageChannel
+ /** @inheritdoc */
public usage: WorkerUsage
private readonly tasksUsage: Map<string, WorkerUsage>
private readonly tasksQueue: Queue<Task<Data>>
+ private readonly tasksQueueBackPressureMaxSize: number
/**
* Constructs a new worker node.
*
* @param worker - The worker.
* @param workerType - The worker type.
+ * @param poolMaxSize - The pool maximum size.
*/
- constructor (worker: Worker, workerType: WorkerType) {
+ constructor (worker: Worker, workerType: WorkerType, poolMaxSize: number) {
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>>()
+ this.tasksQueueBackPressureMaxSize = Math.pow(poolMaxSize, 2)
}
/** @inheritdoc */
this.tasksQueue.clear()
}
+ /** @inheritdoc */
+ public hasBackPressure (): boolean {
+ return this.tasksQueueSize() >= this.tasksQueueBackPressureMaxSize
+ }
+
/** @inheritdoc */
public resetUsage (): void {
this.usage = this.initWorkerUsage()
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))
}
id: this.getWorkerId(worker, workerType),
type: workerType,
dynamic: false,
- ready: false,
- ...(workerType === WorkerTypes.thread && {
- messageChannel: new MessageChannel()
- })
+ ready: false
}
}