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