fix: worker usage for the default task function
[poolifier.git] / src / pools / worker-node.ts
1 import { MessageChannel } from 'node:worker_threads'
2 import { CircularArray } from '../circular-array'
3 import { Queue } from '../queue'
4 import type { Task } from '../utility-types'
5 import { DEFAULT_TASK_NAME } from '../utils'
6 import {
7 type IWorker,
8 type IWorkerNode,
9 type WorkerInfo,
10 type WorkerType,
11 WorkerTypes,
12 type WorkerUsage
13 } from './worker'
14
15 /**
16 * Worker node.
17 *
18 * @typeParam Worker - Type of worker.
19 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
20 */
21 export class WorkerNode<Worker extends IWorker, Data = unknown>
22 implements IWorkerNode<Worker, Data> {
23 /** @inheritdoc */
24 public readonly worker: Worker
25 /** @inheritdoc */
26 public readonly info: WorkerInfo
27 /** @inheritdoc */
28 public messageChannel?: MessageChannel
29 /** @inheritdoc */
30 public usage: WorkerUsage
31 private readonly taskFunctionsUsage: Map<string, WorkerUsage>
32 private readonly tasksQueue: Queue<Task<Data>>
33 private readonly tasksQueueBackPressureSize: number
34
35 /**
36 * Constructs a new worker node.
37 *
38 * @param worker - The worker.
39 * @param workerType - The worker type.
40 * @param poolMaxSize - The pool maximum size.
41 */
42 constructor (worker: Worker, workerType: WorkerType, poolMaxSize: number) {
43 if (worker == null) {
44 throw new TypeError('Cannot construct a worker node without a worker')
45 }
46 if (workerType == null) {
47 throw new TypeError(
48 'Cannot construct a worker node without a worker type'
49 )
50 }
51 if (poolMaxSize == null) {
52 throw new TypeError(
53 'Cannot construct a worker node without a pool maximum size'
54 )
55 }
56 if (!Number.isSafeInteger(poolMaxSize)) {
57 throw new TypeError(
58 'Cannot construct a worker node with a pool maximum size that is not an integer'
59 )
60 }
61 this.worker = worker
62 this.info = this.initWorkerInfo(worker, workerType)
63 if (workerType === WorkerTypes.thread) {
64 this.messageChannel = new MessageChannel()
65 }
66 this.usage = this.initWorkerUsage()
67 this.taskFunctionsUsage = new Map<string, WorkerUsage>()
68 this.tasksQueue = new Queue<Task<Data>>()
69 this.tasksQueueBackPressureSize = Math.pow(poolMaxSize, 2)
70 }
71
72 /** @inheritdoc */
73 public tasksQueueSize (): number {
74 return this.tasksQueue.size
75 }
76
77 /**
78 * Tasks queue maximum size.
79 *
80 * @returns The tasks queue maximum size.
81 */
82 private tasksQueueMaxSize (): number {
83 return this.tasksQueue.maxSize
84 }
85
86 /** @inheritdoc */
87 public enqueueTask (task: Task<Data>): number {
88 return this.tasksQueue.enqueue(task)
89 }
90
91 /** @inheritdoc */
92 public dequeueTask (): Task<Data> | undefined {
93 return this.tasksQueue.dequeue()
94 }
95
96 /** @inheritdoc */
97 public clearTasksQueue (): void {
98 this.tasksQueue.clear()
99 }
100
101 /** @inheritdoc */
102 public hasBackPressure (): boolean {
103 return this.tasksQueue.size >= this.tasksQueueBackPressureSize
104 }
105
106 /** @inheritdoc */
107 public resetUsage (): void {
108 this.usage = this.initWorkerUsage()
109 this.taskFunctionsUsage.clear()
110 }
111
112 /** @inheritdoc */
113 public closeChannel (): void {
114 if (this.messageChannel != null) {
115 this.messageChannel?.port1.unref()
116 this.messageChannel?.port2.unref()
117 this.messageChannel?.port1.close()
118 this.messageChannel?.port2.close()
119 delete this.messageChannel
120 }
121 }
122
123 /** @inheritdoc */
124 public getTaskFunctionWorkerUsage (name: string): WorkerUsage | undefined {
125 if (!Array.isArray(this.info.taskFunctions)) {
126 throw new Error(
127 `Cannot get task function worker usage for task function name '${name}' when task function names list is not yet defined`
128 )
129 }
130 if (
131 Array.isArray(this.info.taskFunctions) &&
132 this.info.taskFunctions.length < 3
133 ) {
134 throw new Error(
135 `Cannot get task function worker usage for task function name '${name}' when task function names list has less than 3 elements`
136 )
137 }
138 if (name === DEFAULT_TASK_NAME) {
139 name = this.info.taskFunctions[1]
140 }
141 if (!this.taskFunctionsUsage.has(name)) {
142 this.taskFunctionsUsage.set(name, this.initTaskFunctionWorkerUsage(name))
143 }
144 return this.taskFunctionsUsage.get(name)
145 }
146
147 private initWorkerInfo (worker: Worker, workerType: WorkerType): WorkerInfo {
148 return {
149 id: this.getWorkerId(worker, workerType),
150 type: workerType,
151 dynamic: false,
152 ready: false
153 }
154 }
155
156 private initWorkerUsage (): WorkerUsage {
157 const getTasksQueueSize = (): number => {
158 return this.tasksQueueSize()
159 }
160 const getTasksQueueMaxSize = (): number => {
161 return this.tasksQueueMaxSize()
162 }
163 return {
164 tasks: {
165 executed: 0,
166 executing: 0,
167 get queued (): number {
168 return getTasksQueueSize()
169 },
170 get maxQueued (): number {
171 return getTasksQueueMaxSize()
172 },
173 failed: 0
174 },
175 runTime: {
176 history: new CircularArray()
177 },
178 waitTime: {
179 history: new CircularArray()
180 },
181 elu: {
182 idle: {
183 history: new CircularArray()
184 },
185 active: {
186 history: new CircularArray()
187 }
188 }
189 }
190 }
191
192 private initTaskFunctionWorkerUsage (name: string): WorkerUsage {
193 const getTaskQueueSize = (): number => {
194 let taskQueueSize = 0
195 for (const task of this.tasksQueue) {
196 if (
197 (name === DEFAULT_TASK_NAME &&
198 task.name === (this.info.taskFunctions as string[])[1]) ||
199 task.name === name
200 ) {
201 ++taskQueueSize
202 }
203 }
204 return taskQueueSize
205 }
206 return {
207 tasks: {
208 executed: 0,
209 executing: 0,
210 get queued (): number {
211 return getTaskQueueSize()
212 },
213 failed: 0
214 },
215 runTime: {
216 history: new CircularArray()
217 },
218 waitTime: {
219 history: new CircularArray()
220 },
221 elu: {
222 idle: {
223 history: new CircularArray()
224 },
225 active: {
226 history: new CircularArray()
227 }
228 }
229 }
230 }
231
232 /**
233 * Gets the worker id.
234 *
235 * @param worker - The worker.
236 * @param workerType - The worker type.
237 * @returns The worker id.
238 */
239 private getWorkerId (
240 worker: Worker,
241 workerType: WorkerType
242 ): number | undefined {
243 if (workerType === WorkerTypes.thread) {
244 return worker.threadId
245 } else if (workerType === WorkerTypes.cluster) {
246 return worker.id
247 }
248 }
249 }