X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;ds=sidebyside;f=src%2Fworker%2FWorkerUtils.ts;h=f36c6046d626d5d4850f1b75dca253edae043b15;hb=47f846b2a74439a610321356604f2f4184cb5c0b;hp=e930a47f826a33674c08cd7f1f99ff31f15facbc;hpb=a418c77b250374b03ad7e8433b254b2fb0080fa0;p=e-mobility-charging-stations-simulator.git diff --git a/src/worker/WorkerUtils.ts b/src/worker/WorkerUtils.ts index e930a47f..f36c6046 100644 --- a/src/worker/WorkerUtils.ts +++ b/src/worker/WorkerUtils.ts @@ -1,19 +1,40 @@ -import chalk from 'chalk'; +import { getRandomValues } from 'node:crypto' + +import chalk from 'chalk' export const sleep = async (milliSeconds: number): Promise => { - return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds)); -}; + return await new Promise(resolve => + setTimeout(resolve as () => void, milliSeconds) + ) +} export const defaultExitHandler = (code: number): void => { if (code === 0) { - console.info(chalk.green('Worker exited successfully')); + console.info(chalk.green('Worker exited successfully')) } else if (code === 1) { - console.info(chalk.green('Worker terminated successfully')); + console.info(chalk.green('Worker terminated successfully')) } else if (code > 1) { - console.error(chalk.red(`Worker exited with exit code: ${code.toString()}`)); + console.error(chalk.red(`Worker exited with exit code: ${code.toString()}`)) } -}; +} export const defaultErrorHandler = (error: Error): void => { - console.error(chalk.red('Worker errored: '), error); -}; + console.error(chalk.red('Worker errored: '), error) +} + +export const randomizeDelay = (delay: number): number => { + const random = secureRandom() + const sign = random < 0.5 ? -1 : 1 + const randomSum = delay * 0.2 * random // 0-20% of the delay + return delay + sign * randomSum +} + +/** + * Generates a cryptographically secure random number in the [0,1[ range + * + * @returns A number in the [0,1[ range + * @internal + */ +const secureRandom = (): number => { + return getRandomValues(new Uint32Array(1))[0] / 0x100000000 +}