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