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