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