]>
Commit | Line | Data |
---|---|---|
1 | import chalk from 'chalk' | |
2 | import { getRandomValues } from 'node:crypto' | |
3 | ||
4 | export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => { | |
5 | return await new Promise<NodeJS.Timeout>(resolve => | |
6 | setTimeout(resolve as () => void, milliSeconds) | |
7 | ) | |
8 | } | |
9 | ||
10 | export const defaultExitHandler = (code: number): void => { | |
11 | if (code === 0) { | |
12 | console.info(chalk.green('Worker exited successfully')) | |
13 | } else if (code === 1) { | |
14 | console.info(chalk.green('Worker terminated successfully')) | |
15 | } else if (code > 1) { | |
16 | console.error(chalk.red(`Worker exited with exit code: ${code.toString()}`)) | |
17 | } | |
18 | } | |
19 | ||
20 | export const defaultErrorHandler = (error: Error): void => { | |
21 | console.error(chalk.red('Worker errored: '), error) | |
22 | } | |
23 | ||
24 | export const randomizeDelay = (delay: number): number => { | |
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 | } | |
30 | ||
31 | /** | |
32 | * Generates a cryptographically secure random number in the [0,1[ range | |
33 | * @returns A number in the [0,1[ range | |
34 | * @internal | |
35 | */ | |
36 | const secureRandom = (): number => { | |
37 | return getRandomValues(new Uint32Array(1))[0] / 0x100000000 | |
38 | } |