All files / backend/cluster master-cycle.ts

93.54% Statements 29/31
100% Branches 8/8
81.81% Functions 9/11
100% Lines 26/26

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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109                                              1x                                     3x 3x 2x 2x   2x 2x 2x   1x 1x                 7x 7x 6x 4x     2x           3x                 4x 1x   3x 2x   1x         2x                 3x 1x   2x 2x    
/*
  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 {
    CycleResult, failCycle, interruptUnfinishedCycle, LoadVersions, ManifestLoadMeta, publishCycle, startCycle
} from './load-cycle.ts';
import {CommandSetter, setReloadCommand} from './reload-command.ts';
import {describeError} from '@back/helpers/errorText.ts';
 
const logger = getLoggerWithTag('cluster');
 
/** Часть кластерного кеша, через которую мастер ведёт версии цикла загрузки (ERA-3627) */
export interface LoadCycleCache extends CommandSetter {
    getLoadCycle(): Promise<LoadVersions>;
    saveLoadCycle(cycle: LoadVersions): Promise<void>;
    readManifestMetas(): Promise<ManifestLoadMeta[]>;
    applyCycleResult(result: CycleResult): Promise<void>;
}
 
/**
 * Запускает цикл загрузки: версия цикла пишется до запуска загрузчика. Если она не записалась, загрузчик не
 * запускается - снаружи такую загрузку приняли бы за начатую после запроса, - а команда, уже снятая мастером,
 * возвращается в кеш, и следующий тик мастера пробует снова.
 * @returns true, если загрузчик запущен
 */
export async function startLoadCycle(
    cache: LoadCycleCache, cycleVersion: number, startLoader: () => void | Promise<void>
): Promise<boolean> {
    try {
        const cycle = await cache.getLoadCycle();
        const started = startCycle(cycle, cycleVersion);
        await cache.saveLoadCycle(started);
    } catch (error) {
        logger.error(() => `Write manifest cycle version failed, reload postponed: ${error}`, error);
        await setReloadCommand(cache);
        return false;
    }
    await startLoader();
    return true;
}
 
// Итог цикла повторить нельзя, а без него снаружи не узнают, чем закончилась загрузка: сбой записи - в лог
async function recordCycleResult(
    cache: LoadCycleCache,
    transition: (cycle: LoadVersions, metas: ManifestLoadMeta[]) => CycleResult | null,
    description: string
): Promise<void> {
    try {
        const result = transition(await cache.getLoadCycle(), await cache.readManifestMetas());
        if (result) {
            await cache.applyCycleResult(result);
        }
    } catch (error) {
        logger.error(() => `Write manifest load versions failed (${description}): ${error}`, error);
    }
}
 
/** Цикл опубликован (момент ready): мета alias, загруженных в нём, затем цикл */
export function publishLoadCycle(cache: LoadCycleCache, cycleVersion: number): Promise<void> {
    return recordCycleResult(cache, (cycle, metas) => publishCycle(cycle, metas, cycleVersion), 'publish cycle');
}
 
/**
 * Текст ошибки упавшего цикла: ошибка, о которой сообщил загрузчик; иначе сбой его потока (исключение, нехватка
 * памяти - событие 'error' перед 'exit'); иначе код выхода.
 * @param threadError - ошибка из события 'error' потока загрузчика; undefined - события не было
 */
export function loaderFailureText(reported: string | null | undefined, threadError: unknown, exitCode: number): string {
    if (reported) {
        return reported;
    }
    if (threadError !== undefined) {
        return describeError(threadError);
    }
    return `Manifest loader exited with code ${exitCode}`;
}
 
/** Цикл упал: ошибка цикла - alias, загруженным в нём, затем циклу */
export function failLoadCycle(cache: LoadCycleCache, cycleVersion: number, error: string, now: number): Promise<void> {
    return recordCycleResult(cache, (cycle, metas) => failCycle(cycle, metas, cycleVersion, error, now), 'cycle failure');
}
 
/**
 * Узел стал мастером: незавершённый цикл прежнего мастера закрывается как прерванный, иначе снаружи ждали бы его
 * бесконечно. Пока этот узел сам загружает, цикл его собственный, и его не трогаем.
 * @returns true, если проверка выполнялась
 */
export async function interruptCycleOnMasterChange(cache: LoadCycleCache, isLoading: boolean, now: number): Promise<boolean> {
    if (isLoading) {
        return false;
    }
    await recordCycleResult(cache, (cycle, metas) => interruptUnfinishedCycle(cycle, metas, now), 'interrupt unfinished cycle');
    return true;
}