1 import { MessageChannel
} from
'node:worker_threads'
2 import { CircularArray
} from
'../circular-array'
3 import type { Task
} from
'../utility-types'
12 import { Deque
} from
'../deque'
18 type WorkerNodeEventCallback
,
27 * @typeParam Worker - Type of worker.
28 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
30 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
45 public onBackPressure
?: WorkerNodeEventCallback
47 public onEmptyQueue
?: WorkerNodeEventCallback
48 private readonly tasksQueue
: Deque
<Task
<Data
>>
49 private onBackPressureStarted
: boolean
50 private onEmptyQueueCount
: number
51 private readonly taskFunctionsUsage
: Map
<string, WorkerUsage
>
54 * Constructs a new worker node.
56 * @param worker - The worker.
57 * @param tasksQueueBackPressureSize - The tasks queue back pressure size.
59 constructor (worker
: Worker
, tasksQueueBackPressureSize
: number) {
60 this.checkWorkerNodeArguments(worker
, tasksQueueBackPressureSize
)
62 this.info
= this.initWorkerInfo(worker
)
63 this.usage
= this.initWorkerUsage()
64 if (this.info
.type === WorkerTypes
.thread
) {
65 this.messageChannel
= new MessageChannel()
67 this.tasksQueueBackPressureSize
= tasksQueueBackPressureSize
68 this.tasksQueue
= new Deque
<Task
<Data
>>()
69 this.onBackPressureStarted
= false
70 this.onEmptyQueueCount
= 0
71 this.taskFunctionsUsage
= new Map
<string, WorkerUsage
>()
75 public tasksQueueSize (): number {
76 return this.tasksQueue
.size
80 public enqueueTask (task
: Task
<Data
>): number {
81 const tasksQueueSize
= this.tasksQueue
.push(task
)
83 this.onBackPressure
!= null &&
84 this.hasBackPressure() &&
85 !this.onBackPressureStarted
87 this.onBackPressureStarted
= true
88 this.onBackPressure(this.info
.id
as number)
89 this.onBackPressureStarted
= false
95 public unshiftTask (task
: Task
<Data
>): number {
96 const tasksQueueSize
= this.tasksQueue
.unshift(task
)
98 this.onBackPressure
!= null &&
99 this.hasBackPressure() &&
100 !this.onBackPressureStarted
102 this.onBackPressureStarted
= true
103 this.onBackPressure(this.info
.id
as number)
104 this.onBackPressureStarted
= false
106 return tasksQueueSize
110 public dequeueTask (): Task
<Data
> | undefined {
111 const task
= this.tasksQueue
.shift()
113 this.onEmptyQueue
!= null &&
114 this.tasksQueue
.size
=== 0 &&
115 this.onEmptyQueueCount
=== 0
117 this.startOnEmptyQueue().catch(EMPTY_FUNCTION
)
123 public popTask (): Task
<Data
> | undefined {
124 const task
= this.tasksQueue
.pop()
126 this.onEmptyQueue
!= null &&
127 this.tasksQueue
.size
=== 0 &&
128 this.onEmptyQueueCount
=== 0
130 this.startOnEmptyQueue().catch(EMPTY_FUNCTION
)
136 public clearTasksQueue (): void {
137 this.tasksQueue
.clear()
141 public hasBackPressure (): boolean {
142 return this.tasksQueue
.size
>= this.tasksQueueBackPressureSize
146 public resetUsage (): void {
147 this.usage
= this.initWorkerUsage()
148 this.taskFunctionsUsage
.clear()
152 public closeChannel (): void {
153 if (this.messageChannel
!= null) {
154 this.messageChannel
?.port1
.unref()
155 this.messageChannel
?.port2
.unref()
156 this.messageChannel
?.port1
.close()
157 this.messageChannel
?.port2
.close()
158 delete this.messageChannel
163 public getTaskFunctionWorkerUsage (name
: string): WorkerUsage
| undefined {
164 if (!Array.isArray(this.info
.taskFunctionNames
)) {
166 `Cannot get task function worker usage for task function name '${name}' when task function names list is not yet defined`
170 Array.isArray(this.info
.taskFunctionNames
) &&
171 this.info
.taskFunctionNames
.length
< 3
174 `Cannot get task function worker usage for task function name '${name}' when task function names list has less than 3 elements`
177 if (name
=== DEFAULT_TASK_NAME
) {
178 name
= this.info
.taskFunctionNames
[1]
180 if (!this.taskFunctionsUsage
.has(name
)) {
181 this.taskFunctionsUsage
.set(name
, this.initTaskFunctionWorkerUsage(name
))
183 return this.taskFunctionsUsage
.get(name
)
186 private async startOnEmptyQueue (): Promise
<void> {
188 this.onEmptyQueueCount
> 0 &&
189 (this.usage
.tasks
.executing
> 0 || this.tasksQueue
.size
> 0)
191 this.onEmptyQueueCount
= 0
194 ++this.onEmptyQueueCount
195 this.onEmptyQueue
?.(this.info
.id
as number)
196 await sleep(exponentialDelay(this.onEmptyQueueCount
))
197 await this.startOnEmptyQueue()
200 private initWorkerInfo (worker
: Worker
): WorkerInfo
{
202 id
: getWorkerId(worker
),
203 type: getWorkerType(worker
) as WorkerType
,
209 private initWorkerUsage (): WorkerUsage
{
210 const getTasksQueueSize
= (): number => {
211 return this.tasksQueue
.size
213 const getTasksQueueMaxSize
= (): number => {
214 return this.tasksQueue
.maxSize
220 get
queued (): number {
221 return getTasksQueueSize()
223 get
maxQueued (): number {
224 return getTasksQueueMaxSize()
230 history
: new CircularArray()
233 history
: new CircularArray()
237 history
: new CircularArray()
240 history
: new CircularArray()
246 private initTaskFunctionWorkerUsage (name
: string): WorkerUsage
{
247 const getTaskFunctionQueueSize
= (): number => {
248 let taskFunctionQueueSize
= 0
249 for (const task
of this.tasksQueue
) {
251 (task
.name
=== DEFAULT_TASK_NAME
&&
252 name
=== (this.info
.taskFunctionNames
as string[])[1]) ||
253 (task
.name
!== DEFAULT_TASK_NAME
&& name
=== task
.name
)
255 ++taskFunctionQueueSize
258 return taskFunctionQueueSize
264 get
queued (): number {
265 return getTaskFunctionQueueSize()
271 history
: new CircularArray()
274 history
: new CircularArray()
278 history
: new CircularArray()
281 history
: new CircularArray()
287 private checkWorkerNodeArguments (
289 tasksQueueBackPressureSize
: number
291 if (worker
== null) {
292 throw new TypeError('Cannot construct a worker node without a worker')
294 if (tasksQueueBackPressureSize
== null) {
296 'Cannot construct a worker node without a tasks queue back pressure size'
299 if (!Number.isSafeInteger(tasksQueueBackPressureSize
)) {
301 'Cannot construct a worker node with a tasks queue back pressure size that is not an integer'
304 if (tasksQueueBackPressureSize
<= 0) {
305 throw new RangeError(
306 'Cannot construct a worker node with a tasks queue back pressure size that is not a positive integer'