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