X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2FWorkerUtils.ts;h=776d7174c664f24a8d1e8bcb8ab59b5d3ee5706b;hb=6a4032b5d8f3cbaa18d3beddcdfe9d335c1cba90;hp=00feba445ff939cbc933eac0daf1a12fc0cfb4c4;hpb=9c5d9fa4cd1904b5e2d4c4a8277bed25865b61b6;p=e-mobility-charging-stations-simulator.git diff --git a/src/worker/WorkerUtils.ts b/src/worker/WorkerUtils.ts index 00feba44..776d7174 100644 --- a/src/worker/WorkerUtils.ts +++ b/src/worker/WorkerUtils.ts @@ -1,13 +1,38 @@ +import { getRandomValues } from 'node:crypto'; + import chalk from 'chalk'; -export class WorkerUtils { - private constructor() { - // This is intentional +export const sleep = async (milliSeconds: number): Promise => { + return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds)); +}; + +export const defaultExitHandler = (code: number): void => { + if (code === 0) { + console.info(chalk.green('Worker exited successfully')); + } else if (code === 1) { + console.info(chalk.green('Worker terminated successfully')); + } else if (code > 1) { + console.error(chalk.red(`Worker exited with exit code: ${code.toString()}`)); } +}; + +export const defaultErrorHandler = (error: Error): void => { + 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; +}; - public static defaultExitHandler = (code: number): void => { - if (code !== 0) { - console.error(chalk.red(`Worker stopped with exit code ${code}`)); - } - }; -} +/** + * 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; +};