Commit | Line | Data |
---|---|---|
d972af76 JB |
1 | import { randomBytes, randomInt, randomUUID } from 'node:crypto'; |
2 | import { inspect } from 'node:util'; | |
8114d10e | 3 | |
088ee3c1 JB |
4 | import clone from 'just-clone'; |
5 | ||
878e026c | 6 | import { Constants } from './Constants'; |
268a74bb | 7 | import { WebSocketCloseEventStatusString } from '../types'; |
5e3cb728 | 8 | |
9bf0ef23 JB |
9 | export const logPrefix = (prefixString = ''): string => { |
10 | return `${new Date().toLocaleString()}${prefixString}`; | |
11 | }; | |
d5bd1c00 | 12 | |
9bf0ef23 JB |
13 | export const generateUUID = (): string => { |
14 | return randomUUID(); | |
15 | }; | |
147d0e0f | 16 | |
9bf0ef23 JB |
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 | }; | |
03eacbe5 | 22 | |
9bf0ef23 JB |
23 | export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => { |
24 | return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds)); | |
25 | }; | |
7dde0b73 | 26 | |
9bf0ef23 JB |
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(); | |
7dde0b73 | 35 | |
9bf0ef23 JB |
36 | if (hours < 10) { |
37 | hoursStr = `0${hours.toString()}`; | |
9ac86a7e | 38 | } |
9bf0ef23 JB |
39 | if (minutes < 10) { |
40 | minutesStr = `0${minutes.toString()}`; | |
7dde0b73 | 41 | } |
9bf0ef23 JB |
42 | if (seconds < 10) { |
43 | secondsStr = `0${seconds.toString()}`; | |
7dde0b73 | 44 | } |
9bf0ef23 JB |
45 | return `${hoursStr}:${minutesStr}:${secondsStr.substring(0, 6)}`; |
46 | }; | |
7dde0b73 | 47 | |
9bf0ef23 JB |
48 | export const formatDurationSeconds = (duration: number): string => { |
49 | return formatDurationMilliSeconds(duration * 1000); | |
50 | }; | |
7dde0b73 | 51 | |
9bf0ef23 JB |
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; | |
7dde0b73 | 57 | } |
9bf0ef23 JB |
58 | if (value instanceof Date) { |
59 | return value; | |
a6e68f34 | 60 | } |
9bf0ef23 JB |
61 | if (isString(value) || typeof value === 'number') { |
62 | return new Date(value); | |
560bcf5b | 63 | } |
9bf0ef23 JB |
64 | return null; |
65 | }; | |
560bcf5b | 66 | |
9bf0ef23 JB |
67 | export const convertToInt = (value: unknown): number => { |
68 | if (!value) { | |
69 | return 0; | |
560bcf5b | 70 | } |
9bf0ef23 JB |
71 | let changedValue: number = value as number; |
72 | if (Number.isSafeInteger(value)) { | |
73 | return value as number; | |
6d3a11a0 | 74 | } |
9bf0ef23 JB |
75 | if (typeof value === 'number') { |
76 | return Math.trunc(value); | |
7dde0b73 | 77 | } |
9bf0ef23 JB |
78 | if (isString(value)) { |
79 | changedValue = parseInt(value as string); | |
9ccca265 | 80 | } |
9bf0ef23 JB |
81 | if (isNaN(changedValue)) { |
82 | throw new Error(`Cannot convert to integer: ${value.toString()}`); | |
dada83ec | 83 | } |
9bf0ef23 JB |
84 | return changedValue; |
85 | }; | |
dada83ec | 86 | |
9bf0ef23 JB |
87 | export const convertToFloat = (value: unknown): number => { |
88 | if (!value) { | |
89 | return 0; | |
dada83ec | 90 | } |
9bf0ef23 JB |
91 | let changedValue: number = value as number; |
92 | if (isString(value)) { | |
93 | changedValue = parseFloat(value as string); | |
560bcf5b | 94 | } |
9bf0ef23 JB |
95 | if (isNaN(changedValue)) { |
96 | throw new Error(`Cannot convert to float: ${value.toString()}`); | |
5a2a53cf | 97 | } |
9bf0ef23 JB |
98 | return changedValue; |
99 | }; | |
5a2a53cf | 100 | |
9bf0ef23 JB |
101 | export const convertToBoolean = (value: unknown): boolean => { |
102 | let result = false; | |
103 | if (value) { | |
104 | // Check the type | |
105 | if (typeof value === 'boolean') { | |
106 | return value; | |
107 | } else if (isString(value) && ((value as string).toLowerCase() === 'true' || value === '1')) { | |
108 | result = true; | |
109 | } else if (typeof value === 'number' && value === 1) { | |
110 | result = true; | |
e7aeea18 | 111 | } |
c37528f1 | 112 | } |
9bf0ef23 JB |
113 | return result; |
114 | }; | |
115 | ||
116 | export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => { | |
117 | if (max < min) { | |
118 | throw new RangeError('Invalid interval'); | |
119 | } | |
120 | if (max - min === Infinity) { | |
121 | throw new RangeError('Invalid interval'); | |
122 | } | |
123 | return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min; | |
124 | }; | |
125 | ||
126 | export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => { | |
127 | max = Math.floor(max); | |
128 | if (!isNullOrUndefined(min) && min !== 0) { | |
129 | min = Math.ceil(min); | |
130 | return Math.floor(randomInt(min, max + 1)); | |
131 | } | |
132 | return Math.floor(randomInt(max + 1)); | |
133 | }; | |
134 | ||
135 | /** | |
136 | * Rounds the given number to the given scale. | |
137 | * The rounding is done using the "round half away from zero" method. | |
138 | * | |
139 | * @param numberValue - The number to round. | |
140 | * @param scale - The scale to round to. | |
141 | * @returns The rounded number. | |
142 | */ | |
143 | export const roundTo = (numberValue: number, scale: number): number => { | |
144 | const roundPower = Math.pow(10, scale); | |
145 | return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower; | |
146 | }; | |
147 | ||
148 | export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => { | |
149 | if (min) { | |
150 | return roundTo(getRandomFloat(max, min), scale); | |
151 | } | |
152 | return roundTo(getRandomFloat(max), scale); | |
153 | }; | |
154 | ||
155 | export const getRandomFloatFluctuatedRounded = ( | |
156 | staticValue: number, | |
157 | fluctuationPercent: number, | |
158 | scale = 2 | |
159 | ): number => { | |
160 | if (fluctuationPercent < 0 || fluctuationPercent > 100) { | |
161 | throw new RangeError( | |
162 | `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}` | |
fe791818 JB |
163 | ); |
164 | } | |
9bf0ef23 JB |
165 | if (fluctuationPercent === 0) { |
166 | return roundTo(staticValue, scale); | |
167 | } | |
168 | const fluctuationRatio = fluctuationPercent / 100; | |
169 | return getRandomFloatRounded( | |
170 | staticValue * (1 + fluctuationRatio), | |
171 | staticValue * (1 - fluctuationRatio), | |
172 | scale | |
173 | ); | |
174 | }; | |
175 | ||
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 => { | |
195 | return !isNullOrUndefined(obj) ? typeof obj[Symbol.iterator] === 'function' : false; | |
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 */ | |
264 | } | |
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>, | |
292 | space?: number | |
293 | ): string => { | |
294 | return JSON.stringify( | |
295 | obj, | |
296 | (key, value: Record<string, unknown>) => { | |
297 | if (value instanceof Map) { | |
298 | return { | |
299 | dataType: 'Map', | |
300 | value: [...value], | |
301 | }; | |
302 | } | |
303 | return value; | |
304 | }, | |
305 | space | |
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 | } |
9bf0ef23 JB |
329 | if (!isUndefined(WebSocketCloseEventStatusString[code])) { |
330 | return WebSocketCloseEventStatusString[code] as string; | |
331 | } | |
332 | return '(Unknown)'; | |
333 | }; |