fix: fix queued tasks rescheduling
[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'
c3f0a074 4import { DEFAULT_TASK_NAME, once } from '../utils'
574b351d 5import { Deque } from '../deque'
4b628b48
JB
6import {
7 type IWorker,
8 type IWorkerNode,
4b628b48
JB
9 type WorkerInfo,
10 type WorkerType,
11 WorkerTypes,
12 type WorkerUsage
13} from './worker'
14
60664f48
JB
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 */
4b628b48
JB
21export class WorkerNode<Worker extends IWorker, Data = unknown>
22implements IWorkerNode<Worker, Data> {
671d5154 23 /** @inheritdoc */
4b628b48 24 public readonly worker: Worker
671d5154 25 /** @inheritdoc */
4b628b48 26 public readonly info: WorkerInfo
671d5154 27 /** @inheritdoc */
7884d183 28 public messageChannel?: MessageChannel
671d5154 29 /** @inheritdoc */
4b628b48 30 public usage: WorkerUsage
20c6f652
JB
31 /** @inheritdoc */
32 public tasksQueueBackPressureSize: number
72695f86
JB
33 /** @inheritdoc */
34 public onBackPressure?: (workerId: number) => void
dd951876
JB
35 /** @inheritdoc */
36 public onEmptyQueue?: (workerId: number) => void
db0e38ee 37 private readonly taskFunctionsUsage: Map<string, WorkerUsage>
574b351d 38 private readonly tasksQueue: Deque<Task<Data>>
4b628b48 39
60664f48
JB
40 /**
41 * Constructs a new worker node.
42 *
43 * @param worker - The worker.
44 * @param workerType - The worker type.
20c6f652 45 * @param tasksQueueBackPressureSize - The tasks queue back pressure size.
60664f48 46 */
20c6f652
JB
47 constructor (
48 worker: Worker,
49 workerType: WorkerType,
50 tasksQueueBackPressureSize: number
51 ) {
8735b4e5 52 if (worker == null) {
e695d66f 53 throw new TypeError('Cannot construct a worker node without a worker')
8735b4e5
JB
54 }
55 if (workerType == null) {
e695d66f
JB
56 throw new TypeError(
57 'Cannot construct a worker node without a worker type'
58 )
8735b4e5 59 }
20c6f652 60 if (tasksQueueBackPressureSize == null) {
e695d66f 61 throw new TypeError(
20c6f652 62 'Cannot construct a worker node without a tasks queue back pressure size'
8735b4e5
JB
63 )
64 }
20c6f652 65 if (!Number.isSafeInteger(tasksQueueBackPressureSize)) {
e695d66f 66 throw new TypeError(
20c6f652 67 'Cannot construct a worker node with a tasks queue back pressure size that is not an integer'
8735b4e5
JB
68 )
69 }
4b628b48
JB
70 this.worker = worker
71 this.info = this.initWorkerInfo(worker, workerType)
7884d183
JB
72 if (workerType === WorkerTypes.thread) {
73 this.messageChannel = new MessageChannel()
74 }
4b628b48 75 this.usage = this.initWorkerUsage()
db0e38ee 76 this.taskFunctionsUsage = new Map<string, WorkerUsage>()
574b351d 77 this.tasksQueue = new Deque<Task<Data>>()
20c6f652 78 this.tasksQueueBackPressureSize = tasksQueueBackPressureSize
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()) {
f7426dd9 90 once(this.onBackPressure, this)(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()) {
f7426dd9 99 once(this.onBackPressure, this)(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) {
108 once(this.onEmptyQueue, this)(this.info.id as number)
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) {
117 once(this.onEmptyQueue, this)(this.info.id as number)
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
173 private initWorkerInfo (worker: Worker, workerType: WorkerType): WorkerInfo {
174 return {
175 id: this.getWorkerId(worker, workerType),
176 type: workerType,
177 dynamic: false,
7884d183 178 ready: false
4b628b48
JB
179 }
180 }
181
182 private initWorkerUsage (): WorkerUsage {
183 const getTasksQueueSize = (): number => {
dd951876 184 return this.tasksQueue.size
4b628b48 185 }
bf4ef2ca 186 const getTasksQueueMaxSize = (): number => {
dd951876 187 return this.tasksQueue.maxSize
4b628b48
JB
188 }
189 return {
190 tasks: {
191 executed: 0,
192 executing: 0,
193 get queued (): number {
194 return getTasksQueueSize()
195 },
196 get maxQueued (): number {
bf4ef2ca 197 return getTasksQueueMaxSize()
4b628b48
JB
198 },
199 failed: 0
200 },
201 runTime: {
202 history: new CircularArray()
203 },
204 waitTime: {
205 history: new CircularArray()
206 },
207 elu: {
208 idle: {
209 history: new CircularArray()
210 },
211 active: {
212 history: new CircularArray()
213 }
214 }
215 }
216 }
217
db0e38ee 218 private initTaskFunctionWorkerUsage (name: string): WorkerUsage {
e5ece61d
JB
219 const getTaskFunctionQueueSize = (): number => {
220 let taskFunctionQueueSize = 0
b25a42cd 221 for (const task of this.tasksQueue) {
dd92a715 222 if (
e5ece61d
JB
223 (task.name === DEFAULT_TASK_NAME &&
224 name === (this.info.taskFunctions as string[])[1]) ||
225 (task.name !== DEFAULT_TASK_NAME && name === task.name)
dd92a715 226 ) {
e5ece61d 227 ++taskFunctionQueueSize
b25a42cd
JB
228 }
229 }
e5ece61d 230 return taskFunctionQueueSize
b25a42cd
JB
231 }
232 return {
233 tasks: {
234 executed: 0,
235 executing: 0,
236 get queued (): number {
e5ece61d 237 return getTaskFunctionQueueSize()
b25a42cd
JB
238 },
239 failed: 0
240 },
241 runTime: {
242 history: new CircularArray()
243 },
244 waitTime: {
245 history: new CircularArray()
246 },
247 elu: {
248 idle: {
249 history: new CircularArray()
250 },
251 active: {
252 history: new CircularArray()
253 }
254 }
255 }
256 }
257
4b628b48
JB
258 /**
259 * Gets the worker id.
260 *
261 * @param worker - The worker.
60664f48 262 * @param workerType - The worker type.
4b628b48
JB
263 * @returns The worker id.
264 */
265 private getWorkerId (
266 worker: Worker,
267 workerType: WorkerType
268 ): number | undefined {
269 if (workerType === WorkerTypes.thread) {
270 return worker.threadId
271 } else if (workerType === WorkerTypes.cluster) {
272 return worker.id
273 }
274 }
275}