958ecccc2f9d4a0d08e20785d7f37fbf471b726e
1 import chalk from
'chalk'
2 import { getRandomValues
} from
'node:crypto'
4 export const sleep
= async (milliSeconds
: number): Promise
<NodeJS
.Timeout
> => {
5 return await new Promise
<NodeJS
.Timeout
>(resolve
=>
6 setTimeout(resolve
as () => void, milliSeconds
)
10 export const defaultExitHandler
= (code
: number): void => {
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()}`))
20 export const defaultErrorHandler
= (error
: Error): void => {
21 console
.error(chalk
.red('Worker errored: '), error
)
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
32 * Generates a cryptographically secure random number in the [0,1[ range
33 * @returns A number in the [0,1[ range
36 const secureRandom
= (): number => {
37 return getRandomValues(new Uint32Array(1))[0] / 0x100000000