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