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();
38 return hoursStr
+ ':' + minutesStr
+ ':' + secondsStr
.substring(0, 6);
41 public static formatDurationSeconds(duration
: number): string {
42 return Utils
.formatDurationMilliSeconds(duration
* 1000);
45 public static convertToDate(value
: unknown
): Date {
51 if (!(value
instanceof Date)) {
52 return new Date(value
as string);
57 public static convertToInt(value
: unknown
): number {
58 let changedValue
: number = value
as number;
62 if (Number.isSafeInteger(value
)) {
63 return value
as number;
66 if (Utils
.isString(value
)) {
68 changedValue
= parseInt(value
as string);
73 public static convertToFloat(value
: unknown
): number {
74 let changedValue
: number = value
as number;
79 if (Utils
.isString(value
)) {
81 changedValue
= parseFloat(value
as string);
86 public static convertToBoolean(value
: unknown
): boolean {
91 if (typeof value
=== 'boolean') {
96 result
= (value
=== 'true');
102 public static getRandomFloat(max
: number, min
= 0, negative
= false): number {
103 if (max
< min
|| min
< 0 || max
< 0) {
104 throw new RangeError('Invalid interval');
106 const randomPositiveFloat
= crypto
.randomBytes(4).readUInt32LE() / 0xffffffff;
107 const sign
= (negative
&& randomPositiveFloat
< 0.5) ? 1 : -1;
108 return sign
* (randomPositiveFloat
* (max
- min
) + min
);
111 public static getRandomInt(max
: number, min
= 0): number {
112 max
= Math.floor(max
);
114 min
= Math.ceil(min
);
115 return Math.floor(Utils
.secureRandom() * (max
- min
+ 1)) + min
;
117 return Math.floor(Utils
.secureRandom() * (max
+ 1));
120 public static roundTo(numberValue
: number, scale
: number): number {
121 const roundPower
= Math.pow(10, scale
);
122 return Math.round(numberValue
* roundPower
) / roundPower
;
125 public static truncTo(numberValue
: number, scale
: number): number {
126 const truncPower
= Math.pow(10, scale
);
127 return Math.trunc(numberValue
* truncPower
) / truncPower
;
130 public static getRandomFloatRounded(max
: number, min
= 0, scale
= 2): number {
132 return Utils
.roundTo(Utils
.getRandomFloat(max
, min
), scale
);
134 return Utils
.roundTo(Utils
.getRandomFloat(max
), scale
);
137 public static getRandomFloatFluctuatedRounded(staticValue
: number, fluctuationPercent
: number, scale
= 2): number {
138 if (fluctuationPercent
=== 0) {
139 return Utils
.roundTo(staticValue
, scale
);
141 const fluctuationRatio
= fluctuationPercent
/ 100;
142 return Utils
.getRandomFloatRounded(staticValue
* (1 + fluctuationRatio
), staticValue
* (1 - fluctuationRatio
), scale
);
145 public static cloneObject
<T
>(object
: T
): T
{
146 return JSON
.parse(JSON
.stringify(object
)) as T
;
149 public static isIterable
<T
>(obj
: T
): boolean {
151 return typeof obj
[Symbol
.iterator
] === 'function';
156 public static isString(value
: unknown
): boolean {
157 return typeof value
=== 'string';
160 public static isUndefined(value
: unknown
): boolean {
161 return typeof value
=== 'undefined';
164 public static isNullOrUndefined(value
: unknown
): boolean {
165 // eslint-disable-next-line no-eq-null, eqeqeq
172 public static isEmptyArray(object
: unknown
): boolean {
176 if (Array.isArray(object
) && object
.length
> 0) {
182 public static isEmptyObject(obj
: Record
<string, unknown
>): boolean {
183 return !Object.keys(obj
).length
;
186 public static insertAt
= (str
: string, subStr
: string, pos
: number): string => `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
189 * @param [retryNumber=0]
190 * @returns delay in milliseconds
192 public static exponentialDelay(retryNumber
= 0): number {
193 const delay
= Math.pow(2, retryNumber
) * 100;
194 const randomSum
= delay
* 0.2 * Utils
.secureRandom(); // 0-20% of the delay
195 return delay
+ randomSum
;
199 * Convert websocket error code to human readable string message
201 * @param code websocket error code
202 * @returns human readable string message
204 public static getWebSocketCloseEventStatusString(code
: number): string {
205 if (code
>= 0 && code
<= 999) {
207 } else if (code
>= 1016) {
209 return '(For WebSocket standard)';
210 } else if (code
<= 2999) {
211 return '(For WebSocket extensions)';
212 } else if (code
<= 3999) {
213 return '(For libraries and frameworks)';
214 } else if (code
<= 4999) {
215 return '(For applications)';
218 if (!Utils
.isUndefined(WebSocketCloseEventStatusString
[code
])) {
219 return WebSocketCloseEventStatusString
[code
] as string;
224 public static workerPoolInUse(): boolean {
225 return [WorkerProcessType
.DYNAMIC_POOL
, WorkerProcessType
.STATIC_POOL
].includes(Configuration
.getWorkerProcess());
228 public static workerDynamicPoolInUse(): boolean {
229 return Configuration
.getWorkerProcess() === WorkerProcessType
.DYNAMIC_POOL
;
233 * Generate a cryptographically secure random number in the [0,1[ range
237 public static secureRandom(): number {
238 return crypto
.randomBytes(4).readUInt32LE() / 0x100000000;