---
[poolifier.git] / src / utils.ts
... / ...
CommitLineData
1import { getRandomValues } from 'node:crypto'
2import * as os from 'node:os'
3
4import type { TaskFunctionProperties } from './utility-types.js'
5import type { TaskFunctionObject } from './worker/task-functions.js'
6import type { KillBehavior } from './worker/worker-options.js'
7
8/**
9 * Default task name.
10 */
11export const DEFAULT_TASK_NAME = 'default'
12
13/**
14 * An intentional empty function.
15 */
16export const EMPTY_FUNCTION: () => void = Object.freeze(() => {
17 /* Intentionally empty */
18})
19
20/**
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.
25 */
26export const availableParallelism = (): number => {
27 let availableParallelism = 1
28 try {
29 availableParallelism = os.availableParallelism()
30 } catch {
31 const cpus = os.cpus()
32 if (Array.isArray(cpus) && cpus.length > 0) {
33 availableParallelism = cpus.length
34 }
35 }
36 return availableParallelism
37}
38
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.
44 * @internal
45 */
46export const sleep = async (ms: number): Promise<void> => {
47 await new Promise(resolve => {
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
56 * @param delayFactor - The base delay factor in milliseconds
57 * @returns Delay in milliseconds
58 * @internal
59 */
60export const exponentialDelay = (
61 retryNumber = 0,
62 delayFactor = 100
63): number => {
64 const delay = Math.pow(2, retryNumber) * delayFactor
65 const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay
66 return delay + randomSum
67}
68
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
79 } else if (Array.isArray(dataSet) && dataSet.length === 1) {
80 return dataSet[0]
81 }
82 return (
83 dataSet.reduce((accumulator, number) => accumulator + number, 0) /
84 dataSet.length
85 )
86}
87
88/**
89 * Computes the median of the given data set.
90 *
91 * @param dataSet - Data set.
92 * @returns The median of the given data set.
93 * @internal
94 */
95export const median = (dataSet: number[]): number => {
96 if (Array.isArray(dataSet) && dataSet.length === 0) {
97 return 0
98 } else if (Array.isArray(dataSet) && dataSet.length === 1) {
99 return dataSet[0]
100 }
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 )
107}
108
109/**
110 * Rounds the given number to the given scale.
111 * The rounding is done using the "round half away from zero" method.
112 *
113 * @param num - The number to round.
114 * @param scale - The scale to round to.
115 * @returns The rounded number.
116 * @internal
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
123/**
124 * Is the given value a plain object?
125 *
126 * @param value - The value to check.
127 * @returns `true` if the given value is a plain object, `false` otherwise.
128 * @internal
129 */
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]'
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.
141 * @param value - Unknown value.
142 * @returns `true` if `value` was strictly equals to `killBehavior`, otherwise `false`.
143 * @internal
144 */
145export const isKillBehavior = <KB extends KillBehavior>(
146 killBehavior: KB,
147 value: unknown
148): value is KB => {
149 return value === killBehavior
150}
151
152/**
153 * Detects whether the given value is an asynchronous function or not.
154 *
155 * @param fn - Unknown value.
156 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
157 * @internal
158 */
159export const isAsyncFunction = (
160 fn: unknown
161): fn is (...args: unknown[]) => Promise<unknown> => {
162 return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction'
163}
164
165/**
166 * Generates a cryptographically secure random number in the [0,1[ range
167 *
168 * @returns A number in the [0,1[ range
169 * @internal
170 */
171export const secureRandom = (): number => {
172 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
173}
174
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 */
183export const min = (...args: number[]): number =>
184 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity)
185
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 */
194export const max = (...args: number[]): number =>
195 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity)
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.
203 *
204 * @typeParam A - The function's arguments.
205 * @typeParam R - The function's return value.
206 * @typeParam C - The function's context.
207 * @internal
208 */
209// eslint-disable-next-line @typescript-eslint/no-explicit-any
210export const once = <A extends any[], R, C extends ThisType<any>>(
211 fn: (...args: A) => R,
212 context: C
213): ((...args: A) => R) => {
214 let result: R
215 return (...args: A) => {
216 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
217 if (fn != null) {
218 result = fn.apply<C, A, R>(context, args)
219 ;(fn as unknown as undefined) = (context as unknown as undefined) =
220 undefined
221 }
222 return result
223 }
224}
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}