fix: ensure worker choice is retried at least the pool max size
[poolifier.git] / src / utils.ts
CommitLineData
aa4bf4b2 1import * as os from 'node:os'
304d379e 2import { getRandomValues } from 'node:crypto'
75de9f41
JB
3import { Worker as ClusterWorker } from 'node:cluster'
4import { Worker as ThreadWorker } from 'node:worker_threads'
3c93feb9 5import type {
26ce26ca
JB
6 InternalWorkerChoiceStrategyOptions,
7 MeasurementStatisticsRequirements
3c93feb9 8} from './pools/selection-strategies/selection-strategies-types'
59317253 9import type { KillBehavior } from './worker/worker-options'
bfc75cca 10import { type IWorker, type WorkerType, WorkerTypes } from './pools/worker'
bbeadd16 11
ff128cc9
JB
12/**
13 * Default task name.
14 */
15export const DEFAULT_TASK_NAME = 'default'
16
6e9d10db
JB
17/**
18 * An intentional empty function.
19 */
4f3c3d89 20export const EMPTY_FUNCTION: () => void = Object.freeze(() => {
6e9d10db 21 /* Intentionally empty */
4f3c3d89 22})
78099a15
JB
23
24/**
bbeadd16 25 * Default worker choice strategy options.
26ce26ca
JB
26 *
27 * @param poolMaxSize - The pool maximum size.
28 * @returns The default worker choice strategy options.
bbeadd16 29 */
26ce26ca
JB
30export const getDefaultInternalWorkerChoiceStrategyOptions = (
31 poolMaxSize: number
32): InternalWorkerChoiceStrategyOptions => {
33 return {
34 retries: poolMaxSize,
932fc8be 35 runTime: { median: false },
5df69fab
JB
36 waitTime: { median: false },
37 elu: { median: false }
bbeadd16 38 }
26ce26ca 39}
bbeadd16 40
3c93feb9
JB
41/**
42 * Default measurement statistics requirements.
43 */
44export const DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS: MeasurementStatisticsRequirements =
45 {
46 aggregate: false,
47 average: false,
48 median: false
49 }
50
51474716 51/**
ab80dc46
JB
52 * Returns safe host OS optimized estimate of the default amount of parallelism a pool should use.
53 * Always returns a value greater than zero.
54 *
55 * @returns The host OS optimized maximum pool size.
51474716
JB
56 */
57export const availableParallelism = (): number => {
58 let availableParallelism = 1
59 try {
aa4bf4b2 60 availableParallelism = os.availableParallelism()
51474716 61 } catch {
562a4037
JB
62 const cpus = os.cpus()
63 if (Array.isArray(cpus) && cpus.length > 0) {
64 availableParallelism = cpus.length
51474716
JB
65 }
66 }
67 return availableParallelism
68}
69
9fe8fd69
JB
70/**
71 * Returns the worker type of the given worker.
72 *
73 * @param worker - The worker to get the type of.
74 * @returns The worker type of the given worker.
75 * @internal
76 */
187601ff 77export const getWorkerType = (worker: IWorker): WorkerType | undefined => {
9fe8fd69
JB
78 if (worker instanceof ThreadWorker) {
79 return WorkerTypes.thread
80 } else if (worker instanceof ClusterWorker) {
81 return WorkerTypes.cluster
82 }
83}
84
85/**
86 * Returns the worker id of the given worker.
87 *
88 * @param worker - The worker to get the id of.
89 * @returns The worker id of the given worker.
90 * @internal
91 */
187601ff 92export const getWorkerId = (worker: IWorker): number | undefined => {
9fe8fd69
JB
93 if (worker instanceof ThreadWorker) {
94 return worker.threadId
95 } else if (worker instanceof ClusterWorker) {
96 return worker.id
97 }
98}
99
68cbdc84
JB
100/**
101 * Sleeps for the given amount of milliseconds.
102 *
103 * @param ms - The amount of milliseconds to sleep.
104 * @returns A promise that resolves after the given amount of milliseconds.
57a29f75 105 * @internal
68cbdc84
JB
106 */
107export const sleep = async (ms: number): Promise<void> => {
041dc05b 108 await new Promise(resolve => {
68cbdc84
JB
109 setTimeout(resolve, ms)
110 })
111}
112
113/**
114 * Computes the retry delay in milliseconds using an exponential back off algorithm.
115 *
116 * @param retryNumber - The number of retries that have already been attempted
147be6fe 117 * @param delayFactor - The base delay factor in milliseconds
68cbdc84
JB
118 * @returns Delay in milliseconds
119 * @internal
120 */
121export const exponentialDelay = (
122 retryNumber = 0,
147be6fe 123 delayFactor = 100
68cbdc84 124): number => {
147be6fe
JB
125 const delay = Math.pow(2, retryNumber) * delayFactor
126 const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay
68cbdc84
JB
127 return delay + randomSum
128}
8990357d 129
dc021bcc
JB
130/**
131 * Computes the average of the given data set.
132 *
133 * @param dataSet - Data set.
134 * @returns The average of the given data set.
135 * @internal
136 */
137export const average = (dataSet: number[]): number => {
138 if (Array.isArray(dataSet) && dataSet.length === 0) {
139 return 0
140 }
141 if (Array.isArray(dataSet) && dataSet.length === 1) {
142 return dataSet[0]
143 }
144 return (
145 dataSet.reduce((accumulator, number) => accumulator + number, 0) /
146 dataSet.length
147 )
148}
149
bbeadd16 150/**
afe0d5bf 151 * Computes the median of the given data set.
78099a15
JB
152 *
153 * @param dataSet - Data set.
154 * @returns The median of the given data set.
4bffc062 155 * @internal
78099a15
JB
156 */
157export const median = (dataSet: number[]): number => {
4a45e8d2
JB
158 if (Array.isArray(dataSet) && dataSet.length === 0) {
159 return 0
160 }
78099a15
JB
161 if (Array.isArray(dataSet) && dataSet.length === 1) {
162 return dataSet[0]
163 }
c6f42dd6
JB
164 const sortedDataSet = dataSet.slice().sort((a, b) => a - b)
165 return (
166 (sortedDataSet[(sortedDataSet.length - 1) >> 1] +
167 sortedDataSet[sortedDataSet.length >> 1]) /
168 2
169 )
78099a15 170}
0d80593b 171
afe0d5bf
JB
172/**
173 * Rounds the given number to the given scale.
64383951 174 * The rounding is done using the "round half away from zero" method.
afe0d5bf
JB
175 *
176 * @param num - The number to round.
177 * @param scale - The scale to round to.
178 * @returns The rounded number.
57a29f75 179 * @internal
afe0d5bf
JB
180 */
181export const round = (num: number, scale = 2): number => {
182 const rounder = Math.pow(10, scale)
183 return Math.round(num * rounder * (1 + Number.EPSILON)) / rounder
184}
185
3c653a03
JB
186/**
187 * Is the given object a plain object?
188 *
189 * @param obj - The object to check.
190 * @returns `true` if the given object is a plain object, `false` otherwise.
57a29f75 191 * @internal
3c653a03 192 */
0d80593b
JB
193export const isPlainObject = (obj: unknown): boolean =>
194 typeof obj === 'object' &&
195 obj !== null &&
196 obj?.constructor === Object &&
197 Object.prototype.toString.call(obj) === '[object Object]'
59317253
JB
198
199/**
200 * Detects whether the given value is a kill behavior or not.
201 *
202 * @typeParam KB - Which specific KillBehavior type to test against.
203 * @param killBehavior - Which kind of kill behavior to detect.
204 * @param value - Any value.
205 * @returns `true` if `value` was strictly equals to `killBehavior`, otherwise `false`.
4bffc062 206 * @internal
59317253
JB
207 */
208export const isKillBehavior = <KB extends KillBehavior>(
209 killBehavior: KB,
210 value: unknown
211): value is KB => {
212 return value === killBehavior
213}
49d1b48c
JB
214
215/**
216 * Detects whether the given value is an asynchronous function or not.
217 *
218 * @param fn - Any value.
219 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
57a29f75 220 * @internal
49d1b48c
JB
221 */
222export const isAsyncFunction = (
223 fn: unknown
224): fn is (...args: unknown[]) => Promise<unknown> => {
225 return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction'
226}
e4f20deb 227
68cbdc84 228/**
57a29f75 229 * Generates a cryptographically secure random number in the [0,1[ range
68cbdc84
JB
230 *
231 * @returns A number in the [0,1[ range
57a29f75 232 * @internal
68cbdc84 233 */
970b38d6 234export const secureRandom = (): number => {
304d379e 235 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
68cbdc84 236}
68e7ed58 237
57a29f75
JB
238/**
239 * Returns the minimum of the given numbers.
240 * If no numbers are given, `Infinity` is returned.
241 *
242 * @param args - The numbers to get the minimum of.
243 * @returns The minimum of the given numbers.
244 * @internal
245 */
90d6701c
JB
246export const min = (...args: number[]): number =>
247 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity)
248
57a29f75
JB
249/**
250 * Returns the maximum of the given numbers.
251 * If no numbers are given, `-Infinity` is returned.
252 *
253 * @param args - The numbers to get the maximum of.
254 * @returns The maximum of the given numbers.
255 * @internal
256 */
90d6701c
JB
257export const max = (...args: number[]): number =>
258 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity)
d91689fd
JB
259
260/**
261 * Wraps a function so that it can only be called once.
262 *
263 * @param fn - The function to wrap.
264 * @param context - The context to bind the function to.
265 * @returns The wrapped function.
266 * @internal
267 */
268// eslint-disable-next-line @typescript-eslint/no-explicit-any
269export const once = <T, A extends any[], R>(
270 fn: (...args: A) => R,
271 context: T
272): ((...args: A) => R) => {
273 let result: R
274 return (...args: A) => {
275 if (fn != null) {
276 result = fn.apply<T, A, R>(context, args)
277 ;(fn as unknown as undefined) = (context as unknown as undefined) =
278 undefined
279 }
280 return result
281 }
282}