Improve OCPP incoming requests handling
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
CommitLineData
a4624c96 1import Configuration from './Configuration';
32a1eb7a 2import { WebSocketCloseEventStatusString } from '../types/WebSocket';
a4624c96 3import { WorkerProcessType } from '../types/Worker';
c37528f1 4import crypto from 'crypto';
6af9012e 5import { v4 as uuid } from 'uuid';
7dde0b73 6
3f40bc9c 7export default class Utils {
0f16a662 8 public static logPrefix(prefixString = ''): string {
147d0e0f
JB
9 return new Date().toLocaleString() + prefixString;
10 }
11
0f16a662 12 public static generateUUID(): string {
2e3ac96d 13 return uuid();
7dde0b73
JB
14 }
15
0f16a662 16 public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
5f8a4fd6 17 return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds));
7dde0b73
JB
18 }
19
d7d1db72
JB
20 public static formatDurationMilliSeconds(duration: number): string {
21 duration = Utils.convertToInt(duration);
22 const hours = Math.floor(duration / (3600 * 1000));
e7aeea18
JB
23 const minutes = Math.floor((duration / 1000 - hours * 3600) / 60);
24 const seconds = duration / 1000 - hours * 3600 - minutes * 60;
a3868ec4
JB
25 let hoursStr = hours.toString();
26 let minutesStr = minutes.toString();
27 let secondsStr = seconds.toString();
d7d1db72
JB
28
29 if (hours < 10) {
30 hoursStr = '0' + hours.toString();
31 }
32 if (minutes < 10) {
33 minutesStr = '0' + minutes.toString();
34 }
35 if (seconds < 10) {
b322b8b4 36 secondsStr = '0' + seconds.toString();
d7d1db72 37 }
b322b8b4 38 return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6);
9ac86a7e
JB
39 }
40
d7d1db72
JB
41 public static formatDurationSeconds(duration: number): string {
42 return Utils.formatDurationMilliSeconds(duration * 1000);
7dde0b73
JB
43 }
44
0f16a662 45 public static convertToDate(value: unknown): Date {
560bcf5b 46 // Check
6af9012e 47 if (!value) {
73d09045 48 return value as Date;
560bcf5b
JB
49 }
50 // Check Type
6af9012e 51 if (!(value instanceof Date)) {
73d09045 52 return new Date(value as string);
7dde0b73 53 }
6af9012e 54 return value;
7dde0b73
JB
55 }
56
0f16a662 57 public static convertToInt(value: unknown): number {
73d09045 58 let changedValue: number = value as number;
72766a82 59 if (!value) {
7dde0b73
JB
60 return 0;
61 }
72766a82 62 if (Number.isSafeInteger(value)) {
95926c9b 63 return value as number;
72766a82 64 }
7dde0b73 65 // Check
087a502d 66 if (Utils.isString(value)) {
7dde0b73 67 // Create Object
73d09045 68 changedValue = parseInt(value as string);
7dde0b73 69 }
72766a82 70 return changedValue;
7dde0b73
JB
71 }
72
0f16a662 73 public static convertToFloat(value: unknown): number {
73d09045 74 let changedValue: number = value as number;
72766a82 75 if (!value) {
7dde0b73
JB
76 return 0;
77 }
78 // Check
087a502d 79 if (Utils.isString(value)) {
7dde0b73 80 // Create Object
73d09045 81 changedValue = parseFloat(value as string);
7dde0b73 82 }
72766a82 83 return changedValue;
7dde0b73
JB
84 }
85
0f16a662 86 public static convertToBoolean(value: unknown): boolean {
a6e68f34
JB
87 let result = false;
88 // Check boolean
89 if (value) {
90 // Check the type
91 if (typeof value === 'boolean') {
92 // Already a boolean
93 result = value;
94 } else {
95 // Convert
e7aeea18 96 result = value === 'true';
a6e68f34
JB
97 }
98 }
99 return result;
100 }
101
fd00fa2e 102 public static getRandomFloat(max: number, min = 0, negative = false): number {
b322b8b4
JB
103 if (max < min || min < 0 || max < 0) {
104 throw new RangeError('Invalid interval');
105 }
fd00fa2e 106 const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
e7aeea18 107 const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1;
fd00fa2e 108 return sign * (randomPositiveFloat * (max - min) + min);
560bcf5b
JB
109 }
110
72740232 111 public static getRandomInteger(max: number, min = 0): number {
a3868ec4
JB
112 if (max < 0) {
113 throw new RangeError('Invalid interval');
114 }
fd00fa2e 115 max = Math.floor(max);
7dde0b73 116 if (min) {
a3868ec4
JB
117 if (max < min || min < 0) {
118 throw new RangeError('Invalid interval');
119 }
fd00fa2e 120 min = Math.ceil(min);
c37528f1 121 return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
7dde0b73 122 }
c37528f1 123 return Math.floor(Utils.secureRandom() * (max + 1));
560bcf5b
JB
124 }
125
0f16a662 126 public static roundTo(numberValue: number, scale: number): number {
ad3de6c4 127 const roundPower = Math.pow(10, scale);
035742f7 128 return Math.round(numberValue * roundPower) / roundPower;
560bcf5b
JB
129 }
130
0f16a662 131 public static truncTo(numberValue: number, scale: number): number {
6d3a11a0 132 const truncPower = Math.pow(10, scale);
035742f7 133 return Math.trunc(numberValue * truncPower) / truncPower;
6d3a11a0
JB
134 }
135
0f16a662 136 public static getRandomFloatRounded(max: number, min = 0, scale = 2): number {
560bcf5b
JB
137 if (min) {
138 return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
139 }
140 return Utils.roundTo(Utils.getRandomFloat(max), scale);
7dde0b73
JB
141 }
142
e7aeea18
JB
143 public static getRandomFloatFluctuatedRounded(
144 staticValue: number,
145 fluctuationPercent: number,
146 scale = 2
147 ): number {
9ccca265
JB
148 if (fluctuationPercent === 0) {
149 return Utils.roundTo(staticValue, scale);
150 }
97ef739c 151 const fluctuationRatio = fluctuationPercent / 100;
e7aeea18
JB
152 return Utils.getRandomFloatRounded(
153 staticValue * (1 + fluctuationRatio),
154 staticValue * (1 - fluctuationRatio),
155 scale
156 );
9ccca265
JB
157 }
158
0f16a662 159 public static cloneObject<T>(object: T): T {
e56aa9a4 160 return JSON.parse(JSON.stringify(object)) as T;
2e6f5966 161 }
facd8ebd 162
0f16a662 163 public static isIterable<T>(obj: T): boolean {
67e9cccf
JB
164 if (obj) {
165 return typeof obj[Symbol.iterator] === 'function';
166 }
167 return false;
168 }
169
0f16a662 170 public static isString(value: unknown): boolean {
560bcf5b
JB
171 return typeof value === 'string';
172 }
173
e8191622
JB
174 public static isEmptyString(value: unknown): boolean {
175 return Utils.isString(value) && (value as string).length === 0;
176 }
177
0f16a662 178 public static isUndefined(value: unknown): boolean {
ead548f2
JB
179 return typeof value === 'undefined';
180 }
181
0f16a662 182 public static isNullOrUndefined(value: unknown): boolean {
32a1eb7a 183 // eslint-disable-next-line no-eq-null, eqeqeq
ead548f2 184 if (value == null) {
facd8ebd
JB
185 return true;
186 }
187 return false;
188 }
4a56deef 189
0f16a662 190 public static isEmptyArray(object: unknown): boolean {
fd1ee77c
JB
191 if (!object) {
192 return true;
193 }
4a56deef
JB
194 if (Array.isArray(object) && object.length > 0) {
195 return false;
196 }
197 return true;
198 }
7abfea5f 199
94ec7e96 200 public static isEmptyObject(obj: object): boolean {
7abfea5f
JB
201 return !Object.keys(obj).length;
202 }
7ec46a9a 203
e7aeea18
JB
204 public static insertAt = (str: string, subStr: string, pos: number): string =>
205 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
032d6efc
JB
206
207 /**
81797102
JB
208 * @param [retryNumber=0]
209 * @returns delay in milliseconds
032d6efc 210 */
0f16a662 211 public static exponentialDelay(retryNumber = 0): number {
032d6efc 212 const delay = Math.pow(2, retryNumber) * 100;
c37528f1 213 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
032d6efc
JB
214 return delay + randomSum;
215 }
32a1eb7a 216
e71cccf3
JB
217 /**
218 * Convert websocket error code to human readable string message
219 *
81797102
JB
220 * @param code websocket error code
221 * @returns human readable string message
e71cccf3 222 */
0f16a662 223 public static getWebSocketCloseEventStatusString(code: number): string {
32a1eb7a
JB
224 if (code >= 0 && code <= 999) {
225 return '(Unused)';
226 } else if (code >= 1016) {
227 if (code <= 1999) {
228 return '(For WebSocket standard)';
229 } else if (code <= 2999) {
230 return '(For WebSocket extensions)';
231 } else if (code <= 3999) {
232 return '(For libraries and frameworks)';
233 } else if (code <= 4999) {
234 return '(For applications)';
235 }
236 }
237 if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) {
17991e8c 238 return WebSocketCloseEventStatusString[code] as string;
32a1eb7a
JB
239 }
240 return '(Unknown)';
241 }
a4624c96 242
0f16a662 243 public static workerPoolInUse(): boolean {
e7aeea18
JB
244 return [WorkerProcessType.DYNAMIC_POOL, WorkerProcessType.STATIC_POOL].includes(
245 Configuration.getWorkerProcess()
246 );
a4624c96 247 }
059f35a5 248
0f16a662 249 public static workerDynamicPoolInUse(): boolean {
059f35a5
JB
250 return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL;
251 }
c37528f1 252
6d9abcc2 253 public static async promiseWithTimeout<T>(
e7aeea18
JB
254 promise: Promise<T>,
255 timeoutMs: number,
256 timeoutError: Error,
257 timeoutCallback: () => void = () => {
258 /* This is intentional */
259 }
6d9abcc2
JB
260 ): Promise<T> {
261 // Create a timeout promise that rejects in timeout milliseconds
262 const timeoutPromise = new Promise<never>((_, reject) => {
263 setTimeout(() => {
ed0f8380 264 timeoutCallback();
6d9abcc2
JB
265 reject(timeoutError);
266 }, timeoutMs);
267 });
268
269 // Returns a race between timeout promise and the passed promise
270 return Promise.race<T>([promise, timeoutPromise]);
271 }
272
c37528f1 273 /**
0f16a662 274 * Generate a cryptographically secure random number in the [0,1[ range
c37528f1
JB
275 *
276 * @returns
277 */
0f16a662 278 public static secureRandom(): number {
c37528f1
JB
279 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
280 }
7dde0b73 281}