X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils.ts;h=b84c4c803efe974b1dde4d8e3988465bef6d94b7;hb=2fb233ea3f8d44a2b8d234dbfccedfe33ab9e5db;hp=d39bfa02c8498ed54d8bebc8d9ace5a7a7fd756f;hpb=ddc35f92c712f38d9cfd79fd558cf80c0e031219;p=poolifier.git diff --git a/src/utils.ts b/src/utils.ts index d39bfa02..b84c4c80 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,4 +1,5 @@ import * as os from 'node:os' +import { webcrypto } from 'node:crypto' import type { MeasurementStatisticsRequirements, WorkerChoiceStrategyOptions @@ -59,22 +60,34 @@ export const availableParallelism = (): number => { return availableParallelism } -// /** -// * Computes the retry delay in milliseconds using an exponential back off algorithm. -// * -// * @param retryNumber - The number of retries that have already been attempted -// * @param maxDelayRatio - The maximum ratio of the delay that can be randomized -// * @returns Delay in milliseconds -// * @internal -// */ -// export const exponentialDelay = ( -// retryNumber = 0, -// maxDelayRatio = 0.2 -// ): number => { -// const delay = Math.pow(2, retryNumber) * 100 -// const randomSum = delay * maxDelayRatio * Math.random() // 0-(maxDelayRatio*100)% of the delay -// return delay + randomSum -// } +/** + * Sleeps for the given amount of milliseconds. + * + * @param ms - The amount of milliseconds to sleep. + * @returns A promise that resolves after the given amount of milliseconds. + */ +export const sleep = async (ms: number): Promise => { + await new Promise((resolve) => { + setTimeout(resolve, ms) + }) +} + +/** + * Computes the retry delay in milliseconds using an exponential back off algorithm. + * + * @param retryNumber - The number of retries that have already been attempted + * @param delayFactor - The base delay factor in milliseconds + * @returns Delay in milliseconds + * @internal + */ +export const exponentialDelay = ( + retryNumber = 0, + delayFactor = 100 +): number => { + const delay = Math.pow(2, retryNumber) * delayFactor + const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay + return delay + randomSum +} /** * Computes the average of the given data set. @@ -234,3 +247,12 @@ export const once = ( } } } + +/** + * Generate a cryptographically secure random number in the [0,1[ range + * + * @returns A number in the [0,1[ range + */ +export const secureRandom = (): number => { + return webcrypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000 +}