Merge branch 'master' of github.com:poolifier/poolifier
[poolifier.git] / src / utils.ts
CommitLineData
aa4bf4b2 1import * as os from 'node:os'
3c93feb9
JB
2import type {
3 MeasurementStatisticsRequirements,
4 WorkerChoiceStrategyOptions
5} from './pools/selection-strategies/selection-strategies-types'
59317253 6import type { KillBehavior } from './worker/worker-options'
e4f20deb 7import type { MeasurementStatistics } from './pools/worker'
bbeadd16 8
ff128cc9
JB
9/**
10 * Default task name.
11 */
12export const DEFAULT_TASK_NAME = 'default'
13
6e9d10db
JB
14/**
15 * An intentional empty function.
16 */
4f3c3d89 17export const EMPTY_FUNCTION: () => void = Object.freeze(() => {
6e9d10db 18 /* Intentionally empty */
4f3c3d89 19})
78099a15
JB
20
21/**
bbeadd16
JB
22 * Default worker choice strategy options.
23 */
24export const DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS: WorkerChoiceStrategyOptions =
25 {
8990357d 26 choiceRetries: 6,
932fc8be 27 runTime: { median: false },
5df69fab
JB
28 waitTime: { median: false },
29 elu: { median: false }
bbeadd16
JB
30 }
31
3c93feb9
JB
32/**
33 * Default measurement statistics requirements.
34 */
35export const DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS: MeasurementStatisticsRequirements =
36 {
37 aggregate: false,
38 average: false,
39 median: false
40 }
41
51474716 42/**
ab80dc46
JB
43 * Returns safe host OS optimized estimate of the default amount of parallelism a pool should use.
44 * Always returns a value greater than zero.
45 *
46 * @returns The host OS optimized maximum pool size.
4bffc062 47 * @internal
51474716
JB
48 */
49export const availableParallelism = (): number => {
50 let availableParallelism = 1
51 try {
aa4bf4b2 52 availableParallelism = os.availableParallelism()
51474716 53 } catch {
aa4bf4b2 54 const numberOfCpus = os.cpus()
2845f2a5
JB
55 if (Array.isArray(numberOfCpus) && numberOfCpus.length > 0) {
56 availableParallelism = numberOfCpus.length
51474716
JB
57 }
58 }
59 return availableParallelism
60}
61
9a9f863c
JB
62// /**
63// * Computes the retry delay in milliseconds using an exponential back off algorithm.
64// *
65// * @param retryNumber - The number of retries that have already been attempted
66// * @param maxDelayRatio - The maximum ratio of the delay that can be randomized
67// * @returns Delay in milliseconds
4bffc062 68// * @internal
9a9f863c
JB
69// */
70// export const exponentialDelay = (
71// retryNumber = 0,
72// maxDelayRatio = 0.2
73// ): number => {
74// const delay = Math.pow(2, retryNumber) * 100
75// const randomSum = delay * maxDelayRatio * Math.random() // 0-(maxDelayRatio*100)% of the delay
76// return delay + randomSum
77// }
8990357d 78
bbeadd16 79/**
afe0d5bf 80 * Computes the median of the given data set.
78099a15
JB
81 *
82 * @param dataSet - Data set.
83 * @returns The median of the given data set.
4bffc062 84 * @internal
78099a15
JB
85 */
86export const median = (dataSet: number[]): number => {
4a45e8d2
JB
87 if (Array.isArray(dataSet) && dataSet.length === 0) {
88 return 0
89 }
78099a15
JB
90 if (Array.isArray(dataSet) && dataSet.length === 1) {
91 return dataSet[0]
92 }
c6f42dd6
JB
93 const sortedDataSet = dataSet.slice().sort((a, b) => a - b)
94 return (
95 (sortedDataSet[(sortedDataSet.length - 1) >> 1] +
96 sortedDataSet[sortedDataSet.length >> 1]) /
97 2
98 )
78099a15 99}
0d80593b 100
afe0d5bf
JB
101/**
102 * Rounds the given number to the given scale.
64383951 103 * The rounding is done using the "round half away from zero" method.
afe0d5bf
JB
104 *
105 * @param num - The number to round.
106 * @param scale - The scale to round to.
107 * @returns The rounded number.
108 */
109export const round = (num: number, scale = 2): number => {
110 const rounder = Math.pow(10, scale)
111 return Math.round(num * rounder * (1 + Number.EPSILON)) / rounder
112}
113
3c653a03
JB
114/**
115 * Is the given object a plain object?
116 *
117 * @param obj - The object to check.
118 * @returns `true` if the given object is a plain object, `false` otherwise.
119 */
0d80593b
JB
120export const isPlainObject = (obj: unknown): boolean =>
121 typeof obj === 'object' &&
122 obj !== null &&
123 obj?.constructor === Object &&
124 Object.prototype.toString.call(obj) === '[object Object]'
59317253
JB
125
126/**
127 * Detects whether the given value is a kill behavior or not.
128 *
129 * @typeParam KB - Which specific KillBehavior type to test against.
130 * @param killBehavior - Which kind of kill behavior to detect.
131 * @param value - Any value.
132 * @returns `true` if `value` was strictly equals to `killBehavior`, otherwise `false`.
4bffc062 133 * @internal
59317253
JB
134 */
135export const isKillBehavior = <KB extends KillBehavior>(
136 killBehavior: KB,
137 value: unknown
138): value is KB => {
139 return value === killBehavior
140}
49d1b48c
JB
141
142/**
143 * Detects whether the given value is an asynchronous function or not.
144 *
145 * @param fn - Any value.
146 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
147 */
148export const isAsyncFunction = (
149 fn: unknown
150): fn is (...args: unknown[]) => Promise<unknown> => {
151 return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction'
152}
e4f20deb
JB
153
154/**
155 * Updates the given measurement statistics.
156 *
157 * @param measurementStatistics - The measurement statistics to update.
158 * @param measurementRequirements - The measurement statistics requirements.
159 * @param measurementValue - The measurement value.
008512c7 160 * @param numberOfMeasurements - The number of measurements.
4bffc062 161 * @internal
e4f20deb
JB
162 */
163export const updateMeasurementStatistics = (
164 measurementStatistics: MeasurementStatistics,
165 measurementRequirements: MeasurementStatisticsRequirements,
166 measurementValue: number,
008512c7 167 numberOfMeasurements: number
e4f20deb
JB
168): void => {
169 if (measurementRequirements.aggregate) {
170 measurementStatistics.aggregate =
171 (measurementStatistics.aggregate ?? 0) + measurementValue
172 measurementStatistics.minimum = Math.min(
173 measurementValue,
174 measurementStatistics.minimum ?? Infinity
175 )
176 measurementStatistics.maximum = Math.max(
177 measurementValue,
178 measurementStatistics.maximum ?? -Infinity
179 )
008512c7 180 if (measurementRequirements.average && numberOfMeasurements !== 0) {
e4f20deb 181 measurementStatistics.average =
008512c7 182 measurementStatistics.aggregate / numberOfMeasurements
e4f20deb
JB
183 }
184 if (measurementRequirements.median && measurementValue != null) {
185 measurementStatistics.history.push(measurementValue)
186 measurementStatistics.median = median(measurementStatistics.history)
187 }
188 }
189}
c3f0a074
JB
190
191/**
192 * Executes a function once at a time.
193 *
194 * @param fn - The function to execute.
195 * @param context - The context to bind the function to.
196 * @returns The function to execute.
197 */
198export const once = (
199 // eslint-disable-next-line @typescript-eslint/no-explicit-any
200 fn: (...args: any[]) => void,
f7426dd9 201 context: unknown
c3f0a074
JB
202 // eslint-disable-next-line @typescript-eslint/no-explicit-any
203): ((...args: any[]) => void) => {
204 let called = false
205 // eslint-disable-next-line @typescript-eslint/no-explicit-any
206 return function (...args: any[]): void {
207 if (!called) {
208 called = true
209 fn.apply(context, args)
210 called = false
211 }
212 }
213}