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