1 import { MessageChannel
} from
'node:worker_threads'
2 import { EventEmitter
} from
'node:events'
3 import { CircularArray
} from
'../circular-array.js'
4 import type { Task
} from
'../utility-types.js'
5 import { DEFAULT_TASK_NAME
, getWorkerId
, getWorkerType
} from
'../utils.js'
6 import { Deque
} from
'../deque.js'
13 type WorkerNodeOptions
,
18 import { checkWorkerNodeArguments
, createWorker
} from
'./utils.js'
23 * @typeParam Worker - Type of worker.
24 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
26 export class WorkerNode
<Worker
extends IWorker
, Data
= unknown
>
28 implements IWorkerNode
<Worker
, Data
> {
30 public readonly worker
: Worker
32 public readonly info
: WorkerInfo
34 public usage
: WorkerUsage
36 public strategyData
?: StrategyData
38 public messageChannel
?: MessageChannel
40 public tasksQueueBackPressureSize
: number
41 private readonly tasksQueue
: Deque
<Task
<Data
>>
42 private onBackPressureStarted
: boolean
43 private readonly taskFunctionsUsage
: Map
<string, WorkerUsage
>
46 * Constructs a new worker node.
48 * @param type - The worker type.
49 * @param filePath - Path to the worker file.
50 * @param opts - The worker node options.
52 constructor (type: WorkerType
, filePath
: string, opts
: WorkerNodeOptions
) {
54 checkWorkerNodeArguments(type, filePath
, opts
)
55 this.worker
= createWorker
<Worker
>(type, filePath
, {
57 workerOptions
: opts
.workerOptions
59 this.info
= this.initWorkerInfo(this.worker
)
60 this.usage
= this.initWorkerUsage()
61 if (this.info
.type === WorkerTypes
.thread
) {
62 this.messageChannel
= new MessageChannel()
64 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
65 this.tasksQueueBackPressureSize
= opts
.tasksQueueBackPressureSize
!
66 this.tasksQueue
= new Deque
<Task
<Data
>>()
67 this.onBackPressureStarted
= false
68 this.taskFunctionsUsage
= new Map
<string, WorkerUsage
>()
72 public tasksQueueSize (): number {
73 return this.tasksQueue
.size
77 public enqueueTask (task
: Task
<Data
>): number {
78 const tasksQueueSize
= this.tasksQueue
.push(task
)
79 if (this.hasBackPressure() && !this.onBackPressureStarted
) {
80 this.onBackPressureStarted
= true
81 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
82 this.emit('backPressure', { workerId
: this.info
.id
! })
83 this.onBackPressureStarted
= false
89 public unshiftTask (task
: Task
<Data
>): number {
90 const tasksQueueSize
= this.tasksQueue
.unshift(task
)
91 if (this.hasBackPressure() && !this.onBackPressureStarted
) {
92 this.onBackPressureStarted
= true
93 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
94 this.emit('backPressure', { workerId
: this.info
.id
! })
95 this.onBackPressureStarted
= false
101 public dequeueTask (): Task
<Data
> | undefined {
102 return this.tasksQueue
.shift()
106 public popTask (): Task
<Data
> | undefined {
107 return this.tasksQueue
.pop()
111 public clearTasksQueue (): void {
112 this.tasksQueue
.clear()
116 public hasBackPressure (): boolean {
117 return this.tasksQueue
.size
>= this.tasksQueueBackPressureSize
121 public resetUsage (): void {
122 this.usage
= this.initWorkerUsage()
123 this.taskFunctionsUsage
.clear()
127 public async terminate (): Promise
<void> {
128 const waitWorkerExit
= new Promise
<void>(resolve
=> {
129 this.registerOnceWorkerEventHandler('exit', () => {
133 this.closeMessageChannel()
134 this.removeAllListeners()
135 switch (this.info
.type) {
136 case WorkerTypes
.thread
:
137 await this.worker
.terminate
?.()
139 case WorkerTypes
.cluster
:
140 this.registerOnceWorkerEventHandler('disconnect', () => {
143 this.worker
.disconnect
?.()
150 public registerWorkerEventHandler (
152 handler
: EventHandler
<Worker
>
154 this.worker
.on(event
, handler
)
158 public registerOnceWorkerEventHandler (
160 handler
: EventHandler
<Worker
>
162 this.worker
.once(event
, handler
)
166 public getTaskFunctionWorkerUsage (name
: string): WorkerUsage
| undefined {
167 if (!Array.isArray(this.info
.taskFunctionNames
)) {
169 `Cannot get task function worker usage for task function name '${name}' when task function names list is not yet defined`
173 Array.isArray(this.info
.taskFunctionNames
) &&
174 this.info
.taskFunctionNames
.length
< 3
177 `Cannot get task function worker usage for task function name '${name}' when task function names list has less than 3 elements`
180 if (name
=== DEFAULT_TASK_NAME
) {
181 name
= this.info
.taskFunctionNames
[1]
183 if (!this.taskFunctionsUsage
.has(name
)) {
184 this.taskFunctionsUsage
.set(name
, this.initTaskFunctionWorkerUsage(name
))
186 return this.taskFunctionsUsage
.get(name
)
190 public deleteTaskFunctionWorkerUsage (name
: string): boolean {
191 return this.taskFunctionsUsage
.delete(name
)
194 private closeMessageChannel (): void {
195 if (this.messageChannel
!= null) {
196 this.messageChannel
.port1
.unref()
197 this.messageChannel
.port2
.unref()
198 this.messageChannel
.port1
.close()
199 this.messageChannel
.port2
.close()
200 delete this.messageChannel
204 private initWorkerInfo (worker
: Worker
): WorkerInfo
{
206 id
: getWorkerId(worker
),
207 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
208 type: getWorkerType(worker
)!,
215 private initWorkerUsage (): WorkerUsage
{
216 const getTasksQueueSize
= (): number => {
217 return this.tasksQueue
.size
219 const getTasksQueueMaxSize
= (): number => {
220 return this.tasksQueue
.maxSize
226 get
queued (): number {
227 return getTasksQueueSize()
229 get
maxQueued (): number {
230 return getTasksQueueMaxSize()
232 sequentiallyStolen
: 0,
237 history
: new CircularArray
<number>()
240 history
: new CircularArray
<number>()
244 history
: new CircularArray
<number>()
247 history
: new CircularArray
<number>()
253 private initTaskFunctionWorkerUsage (name
: string): WorkerUsage
{
254 const getTaskFunctionQueueSize
= (): number => {
255 let taskFunctionQueueSize
= 0
256 for (const task
of this.tasksQueue
) {
258 (task
.name
=== DEFAULT_TASK_NAME
&&
259 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
260 name
=== this.info
.taskFunctionNames
![1]) ||
261 (task
.name
!== DEFAULT_TASK_NAME
&& name
=== task
.name
)
263 ++taskFunctionQueueSize
266 return taskFunctionQueueSize
272 get
queued (): number {
273 return getTaskFunctionQueueSize()
275 sequentiallyStolen
: 0,
280 history
: new CircularArray
<number>()
283 history
: new CircularArray
<number>()
287 history
: new CircularArray
<number>()
290 history
: new CircularArray
<number>()