X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2FWorkerUtils.ts;h=1874767370a1a5d438993fd6ec2dba1b9f1318d1;hb=1a6188b2fcd2bf644e6fea0c697a095228c1aed0;hp=452f8cfe8e4d549cb0563e20c78d8e686f4de018;hpb=474d4ffcd45d49bb242f51510a28569b00328676;p=e-mobility-charging-stations-simulator.git diff --git a/src/worker/WorkerUtils.ts b/src/worker/WorkerUtils.ts index 452f8cfe..18747673 100644 --- a/src/worker/WorkerUtils.ts +++ b/src/worker/WorkerUtils.ts @@ -1,3 +1,5 @@ +import { webcrypto } from 'node:crypto'; + import chalk from 'chalk'; export const sleep = async (milliSeconds: number): Promise => { @@ -15,5 +17,22 @@ export const defaultExitHandler = (code: number): void => { }; 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 webcrypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000; };