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