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