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'
14 type BackPressureCallback
,
15 type EmptyQueueCallback
,
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 messageChannel
?: MessageChannel
41 public tasksQueueBackPressureSize
: number
43 public onBackPressure
?: BackPressureCallback
45 public onEmptyQueue
?: EmptyQueueCallback
46 private readonly tasksQueue
: Deque
<Task
<Data
>>
47 private onEmptyQueueCount
: number
48 private readonly taskFunctionsUsage
: Map
<string, WorkerUsage
>
51 * Constructs a new worker node.
53 * @param worker - The worker.
54 * @param tasksQueueBackPressureSize - The tasks queue back pressure size.
56 constructor (worker
: Worker
, tasksQueueBackPressureSize
: number) {
58 throw new TypeError('Cannot construct a worker node without a worker')
60 if (tasksQueueBackPressureSize
== null) {
62 'Cannot construct a worker node without a tasks queue back pressure size'
65 if (!Number.isSafeInteger(tasksQueueBackPressureSize
)) {
67 'Cannot construct a worker node with a tasks queue back pressure size that is not an integer'
71 this.info
= this.initWorkerInfo(worker
)
72 this.usage
= this.initWorkerUsage()
73 if (this.info
.type === WorkerTypes
.thread
) {
74 this.messageChannel
= new MessageChannel()
76 this.tasksQueueBackPressureSize
= tasksQueueBackPressureSize
77 this.tasksQueue
= new Deque
<Task
<Data
>>()
78 this.onEmptyQueueCount
= 0
79 this.taskFunctionsUsage
= new Map
<string, WorkerUsage
>()
83 public tasksQueueSize (): number {
84 return this.tasksQueue
.size
88 public enqueueTask (task
: Task
<Data
>): number {
89 const tasksQueueSize
= this.tasksQueue
.push(task
)
90 if (this.onBackPressure
!= null && this.hasBackPressure()) {
91 this.onBackPressure(this.info
.id
as number)
97 public unshiftTask (task
: Task
<Data
>): number {
98 const tasksQueueSize
= this.tasksQueue
.unshift(task
)
99 if (this.onBackPressure
!= null && this.hasBackPressure()) {
100 this.onBackPressure(this.info
.id
as number)
102 return tasksQueueSize
106 public dequeueTask (): Task
<Data
> | undefined {
107 const task
= this.tasksQueue
.shift()
108 if (this.onEmptyQueue
!= null && this.tasksQueue
.size
=== 0) {
109 this.startOnEmptyQueue().catch(EMPTY_FUNCTION
)
115 public popTask (): Task
<Data
> | undefined {
116 const task
= this.tasksQueue
.pop()
117 if (this.onEmptyQueue
!= null && this.tasksQueue
.size
=== 0) {
118 this.startOnEmptyQueue().catch(EMPTY_FUNCTION
)
124 public clearTasksQueue (): void {
125 this.tasksQueue
.clear()
129 public hasBackPressure (): boolean {
130 return this.tasksQueue
.size
>= this.tasksQueueBackPressureSize
134 public resetUsage (): void {
135 this.usage
= this.initWorkerUsage()
136 this.taskFunctionsUsage
.clear()
140 public closeChannel (): void {
141 if (this.messageChannel
!= null) {
142 this.messageChannel
?.port1
.unref()
143 this.messageChannel
?.port2
.unref()
144 this.messageChannel
?.port1
.close()
145 this.messageChannel
?.port2
.close()
146 delete this.messageChannel
151 public getTaskFunctionWorkerUsage (name
: string): WorkerUsage
| undefined {
152 if (!Array.isArray(this.info
.taskFunctions
)) {
154 `Cannot get task function worker usage for task function name '${name}' when task function names list is not yet defined`
158 Array.isArray(this.info
.taskFunctions
) &&
159 this.info
.taskFunctions
.length
< 3
162 `Cannot get task function worker usage for task function name '${name}' when task function names list has less than 3 elements`
165 if (name
=== DEFAULT_TASK_NAME
) {
166 name
= this.info
.taskFunctions
[1]
168 if (!this.taskFunctionsUsage
.has(name
)) {
169 this.taskFunctionsUsage
.set(name
, this.initTaskFunctionWorkerUsage(name
))
171 return this.taskFunctionsUsage
.get(name
)
174 private async startOnEmptyQueue (): Promise
<void> {
176 this.onEmptyQueueCount
> 0 &&
177 (this.usage
.tasks
.executing
> 0 || this.tasksQueue
.size
> 0)
179 this.onEmptyQueueCount
= 0
182 (this.onEmptyQueue
as EmptyQueueCallback
)(this.info
.id
as number)
183 ++this.onEmptyQueueCount
184 await sleep(exponentialDelay(this.onEmptyQueueCount
))
185 await this.startOnEmptyQueue()
188 private initWorkerInfo (worker
: Worker
): WorkerInfo
{
190 id
: getWorkerId(worker
),
191 type: getWorkerType(worker
) as WorkerType
,
197 private initWorkerUsage (): WorkerUsage
{
198 const getTasksQueueSize
= (): number => {
199 return this.tasksQueue
.size
201 const getTasksQueueMaxSize
= (): number => {
202 return this.tasksQueue
.maxSize
208 get
queued (): number {
209 return getTasksQueueSize()
211 get
maxQueued (): number {
212 return getTasksQueueMaxSize()
218 history
: new CircularArray()
221 history
: new CircularArray()
225 history
: new CircularArray()
228 history
: new CircularArray()
234 private initTaskFunctionWorkerUsage (name
: string): WorkerUsage
{
235 const getTaskFunctionQueueSize
= (): number => {
236 let taskFunctionQueueSize
= 0
237 for (const task
of this.tasksQueue
) {
239 (task
.name
=== DEFAULT_TASK_NAME
&&
240 name
=== (this.info
.taskFunctions
as string[])[1]) ||
241 (task
.name
!== DEFAULT_TASK_NAME
&& name
=== task
.name
)
243 ++taskFunctionQueueSize
246 return taskFunctionQueueSize
252 get
queued (): number {
253 return getTaskFunctionQueueSize()
259 history
: new CircularArray()
262 history
: new CircularArray()
266 history
: new CircularArray()
269 history
: new CircularArray()