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