| 1 | import { randomBytes, randomInt, randomUUID } from 'node:crypto'; |
| 2 | import { inspect } from 'node:util'; |
| 3 | |
| 4 | import clone from 'just-clone'; |
| 5 | |
| 6 | import { Constants } from './Constants'; |
| 7 | import { type TimestampedData, WebSocketCloseEventStatusString } from '../types'; |
| 8 | |
| 9 | export const logPrefix = (prefixString = ''): string => { |
| 10 | return `${new Date().toLocaleString()}${prefixString}`; |
| 11 | }; |
| 12 | |
| 13 | export const generateUUID = (): string => { |
| 14 | return randomUUID(); |
| 15 | }; |
| 16 | |
| 17 | export const validateUUID = (uuid: string): boolean => { |
| 18 | return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test( |
| 19 | uuid, |
| 20 | ); |
| 21 | }; |
| 22 | |
| 23 | export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => { |
| 24 | return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds)); |
| 25 | }; |
| 26 | |
| 27 | export const formatDurationMilliSeconds = (duration: number): string => { |
| 28 | duration = convertToInt(duration); |
| 29 | const hours = Math.floor(duration / (3600 * 1000)); |
| 30 | const minutes = Math.floor((duration / 1000 - hours * 3600) / 60); |
| 31 | const seconds = duration / 1000 - hours * 3600 - minutes * 60; |
| 32 | let hoursStr = hours.toString(); |
| 33 | let minutesStr = minutes.toString(); |
| 34 | let secondsStr = seconds.toString(); |
| 35 | |
| 36 | if (hours < 10) { |
| 37 | hoursStr = `0${hours.toString()}`; |
| 38 | } |
| 39 | if (minutes < 10) { |
| 40 | minutesStr = `0${minutes.toString()}`; |
| 41 | } |
| 42 | if (seconds < 10) { |
| 43 | secondsStr = `0${seconds.toString()}`; |
| 44 | } |
| 45 | return `${hoursStr}:${minutesStr}:${secondsStr.substring(0, 6)}`; |
| 46 | }; |
| 47 | |
| 48 | export const formatDurationSeconds = (duration: number): string => { |
| 49 | return formatDurationMilliSeconds(duration * 1000); |
| 50 | }; |
| 51 | |
| 52 | export const convertToDate = ( |
| 53 | value: Date | string | number | null | undefined, |
| 54 | ): Date | null | undefined => { |
| 55 | if (isNullOrUndefined(value)) { |
| 56 | return value as null | undefined; |
| 57 | } |
| 58 | if (value instanceof Date) { |
| 59 | return value; |
| 60 | } |
| 61 | if (isString(value) || typeof value === 'number') { |
| 62 | return new Date(value!); |
| 63 | } |
| 64 | return null; |
| 65 | }; |
| 66 | |
| 67 | export const convertToInt = (value: unknown): number => { |
| 68 | if (!value) { |
| 69 | return 0; |
| 70 | } |
| 71 | let changedValue: number = value as number; |
| 72 | if (Number.isSafeInteger(value)) { |
| 73 | return value as number; |
| 74 | } |
| 75 | if (typeof value === 'number') { |
| 76 | return Math.trunc(value); |
| 77 | } |
| 78 | if (isString(value)) { |
| 79 | changedValue = parseInt(value as string); |
| 80 | } |
| 81 | if (isNaN(changedValue)) { |
| 82 | // eslint-disable-next-line @typescript-eslint/no-base-to-string |
| 83 | throw new Error(`Cannot convert to integer: ${value.toString()}`); |
| 84 | } |
| 85 | return changedValue; |
| 86 | }; |
| 87 | |
| 88 | export const convertToFloat = (value: unknown): number => { |
| 89 | if (!value) { |
| 90 | return 0; |
| 91 | } |
| 92 | let changedValue: number = value as number; |
| 93 | if (isString(value)) { |
| 94 | changedValue = parseFloat(value as string); |
| 95 | } |
| 96 | if (isNaN(changedValue)) { |
| 97 | // eslint-disable-next-line @typescript-eslint/no-base-to-string |
| 98 | throw new Error(`Cannot convert to float: ${value.toString()}`); |
| 99 | } |
| 100 | return changedValue; |
| 101 | }; |
| 102 | |
| 103 | export const convertToBoolean = (value: unknown): boolean => { |
| 104 | let result = false; |
| 105 | if (value) { |
| 106 | // Check the type |
| 107 | if (typeof value === 'boolean') { |
| 108 | return value; |
| 109 | } else if (isString(value) && ((value as string).toLowerCase() === 'true' || value === '1')) { |
| 110 | result = true; |
| 111 | } else if (typeof value === 'number' && value === 1) { |
| 112 | result = true; |
| 113 | } |
| 114 | } |
| 115 | return result; |
| 116 | }; |
| 117 | |
| 118 | export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => { |
| 119 | if (max < min) { |
| 120 | throw new RangeError('Invalid interval'); |
| 121 | } |
| 122 | if (max - min === Infinity) { |
| 123 | throw new RangeError('Invalid interval'); |
| 124 | } |
| 125 | return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min; |
| 126 | }; |
| 127 | |
| 128 | export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => { |
| 129 | max = Math.floor(max); |
| 130 | if (!isNullOrUndefined(min) && min !== 0) { |
| 131 | min = Math.ceil(min); |
| 132 | return Math.floor(randomInt(min, max + 1)); |
| 133 | } |
| 134 | return Math.floor(randomInt(max + 1)); |
| 135 | }; |
| 136 | |
| 137 | /** |
| 138 | * Rounds the given number to the given scale. |
| 139 | * The rounding is done using the "round half away from zero" method. |
| 140 | * |
| 141 | * @param numberValue - The number to round. |
| 142 | * @param scale - The scale to round to. |
| 143 | * @returns The rounded number. |
| 144 | */ |
| 145 | export const roundTo = (numberValue: number, scale: number): number => { |
| 146 | const roundPower = Math.pow(10, scale); |
| 147 | return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower; |
| 148 | }; |
| 149 | |
| 150 | export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => { |
| 151 | if (min) { |
| 152 | return roundTo(getRandomFloat(max, min), scale); |
| 153 | } |
| 154 | return roundTo(getRandomFloat(max), scale); |
| 155 | }; |
| 156 | |
| 157 | export const getRandomFloatFluctuatedRounded = ( |
| 158 | staticValue: number, |
| 159 | fluctuationPercent: number, |
| 160 | scale = 2, |
| 161 | ): number => { |
| 162 | if (fluctuationPercent < 0 || fluctuationPercent > 100) { |
| 163 | throw new RangeError( |
| 164 | `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`, |
| 165 | ); |
| 166 | } |
| 167 | if (fluctuationPercent === 0) { |
| 168 | return roundTo(staticValue, scale); |
| 169 | } |
| 170 | const fluctuationRatio = fluctuationPercent / 100; |
| 171 | return getRandomFloatRounded( |
| 172 | staticValue * (1 + fluctuationRatio), |
| 173 | staticValue * (1 - fluctuationRatio), |
| 174 | scale, |
| 175 | ); |
| 176 | }; |
| 177 | |
| 178 | export const extractTimeSeriesValues = (timeSeries: Array<TimestampedData>): number[] => { |
| 179 | return timeSeries.map((timeSeriesItem) => timeSeriesItem.value); |
| 180 | }; |
| 181 | |
| 182 | export const isObject = (item: unknown): boolean => { |
| 183 | return ( |
| 184 | isNullOrUndefined(item) === false && typeof item === 'object' && Array.isArray(item) === false |
| 185 | ); |
| 186 | }; |
| 187 | |
| 188 | export const cloneObject = <T extends object>(object: T): T => { |
| 189 | return clone<T>(object); |
| 190 | }; |
| 191 | |
| 192 | export const hasOwnProp = (object: unknown, property: PropertyKey): boolean => { |
| 193 | return isObject(object) && Object.hasOwn(object as object, property); |
| 194 | }; |
| 195 | |
| 196 | export const isCFEnvironment = (): boolean => { |
| 197 | return !isNullOrUndefined(process.env.VCAP_APPLICATION); |
| 198 | }; |
| 199 | |
| 200 | export const isIterable = <T>(obj: T): boolean => { |
| 201 | return !isNullOrUndefined(obj) ? typeof obj[Symbol.iterator as keyof T] === 'function' : false; |
| 202 | }; |
| 203 | |
| 204 | const isString = (value: unknown): boolean => { |
| 205 | return typeof value === 'string'; |
| 206 | }; |
| 207 | |
| 208 | export const isEmptyString = (value: unknown): boolean => { |
| 209 | return isNullOrUndefined(value) || (isString(value) && (value as string).trim().length === 0); |
| 210 | }; |
| 211 | |
| 212 | export const isNotEmptyString = (value: unknown): boolean => { |
| 213 | return isString(value) && (value as string).trim().length > 0; |
| 214 | }; |
| 215 | |
| 216 | export const isUndefined = (value: unknown): boolean => { |
| 217 | return value === undefined; |
| 218 | }; |
| 219 | |
| 220 | export const isNullOrUndefined = (value: unknown): boolean => { |
| 221 | // eslint-disable-next-line eqeqeq, no-eq-null |
| 222 | return value == null; |
| 223 | }; |
| 224 | |
| 225 | export const isEmptyArray = (object: unknown): boolean => { |
| 226 | return Array.isArray(object) && object.length === 0; |
| 227 | }; |
| 228 | |
| 229 | export const isNotEmptyArray = (object: unknown): boolean => { |
| 230 | return Array.isArray(object) && object.length > 0; |
| 231 | }; |
| 232 | |
| 233 | export const isEmptyObject = (obj: object): boolean => { |
| 234 | if (obj?.constructor !== Object) { |
| 235 | return false; |
| 236 | } |
| 237 | // Iterates over the keys of an object, if |
| 238 | // any exist, return false. |
| 239 | for (const _ in obj) { |
| 240 | return false; |
| 241 | } |
| 242 | return true; |
| 243 | }; |
| 244 | |
| 245 | export const insertAt = (str: string, subStr: string, pos: number): string => |
| 246 | `${str.slice(0, pos)}${subStr}${str.slice(pos)}`; |
| 247 | |
| 248 | /** |
| 249 | * Computes the retry delay in milliseconds using an exponential backoff algorithm. |
| 250 | * |
| 251 | * @param retryNumber - the number of retries that have already been attempted |
| 252 | * @returns delay in milliseconds |
| 253 | */ |
| 254 | export const exponentialDelay = (retryNumber = 0, maxDelayRatio = 0.2): number => { |
| 255 | const delay = Math.pow(2, retryNumber) * 100; |
| 256 | const randomSum = delay * maxDelayRatio * secureRandom(); // 0-20% of the delay |
| 257 | return delay + randomSum; |
| 258 | }; |
| 259 | |
| 260 | const isPromisePending = (promise: Promise<unknown>): boolean => { |
| 261 | return inspect(promise).includes('pending'); |
| 262 | }; |
| 263 | |
| 264 | export const promiseWithTimeout = async <T>( |
| 265 | promise: Promise<T>, |
| 266 | timeoutMs: number, |
| 267 | timeoutError: Error, |
| 268 | timeoutCallback: () => void = () => { |
| 269 | /* This is intentional */ |
| 270 | }, |
| 271 | ): Promise<T> => { |
| 272 | // Create a timeout promise that rejects in timeout milliseconds |
| 273 | const timeoutPromise = new Promise<never>((_, reject) => { |
| 274 | setTimeout(() => { |
| 275 | if (isPromisePending(promise)) { |
| 276 | timeoutCallback(); |
| 277 | // FIXME: The original promise shall be canceled |
| 278 | } |
| 279 | reject(timeoutError); |
| 280 | }, timeoutMs); |
| 281 | }); |
| 282 | |
| 283 | // Returns a race between timeout promise and the passed promise |
| 284 | return Promise.race<T>([promise, timeoutPromise]); |
| 285 | }; |
| 286 | |
| 287 | /** |
| 288 | * Generates a cryptographically secure random number in the [0,1[ range |
| 289 | * |
| 290 | * @returns |
| 291 | */ |
| 292 | export const secureRandom = (): number => { |
| 293 | return randomBytes(4).readUInt32LE() / 0x100000000; |
| 294 | }; |
| 295 | |
| 296 | export const JSONStringifyWithMapSupport = ( |
| 297 | obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>, |
| 298 | space?: number, |
| 299 | ): string => { |
| 300 | return JSON.stringify( |
| 301 | obj, |
| 302 | (_, value: Record<string, unknown>) => { |
| 303 | if (value instanceof Map) { |
| 304 | return { |
| 305 | dataType: 'Map', |
| 306 | value: [...value], |
| 307 | }; |
| 308 | } |
| 309 | return value; |
| 310 | }, |
| 311 | space, |
| 312 | ); |
| 313 | }; |
| 314 | |
| 315 | /** |
| 316 | * Converts websocket error code to human readable string message |
| 317 | * |
| 318 | * @param code - websocket error code |
| 319 | * @returns human readable string message |
| 320 | */ |
| 321 | export const getWebSocketCloseEventStatusString = (code: number): string => { |
| 322 | if (code >= 0 && code <= 999) { |
| 323 | return '(Unused)'; |
| 324 | } else if (code >= 1016) { |
| 325 | if (code <= 1999) { |
| 326 | return '(For WebSocket standard)'; |
| 327 | } else if (code <= 2999) { |
| 328 | return '(For WebSocket extensions)'; |
| 329 | } else if (code <= 3999) { |
| 330 | return '(For libraries and frameworks)'; |
| 331 | } else if (code <= 4999) { |
| 332 | return '(For applications)'; |
| 333 | } |
| 334 | } |
| 335 | if ( |
| 336 | !isUndefined( |
| 337 | WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString], |
| 338 | ) |
| 339 | ) { |
| 340 | return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString]; |
| 341 | } |
| 342 | return '(Unknown)'; |
| 343 | }; |