build(deps-dev): apply updates
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerUtils.ts
index 4d6868f76f35cf77166cfcff54c7e23ccae0036d..f36c6046d626d5d4850f1b75dca253edae043b15 100644 (file)
@@ -1,17 +1,40 @@
-import chalk from 'chalk';
+import { getRandomValues } from 'node:crypto'
 
-export class WorkerUtils {
-  private constructor() {
-    // This is intentional
+import chalk from 'chalk'
+
+export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => {
+  return await new Promise<NodeJS.Timeout>(resolve =>
+    setTimeout(resolve as () => void, milliSeconds)
+  )
+}
+
+export const defaultExitHandler = (code: number): void => {
+  if (code === 0) {
+    console.info(chalk.green('Worker exited successfully'))
+  } else if (code === 1) {
+    console.info(chalk.green('Worker terminated successfully'))
+  } else if (code > 1) {
+    console.error(chalk.red(`Worker exited with exit code: ${code.toString()}`))
   }
+}
 
-  public static defaultExitHandler = (code: number): void => {
-    if (code !== 0) {
-      console.error(chalk.red(`Worker stopped with exit code ${code}`));
-    }
-  };
+export const defaultErrorHandler = (error: Error): void => {
+  console.error(chalk.red('Worker errored: '), error)
+}
+
+export const randomizeDelay = (delay: number): number => {
+  const random = secureRandom()
+  const sign = random < 0.5 ? -1 : 1
+  const randomSum = delay * 0.2 * random // 0-20% of the delay
+  return delay + sign * randomSum
+}
 
-  public static defaultErrorHandler = (error: Error): void => {
-    console.error(chalk.red('Worker errored: ', error));
-  };
+/**
+ * Generates a cryptographically secure random number in the [0,1[ range
+ *
+ * @returns A number in the [0,1[ range
+ * @internal
+ */
+const secureRandom = (): number => {
+  return getRandomValues(new Uint32Array(1))[0] / 0x100000000
 }