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 setBackPressureFlag
: 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.setBackPressureFlag
= 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
)
86 !this.setBackPressureFlag
&&
87 this.hasBackPressure() &&
88 !this.info
.backPressure
90 this.setBackPressureFlag
= true
91 this.info
.backPressure
= true
92 this.emit('backPressure', { workerId
: this.info
.id
})
93 this.setBackPressureFlag
= false
99 public dequeueTask (bucket
?: number): Task
<Data
> | undefined {
100 const task
= this.tasksQueue
.dequeue(bucket
)
102 !this.setBackPressureFlag
&&
103 !this.hasBackPressure() &&
104 this.info
.backPressure
106 this.setBackPressureFlag
= true
107 this.info
.backPressure
= false
108 this.setBackPressureFlag
= false
114 public dequeueLastPrioritizedTask (): Task
<Data
> | undefined {
115 // Start from the last empty or partially filled bucket
116 return this.dequeueTask(this.tasksQueue
.buckets
+ 1)
120 public clearTasksQueue (): void {
121 this.tasksQueue
.clear()
125 public hasBackPressure (): boolean {
126 return this.tasksQueue
.size
>= this.tasksQueueBackPressureSize
130 public async terminate (): Promise
<void> {
131 const waitWorkerExit
= new Promise
<void>(resolve
=> {
132 this.registerOnceWorkerEventHandler('exit', () => {
136 this.closeMessageChannel()
137 this.removeAllListeners()
138 switch (this.info
.type) {
139 case WorkerTypes
.thread
:
140 this.worker
.unref
?.()
141 await this.worker
.terminate
?.()
143 case WorkerTypes
.cluster
:
144 this.registerOnceWorkerEventHandler('disconnect', () => {
147 this.worker
.disconnect
?.()
154 public registerWorkerEventHandler (
156 handler
: EventHandler
<Worker
>
158 this.worker
.on(event
, handler
)
162 public registerOnceWorkerEventHandler (
164 handler
: EventHandler
<Worker
>
166 this.worker
.once(event
, handler
)
170 public getTaskFunctionWorkerUsage (name
: string): WorkerUsage
| undefined {
171 if (!Array.isArray(this.info
.taskFunctionsProperties
)) {
173 `Cannot get task function worker usage for task function name '${name}' when task function properties list is not yet defined`
177 Array.isArray(this.info
.taskFunctionsProperties
) &&
178 this.info
.taskFunctionsProperties
.length
< 3
181 `Cannot get task function worker usage for task function name '${name}' when task function properties list has less than 3 elements`
184 if (name
=== DEFAULT_TASK_NAME
) {
185 name
= this.info
.taskFunctionsProperties
[1].name
187 if (!this.taskFunctionsUsage
.has(name
)) {
188 this.taskFunctionsUsage
.set(name
, this.initTaskFunctionWorkerUsage(name
))
190 return this.taskFunctionsUsage
.get(name
)
194 public deleteTaskFunctionWorkerUsage (name
: string): boolean {
195 return this.taskFunctionsUsage
.delete(name
)
198 private closeMessageChannel (): void {
199 if (this.messageChannel
!= null) {
200 this.messageChannel
.port1
.unref()
201 this.messageChannel
.port2
.unref()
202 this.messageChannel
.port1
.close()
203 this.messageChannel
.port2
.close()
204 delete this.messageChannel
208 private initWorkerInfo (worker
: Worker
): WorkerInfo
{
210 id
: getWorkerId(worker
),
211 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
212 type: getWorkerType(worker
)!,
220 private initWorkerUsage (): WorkerUsage
{
221 const getTasksQueueSize
= (): number => {
222 return this.tasksQueue
.size
224 const getTasksQueueMaxSize
= (): number => {
225 return this.tasksQueue
.maxSize
231 get
queued (): number {
232 return getTasksQueueSize()
234 get
maxQueued (): number {
235 return getTasksQueueMaxSize()
237 sequentiallyStolen
: 0,
242 history
: new CircularArray
<number>()
245 history
: new CircularArray
<number>()
249 history
: new CircularArray
<number>()
252 history
: new CircularArray
<number>()
258 private initTaskFunctionWorkerUsage (name
: string): WorkerUsage
{
259 const getTaskFunctionQueueSize
= (): number => {
260 let taskFunctionQueueSize
= 0
261 for (const task
of this.tasksQueue
) {
263 (task
.name
=== DEFAULT_TASK_NAME
&&
264 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
265 name
=== this.info
.taskFunctionsProperties
![1].name
) ||
266 (task
.name
!== DEFAULT_TASK_NAME
&& name
=== task
.name
)
268 ++taskFunctionQueueSize
271 return taskFunctionQueueSize
277 get
queued (): number {
278 return getTaskFunctionQueueSize()
280 sequentiallyStolen
: 0,
285 history
: new CircularArray
<number>()
288 history
: new CircularArray
<number>()
292 history
: new CircularArray
<number>()
295 history
: new CircularArray
<number>()