]> Piment Noir Git Repositories - e-mobility-charging-stations-simulator.git/blame - src/worker/WorkerUtils.ts
chore(deps-dev): apply updates
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerUtils.ts
CommitLineData
66a7748d 1import chalk from 'chalk'
0749233f 2import { getRandomValues } from 'node:crypto'
8eac9a09 3
789871d6 4export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => {
a974c8e4 5 return await new Promise<NodeJS.Timeout>(resolve =>
66a7748d
JB
6 setTimeout(resolve as () => void, milliSeconds)
7 )
8}
d5bd1c00 9
789871d6
JB
10export const defaultExitHandler = (code: number): void => {
11 if (code === 0) {
66a7748d 12 console.info(chalk.green('Worker exited successfully'))
789871d6 13 } else if (code === 1) {
66a7748d 14 console.info(chalk.green('Worker terminated successfully'))
789871d6 15 } else if (code > 1) {
66a7748d 16 console.error(chalk.red(`Worker exited with exit code: ${code.toString()}`))
268a74bb 17 }
66a7748d 18}
268a74bb 19
789871d6 20export const defaultErrorHandler = (error: Error): void => {
66a7748d
JB
21 console.error(chalk.red('Worker errored: '), error)
22}
ab93b184
JB
23
24export const randomizeDelay = (delay: number): number => {
66a7748d
JB
25 const random = secureRandom()
26 const sign = random < 0.5 ? -1 : 1
27 const randomSum = delay * 0.2 * random // 0-20% of the delay
28 return delay + sign * randomSum
29}
ab93b184
JB
30
31/**
32 * Generates a cryptographically secure random number in the [0,1[ range
ab93b184
JB
33 * @returns A number in the [0,1[ range
34 * @internal
35 */
36const secureRandom = (): number => {
66a7748d
JB
37 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
38}