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