| 1 | import { webcrypto } from 'node:crypto'; |
| 2 | |
| 3 | import chalk from 'chalk'; |
| 4 | |
| 5 | export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => { |
| 6 | return new Promise<NodeJS.Timeout>((resolve) => setTimeout(resolve as () => void, milliSeconds)); |
| 7 | }; |
| 8 | |
| 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()}`)); |
| 16 | } |
| 17 | }; |
| 18 | |
| 19 | export const defaultErrorHandler = (error: Error): void => { |
| 20 | console.error(chalk.red('Worker errored: '), error); |
| 21 | }; |
| 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 | }; |