redup-bootstrap 0.3.3

Ядро платформы: инстанс службы, модули, жизненный цикл, здоровье и телеметрия.
Documentation
//! Главная страница сведений: `/info`.

use super::dependency;
use super::escape::encode_segment;
use super::format::{format_duration, format_load, format_size};
use super::layout::{PLACEHOLDER, document, link, link_cell, list, row, section, table, text_cell};
use super::{Info, Memory};

/// Заголовки таблицы сведений.
const FACT_HEADERS: [&str; 2] = ["Показатель", "Значение"];
/// Заголовки таблицы нагрузки.
const LOAD_HEADERS: [&str; 4] = ["Вид", "1 мин", "5 мин", "15 мин"];
/// Заголовки таблицы модулей.
const MODULE_HEADERS: [&str; 4] = ["Модуль", "Фаза", "Проблемы", "Готовность"];

/// Собирает главную страницу сведений инстанса.
pub(super) fn render(info: &Info) -> String {
    let mut body = String::new();
    body.push_str(&section("Сведения", &facts_table(info)));
    body.push_str(&section("Нагрузка", &load_table(info)));
    body.push_str(&section("Модули", &modules_table(info)));
    if has_dependencies(info) {
        body.push_str(&section("Зависимости", &dependencies_table(info)));
    }
    if !info.configs.is_empty() {
        body.push_str(&section("Конфигурации", &configs_list(info)));
    }
    document(&info.service.name, &body, false, &info.platform_version)
}

/// Таблица общих сведений об инстансе.
fn facts_table(info: &Info) -> String {
    let rows = vec![
        row(&[text_cell("Версия"), text_cell(&info.service.version)]),
        row(&[text_cell("Платформа"), text_cell(&info.platform_version)]),
        row(&[
            text_cell("Идентификатор инстанса"),
            text_cell(&info.instance_id),
        ]),
        row(&[text_cell("Узел"), text_cell(&info.hostname)]),
        row(&[text_cell("Процессоров"), text_cell(&info.cpus.to_string())]),
        row(&[
            text_cell("Время работы"),
            text_cell(&format_duration(info.uptime)),
        ]),
        row(&[text_cell("Состояние"), text_cell(&info.state)]),
        row(&[
            text_cell("Готовность"),
            link_cell("/readyz", &info.readiness.to_string()),
        ]),
        row(&[
            text_cell("Живость"),
            link_cell("/livez", &info.liveness.to_string()),
        ]),
        row(&[text_cell("Память"), text_cell(&memory_text(info.memory))]),
    ];
    table(&FACT_HEADERS, &rows)
}

/// Описание памяти: резидентная память, предел или отметка об отсутствии
/// сведений.
fn memory_text(memory: Memory) -> String {
    let Some(resident) = memory.resident_bytes else {
        return "неизвестна".to_string();
    };
    let resident = format_size(resident);
    match memory.container_limit_bytes {
        Some(limit) => format!("{resident} — {}", format_size(limit)),
        None => format!("{resident} — без предела"),
    }
}

/// Таблица нагрузки по видам.
fn load_table(info: &Info) -> String {
    let [incoming, outgoing, background] = info.load;
    let kinds = [
        ("Входящие", incoming),
        ("Исходящие", outgoing),
        ("Фоновая работа", background),
    ];
    let rows: Vec<String> = kinds
        .into_iter()
        .map(|(name, load)| {
            row(&[
                text_cell(name),
                text_cell(&format_load(load.one_minute)),
                text_cell(&format_load(load.five_minutes)),
                text_cell(&format_load(load.fifteen_minutes)),
            ])
        })
        .collect();
    table(&LOAD_HEADERS, &rows)
}

/// Таблица модулей: имя — ссылка на карточку, проблемы — числом, готовность —
/// ссылкой на проверку.
fn modules_table(info: &Info) -> String {
    let rows: Vec<String> = info
        .modules
        .iter()
        .map(|module| {
            let problems = if module.problems.is_empty() {
                PLACEHOLDER.to_string()
            } else {
                module.problems.len().to_string()
            };
            row(&[
                link_cell(
                    &format!("/info/{}", encode_segment(&module.name)),
                    &module.name,
                ),
                text_cell(&module.phase.to_string()),
                text_cell(&problems),
                link_cell(
                    &format!("/readyz/{}", encode_segment(&module.name)),
                    &module.phase.to_string(),
                ),
            ])
        })
        .collect();
    table(&MODULE_HEADERS, &rows)
}

/// Есть ли хоть одна зависимость у любого модуля.
fn has_dependencies(info: &Info) -> bool {
    info.modules
        .iter()
        .any(|module| !module.dependencies.is_empty())
}

/// Таблица зависимостей всех модулей.
fn dependencies_table(info: &Info) -> String {
    let rows: Vec<String> = info
        .modules
        .iter()
        .flat_map(|module| {
            module
                .dependencies
                .iter()
                .map(move |(name, dep)| dependency::row_cells(Some(&module.name), name, dep))
        })
        .collect();
    table(&dependency::HEADERS_WITH_MODULE, &rows)
}

/// Список ссылок на конфигурации.
fn configs_list(info: &Info) -> String {
    let items: Vec<String> = info
        .configs
        .iter()
        .map(|config| {
            link(
                &format!("/config/{}", encode_segment(&config.name)),
                &config.name,
            )
        })
        .collect();
    list(&items)
}