| 1 | import Configuration from './Configuration'; |
| 2 | import { WebSocketCloseEventStatusString } from '../types/WebSocket'; |
| 3 | import { WorkerProcessType } from '../types/Worker'; |
| 4 | import crypto from 'crypto'; |
| 5 | import { v4 as uuid } from 'uuid'; |
| 6 | |
| 7 | export default class Utils { |
| 8 | public static logPrefix(prefixString = ''): string { |
| 9 | return new Date().toLocaleString() + prefixString; |
| 10 | } |
| 11 | |
| 12 | public static generateUUID(): string { |
| 13 | return uuid(); |
| 14 | } |
| 15 | |
| 16 | public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> { |
| 17 | return new Promise((resolve) => setTimeout(resolve, milliSeconds)); |
| 18 | } |
| 19 | |
| 20 | public static formatDurationMilliSeconds(duration: number): string { |
| 21 | duration = Utils.convertToInt(duration); |
| 22 | const hours = Math.floor(duration / (3600 * 1000)); |
| 23 | const minutes = Math.floor((duration - (hours * (3600 * 1000))) / (60 * 1000)); |
| 24 | const seconds = (duration - (hours * 3600 * 1000) - (minutes * 60 * 1000)) / 1000; |
| 25 | let hoursStr: string = hours.toString(); |
| 26 | let minutesStr: string = minutes.toString(); |
| 27 | let secondsStr: string = seconds.toString(); |
| 28 | |
| 29 | if (hours < 10) { |
| 30 | hoursStr = '0' + hours.toString(); |
| 31 | } |
| 32 | if (minutes < 10) { |
| 33 | minutesStr = '0' + minutes.toString(); |
| 34 | } |
| 35 | if (seconds < 10) { |
| 36 | secondsStr = ('0' + seconds.toString()).substring(0, 6); |
| 37 | } |
| 38 | return hoursStr + ':' + minutesStr + ':' + secondsStr; |
| 39 | } |
| 40 | |
| 41 | public static formatDurationSeconds(duration: number): string { |
| 42 | return Utils.formatDurationMilliSeconds(duration * 1000); |
| 43 | } |
| 44 | |
| 45 | public static removeExtraEmptyLines(tab: string[]): void { |
| 46 | // Start from the end |
| 47 | for (let i = tab.length - 1; i > 0; i--) { |
| 48 | // Two consecutive empty lines? |
| 49 | if (tab[i].length === 0 && tab[i - 1].length === 0) { |
| 50 | // Remove the last one |
| 51 | tab.splice(i, 1); |
| 52 | } |
| 53 | // Check last line |
| 54 | if (i === 1 && tab[i - 1].length === 0) { |
| 55 | // Remove the first one |
| 56 | tab.splice(i - 1, 1); |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | public static convertToDate(value: unknown): Date { |
| 62 | // Check |
| 63 | if (!value) { |
| 64 | return value as Date; |
| 65 | } |
| 66 | // Check Type |
| 67 | if (!(value instanceof Date)) { |
| 68 | return new Date(value as string); |
| 69 | } |
| 70 | return value; |
| 71 | } |
| 72 | |
| 73 | public static convertToInt(value: unknown): number { |
| 74 | let changedValue: number = value as number; |
| 75 | if (!value) { |
| 76 | return 0; |
| 77 | } |
| 78 | if (Number.isSafeInteger(value)) { |
| 79 | return value as number; |
| 80 | } |
| 81 | // Check |
| 82 | if (Utils.isString(value)) { |
| 83 | // Create Object |
| 84 | changedValue = parseInt(value as string); |
| 85 | } |
| 86 | return changedValue; |
| 87 | } |
| 88 | |
| 89 | public static convertToFloat(value: unknown): number { |
| 90 | let changedValue: number = value as number; |
| 91 | if (!value) { |
| 92 | return 0; |
| 93 | } |
| 94 | // Check |
| 95 | if (Utils.isString(value)) { |
| 96 | // Create Object |
| 97 | changedValue = parseFloat(value as string); |
| 98 | } |
| 99 | return changedValue; |
| 100 | } |
| 101 | |
| 102 | public static convertToBoolean(value: unknown): boolean { |
| 103 | let result = false; |
| 104 | // Check boolean |
| 105 | if (value) { |
| 106 | // Check the type |
| 107 | if (typeof value === 'boolean') { |
| 108 | // Already a boolean |
| 109 | result = value; |
| 110 | } else { |
| 111 | // Convert |
| 112 | result = (value === 'true'); |
| 113 | } |
| 114 | } |
| 115 | return result; |
| 116 | } |
| 117 | |
| 118 | public static getRandomFloat(max: number, min = 0, negative = false): number { |
| 119 | const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff; |
| 120 | const sign = (negative && randomPositiveFloat < 0.5) ? 1 : -1; |
| 121 | return sign * (randomPositiveFloat * (max - min) + min); |
| 122 | } |
| 123 | |
| 124 | public static getRandomInt(max: number, min = 0): number { |
| 125 | max = Math.floor(max); |
| 126 | if (min) { |
| 127 | min = Math.ceil(min); |
| 128 | return Math.floor(Utils.secureRandom() * (max - min + 1)) + min; |
| 129 | } |
| 130 | return Math.floor(Utils.secureRandom() * (max + 1)); |
| 131 | } |
| 132 | |
| 133 | public static roundTo(numberValue: number, scale: number): number { |
| 134 | const roundPower = Math.pow(10, scale); |
| 135 | return Math.round(numberValue * roundPower) / roundPower; |
| 136 | } |
| 137 | |
| 138 | public static truncTo(numberValue: number, scale: number): number { |
| 139 | const truncPower = Math.pow(10, scale); |
| 140 | return Math.trunc(numberValue * truncPower) / truncPower; |
| 141 | } |
| 142 | |
| 143 | public static getRandomFloatRounded(max: number, min = 0, scale = 2): number { |
| 144 | if (min) { |
| 145 | return Utils.roundTo(Utils.getRandomFloat(max, min), scale); |
| 146 | } |
| 147 | return Utils.roundTo(Utils.getRandomFloat(max), scale); |
| 148 | } |
| 149 | |
| 150 | public static getRandomFloatFluctuatedRounded(staticValue: number, fluctuationPercent: number, scale = 2): number { |
| 151 | if (fluctuationPercent === 0) { |
| 152 | return Utils.roundTo(staticValue, scale); |
| 153 | } |
| 154 | const fluctuationRatio = fluctuationPercent / 100; |
| 155 | return Utils.getRandomFloatRounded(staticValue * (1 + fluctuationRatio), staticValue * (1 - fluctuationRatio), scale); |
| 156 | } |
| 157 | |
| 158 | public static cloneObject<T>(object: T): T { |
| 159 | return JSON.parse(JSON.stringify(object)) as T; |
| 160 | } |
| 161 | |
| 162 | public static isIterable<T>(obj: T): boolean { |
| 163 | if (obj) { |
| 164 | return typeof obj[Symbol.iterator] === 'function'; |
| 165 | } |
| 166 | return false; |
| 167 | } |
| 168 | |
| 169 | public static isEmptyJSon(document: unknown): boolean { |
| 170 | // Empty? |
| 171 | if (!document) { |
| 172 | return true; |
| 173 | } |
| 174 | // Check type |
| 175 | if (typeof document !== 'object') { |
| 176 | return true; |
| 177 | } |
| 178 | // Check |
| 179 | return Object.keys(document).length === 0; |
| 180 | } |
| 181 | |
| 182 | public static isString(value: unknown): boolean { |
| 183 | return typeof value === 'string'; |
| 184 | } |
| 185 | |
| 186 | public static isUndefined(value: unknown): boolean { |
| 187 | return typeof value === 'undefined'; |
| 188 | } |
| 189 | |
| 190 | public static isNullOrUndefined(value: unknown): boolean { |
| 191 | // eslint-disable-next-line no-eq-null, eqeqeq |
| 192 | if (value == null) { |
| 193 | return true; |
| 194 | } |
| 195 | return false; |
| 196 | } |
| 197 | |
| 198 | public static isEmptyArray(object: unknown): boolean { |
| 199 | if (!object) { |
| 200 | return true; |
| 201 | } |
| 202 | if (Array.isArray(object) && object.length > 0) { |
| 203 | return false; |
| 204 | } |
| 205 | return true; |
| 206 | } |
| 207 | |
| 208 | public static isEmptyObject(obj: Record<string, unknown>): boolean { |
| 209 | return !Object.keys(obj).length; |
| 210 | } |
| 211 | |
| 212 | public static insertAt = (str: string, subStr: string, pos: number): string => `${str.slice(0, pos)}${subStr}${str.slice(pos)}`; |
| 213 | |
| 214 | /** |
| 215 | * @param [retryNumber=0] |
| 216 | * @returns delay in milliseconds |
| 217 | */ |
| 218 | public static exponentialDelay(retryNumber = 0): number { |
| 219 | const delay = Math.pow(2, retryNumber) * 100; |
| 220 | const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay |
| 221 | return delay + randomSum; |
| 222 | } |
| 223 | |
| 224 | /** |
| 225 | * Convert websocket error code to human readable string message |
| 226 | * |
| 227 | * @param code websocket error code |
| 228 | * @returns human readable string message |
| 229 | */ |
| 230 | public static getWebSocketCloseEventStatusString(code: number): string { |
| 231 | if (code >= 0 && code <= 999) { |
| 232 | return '(Unused)'; |
| 233 | } else if (code >= 1016) { |
| 234 | if (code <= 1999) { |
| 235 | return '(For WebSocket standard)'; |
| 236 | } else if (code <= 2999) { |
| 237 | return '(For WebSocket extensions)'; |
| 238 | } else if (code <= 3999) { |
| 239 | return '(For libraries and frameworks)'; |
| 240 | } else if (code <= 4999) { |
| 241 | return '(For applications)'; |
| 242 | } |
| 243 | } |
| 244 | if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) { |
| 245 | return WebSocketCloseEventStatusString[code] as string; |
| 246 | } |
| 247 | return '(Unknown)'; |
| 248 | } |
| 249 | |
| 250 | public static workerPoolInUse(): boolean { |
| 251 | return [WorkerProcessType.DYNAMIC_POOL, WorkerProcessType.STATIC_POOL].includes(Configuration.getWorkerProcess()); |
| 252 | } |
| 253 | |
| 254 | public static workerDynamicPoolInUse(): boolean { |
| 255 | return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL; |
| 256 | } |
| 257 | |
| 258 | /** |
| 259 | * Generate a cryptographically secure random number in the [0,1[ range |
| 260 | * |
| 261 | * @returns |
| 262 | */ |
| 263 | public static secureRandom(): number { |
| 264 | return crypto.randomBytes(4).readUInt32LE() / 0x100000000; |
| 265 | } |
| 266 | } |