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