redup-bootstrap 0.3.3

Ядро платформы: инстанс службы, модули, жизненный цикл, здоровье и телеметрия.
Documentation
//! Съём запроса и ответа для дампов на границе gRPC.

use std::net::SocketAddr;
use std::sync::Arc;
use std::time::SystemTime;

use axum::extract::ConnectInfo;
use redup_bootstrap_grpc::diagnostics::{
    BODY_LIMIT, DumpRecord, DumpRegistry, ExceptionInfo, PackedBody, code_name, unpack_body,
};
use tonic::Status;

use crate::grpc_server::capture::Capture;

/// Съём одного вызова: метод, тела, адрес и момент начала.
pub(crate) struct DumpCapture {
    /// Реестр подписок.
    pub(crate) registry: Arc<DumpRegistry>,
    /// Полный путь метода.
    pub(crate) method: String,
    /// Адрес вызывающей стороны.
    pub(crate) remote: String,
    /// Момент начала обработки.
    pub(crate) started_at: SystemTime,
    /// Полное имя входного сообщения.
    pub(crate) input_type: Option<String>,
    /// Полное имя выходного сообщения.
    pub(crate) output_type: Option<String>,
    /// Накопитель тела запроса.
    pub(crate) request: Option<Arc<Capture>>,
    /// Накопитель тела ответа.
    pub(crate) response: Option<Arc<Capture>>,
    /// Сжатие тела запроса.
    pub(crate) request_encoding: Option<String>,
    /// Сжатие тела ответа.
    pub(crate) response_encoding: Option<String>,
}

impl DumpCapture {
    /// Накопитель ответа, если тело ответа снимается.
    pub(crate) fn response_capture(&self) -> Option<&Arc<Capture>> {
        self.response.as_ref()
    }

    /// Записать сведение о вызове в реестр.
    ///
    /// `failure` — исходная ошибка обработки до перепаковки в безопасный текст.
    pub(crate) fn record(self, failure: Option<&Status>) -> DumpRecord {
        let end_date = SystemTime::now();
        let exception = failure.map(exception_info);
        let request = match &exception {
            Some(_) => None,
            None => self.packed(
                self.request.as_ref(),
                self.input_type.as_deref(),
                self.request_encoding.as_deref(),
            ),
        };
        let response = match &exception {
            Some(_) => None,
            None => self.packed(
                self.response.as_ref(),
                self.output_type.as_deref(),
                self.response_encoding.as_deref(),
            ),
        };
        let record = DumpRecord {
            method: self.method,
            remote_address: self.remote,
            request,
            start_date: self.started_at,
            response,
            end_date,
            exception,
        };
        self.registry.record(&record);
        record
    }

    /// Разобрать накопленное тело в сообщение с полным именем типа.
    fn packed(
        &self,
        capture: Option<&Arc<Capture>>,
        message_type: Option<&str>,
        encoding: Option<&str>,
    ) -> Option<PackedBody> {
        let frames = capture?.take()?;
        let body = unpack_body(&frames, encoding)?;
        Some(PackedBody {
            r#type: message_type.unwrap_or_default().to_owned(),
            body,
        })
    }
}

/// Описание ошибки дампа по исходному статусу.
fn exception_info(status: &Status) -> ExceptionInfo {
    let parsed = redup_bootstrap_grpc::details(status);
    let internal = parsed.domain.is_none();
    let r#type = parsed
        .reason
        .as_deref()
        .filter(|reason| !reason.is_empty())
        .map_or_else(|| code_name(status.code()).to_owned(), str::to_owned);
    ExceptionInfo {
        r#type,
        message: status.message().to_owned(),
        stack_trace: parsed.debug,
        internal,
    }
}

/// Предел съёма одного тела.
pub(crate) const CAPTURE_LIMIT: usize = BODY_LIMIT;

/// Адрес вызывающей стороны по расширению соединения.
pub(crate) fn peer(request: &http::Request<axum::body::Body>) -> String {
    match request.extensions().get::<ConnectInfo<SocketAddr>>() {
        Some(ConnectInfo(address)) => {
            let family = if address.is_ipv4() { "ipv4" } else { "ipv6" };
            format!("{family}:{address}")
        }
        None => String::new(),
    }
}