All files / backend/cluster health-info.ts

92% Statements 23/25
100% Branches 12/12
33.33% Functions 1/3
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 80 81 82 83 84                                    1x                                                                 9x 1x   8x 8x 1x   7x 7x 7x 6x 6x 2x   4x   1x     5x 5x 1x 1x   4x 4x 4x   1x   4x    
/*
  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';
 
const logger = getLoggerWithTag('cluster');
 
/** Часть кластерного кеша, которую читает /health/info. Метода status() здесь нет намеренно (CAP-14) */
export interface HealthInfoCache {
    getInfoProbeState(nodeId: string): Promise<unknown>;
    getMasterInfo(): Promise<{id?: string}>;
    getAllManifestState(): Promise<Record<string, unknown>[] | undefined>;
    getLoadCycle(): Promise<unknown>;
}
 
export interface HealthInfoResponse {
    status: number;
    body: Record<string, unknown>;
}
 
/**
 * Ответ GET /health/info. Ручку обслуживает worker, и во время перезагрузки её опрашивают часто, поэтому она только
 * читает состояние кластера: метку мастера - через getMasterInfo(), а не status(), который захватывает и продлевает
 * мастерство (ERA-3627, CAP-14).
 * Версии загрузки: сначала мета манифестов (manifests), затем цикл (loadCycle). Итог цикла мастер пишет в том же
 * порядке (master-cycle.ts), и ответ, прочитанный между двумя записями, содержит новый цикл и прежнюю мету. Такой
 * ответ не противоречит полному: alias, итог которых мастер ещё не записал, выглядят в нём загружающимися, а при
 * упавшем цикле - закрытыми ошибкой цикла, как и после обеих записей.
 * Мету прочитать не удалось - в ответе нет ни manifests, ни loadCycle: пустой список означал бы, что alias нет.
 * @param describe - описание состояния пода (utils/getInfoResponse.mjs)
 * @param toManifest - элемент manifests[] из меты манифеста (cluster/manifestInfoDto.mjs)
 */
export async function buildHealthInfo(
    cache: HealthInfoCache,
    primaryProcessId: string | undefined,
    describe: (state: unknown) => unknown,
    toManifest: (meta: Record<string, unknown>) => unknown
): Promise<HealthInfoResponse> {
    if (!primaryProcessId) {
        return {status: 503, body: {message: 'No info, did not receive primary process id yet.'}};
    }
    const primaryState = await cache.getInfoProbeState(primaryProcessId);
    if (!primaryState) {
        return {status: 503, body: {primaryProcessId, message: 'Cannot read pod state info from clusterCache.'}};
    }
    const body: Record<string, unknown> = {self: describe(primaryState)};
    const masterId = (await cache.getMasterInfo()).id;
    if (primaryProcessId !== masterId) {
        const masterState = masterId ? await cache.getInfoProbeState(masterId) : undefined;
        if (!masterState) {
            return {status: 503, body: {masterId, primaryProcessId, message: 'Cannot read master state info from clusterCache.'}};
        }
        body.master = describe(masterState);
    } else {
        body.master = body.self;
    }
 
    const metas = await cache.getAllManifestState();
    if (!metas) {
        logger.warn(() => 'Read manifest meta for health info failed, respond without load versions');
        return {status: 200, body};
    }
    body.manifests = metas.map(toManifest);
    try {
        body.loadCycle = await cache.getLoadCycle();
    } catch (error) {
        logger.warn(() => 'Read manifest load cycle for health info failed', error);
    }
    return {status: 200, body};
}