- public static async promiseWithTimeout<T>(
- promise: Promise<T>,
- timeoutMs: number,
- timeoutError: Error,
- timeoutCallback: () => void = () => {
- /* This is intentional */
- }
- ): Promise<T> {
- // Create a timeout promise that rejects in timeout milliseconds
- const timeoutPromise = new Promise<never>((_, reject) => {
- setTimeout(() => {
- if (Utils.isPromisePending(promise)) {
- timeoutCallback();
- // FIXME: The original promise shall be canceled
- }
- reject(timeoutError);
- }, timeoutMs);
- });
-
- // Returns a race between timeout promise and the passed promise
- return Promise.race<T>([promise, timeoutPromise]);
- }
-
- /**
- * Generate a cryptographically secure random number in the [0,1[ range
- *
- * @returns
- */
- public static secureRandom(): number {
- return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
- }
-
- public static JSONStringifyWithMapSupport(
- obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>,
- space?: number
- ): string {
- return JSON.stringify(
- obj,
- (key, value: Record<string, unknown>) => {
- if (value instanceof Map) {
- return {
- dataType: 'Map',
- value: [...value],
- };
+export const isNotEmptyString = (value: unknown): value is string => {
+ return isString(value) && value.trim().length > 0
+}
+
+export const isEmptyArray = (value: unknown): value is never[] => {
+ return Array.isArray(value) && value.length === 0
+}
+
+export const isNotEmptyArray = (value: unknown): value is unknown[] => {
+ return Array.isArray(value) && value.length > 0
+}
+
+export const insertAt = (str: string, subStr: string, pos: number): string =>
+ `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
+
+/**
+ * Computes the retry delay in milliseconds using an exponential backoff algorithm.
+ *
+ * @param retryNumber - the number of retries that have already been attempted
+ * @param delayFactor - the base delay factor in milliseconds
+ * @returns delay in milliseconds
+ */
+export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => {
+ const delay = Math.pow(2, retryNumber) * delayFactor
+ const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay
+ return delay + randomSum
+}
+
+/**
+ * Generates a cryptographically secure random number in the [0,1[ range
+ *
+ * @returns A number in the [0,1[ range
+ */
+export const secureRandom = (): number => {
+ return getRandomValues(new Uint32Array(1))[0] / 0x100000000
+}
+
+export const JSONStringifyWithMapSupport = (
+ object: Record<string, unknown> | Array<Record<string, unknown>> | Map<unknown, unknown>,
+ space?: number
+): string => {
+ return JSON.stringify(
+ object,
+ (_, value: Record<string, unknown>) => {
+ if (value instanceof Map) {
+ return {
+ dataType: 'Map',
+ value: [...value]