1 import { MessageChannel
} from
'node:worker_threads'
2 import { EventEmitter
} from
'node:events'
3 import { CircularArray
} from
'../circular-array'
4 import type { Task
} from
'../utility-types'
5 import { DEFAULT_TASK_NAME
, getWorkerId
, getWorkerType
} from
'../utils'
6 import { Deque
} from
'../deque'
16 type WorkerNodeOptions
,
21 import { checkWorkerNodeArguments
, createWorker
} from
'./utils'
26 * @typeParam Worker - Type of worker.
27 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
29 export class WorkerNode
<Worker
extends IWorker
, Data
= unknown
>
31 implements IWorkerNode
<Worker
, Data
> {
33 public readonly worker
: Worker
35 public readonly info
: WorkerInfo
37 public usage
: WorkerUsage
39 public strategyData
?: StrategyData
41 public messageChannel
?: MessageChannel
43 public tasksQueueBackPressureSize
: number
44 private readonly tasksQueue
: Deque
<Task
<Data
>>
45 private onBackPressureStarted
: boolean
46 private readonly taskFunctionsUsage
: Map
<string, WorkerUsage
>
49 * Constructs a new worker node.
51 * @param type - The worker type.
52 * @param filePath - Path to the worker file.
53 * @param opts - The worker node options.
55 constructor (type: WorkerType
, filePath
: string, opts
: WorkerNodeOptions
) {
57 checkWorkerNodeArguments(type, filePath
, opts
)
58 this.worker
= createWorker
<Worker
>(type, filePath
, {
60 workerOptions
: opts
.workerOptions
62 this.info
= this.initWorkerInfo(this.worker
)
63 this.usage
= this.initWorkerUsage()
64 if (this.info
.type === WorkerTypes
.thread
) {
65 this.messageChannel
= new MessageChannel()
67 this.tasksQueueBackPressureSize
= opts
.tasksQueueBackPressureSize
68 this.tasksQueue
= new Deque
<Task
<Data
>>()
69 this.onBackPressureStarted
= false
70 this.taskFunctionsUsage
= new Map
<string, WorkerUsage
>()
74 public tasksQueueSize (): number {
75 return this.tasksQueue
.size
79 public enqueueTask (task
: Task
<Data
>): number {
80 const tasksQueueSize
= this.tasksQueue
.push(task
)
81 if (this.hasBackPressure() && !this.onBackPressureStarted
) {
82 this.onBackPressureStarted
= true
83 this.emit('backPressure', { workerId
: this.info
.id
as number })
84 this.onBackPressureStarted
= false
90 public unshiftTask (task
: Task
<Data
>): number {
91 const tasksQueueSize
= this.tasksQueue
.unshift(task
)
92 if (this.hasBackPressure() && !this.onBackPressureStarted
) {
93 this.onBackPressureStarted
= true
94 this.emit('backPressure', { workerId
: this.info
.id
as number })
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 if (this.info
.type === WorkerTypes
.thread
) {
136 await this.worker
.terminate
?.()
137 } else if (this.info
.type === WorkerTypes
.cluster
) {
138 this.registerOnceWorkerEventHandler('disconnect', () => {
141 this.worker
.disconnect
?.()
147 public registerWorkerEventHandler (
150 | OnlineHandler
<Worker
>
151 | MessageHandler
<Worker
>
152 | ErrorHandler
<Worker
>
153 | ExitHandler
<Worker
>
155 this.worker
.on(event
, handler
)
159 public registerOnceWorkerEventHandler (
162 | OnlineHandler
<Worker
>
163 | MessageHandler
<Worker
>
164 | ErrorHandler
<Worker
>
165 | ExitHandler
<Worker
>
167 this.worker
.once(event
, handler
)
171 public getTaskFunctionWorkerUsage (name
: string): WorkerUsage
| undefined {
172 if (!Array.isArray(this.info
.taskFunctionNames
)) {
174 `Cannot get task function worker usage for task function name '${name}' when task function names list is not yet defined`
178 Array.isArray(this.info
.taskFunctionNames
) &&
179 this.info
.taskFunctionNames
.length
< 3
182 `Cannot get task function worker usage for task function name '${name}' when task function names list has less than 3 elements`
185 if (name
=== DEFAULT_TASK_NAME
) {
186 name
= this.info
.taskFunctionNames
[1]
188 if (!this.taskFunctionsUsage
.has(name
)) {
189 this.taskFunctionsUsage
.set(name
, this.initTaskFunctionWorkerUsage(name
))
191 return this.taskFunctionsUsage
.get(name
)
195 public deleteTaskFunctionWorkerUsage (name
: string): boolean {
196 return this.taskFunctionsUsage
.delete(name
)
199 private closeMessageChannel (): void {
200 if (this.messageChannel
!= null) {
201 this.messageChannel
.port1
.unref()
202 this.messageChannel
.port2
.unref()
203 this.messageChannel
.port1
.close()
204 this.messageChannel
.port2
.close()
205 delete this.messageChannel
209 private initWorkerInfo (worker
: Worker
): WorkerInfo
{
211 id
: getWorkerId(worker
),
212 type: getWorkerType(worker
) as WorkerType
,
218 private initWorkerUsage (): WorkerUsage
{
219 const getTasksQueueSize
= (): number => {
220 return this.tasksQueue
.size
222 const getTasksQueueMaxSize
= (): number => {
223 return this.tasksQueue
.maxSize
229 get
queued (): number {
230 return getTasksQueueSize()
232 get
maxQueued (): number {
233 return getTasksQueueMaxSize()
235 sequentiallyStolen
: 0,
240 history
: new CircularArray
<number>()
243 history
: new CircularArray
<number>()
247 history
: new CircularArray
<number>()
250 history
: new CircularArray
<number>()
256 private initTaskFunctionWorkerUsage (name
: string): WorkerUsage
{
257 const getTaskFunctionQueueSize
= (): number => {
258 let taskFunctionQueueSize
= 0
259 for (const task
of this.tasksQueue
) {
261 (task
.name
=== DEFAULT_TASK_NAME
&&
262 name
=== (this.info
.taskFunctionNames
as string[])[1]) ||
263 (task
.name
!== DEFAULT_TASK_NAME
&& name
=== task
.name
)
265 ++taskFunctionQueueSize
268 return taskFunctionQueueSize
274 get
queued (): number {
275 return getTaskFunctionQueueSize()
277 sequentiallyStolen
: 0,
282 history
: new CircularArray
<number>()
285 history
: new CircularArray
<number>()
289 history
: new CircularArray
<number>()
292 history
: new CircularArray
<number>()