All files / global/helpers retry.mjs

100% Statements 33/33
80% Branches 16/20
100% Functions 10/10
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79                                      23x                                 869x 869x       869x       869x 869x 910x 910x 910x       822x 9x   822x   81x   81x 27x 27x   54x 41x 41x 41x 41x             13x 13x    
/*
  Copyright (C) 2026 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import {v4 as uuidv4} from 'uuid';
 
const logger = getLoggerWithTag('retry_func');
 
/**
 * Выполняет fn с повторами при ошибке.
 * @param {number} retryCount - число повторов (всего попыток retryCount + 1)
 * @param {number | ((attemptIndex: number) => number)} pauseBetweenAttemptMs - пауза перед повтором, мс;
 *   функция получает индекс неудачной попытки с нуля (0 - пауза перед первым повтором)
 * @param {() => Promise<any>} fn - операция
 * @param {{
 *   shouldRetry?: (error: any, attemptIndex: number) => boolean,
 *   onRetry?: (error: any, attemptIndex: number, pauseMs: number) => void,
 *   formatErrorForLog?: (error: any) => string | undefined
 * }} [options] - shouldRetry = false пробрасывает ошибку сразу, без повторов;
 *   onRetry вызывается перед паузой, когда повтор точно будет;
 *   formatErrorForLog задаёт описание ошибки для debug, по умолчанию используется её сообщение
 */
export async function execWithRetry(retryCount = 0, pauseBetweenAttemptMs = 0, fn, options = {}) {
    const {shouldRetry, onRetry, formatErrorForLog = (error) => error?.message} = options || {};
    const pauseOf = (attempt) => (typeof pauseBetweenAttemptMs === 'function'
        ? pauseBetweenAttemptMs(attempt)
        : pauseBetweenAttemptMs);
    let lastError;
    let logUuid = '';
    // uuid связывает между собой строки одной серии попыток. Генерим лениво: на успешном пути (а это
    // подавляющее большинство операций кеша) он не нужен вовсе. Звать uid() внутри msgFn безопасно:
    // логгер вычисляет сообщение, только если уровень включён.
    const uid = () => logUuid || (logUuid = uuidv4());
    for (let attempt = 0; attempt <= retryCount; attempt++) {
        logger.trace(() => `${uid()}: Attempt ${attempt + 1}`);
        try {
            const result = await fn();
            // Только после неудачных попыток - иначе строка печаталась бы на каждую операцию кеша.
            // Без неё в логе оставалось "Attempt N failed ... trying again" и тишина: не отличить
            // восстановившийся ретрай от окончательного отказа.
            if (attempt !== 0) {
                logger.debug(() => `${uid()}: Attempt ${attempt + 1} success`);
            }
            return result;
        } catch (error) {
            lastError = error;
            // Неповторяемая ошибка уходит вызывающему как есть, без строки об исчерпании попыток.
            if (shouldRetry && !shouldRetry(error, attempt)) {
                logger.debug(() => `${uid()}: Attempt ${attempt + 1} failed with non-retryable error: ${formatErrorForLog(error)}`);
                throw error;
            }
            if (attempt < retryCount) {
                const pauseMs = pauseOf(attempt);
                logger.debug(() => `${uid()}: Attempt ${attempt + 1} failed with error: ${formatErrorForLog(error)}, wait ${pauseMs} ms and trying again...`);
                onRetry?.(error, attempt, pauseMs);
                await new Promise(resolve => setTimeout(resolve, pauseMs));
            }
        }
    }
 
    // Исчерпание попыток видно на уровне ретрая независимо от того, логирует вызывающий или нет:
    // до этого серия обрывалась в логе на последнем "trying again".
    logger.debug(() => `${uid()}: All ${retryCount + 1} attempt(s) failed, last error: ${formatErrorForLog(lastError)}`);
    throw lastError || new Error(`${uid()}: All attempt failed`);
}