perf: optimize min/max in hot code path
[poolifier.git] / src / utils.ts
CommitLineData
aa4bf4b2 1import * as os from 'node:os'
98446b39 2import { webcrypto } from 'node:crypto'
75de9f41
JB
3import { Worker as ClusterWorker } from 'node:cluster'
4import { Worker as ThreadWorker } from 'node:worker_threads'
3c93feb9
JB
5import type {
6 MeasurementStatisticsRequirements,
7 WorkerChoiceStrategyOptions
8} from './pools/selection-strategies/selection-strategies-types'
59317253 9import type { KillBehavior } from './worker/worker-options'
75de9f41
JB
10import {
11 type IWorker,
12 type MeasurementStatistics,
13 type WorkerType,
14 WorkerTypes
15} from './pools/worker'
bbeadd16 16
ff128cc9
JB
17/**
18 * Default task name.
19 */
20export const DEFAULT_TASK_NAME = 'default'
21
6e9d10db
JB
22/**
23 * An intentional empty function.
24 */
4f3c3d89 25export const EMPTY_FUNCTION: () => void = Object.freeze(() => {
6e9d10db 26 /* Intentionally empty */
4f3c3d89 27})
78099a15
JB
28
29/**
bbeadd16
JB
30 * Default worker choice strategy options.
31 */
32export const DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS: WorkerChoiceStrategyOptions =
33 {
8c0b113f 34 retries: 6,
932fc8be 35 runTime: { median: false },
5df69fab
JB
36 waitTime: { median: false },
37 elu: { median: false }
bbeadd16
JB
38 }
39
3c93feb9
JB
40/**
41 * Default measurement statistics requirements.
42 */
43export const DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS: MeasurementStatisticsRequirements =
44 {
45 aggregate: false,
46 average: false,
47 median: false
48 }
49
51474716 50/**
ab80dc46
JB
51 * Returns safe host OS optimized estimate of the default amount of parallelism a pool should use.
52 * Always returns a value greater than zero.
53 *
54 * @returns The host OS optimized maximum pool size.
4bffc062 55 * @internal
51474716
JB
56 */
57export const availableParallelism = (): number => {
58 let availableParallelism = 1
59 try {
aa4bf4b2 60 availableParallelism = os.availableParallelism()
51474716 61 } catch {
562a4037
JB
62 const cpus = os.cpus()
63 if (Array.isArray(cpus) && cpus.length > 0) {
64 availableParallelism = cpus.length
51474716
JB
65 }
66 }
67 return availableParallelism
68}
69
9fe8fd69
JB
70/**
71 * Returns the worker type of the given worker.
72 *
73 * @param worker - The worker to get the type of.
74 * @returns The worker type of the given worker.
75 * @internal
76 */
187601ff 77export const getWorkerType = (worker: IWorker): WorkerType | undefined => {
9fe8fd69
JB
78 if (worker instanceof ThreadWorker) {
79 return WorkerTypes.thread
80 } else if (worker instanceof ClusterWorker) {
81 return WorkerTypes.cluster
82 }
83}
84
85/**
86 * Returns the worker id of the given worker.
87 *
88 * @param worker - The worker to get the id of.
89 * @returns The worker id of the given worker.
90 * @internal
91 */
187601ff 92export const getWorkerId = (worker: IWorker): number | undefined => {
9fe8fd69
JB
93 if (worker instanceof ThreadWorker) {
94 return worker.threadId
95 } else if (worker instanceof ClusterWorker) {
96 return worker.id
97 }
98}
99
68cbdc84
JB
100/**
101 * Sleeps for the given amount of milliseconds.
102 *
103 * @param ms - The amount of milliseconds to sleep.
104 * @returns A promise that resolves after the given amount of milliseconds.
105 */
106export const sleep = async (ms: number): Promise<void> => {
107 await new Promise((resolve) => {
108 setTimeout(resolve, ms)
109 })
110}
111
112/**
113 * Computes the retry delay in milliseconds using an exponential back off algorithm.
114 *
115 * @param retryNumber - The number of retries that have already been attempted
147be6fe 116 * @param delayFactor - The base delay factor in milliseconds
68cbdc84
JB
117 * @returns Delay in milliseconds
118 * @internal
119 */
120export const exponentialDelay = (
121 retryNumber = 0,
147be6fe 122 delayFactor = 100
68cbdc84 123): number => {
147be6fe
JB
124 const delay = Math.pow(2, retryNumber) * delayFactor
125 const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay
68cbdc84
JB
126 return delay + randomSum
127}
8990357d 128
dc021bcc
JB
129/**
130 * Computes the average of the given data set.
131 *
132 * @param dataSet - Data set.
133 * @returns The average of the given data set.
134 * @internal
135 */
136export const average = (dataSet: number[]): number => {
137 if (Array.isArray(dataSet) && dataSet.length === 0) {
138 return 0
139 }
140 if (Array.isArray(dataSet) && dataSet.length === 1) {
141 return dataSet[0]
142 }
143 return (
144 dataSet.reduce((accumulator, number) => accumulator + number, 0) /
145 dataSet.length
146 )
147}
148
bbeadd16 149/**
afe0d5bf 150 * Computes the median of the given data set.
78099a15
JB
151 *
152 * @param dataSet - Data set.
153 * @returns The median of the given data set.
4bffc062 154 * @internal
78099a15
JB
155 */
156export const median = (dataSet: number[]): number => {
4a45e8d2
JB
157 if (Array.isArray(dataSet) && dataSet.length === 0) {
158 return 0
159 }
78099a15
JB
160 if (Array.isArray(dataSet) && dataSet.length === 1) {
161 return dataSet[0]
162 }
c6f42dd6
JB
163 const sortedDataSet = dataSet.slice().sort((a, b) => a - b)
164 return (
165 (sortedDataSet[(sortedDataSet.length - 1) >> 1] +
166 sortedDataSet[sortedDataSet.length >> 1]) /
167 2
168 )
78099a15 169}
0d80593b 170
afe0d5bf
JB
171/**
172 * Rounds the given number to the given scale.
64383951 173 * The rounding is done using the "round half away from zero" method.
afe0d5bf
JB
174 *
175 * @param num - The number to round.
176 * @param scale - The scale to round to.
177 * @returns The rounded number.
178 */
179export const round = (num: number, scale = 2): number => {
180 const rounder = Math.pow(10, scale)
181 return Math.round(num * rounder * (1 + Number.EPSILON)) / rounder
182}
183
3c653a03
JB
184/**
185 * Is the given object a plain object?
186 *
187 * @param obj - The object to check.
188 * @returns `true` if the given object is a plain object, `false` otherwise.
189 */
0d80593b
JB
190export const isPlainObject = (obj: unknown): boolean =>
191 typeof obj === 'object' &&
192 obj !== null &&
193 obj?.constructor === Object &&
194 Object.prototype.toString.call(obj) === '[object Object]'
59317253
JB
195
196/**
197 * Detects whether the given value is a kill behavior or not.
198 *
199 * @typeParam KB - Which specific KillBehavior type to test against.
200 * @param killBehavior - Which kind of kill behavior to detect.
201 * @param value - Any value.
202 * @returns `true` if `value` was strictly equals to `killBehavior`, otherwise `false`.
4bffc062 203 * @internal
59317253
JB
204 */
205export const isKillBehavior = <KB extends KillBehavior>(
206 killBehavior: KB,
207 value: unknown
208): value is KB => {
209 return value === killBehavior
210}
49d1b48c
JB
211
212/**
213 * Detects whether the given value is an asynchronous function or not.
214 *
215 * @param fn - Any value.
216 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
217 */
218export const isAsyncFunction = (
219 fn: unknown
220): fn is (...args: unknown[]) => Promise<unknown> => {
221 return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction'
222}
e4f20deb
JB
223
224/**
225 * Updates the given measurement statistics.
226 *
227 * @param measurementStatistics - The measurement statistics to update.
228 * @param measurementRequirements - The measurement statistics requirements.
229 * @param measurementValue - The measurement value.
008512c7 230 * @param numberOfMeasurements - The number of measurements.
4bffc062 231 * @internal
e4f20deb
JB
232 */
233export const updateMeasurementStatistics = (
234 measurementStatistics: MeasurementStatistics,
235 measurementRequirements: MeasurementStatisticsRequirements,
dc021bcc 236 measurementValue: number
e4f20deb
JB
237): void => {
238 if (measurementRequirements.aggregate) {
239 measurementStatistics.aggregate =
240 (measurementStatistics.aggregate ?? 0) + measurementValue
68e7ed58 241 measurementStatistics.minimum = min(
e4f20deb
JB
242 measurementValue,
243 measurementStatistics.minimum ?? Infinity
244 )
68e7ed58 245 measurementStatistics.maximum = max(
e4f20deb
JB
246 measurementValue,
247 measurementStatistics.maximum ?? -Infinity
248 )
dc021bcc
JB
249 if (
250 (measurementRequirements.average || measurementRequirements.median) &&
251 measurementValue != null
252 ) {
e4f20deb 253 measurementStatistics.history.push(measurementValue)
dc021bcc
JB
254 if (measurementRequirements.average) {
255 measurementStatistics.average = average(measurementStatistics.history)
bdb9d712
JB
256 } else if (measurementStatistics.average != null) {
257 delete measurementStatistics.average
dc021bcc
JB
258 }
259 if (measurementRequirements.median) {
260 measurementStatistics.median = median(measurementStatistics.history)
bdb9d712
JB
261 } else if (measurementStatistics.median != null) {
262 delete measurementStatistics.median
dc021bcc 263 }
e4f20deb
JB
264 }
265 }
266}
c3f0a074 267
68cbdc84
JB
268/**
269 * Generate a cryptographically secure random number in the [0,1[ range
270 *
271 * @returns A number in the [0,1[ range
272 */
970b38d6 273export const secureRandom = (): number => {
98446b39 274 return webcrypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000
68cbdc84 275}
68e7ed58
JB
276
277const min = (a: number, b: number): number => (a < b ? a : b)
278const max = (a: number, b: number): number => (a > b ? a : b)