Fix random number generators input checks
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
index 73e5e3f96e421b7f2bbec4bb1021ab58f5c09d47..d396cfa959f930167978cd35dd240eae08ff29cd 100644 (file)
@@ -1,46 +1,54 @@
-import Configuration from './Configuration';
+import crypto from 'crypto';
+
 import { WebSocketCloseEventStatusString } from '../types/WebSocket';
-import { WorkerProcessType } from '../types/Worker';
-import { v4 as uuid } from 'uuid';
 
 export default class Utils {
-  static logPrefix(prefixString = ''): string {
-    return new Date().toLocaleString() + prefixString;
+  private constructor() {
+    // This is intentional
   }
 
-  static generateUUID(): string {
-    return uuid();
+  public static logPrefix(prefixString = ''): string {
+    return new Date().toLocaleString() + prefixString;
   }
 
-  static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
-    return new Promise((resolve) => setTimeout(resolve, milliSeconds));
+  public static generateUUID(): string {
+    return crypto.randomUUID();
   }
 
-  static secondsToHHMMSS(seconds: number): string {
-    return Utils.milliSecondsToHHMMSS(seconds * 1000);
+  public static validateUUID(uuid: string): boolean {
+    return /\/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$\/i/.test(uuid);
   }
 
-  static milliSecondsToHHMMSS(milliSeconds: number): string {
-    return new Date(milliSeconds).toISOString().substr(11, 8);
+  public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
+    return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds));
   }
 
-  static removeExtraEmptyLines(tab: string[]): void {
-    // Start from the end
-    for (let i = tab.length - 1; i > 0; i--) {
-      // Two consecutive empty lines?
-      if (tab[i].length === 0 && tab[i - 1].length === 0) {
-        // Remove the last one
-        tab.splice(i, 1);
-      }
-      // Check last line
-      if (i === 1 && tab[i - 1].length === 0) {
-        // Remove the first one
-        tab.splice(i - 1, 1);
-      }
+  public static formatDurationMilliSeconds(duration: number): string {
+    duration = Utils.convertToInt(duration);
+    const hours = Math.floor(duration / (3600 * 1000));
+    const minutes = Math.floor((duration / 1000 - hours * 3600) / 60);
+    const seconds = duration / 1000 - hours * 3600 - minutes * 60;
+    let hoursStr = hours.toString();
+    let minutesStr = minutes.toString();
+    let secondsStr = seconds.toString();
+
+    if (hours < 10) {
+      hoursStr = '0' + hours.toString();
+    }
+    if (minutes < 10) {
+      minutesStr = '0' + minutes.toString();
+    }
+    if (seconds < 10) {
+      secondsStr = '0' + seconds.toString();
     }
+    return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6);
+  }
+
+  public static formatDurationSeconds(duration: number): string {
+    return Utils.formatDurationMilliSeconds(duration * 1000);
   }
 
-  static convertToDate(value: unknown): Date {
+  public static convertToDate(value: unknown): Date {
     // Check
     if (!value) {
       return value as Date;
@@ -52,7 +60,7 @@ export default class Utils {
     return value;
   }
 
-  static convertToInt(value: unknown): number {
+  public static convertToInt(value: unknown): number {
     let changedValue: number = value as number;
     if (!value) {
       return 0;
@@ -68,7 +76,7 @@ export default class Utils {
     return changedValue;
   }
 
-  static convertToFloat(value: unknown): number {
+  public static convertToFloat(value: unknown): number {
     let changedValue: number = value as number;
     if (!value) {
       return 0;
@@ -81,7 +89,7 @@ export default class Utils {
     return changedValue;
   }
 
-  static convertToBoolean(value: unknown): boolean {
+  public static convertToBoolean(value: unknown): boolean {
     let result = false;
     // Check boolean
     if (value) {
@@ -91,121 +99,173 @@ export default class Utils {
         result = value;
       } else {
         // Convert
-        result = (value === 'true');
+        result = value === 'true';
       }
     }
     return result;
   }
 
-  static getRandomFloat(max: number, min = 0): number {
-    return Math.random() < 0.5 ? (1 - Math.random()) * (max - min) + min : Math.random() * (max - min) + min;
+  public static getRandomFloat(max = Number.MAX_VALUE, min = 0, negative = false): number {
+    if (max < min || max < 0 || min < 0) {
+      throw new RangeError('Invalid interval');
+    }
+    const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
+    const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1;
+    return sign * (randomPositiveFloat * (max - min) + min);
   }
 
-  static getRandomInt(max: number, min = 0): number {
-    if (min) {
-      return Math.floor(Math.random() * (max - min + 1) + min);
+  public static getRandomInteger(max = Number.MAX_SAFE_INTEGER, min = 0): number {
+    if (max < min || max < 0 || min < 0) {
+      throw new RangeError('Invalid interval');
+    }
+    max = Math.floor(max);
+    if (!Utils.isNullOrUndefined(min) && min !== 0) {
+      min = Math.ceil(min);
+      return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
     }
-    return Math.floor(Math.random() * max + 1);
+    return Math.floor(Utils.secureRandom() * (max + 1));
   }
 
-  static roundTo(numberValue: number, scale: number): number {
+  public static roundTo(numberValue: number, scale: number): number {
     const roundPower = Math.pow(10, scale);
     return Math.round(numberValue * roundPower) / roundPower;
   }
 
-  static truncTo(numberValue: number, scale: number): number {
+  public static truncTo(numberValue: number, scale: number): number {
     const truncPower = Math.pow(10, scale);
     return Math.trunc(numberValue * truncPower) / truncPower;
   }
 
-  static getRandomFloatRounded(max: number, min = 0, scale = 2): number {
+  public static getRandomFloatRounded(max = Number.MAX_VALUE, min = 0, scale = 2): number {
     if (min) {
       return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
     }
     return Utils.roundTo(Utils.getRandomFloat(max), scale);
   }
 
-  static getRandomFloatFluctuatedRounded(staticValue: number, fluctuationPercent: number, scale = 2): number {
+  public static getRandomFloatFluctuatedRounded(
+    staticValue: number,
+    fluctuationPercent: number,
+    scale = 2
+  ): number {
     if (fluctuationPercent === 0) {
       return Utils.roundTo(staticValue, scale);
     }
     const fluctuationRatio = fluctuationPercent / 100;
-    return Utils.getRandomFloatRounded(staticValue * (1 + fluctuationRatio), staticValue * (1 - fluctuationRatio), scale);
+    return Utils.getRandomFloatRounded(
+      staticValue * (1 + fluctuationRatio),
+      staticValue * (1 - fluctuationRatio),
+      scale
+    );
   }
 
-  static cloneObject<T>(object: T): T {
+  public static cloneObject<T>(object: T): T {
     return JSON.parse(JSON.stringify(object)) as T;
   }
 
-  static isIterable<T>(obj: T): boolean {
-    if (obj) {
-      return typeof obj[Symbol.iterator] === 'function';
-    }
-    return false;
+  public static isIterable<T>(obj: T): boolean {
+    return obj ? typeof obj[Symbol.iterator] === 'function' : false;
   }
 
-  static isEmptyJSon(document: unknown): boolean {
-    // Empty?
-    if (!document) {
-      return true;
-    }
-    // Check type
-    if (typeof document !== 'object') {
-      return true;
-    }
-    // Check
-    return Object.keys(document).length === 0;
+  public static isString(value: unknown): boolean {
+    return typeof value === 'string';
   }
 
-  static isString(value: unknown): boolean {
-    return typeof value === 'string';
+  public static isEmptyString(value: unknown): boolean {
+    return Utils.isString(value) && (value as string).length === 0;
   }
 
-  static isUndefined(value: unknown): boolean {
+  public static isUndefined(value: unknown): boolean {
     return typeof value === 'undefined';
   }
 
-  static isNullOrUndefined(value: unknown): boolean {
-    // eslint-disable-next-line no-eq-null, eqeqeq
-    if (value == null) {
-      return true;
-    }
-    return false;
+  public static isNullOrUndefined(value: unknown): boolean {
+    // eslint-disable-next-line eqeqeq, no-eq-null
+    return value == null ? true : false;
   }
 
-  static isEmptyArray(object: unknown): boolean {
+  public static isEmptyArray(object: unknown): boolean {
     if (!object) {
       return true;
     }
-    if (Array.isArray(object) && object.length > 0) {
+    if (Array.isArray(object) === true && (object as unknown[]).length > 0) {
       return false;
     }
     return true;
   }
 
-  static isEmptyObject(obj: Record<string, unknown>): boolean {
+  public static isEmptyObject(obj: object): boolean {
     return !Object.keys(obj).length;
   }
 
-  static insertAt = (str: string, subStr: string, pos: number): string => `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
+  public static insertAt = (str: string, subStr: string, pos: number): string =>
+    `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
 
   /**
    * @param [retryNumber=0]
    * @returns delay in milliseconds
    */
-  static exponentialDelay(retryNumber = 0): number {
+  public static exponentialDelay(retryNumber = 0): number {
     const delay = Math.pow(2, retryNumber) * 100;
-    const randomSum = delay * 0.2 * Math.random(); // 0-20% of the delay
+    const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
     return delay + randomSum;
   }
 
+  public static async promiseWithTimeout<T>(
+    promise: Promise<T>,
+    timeoutMs: number,
+    timeoutError: Error,
+    timeoutCallback: () => void = () => {
+      /* This is intentional */
+    }
+  ): Promise<T> {
+    // Create a timeout promise that rejects in timeout milliseconds
+    const timeoutPromise = new Promise<never>((_, reject) => {
+      setTimeout(() => {
+        timeoutCallback();
+        reject(timeoutError);
+      }, timeoutMs);
+    });
+
+    // Returns a race between timeout promise and the passed promise
+    return Promise.race<T>([promise, timeoutPromise]);
+  }
+
+  /**
+   * Generate a cryptographically secure random number in the [0,1[ range
+   *
+   * @returns
+   */
+  public static secureRandom(): number {
+    return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
+  }
+
+  public static JSONStringifyWithMapSupport(
+    obj: Record<string, unknown> | Record<string, unknown>[],
+    space?: number
+  ): string {
+    return JSON.stringify(
+      obj,
+      (key, value: Record<string, unknown>) => {
+        if (value instanceof Map) {
+          return {
+            dataType: 'Map',
+            value: [...value],
+          };
+        }
+        return value;
+      },
+      space
+    );
+  }
+
   /**
    * Convert websocket error code to human readable string message
    *
    * @param code websocket error code
    * @returns human readable string message
    */
-  static getWebSocketCloseEventStatusString(code: number): string {
+  public static getWebSocketCloseEventStatusString(code: number): string {
     if (code >= 0 && code <= 999) {
       return '(Unused)';
     } else if (code >= 1016) {
@@ -224,12 +284,4 @@ export default class Utils {
     }
     return '(Unknown)';
   }
-
-  static workerPoolInUse(): boolean {
-    return [WorkerProcessType.DYNAMIC_POOL, WorkerProcessType.STATIC_POOL].includes(Configuration.getWorkerProcess());
-  }
-
-  static workerDynamicPoolInUse(): boolean {
-    return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL;
-  }
 }