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 onEmptyQueueCount
: number
50 private readonly taskFunctionsUsage
: Map
<string, WorkerUsage
>
53 * Constructs a new worker node.
55 * @param worker - The worker.
56 * @param tasksQueueBackPressureSize - The tasks queue back pressure size.
58 constructor (worker
: Worker
, tasksQueueBackPressureSize
: number) {
59 this.checkWorkerNodeArguments(worker
, tasksQueueBackPressureSize
)
61 this.info
= this.initWorkerInfo(worker
)
62 this.usage
= this.initWorkerUsage()
63 if (this.info
.type === WorkerTypes
.thread
) {
64 this.messageChannel
= new MessageChannel()
66 this.tasksQueueBackPressureSize
= tasksQueueBackPressureSize
67 this.tasksQueue
= new Deque
<Task
<Data
>>()
68 this.onEmptyQueueCount
= 0
69 this.taskFunctionsUsage
= new Map
<string, WorkerUsage
>()
73 public tasksQueueSize (): number {
74 return this.tasksQueue
.size
78 public enqueueTask (task
: Task
<Data
>): number {
79 const tasksQueueSize
= this.tasksQueue
.push(task
)
80 if (this.onBackPressure
!= null && this.hasBackPressure()) {
81 this.onBackPressure(this.info
.id
as number)
87 public unshiftTask (task
: Task
<Data
>): number {
88 const tasksQueueSize
= this.tasksQueue
.unshift(task
)
89 if (this.onBackPressure
!= null && this.hasBackPressure()) {
90 this.onBackPressure(this.info
.id
as number)
96 public dequeueTask (): Task
<Data
> | undefined {
97 const task
= this.tasksQueue
.shift()
98 if (this.onEmptyQueue
!= null && this.tasksQueue
.size
=== 0) {
99 this.startOnEmptyQueue().catch(EMPTY_FUNCTION
)
105 public popTask (): Task
<Data
> | undefined {
106 const task
= this.tasksQueue
.pop()
107 if (this.onEmptyQueue
!= null && this.tasksQueue
.size
=== 0) {
108 this.startOnEmptyQueue().catch(EMPTY_FUNCTION
)
114 public clearTasksQueue (): void {
115 this.tasksQueue
.clear()
119 public hasBackPressure (): boolean {
120 return this.tasksQueue
.size
>= this.tasksQueueBackPressureSize
124 public resetUsage (): void {
125 this.usage
= this.initWorkerUsage()
126 this.taskFunctionsUsage
.clear()
130 public closeChannel (): void {
131 if (this.messageChannel
!= null) {
132 this.messageChannel
?.port1
.unref()
133 this.messageChannel
?.port2
.unref()
134 this.messageChannel
?.port1
.close()
135 this.messageChannel
?.port2
.close()
136 delete this.messageChannel
141 public getTaskFunctionWorkerUsage (name
: string): WorkerUsage
| undefined {
142 if (!Array.isArray(this.info
.taskFunctions
)) {
144 `Cannot get task function worker usage for task function name '${name}' when task function names list is not yet defined`
148 Array.isArray(this.info
.taskFunctions
) &&
149 this.info
.taskFunctions
.length
< 3
152 `Cannot get task function worker usage for task function name '${name}' when task function names list has less than 3 elements`
155 if (name
=== DEFAULT_TASK_NAME
) {
156 name
= this.info
.taskFunctions
[1]
158 if (!this.taskFunctionsUsage
.has(name
)) {
159 this.taskFunctionsUsage
.set(name
, this.initTaskFunctionWorkerUsage(name
))
161 return this.taskFunctionsUsage
.get(name
)
164 private async startOnEmptyQueue (): Promise
<void> {
166 this.onEmptyQueueCount
> 0 &&
167 (this.usage
.tasks
.executing
> 0 || this.tasksQueue
.size
> 0)
169 this.onEmptyQueueCount
= 0
172 (this.onEmptyQueue
as WorkerNodeEventCallback
)(this.info
.id
as number)
173 ++this.onEmptyQueueCount
174 await sleep(exponentialDelay(this.onEmptyQueueCount
))
175 await this.startOnEmptyQueue()
178 private initWorkerInfo (worker
: Worker
): WorkerInfo
{
180 id
: getWorkerId(worker
),
181 type: getWorkerType(worker
) as WorkerType
,
187 private initWorkerUsage (): WorkerUsage
{
188 const getTasksQueueSize
= (): number => {
189 return this.tasksQueue
.size
191 const getTasksQueueMaxSize
= (): number => {
192 return this.tasksQueue
.maxSize
198 get
queued (): number {
199 return getTasksQueueSize()
201 get
maxQueued (): number {
202 return getTasksQueueMaxSize()
208 history
: new CircularArray()
211 history
: new CircularArray()
215 history
: new CircularArray()
218 history
: new CircularArray()
224 private initTaskFunctionWorkerUsage (name
: string): WorkerUsage
{
225 const getTaskFunctionQueueSize
= (): number => {
226 let taskFunctionQueueSize
= 0
227 for (const task
of this.tasksQueue
) {
229 (task
.name
=== DEFAULT_TASK_NAME
&&
230 name
=== (this.info
.taskFunctions
as string[])[1]) ||
231 (task
.name
!== DEFAULT_TASK_NAME
&& name
=== task
.name
)
233 ++taskFunctionQueueSize
236 return taskFunctionQueueSize
242 get
queued (): number {
243 return getTaskFunctionQueueSize()
249 history
: new CircularArray()
252 history
: new CircularArray()
256 history
: new CircularArray()
259 history
: new CircularArray()
265 private checkWorkerNodeArguments (
267 tasksQueueBackPressureSize
: number
269 if (worker
== null) {
270 throw new TypeError('Cannot construct a worker node without a worker')
272 if (tasksQueueBackPressureSize
== null) {
274 'Cannot construct a worker node without a tasks queue back pressure size'
277 if (!Number.isSafeInteger(tasksQueueBackPressureSize
)) {
279 'Cannot construct a worker node with a tasks queue back pressure size that is not an integer'
282 if (tasksQueueBackPressureSize
<= 0) {
283 throw new RangeError(
284 'Cannot construct a worker node with a tasks queue back pressure size that is not a positive integer'