1 import { EventEmitter
} from
'node:events'
2 import { MessageChannel
} from
'node:worker_threads'
4 import { CircularArray
} from
'../circular-array.js'
5 import { PriorityQueue
} from
'../priority-queue.js'
6 import type { Task
} from
'../utility-types.js'
7 import { DEFAULT_TASK_NAME
} from
'../utils.js'
9 checkWorkerNodeArguments
,
20 type WorkerNodeOptions
,
29 * @typeParam Worker - Type of worker.
30 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
32 export class WorkerNode
<Worker
extends IWorker
, Data
= unknown
>
34 implements IWorkerNode
<Worker
, Data
> {
36 public readonly worker
: Worker
38 public readonly info
: WorkerInfo
40 public usage
: WorkerUsage
42 public strategyData
?: StrategyData
44 public messageChannel
?: MessageChannel
46 public tasksQueueBackPressureSize
: number
47 private readonly tasksQueue
: PriorityQueue
<Task
<Data
>>
48 private onBackPressureStarted
: boolean
49 private readonly taskFunctionsUsage
: Map
<string, WorkerUsage
>
52 * Constructs a new worker node.
54 * @param type - The worker type.
55 * @param filePath - Path to the worker file.
56 * @param opts - The worker node options.
58 constructor (type: WorkerType
, filePath
: string, opts
: WorkerNodeOptions
) {
60 checkWorkerNodeArguments(type, filePath
, opts
)
61 this.worker
= createWorker
<Worker
>(type, filePath
, {
63 workerOptions
: opts
.workerOptions
65 this.info
= this.initWorkerInfo(this.worker
)
66 this.usage
= this.initWorkerUsage()
67 if (this.info
.type === WorkerTypes
.thread
) {
68 this.messageChannel
= new MessageChannel()
70 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
71 this.tasksQueueBackPressureSize
= opts
.tasksQueueBackPressureSize
!
72 this.tasksQueue
= new PriorityQueue
<Task
<Data
>>(opts
.tasksQueueBucketSize
)
73 this.onBackPressureStarted
= false
74 this.taskFunctionsUsage
= new Map
<string, WorkerUsage
>()
78 public tasksQueueSize (): number {
79 return this.tasksQueue
.size
83 public enqueueTask (task
: Task
<Data
>): number {
84 const tasksQueueSize
= this.tasksQueue
.enqueue(task
, task
.priority
)
85 if (this.hasBackPressure() && !this.onBackPressureStarted
) {
86 this.onBackPressureStarted
= true
87 this.emit('backPressure', { workerId
: this.info
.id
})
88 this.onBackPressureStarted
= false
94 public dequeueTask (bucket
?: number): Task
<Data
> | undefined {
95 return this.tasksQueue
.dequeue(bucket
)
99 public clearTasksQueue (): void {
100 this.tasksQueue
.clear()
104 public hasBackPressure (): boolean {
105 return this.tasksQueue
.size
>= this.tasksQueueBackPressureSize
109 public async terminate (): Promise
<void> {
110 const waitWorkerExit
= new Promise
<void>(resolve
=> {
111 this.registerOnceWorkerEventHandler('exit', () => {
115 this.closeMessageChannel()
116 this.removeAllListeners()
117 switch (this.info
.type) {
118 case WorkerTypes
.thread
:
119 this.worker
.unref
?.()
120 await this.worker
.terminate
?.()
122 case WorkerTypes
.cluster
:
123 this.registerOnceWorkerEventHandler('disconnect', () => {
126 this.worker
.disconnect
?.()
133 public registerWorkerEventHandler (
135 handler
: EventHandler
<Worker
>
137 this.worker
.on(event
, handler
)
141 public registerOnceWorkerEventHandler (
143 handler
: EventHandler
<Worker
>
145 this.worker
.once(event
, handler
)
149 public getTaskFunctionWorkerUsage (name
: string): WorkerUsage
| undefined {
150 if (!Array.isArray(this.info
.taskFunctionsProperties
)) {
152 `Cannot get task function worker usage for task function name '${name}' when task function properties list is not yet defined`
156 Array.isArray(this.info
.taskFunctionsProperties
) &&
157 this.info
.taskFunctionsProperties
.length
< 3
160 `Cannot get task function worker usage for task function name '${name}' when task function properties list has less than 3 elements`
163 if (name
=== DEFAULT_TASK_NAME
) {
164 name
= this.info
.taskFunctionsProperties
[1].name
166 if (!this.taskFunctionsUsage
.has(name
)) {
167 this.taskFunctionsUsage
.set(name
, this.initTaskFunctionWorkerUsage(name
))
169 return this.taskFunctionsUsage
.get(name
)
173 public deleteTaskFunctionWorkerUsage (name
: string): boolean {
174 return this.taskFunctionsUsage
.delete(name
)
177 private closeMessageChannel (): void {
178 if (this.messageChannel
!= null) {
179 this.messageChannel
.port1
.unref()
180 this.messageChannel
.port2
.unref()
181 this.messageChannel
.port1
.close()
182 this.messageChannel
.port2
.close()
183 delete this.messageChannel
187 private initWorkerInfo (worker
: Worker
): WorkerInfo
{
189 id
: getWorkerId(worker
),
190 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
191 type: getWorkerType(worker
)!,
198 private initWorkerUsage (): WorkerUsage
{
199 const getTasksQueueSize
= (): number => {
200 return this.tasksQueue
.size
202 const getTasksQueueMaxSize
= (): number => {
203 return this.tasksQueue
.maxSize
209 get
queued (): number {
210 return getTasksQueueSize()
212 get
maxQueued (): number {
213 return getTasksQueueMaxSize()
215 sequentiallyStolen
: 0,
220 history
: new CircularArray
<number>()
223 history
: new CircularArray
<number>()
227 history
: new CircularArray
<number>()
230 history
: new CircularArray
<number>()
236 private initTaskFunctionWorkerUsage (name
: string): WorkerUsage
{
237 const getTaskFunctionQueueSize
= (): number => {
238 let taskFunctionQueueSize
= 0
239 for (const task
of this.tasksQueue
) {
241 (task
.name
=== DEFAULT_TASK_NAME
&&
242 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
243 name
=== this.info
.taskFunctionsProperties
![1].name
) ||
244 (task
.name
!== DEFAULT_TASK_NAME
&& name
=== task
.name
)
246 ++taskFunctionQueueSize
249 return taskFunctionQueueSize
255 get
queued (): number {
256 return getTaskFunctionQueueSize()
258 sequentiallyStolen
: 0,
263 history
: new CircularArray
<number>()
266 history
: new CircularArray
<number>()
270 history
: new CircularArray
<number>()
273 history
: new CircularArray
<number>()