Commit | Line | Data |
---|---|---|
a4624c96 | 1 | import Configuration from './Configuration'; |
32a1eb7a | 2 | import { WebSocketCloseEventStatusString } from '../types/WebSocket'; |
a4624c96 | 3 | import { WorkerProcessType } from '../types/Worker'; |
c37528f1 | 4 | import crypto from 'crypto'; |
6af9012e | 5 | import { v4 as uuid } from 'uuid'; |
7dde0b73 | 6 | |
3f40bc9c | 7 | export 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)); | |
d10397af 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 | |
96 | result = (value === 'true'); | |
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; |
87f1fc2a | 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 | ||
0f16a662 | 143 | public static getRandomFloatFluctuatedRounded(staticValue: number, fluctuationPercent: number, scale = 2): number { |
9ccca265 JB |
144 | if (fluctuationPercent === 0) { |
145 | return Utils.roundTo(staticValue, scale); | |
146 | } | |
97ef739c JB |
147 | const fluctuationRatio = fluctuationPercent / 100; |
148 | return Utils.getRandomFloatRounded(staticValue * (1 + fluctuationRatio), staticValue * (1 - fluctuationRatio), scale); | |
9ccca265 JB |
149 | } |
150 | ||
0f16a662 | 151 | public static cloneObject<T>(object: T): T { |
e56aa9a4 | 152 | return JSON.parse(JSON.stringify(object)) as T; |
2e6f5966 | 153 | } |
facd8ebd | 154 | |
0f16a662 | 155 | public static isIterable<T>(obj: T): boolean { |
67e9cccf JB |
156 | if (obj) { |
157 | return typeof obj[Symbol.iterator] === 'function'; | |
158 | } | |
159 | return false; | |
160 | } | |
161 | ||
0f16a662 | 162 | public static isString(value: unknown): boolean { |
560bcf5b JB |
163 | return typeof value === 'string'; |
164 | } | |
165 | ||
0f16a662 | 166 | public static isUndefined(value: unknown): boolean { |
ead548f2 JB |
167 | return typeof value === 'undefined'; |
168 | } | |
169 | ||
0f16a662 | 170 | public static isNullOrUndefined(value: unknown): boolean { |
32a1eb7a | 171 | // eslint-disable-next-line no-eq-null, eqeqeq |
ead548f2 | 172 | if (value == null) { |
facd8ebd JB |
173 | return true; |
174 | } | |
175 | return false; | |
176 | } | |
4a56deef | 177 | |
0f16a662 | 178 | public static isEmptyArray(object: unknown): boolean { |
fd1ee77c JB |
179 | if (!object) { |
180 | return true; | |
181 | } | |
4a56deef JB |
182 | if (Array.isArray(object) && object.length > 0) { |
183 | return false; | |
184 | } | |
185 | return true; | |
186 | } | |
7abfea5f | 187 | |
0f16a662 | 188 | public static isEmptyObject(obj: Record<string, unknown>): boolean { |
7abfea5f JB |
189 | return !Object.keys(obj).length; |
190 | } | |
7ec46a9a | 191 | |
0f16a662 | 192 | public static insertAt = (str: string, subStr: string, pos: number): string => `${str.slice(0, pos)}${subStr}${str.slice(pos)}`; |
032d6efc JB |
193 | |
194 | /** | |
81797102 JB |
195 | * @param [retryNumber=0] |
196 | * @returns delay in milliseconds | |
032d6efc | 197 | */ |
0f16a662 | 198 | public static exponentialDelay(retryNumber = 0): number { |
032d6efc | 199 | const delay = Math.pow(2, retryNumber) * 100; |
c37528f1 | 200 | const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay |
032d6efc JB |
201 | return delay + randomSum; |
202 | } | |
32a1eb7a | 203 | |
e71cccf3 JB |
204 | /** |
205 | * Convert websocket error code to human readable string message | |
206 | * | |
81797102 JB |
207 | * @param code websocket error code |
208 | * @returns human readable string message | |
e71cccf3 | 209 | */ |
0f16a662 | 210 | public static getWebSocketCloseEventStatusString(code: number): string { |
32a1eb7a JB |
211 | if (code >= 0 && code <= 999) { |
212 | return '(Unused)'; | |
213 | } else if (code >= 1016) { | |
214 | if (code <= 1999) { | |
215 | return '(For WebSocket standard)'; | |
216 | } else if (code <= 2999) { | |
217 | return '(For WebSocket extensions)'; | |
218 | } else if (code <= 3999) { | |
219 | return '(For libraries and frameworks)'; | |
220 | } else if (code <= 4999) { | |
221 | return '(For applications)'; | |
222 | } | |
223 | } | |
224 | if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) { | |
17991e8c | 225 | return WebSocketCloseEventStatusString[code] as string; |
32a1eb7a JB |
226 | } |
227 | return '(Unknown)'; | |
228 | } | |
a4624c96 | 229 | |
0f16a662 | 230 | public static workerPoolInUse(): boolean { |
9ab7950c | 231 | return [WorkerProcessType.DYNAMIC_POOL, WorkerProcessType.STATIC_POOL].includes(Configuration.getWorkerProcess()); |
a4624c96 | 232 | } |
059f35a5 | 233 | |
0f16a662 | 234 | public static workerDynamicPoolInUse(): boolean { |
059f35a5 JB |
235 | return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL; |
236 | } | |
c37528f1 | 237 | |
6d9abcc2 JB |
238 | public static async promiseWithTimeout<T>( |
239 | promise: Promise<T>, | |
240 | timeoutMs: number, | |
241 | timeoutError: Error, | |
242 | timeoutCallback: () => void = () => { /* This is intentional */ } | |
243 | ): Promise<T> { | |
244 | // Create a timeout promise that rejects in timeout milliseconds | |
245 | const timeoutPromise = new Promise<never>((_, reject) => { | |
246 | setTimeout(() => { | |
ed0f8380 | 247 | timeoutCallback(); |
6d9abcc2 JB |
248 | reject(timeoutError); |
249 | }, timeoutMs); | |
250 | }); | |
251 | ||
252 | // Returns a race between timeout promise and the passed promise | |
253 | return Promise.race<T>([promise, timeoutPromise]); | |
254 | } | |
255 | ||
c37528f1 | 256 | /** |
0f16a662 | 257 | * Generate a cryptographically secure random number in the [0,1[ range |
c37528f1 JB |
258 | * |
259 | * @returns | |
260 | */ | |
0f16a662 | 261 | public static secureRandom(): number { |
c37528f1 JB |
262 | return crypto.randomBytes(4).readUInt32LE() / 0x100000000; |
263 | } | |
7dde0b73 | 264 | } |