a33758ce64c1ad72890b8d6e8b40b96336316c65
[poolifier.git] / src / utils.ts
1 import * as os from 'node:os'
2 import { getRandomValues } from 'node:crypto'
3 import type { KillBehavior } from './worker/worker-options.js'
4
5 /**
6 * Default task name.
7 */
8 export const DEFAULT_TASK_NAME = 'default'
9
10 /**
11 * An intentional empty function.
12 */
13 export const EMPTY_FUNCTION: () => void = Object.freeze(() => {
14 /* Intentionally empty */
15 })
16
17 /**
18 * Returns safe host OS optimized estimate of the default amount of parallelism a pool should use.
19 * Always returns a value greater than zero.
20 *
21 * @returns The host OS optimized maximum pool size.
22 */
23 export const availableParallelism = (): number => {
24 let availableParallelism = 1
25 try {
26 availableParallelism = os.availableParallelism()
27 } catch {
28 const cpus = os.cpus()
29 if (Array.isArray(cpus) && cpus.length > 0) {
30 availableParallelism = cpus.length
31 }
32 }
33 return availableParallelism
34 }
35
36 /**
37 * Sleeps for the given amount of milliseconds.
38 *
39 * @param ms - The amount of milliseconds to sleep.
40 * @returns A promise that resolves after the given amount of milliseconds.
41 * @internal
42 */
43 export const sleep = async (ms: number): Promise<void> => {
44 await new Promise(resolve => {
45 setTimeout(resolve, ms)
46 })
47 }
48
49 /**
50 * Computes the retry delay in milliseconds using an exponential back off algorithm.
51 *
52 * @param retryNumber - The number of retries that have already been attempted
53 * @param delayFactor - The base delay factor in milliseconds
54 * @returns Delay in milliseconds
55 * @internal
56 */
57 export const exponentialDelay = (
58 retryNumber = 0,
59 delayFactor = 100
60 ): number => {
61 const delay = Math.pow(2, retryNumber) * delayFactor
62 const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay
63 return delay + randomSum
64 }
65
66 /**
67 * Computes the average of the given data set.
68 *
69 * @param dataSet - Data set.
70 * @returns The average of the given data set.
71 * @internal
72 */
73 export const average = (dataSet: number[]): number => {
74 if (Array.isArray(dataSet) && dataSet.length === 0) {
75 return 0
76 } else if (Array.isArray(dataSet) && dataSet.length === 1) {
77 return dataSet[0]
78 }
79 return (
80 dataSet.reduce((accumulator, number) => accumulator + number, 0) /
81 dataSet.length
82 )
83 }
84
85 /**
86 * Computes the median of the given data set.
87 *
88 * @param dataSet - Data set.
89 * @returns The median of the given data set.
90 * @internal
91 */
92 export const median = (dataSet: number[]): number => {
93 if (Array.isArray(dataSet) && dataSet.length === 0) {
94 return 0
95 } else if (Array.isArray(dataSet) && dataSet.length === 1) {
96 return dataSet[0]
97 }
98 const sortedDataSet = dataSet.slice().sort((a, b) => a - b)
99 return (
100 (sortedDataSet[(sortedDataSet.length - 1) >> 1] +
101 sortedDataSet[sortedDataSet.length >> 1]) /
102 2
103 )
104 }
105
106 /**
107 * Rounds the given number to the given scale.
108 * The rounding is done using the "round half away from zero" method.
109 *
110 * @param num - The number to round.
111 * @param scale - The scale to round to.
112 * @returns The rounded number.
113 * @internal
114 */
115 export const round = (num: number, scale = 2): number => {
116 const rounder = Math.pow(10, scale)
117 return Math.round(num * rounder * (1 + Number.EPSILON)) / rounder
118 }
119
120 /**
121 * Is the given value a plain object?
122 *
123 * @param value - The value to check.
124 * @returns `true` if the given value is a plain object, `false` otherwise.
125 * @internal
126 */
127 export const isPlainObject = (value: unknown): value is object =>
128 typeof value === 'object' &&
129 value !== null &&
130 value.constructor === Object &&
131 Object.prototype.toString.call(value) === '[object Object]'
132
133 /**
134 * Detects whether the given value is a kill behavior or not.
135 *
136 * @typeParam KB - Which specific KillBehavior type to test against.
137 * @param killBehavior - Which kind of kill behavior to detect.
138 * @param value - Unknown value.
139 * @returns `true` if `value` was strictly equals to `killBehavior`, otherwise `false`.
140 * @internal
141 */
142 export const isKillBehavior = <KB extends KillBehavior>(
143 killBehavior: KB,
144 value: unknown
145 ): value is KB => {
146 return value === killBehavior
147 }
148
149 /**
150 * Detects whether the given value is an asynchronous function or not.
151 *
152 * @param fn - Unknown value.
153 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
154 * @internal
155 */
156 export const isAsyncFunction = (
157 fn: unknown
158 ): fn is (...args: unknown[]) => Promise<unknown> => {
159 return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction'
160 }
161
162 /**
163 * Generates a cryptographically secure random number in the [0,1[ range
164 *
165 * @returns A number in the [0,1[ range
166 * @internal
167 */
168 export const secureRandom = (): number => {
169 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
170 }
171
172 /**
173 * Returns the minimum of the given numbers.
174 * If no numbers are given, `Infinity` is returned.
175 *
176 * @param args - The numbers to get the minimum of.
177 * @returns The minimum of the given numbers.
178 * @internal
179 */
180 export const min = (...args: number[]): number =>
181 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity)
182
183 /**
184 * Returns the maximum of the given numbers.
185 * If no numbers are given, `-Infinity` is returned.
186 *
187 * @param args - The numbers to get the maximum of.
188 * @returns The maximum of the given numbers.
189 * @internal
190 */
191 export const max = (...args: number[]): number =>
192 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity)
193
194 /**
195 * Wraps a function so that it can only be called once.
196 *
197 * @param fn - The function to wrap.
198 * @param context - The context to bind the function to.
199 * @returns The wrapped function.
200 * @internal
201 */
202 // eslint-disable-next-line @typescript-eslint/no-explicit-any
203 export const once = <T, A extends any[], R>(
204 fn: (...args: A) => R,
205 context: T
206 ): ((...args: A) => R) => {
207 let result: R
208 return (...args: A) => {
209 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
210 if (fn != null) {
211 result = fn.apply<T, A, R>(context, args)
212 ;(fn as unknown as undefined) = (context as unknown as undefined) =
213 undefined
214 }
215 return result
216 }
217 }