1 import Configuration from
'./Configuration';
2 import { WebSocketCloseEventStatusString
} from
'../types/WebSocket';
3 import { WorkerProcessType
} from
'../types/Worker';
4 import crypto from
'crypto';
5 import { v4
as uuid
} from
'uuid';
7 export default class Utils
{
8 public static logPrefix(prefixString
= ''): string {
9 return new Date().toLocaleString() + prefixString
;
12 public static generateUUID(): string {
16 public static async sleep(milliSeconds
: number): Promise
<NodeJS
.Timeout
> {
17 return new Promise((resolve
) => setTimeout(resolve
, milliSeconds
));
20 public static formatDurationMilliSeconds(duration
: number): string {
21 duration
= Utils
.convertToInt(duration
);
22 const hours
= Math.floor(duration
/ (3600 * 1000));
23 const minutes
= Math.floor((duration
/ 1000 - (hours
* 3600)) / 60);
24 const seconds
= duration
/ 1000 - (hours
* 3600) - (minutes
* 60);
25 let hoursStr
: string = hours
.toString();
26 let minutesStr
: string = minutes
.toString();
27 let secondsStr
: string = seconds
.toString();
30 hoursStr
= '0' + hours
.toString();
33 minutesStr
= '0' + minutes
.toString();
36 secondsStr
= ('0' + seconds
.toString()).substring(0, 6);
38 return hoursStr
+ ':' + minutesStr
+ ':' + secondsStr
;
41 public static formatDurationSeconds(duration
: number): string {
42 return Utils
.formatDurationMilliSeconds(duration
* 1000);
45 public static removeExtraEmptyLines(tab
: string[]): void {
47 for (let i
= tab
.length
- 1; i
> 0; i
--) {
48 // Two consecutive empty lines?
49 if (tab
[i
].length
=== 0 && tab
[i
- 1].length
=== 0) {
50 // Remove the last one
54 if (i
=== 1 && tab
[i
- 1].length
=== 0) {
55 // Remove the first one
61 public static convertToDate(value
: unknown
): Date {
67 if (!(value
instanceof Date)) {
68 return new Date(value
as string);
73 public static convertToInt(value
: unknown
): number {
74 let changedValue
: number = value
as number;
78 if (Number.isSafeInteger(value
)) {
79 return value
as number;
82 if (Utils
.isString(value
)) {
84 changedValue
= parseInt(value
as string);
89 public static convertToFloat(value
: unknown
): number {
90 let changedValue
: number = value
as number;
95 if (Utils
.isString(value
)) {
97 changedValue
= parseFloat(value
as string);
102 public static convertToBoolean(value
: unknown
): boolean {
107 if (typeof value
=== 'boolean') {
112 result
= (value
=== 'true');
118 public static getRandomFloat(max
: number, min
= 0, negative
= false): number {
119 const randomPositiveFloat
= crypto
.randomBytes(4).readUInt32LE() / 0xffffffff;
120 const sign
= (negative
&& randomPositiveFloat
< 0.5) ? 1 : -1;
121 return sign
* (randomPositiveFloat
* (max
- min
) + min
);
124 public static getRandomInt(max
: number, min
= 0): number {
125 max
= Math.floor(max
);
127 min
= Math.ceil(min
);
128 return Math.floor(Utils
.secureRandom() * (max
- min
+ 1)) + min
;
130 return Math.floor(Utils
.secureRandom() * (max
+ 1));
133 public static roundTo(numberValue
: number, scale
: number): number {
134 const roundPower
= Math.pow(10, scale
);
135 return Math.round(numberValue
* roundPower
) / roundPower
;
138 public static truncTo(numberValue
: number, scale
: number): number {
139 const truncPower
= Math.pow(10, scale
);
140 return Math.trunc(numberValue
* truncPower
) / truncPower
;
143 public static getRandomFloatRounded(max
: number, min
= 0, scale
= 2): number {
145 return Utils
.roundTo(Utils
.getRandomFloat(max
, min
), scale
);
147 return Utils
.roundTo(Utils
.getRandomFloat(max
), scale
);
150 public static getRandomFloatFluctuatedRounded(staticValue
: number, fluctuationPercent
: number, scale
= 2): number {
151 if (fluctuationPercent
=== 0) {
152 return Utils
.roundTo(staticValue
, scale
);
154 const fluctuationRatio
= fluctuationPercent
/ 100;
155 return Utils
.getRandomFloatRounded(staticValue
* (1 + fluctuationRatio
), staticValue
* (1 - fluctuationRatio
), scale
);
158 public static cloneObject
<T
>(object
: T
): T
{
159 return JSON
.parse(JSON
.stringify(object
)) as T
;
162 public static isIterable
<T
>(obj
: T
): boolean {
164 return typeof obj
[Symbol
.iterator
] === 'function';
169 public static isEmptyJSon(document
: unknown
): boolean {
175 if (typeof document
!== 'object') {
179 return Object.keys(document
).length
=== 0;
182 public static isString(value
: unknown
): boolean {
183 return typeof value
=== 'string';
186 public static isUndefined(value
: unknown
): boolean {
187 return typeof value
=== 'undefined';
190 public static isNullOrUndefined(value
: unknown
): boolean {
191 // eslint-disable-next-line no-eq-null, eqeqeq
198 public static isEmptyArray(object
: unknown
): boolean {
202 if (Array.isArray(object
) && object
.length
> 0) {
208 public static isEmptyObject(obj
: Record
<string, unknown
>): boolean {
209 return !Object.keys(obj
).length
;
212 public static insertAt
= (str
: string, subStr
: string, pos
: number): string => `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
215 * @param [retryNumber=0]
216 * @returns delay in milliseconds
218 public static exponentialDelay(retryNumber
= 0): number {
219 const delay
= Math.pow(2, retryNumber
) * 100;
220 const randomSum
= delay
* 0.2 * Utils
.secureRandom(); // 0-20% of the delay
221 return delay
+ randomSum
;
225 * Convert websocket error code to human readable string message
227 * @param code websocket error code
228 * @returns human readable string message
230 public static getWebSocketCloseEventStatusString(code
: number): string {
231 if (code
>= 0 && code
<= 999) {
233 } else if (code
>= 1016) {
235 return '(For WebSocket standard)';
236 } else if (code
<= 2999) {
237 return '(For WebSocket extensions)';
238 } else if (code
<= 3999) {
239 return '(For libraries and frameworks)';
240 } else if (code
<= 4999) {
241 return '(For applications)';
244 if (!Utils
.isUndefined(WebSocketCloseEventStatusString
[code
])) {
245 return WebSocketCloseEventStatusString
[code
] as string;
250 public static workerPoolInUse(): boolean {
251 return [WorkerProcessType
.DYNAMIC_POOL
, WorkerProcessType
.STATIC_POOL
].includes(Configuration
.getWorkerProcess());
254 public static workerDynamicPoolInUse(): boolean {
255 return Configuration
.getWorkerProcess() === WorkerProcessType
.DYNAMIC_POOL
;
259 * Generate a cryptographically secure random number in the [0,1[ range
263 public static secureRandom(): number {
264 return crypto
.randomBytes(4).readUInt32LE() / 0x100000000;