1 import { existsSync
} from
'node:fs'
2 import cluster from
'node:cluster'
3 import { SHARE_ENV
, Worker
, type WorkerOptions
} from
'node:worker_threads'
4 import { env
} from
'node:process'
5 import { average
, isPlainObject
, max
, median
, min
} from
'../utils'
6 import type { MessageValue
, Task
} from
'../utility-types'
8 type MeasurementStatisticsRequirements
,
9 WorkerChoiceStrategies
,
10 type WorkerChoiceStrategy
11 } from
'./selection-strategies/selection-strategies-types'
12 import type { TasksQueueOptions
} from
'./pool'
16 type MeasurementStatistics
,
17 type WorkerNodeOptions
,
22 import type { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
24 export const getDefaultTasksQueueOptions
= (
26 ): Required
<TasksQueueOptions
> => {
28 size
: Math.pow(poolMaxSize
, 2),
31 tasksStealingOnBackPressure
: true,
32 tasksFinishedTimeout
: 2000
36 export const checkFilePath
= (filePath
: string): void => {
37 if (filePath
== null) {
38 throw new TypeError('The worker file path must be specified')
40 if (typeof filePath
!== 'string') {
41 throw new TypeError('The worker file path must be a string')
43 if (!existsSync(filePath
)) {
44 throw new Error(`Cannot find the worker file '${filePath}'`)
48 export const checkDynamicPoolSize
= (min
: number, max
: number): void => {
51 'Cannot instantiate a dynamic pool without specifying the maximum pool size'
53 } else if (!Number.isSafeInteger(max
)) {
55 'Cannot instantiate a dynamic pool with a non safe integer maximum pool size'
57 } else if (min
> max
) {
59 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
61 } else if (max
=== 0) {
63 'Cannot instantiate a dynamic pool with a maximum pool size equal to zero'
65 } else if (min
=== max
) {
67 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
72 export const checkValidWorkerChoiceStrategy
= (
73 workerChoiceStrategy
: WorkerChoiceStrategy
76 workerChoiceStrategy
!= null &&
77 !Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)
79 throw new Error(`Invalid worker choice strategy '${workerChoiceStrategy}'`)
83 export const checkValidTasksQueueOptions
= (
84 tasksQueueOptions
: TasksQueueOptions
86 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
87 throw new TypeError('Invalid tasks queue options: must be a plain object')
90 tasksQueueOptions
?.concurrency
!= null &&
91 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
94 'Invalid worker node tasks concurrency: must be an integer'
98 tasksQueueOptions
?.concurrency
!= null &&
99 tasksQueueOptions
.concurrency
<= 0
101 throw new RangeError(
102 `Invalid worker node tasks concurrency: ${tasksQueueOptions.concurrency} is a negative integer or zero`
106 tasksQueueOptions
?.size
!= null &&
107 !Number.isSafeInteger(tasksQueueOptions
.size
)
110 'Invalid worker node tasks queue size: must be an integer'
113 if (tasksQueueOptions
?.size
!= null && tasksQueueOptions
.size
<= 0) {
114 throw new RangeError(
115 `Invalid worker node tasks queue size: ${tasksQueueOptions.size} is a negative integer or zero`
120 export const checkWorkerNodeArguments
= (
123 opts
: WorkerNodeOptions
126 throw new TypeError('Cannot construct a worker node without a worker type')
128 if (!Object.values(WorkerTypes
).includes(type)) {
130 `Cannot construct a worker node with an invalid worker type '${type}'`
133 checkFilePath(filePath
)
136 'Cannot construct a worker node without worker node options'
139 if (!isPlainObject(opts
)) {
141 'Cannot construct a worker node with invalid options: must be a plain object'
144 if (opts
.tasksQueueBackPressureSize
== null) {
146 'Cannot construct a worker node without a tasks queue back pressure size option'
149 if (!Number.isSafeInteger(opts
.tasksQueueBackPressureSize
)) {
151 'Cannot construct a worker node with a tasks queue back pressure size option that is not an integer'
154 if (opts
.tasksQueueBackPressureSize
<= 0) {
155 throw new RangeError(
156 'Cannot construct a worker node with a tasks queue back pressure size option that is not a positive integer'
162 * Updates the given measurement statistics.
164 * @param measurementStatistics - The measurement statistics to update.
165 * @param measurementRequirements - The measurement statistics requirements.
166 * @param measurementValue - The measurement value.
167 * @param numberOfMeasurements - The number of measurements.
170 const updateMeasurementStatistics
= (
171 measurementStatistics
: MeasurementStatistics
,
172 measurementRequirements
: MeasurementStatisticsRequirements
,
173 measurementValue
: number
175 if (measurementRequirements
.aggregate
) {
176 measurementStatistics
.aggregate
=
177 (measurementStatistics
.aggregate
?? 0) + measurementValue
178 measurementStatistics
.minimum
= min(
180 measurementStatistics
.minimum
?? Infinity
182 measurementStatistics
.maximum
= max(
184 measurementStatistics
.maximum
?? -Infinity
187 (measurementRequirements
.average
|| measurementRequirements
.median
) &&
188 measurementValue
!= null
190 measurementStatistics
.history
.push(measurementValue
)
191 if (measurementRequirements
.average
) {
192 measurementStatistics
.average
= average(measurementStatistics
.history
)
193 } else if (measurementStatistics
.average
!= null) {
194 delete measurementStatistics
.average
196 if (measurementRequirements
.median
) {
197 measurementStatistics
.median
= median(measurementStatistics
.history
)
198 } else if (measurementStatistics
.median
!= null) {
199 delete measurementStatistics
.median
204 if (env
.NODE_ENV
=== 'test') {
205 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
206 exports
.updateMeasurementStatistics
= updateMeasurementStatistics
209 export const updateWaitTimeWorkerUsage
= <
210 Worker
extends IWorker
,
214 workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
219 workerUsage
: WorkerUsage
,
222 const timestamp
= performance
.now()
223 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
224 updateMeasurementStatistics(
225 workerUsage
.waitTime
,
226 workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
231 export const updateTaskStatisticsWorkerUsage
= <Response
= unknown
>(
232 workerUsage
: WorkerUsage
,
233 message
: MessageValue
<Response
>
235 const workerTaskStatistics
= workerUsage
.tasks
237 workerTaskStatistics
.executing
!= null &&
238 workerTaskStatistics
.executing
> 0
240 --workerTaskStatistics
.executing
242 if (message
.workerError
== null) {
243 ++workerTaskStatistics
.executed
245 ++workerTaskStatistics
.failed
249 export const updateRunTimeWorkerUsage
= <
250 Worker
extends IWorker
,
254 workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
259 workerUsage
: WorkerUsage
,
260 message
: MessageValue
<Response
>
262 if (message
.workerError
!= null) {
265 updateMeasurementStatistics(
267 workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
268 message
.taskPerformance
?.runTime
?? 0
272 export const updateEluWorkerUsage
= <
273 Worker
extends IWorker
,
277 workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
282 workerUsage
: WorkerUsage
,
283 message
: MessageValue
<Response
>
285 if (message
.workerError
!= null) {
288 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
289 workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
290 updateMeasurementStatistics(
291 workerUsage
.elu
.active
,
292 eluTaskStatisticsRequirements
,
293 message
.taskPerformance
?.elu
?.active
?? 0
295 updateMeasurementStatistics(
296 workerUsage
.elu
.idle
,
297 eluTaskStatisticsRequirements
,
298 message
.taskPerformance
?.elu
?.idle
?? 0
300 if (eluTaskStatisticsRequirements
.aggregate
) {
301 if (message
.taskPerformance
?.elu
!= null) {
302 if (workerUsage
.elu
.utilization
!= null) {
303 workerUsage
.elu
.utilization
=
304 (workerUsage
.elu
.utilization
+
305 message
.taskPerformance
.elu
.utilization
) /
308 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
314 export const createWorker
= <Worker
extends IWorker
>(
317 opts
: { env
?: Record
<string, unknown
>, workerOptions
?: WorkerOptions
}
320 case WorkerTypes
.thread
:
321 return new Worker(filePath
, {
323 ...opts
?.workerOptions
324 }) as unknown
as Worker
325 case WorkerTypes
.cluster
:
326 return cluster
.fork(opts
?.env
) as unknown
as Worker
328 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
329 throw new Error(`Unknown worker type '${type}'`)
333 export const waitWorkerNodeEvents
= async <
334 Worker
extends IWorker
,
337 workerNode
: IWorkerNode
<Worker
, Data
>,
338 workerNodeEvent
: string,
339 numberOfEventsToWait
: number,
341 ): Promise
<number> => {
342 return await new Promise
<number>(resolve
=> {
344 if (numberOfEventsToWait
=== 0) {
348 workerNode
.on(workerNodeEvent
, () => {
350 if (events
=== numberOfEventsToWait
) {