Merge dependabot/npm_and_yarn/examples/typescript/http-server-pool/fastify-worker_thr...
[poolifier.git] / src / pools / worker-node.ts
CommitLineData
85aeb3f3 1import { MessageChannel } from 'node:worker_threads'
4b628b48 2import { CircularArray } from '../circular-array'
5c4d16da 3import type { Task } from '../utility-types'
68cbdc84
JB
4import {
5 DEFAULT_TASK_NAME,
6 EMPTY_FUNCTION,
7 exponentialDelay,
75de9f41
JB
8 getWorkerId,
9 getWorkerType,
68cbdc84
JB
10 sleep
11} from '../utils'
574b351d 12import { Deque } from '../deque'
4b628b48
JB
13import {
14 type IWorker,
15 type IWorkerNode,
f3a91bac 16 type StrategyData,
4b628b48 17 type WorkerInfo,
a9780ad2 18 type WorkerNodeEventCallback,
4b628b48
JB
19 type WorkerType,
20 WorkerTypes,
21 type WorkerUsage
22} from './worker'
23
60664f48
JB
24/**
25 * Worker node.
26 *
27 * @typeParam Worker - Type of worker.
28 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
29 */
4b628b48
JB
30export class WorkerNode<Worker extends IWorker, Data = unknown>
31implements IWorkerNode<Worker, Data> {
671d5154 32 /** @inheritdoc */
4b628b48 33 public readonly worker: Worker
671d5154 34 /** @inheritdoc */
4b628b48 35 public readonly info: WorkerInfo
671d5154 36 /** @inheritdoc */
4b628b48 37 public usage: WorkerUsage
20c6f652 38 /** @inheritdoc */
f3a91bac
JB
39 public strategyData?: StrategyData
40 /** @inheritdoc */
26fb3c18
JB
41 public messageChannel?: MessageChannel
42 /** @inheritdoc */
20c6f652 43 public tasksQueueBackPressureSize: number
72695f86 44 /** @inheritdoc */
a9780ad2 45 public onBackPressure?: WorkerNodeEventCallback
dd951876 46 /** @inheritdoc */
a9780ad2 47 public onEmptyQueue?: WorkerNodeEventCallback
574b351d 48 private readonly tasksQueue: Deque<Task<Data>>
47352846 49 private onBackPressureStarted: boolean
68cbdc84 50 private onEmptyQueueCount: number
26fb3c18 51 private readonly taskFunctionsUsage: Map<string, WorkerUsage>
4b628b48 52
60664f48
JB
53 /**
54 * Constructs a new worker node.
55 *
56 * @param worker - The worker.
20c6f652 57 * @param tasksQueueBackPressureSize - The tasks queue back pressure size.
60664f48 58 */
75de9f41 59 constructor (worker: Worker, tasksQueueBackPressureSize: number) {
5b49e864 60 this.checkWorkerNodeArguments(worker, tasksQueueBackPressureSize)
4b628b48 61 this.worker = worker
75de9f41 62 this.info = this.initWorkerInfo(worker)
26fb3c18 63 this.usage = this.initWorkerUsage()
75de9f41 64 if (this.info.type === WorkerTypes.thread) {
7884d183
JB
65 this.messageChannel = new MessageChannel()
66 }
20c6f652 67 this.tasksQueueBackPressureSize = tasksQueueBackPressureSize
26fb3c18 68 this.tasksQueue = new Deque<Task<Data>>()
47352846 69 this.onBackPressureStarted = false
68cbdc84 70 this.onEmptyQueueCount = 0
26fb3c18 71 this.taskFunctionsUsage = new Map<string, WorkerUsage>()
4b628b48
JB
72 }
73
74 /** @inheritdoc */
75 public tasksQueueSize (): number {
76 return this.tasksQueue.size
77 }
78
4b628b48
JB
79 /** @inheritdoc */
80 public enqueueTask (task: Task<Data>): number {
72695f86 81 const tasksQueueSize = this.tasksQueue.push(task)
47352846
JB
82 if (
83 this.onBackPressure != null &&
84 this.hasBackPressure() &&
85 !this.onBackPressureStarted
86 ) {
87 this.onBackPressureStarted = true
0741fbeb 88 this.onBackPressure(this.info.id as number)
47352846 89 this.onBackPressureStarted = false
72695f86
JB
90 }
91 return tasksQueueSize
92 }
93
94 /** @inheritdoc */
95 public unshiftTask (task: Task<Data>): number {
96 const tasksQueueSize = this.tasksQueue.unshift(task)
47352846
JB
97 if (
98 this.onBackPressure != null &&
99 this.hasBackPressure() &&
100 !this.onBackPressureStarted
101 ) {
102 this.onBackPressureStarted = true
0741fbeb 103 this.onBackPressure(this.info.id as number)
47352846 104 this.onBackPressureStarted = false
72695f86
JB
105 }
106 return tasksQueueSize
4b628b48
JB
107 }
108
109 /** @inheritdoc */
110 public dequeueTask (): Task<Data> | undefined {
dd951876 111 const task = this.tasksQueue.shift()
47352846
JB
112 if (
113 this.onEmptyQueue != null &&
114 this.tasksQueue.size === 0 &&
115 this.onEmptyQueueCount === 0
116 ) {
68cbdc84 117 this.startOnEmptyQueue().catch(EMPTY_FUNCTION)
dd951876
JB
118 }
119 return task
4b628b48
JB
120 }
121
72695f86
JB
122 /** @inheritdoc */
123 public popTask (): Task<Data> | undefined {
dd951876 124 const task = this.tasksQueue.pop()
47352846
JB
125 if (
126 this.onEmptyQueue != null &&
127 this.tasksQueue.size === 0 &&
128 this.onEmptyQueueCount === 0
129 ) {
68cbdc84 130 this.startOnEmptyQueue().catch(EMPTY_FUNCTION)
dd951876
JB
131 }
132 return task
72695f86
JB
133 }
134
4b628b48
JB
135 /** @inheritdoc */
136 public clearTasksQueue (): void {
137 this.tasksQueue.clear()
138 }
139
671d5154
JB
140 /** @inheritdoc */
141 public hasBackPressure (): boolean {
8735b4e5 142 return this.tasksQueue.size >= this.tasksQueueBackPressureSize
671d5154
JB
143 }
144
ff128cc9 145 /** @inheritdoc */
4b628b48
JB
146 public resetUsage (): void {
147 this.usage = this.initWorkerUsage()
db0e38ee 148 this.taskFunctionsUsage.clear()
ff128cc9
JB
149 }
150
3f09ed9f
JB
151 /** @inheritdoc */
152 public closeChannel (): void {
7884d183
JB
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
3f09ed9f
JB
159 }
160 }
161
ff128cc9 162 /** @inheritdoc */
db0e38ee 163 public getTaskFunctionWorkerUsage (name: string): WorkerUsage | undefined {
a5d15204 164 if (!Array.isArray(this.info.taskFunctions)) {
71b2b6d8 165 throw new Error(
db0e38ee 166 `Cannot get task function worker usage for task function name '${name}' when task function names list is not yet defined`
71b2b6d8
JB
167 )
168 }
b558f6b5 169 if (
71b2b6d8 170 Array.isArray(this.info.taskFunctions) &&
db0e38ee 171 this.info.taskFunctions.length < 3
b558f6b5 172 ) {
db0e38ee
JB
173 throw new Error(
174 `Cannot get task function worker usage for task function name '${name}' when task function names list has less than 3 elements`
175 )
176 }
177 if (name === DEFAULT_TASK_NAME) {
71b2b6d8 178 name = this.info.taskFunctions[1]
b558f6b5 179 }
db0e38ee
JB
180 if (!this.taskFunctionsUsage.has(name)) {
181 this.taskFunctionsUsage.set(name, this.initTaskFunctionWorkerUsage(name))
ff128cc9 182 }
db0e38ee 183 return this.taskFunctionsUsage.get(name)
4b628b48
JB
184 }
185
68cbdc84 186 private async startOnEmptyQueue (): Promise<void> {
1f0766e7
JB
187 if (
188 this.onEmptyQueueCount > 0 &&
79b197bb 189 (this.usage.tasks.executing > 0 || this.tasksQueue.size > 0)
1f0766e7 190 ) {
60b7a7cc
JB
191 this.onEmptyQueueCount = 0
192 return
193 }
60b7a7cc 194 ++this.onEmptyQueueCount
47352846 195 this.onEmptyQueue?.(this.info.id as number)
60b7a7cc
JB
196 await sleep(exponentialDelay(this.onEmptyQueueCount))
197 await this.startOnEmptyQueue()
68cbdc84
JB
198 }
199
75de9f41 200 private initWorkerInfo (worker: Worker): WorkerInfo {
4b628b48 201 return {
75de9f41
JB
202 id: getWorkerId(worker),
203 type: getWorkerType(worker) as WorkerType,
4b628b48 204 dynamic: false,
7884d183 205 ready: false
4b628b48
JB
206 }
207 }
208
209 private initWorkerUsage (): WorkerUsage {
210 const getTasksQueueSize = (): number => {
dd951876 211 return this.tasksQueue.size
4b628b48 212 }
bf4ef2ca 213 const getTasksQueueMaxSize = (): number => {
dd951876 214 return this.tasksQueue.maxSize
4b628b48
JB
215 }
216 return {
217 tasks: {
218 executed: 0,
219 executing: 0,
220 get queued (): number {
221 return getTasksQueueSize()
222 },
223 get maxQueued (): number {
bf4ef2ca 224 return getTasksQueueMaxSize()
4b628b48 225 },
68cbdc84 226 stolen: 0,
4b628b48
JB
227 failed: 0
228 },
229 runTime: {
230 history: new CircularArray()
231 },
232 waitTime: {
233 history: new CircularArray()
234 },
235 elu: {
236 idle: {
237 history: new CircularArray()
238 },
239 active: {
240 history: new CircularArray()
241 }
242 }
243 }
244 }
245
db0e38ee 246 private initTaskFunctionWorkerUsage (name: string): WorkerUsage {
e5ece61d
JB
247 const getTaskFunctionQueueSize = (): number => {
248 let taskFunctionQueueSize = 0
b25a42cd 249 for (const task of this.tasksQueue) {
dd92a715 250 if (
e5ece61d
JB
251 (task.name === DEFAULT_TASK_NAME &&
252 name === (this.info.taskFunctions as string[])[1]) ||
253 (task.name !== DEFAULT_TASK_NAME && name === task.name)
dd92a715 254 ) {
e5ece61d 255 ++taskFunctionQueueSize
b25a42cd
JB
256 }
257 }
e5ece61d 258 return taskFunctionQueueSize
b25a42cd
JB
259 }
260 return {
261 tasks: {
262 executed: 0,
263 executing: 0,
264 get queued (): number {
e5ece61d 265 return getTaskFunctionQueueSize()
b25a42cd 266 },
68cbdc84 267 stolen: 0,
b25a42cd
JB
268 failed: 0
269 },
270 runTime: {
271 history: new CircularArray()
272 },
273 waitTime: {
274 history: new CircularArray()
275 },
276 elu: {
277 idle: {
278 history: new CircularArray()
279 },
280 active: {
281 history: new CircularArray()
282 }
283 }
284 }
285 }
5b49e864
JB
286
287 private checkWorkerNodeArguments (
288 worker: Worker,
289 tasksQueueBackPressureSize: number
290 ): void {
291 if (worker == null) {
292 throw new TypeError('Cannot construct a worker node without a worker')
293 }
294 if (tasksQueueBackPressureSize == null) {
295 throw new TypeError(
296 'Cannot construct a worker node without a tasks queue back pressure size'
297 )
298 }
299 if (!Number.isSafeInteger(tasksQueueBackPressureSize)) {
300 throw new TypeError(
301 'Cannot construct a worker node with a tasks queue back pressure size that is not an integer'
302 )
303 }
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'
307 )
308 }
309 }
4b628b48 310}