loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
//! 向当前请求日志上下文追加业务审计信息的便捷接口。
//!
//! 这些函数只丰富由请求日志中间件统一输出的结构化上下文,
//! 不代替需要与业务事务一起持久化的合规审计记录。

use std::fmt::Display;

use serde::Serialize;

use super::{
    Diagnostic, DiagnosticKind, FieldChange, RequestLogContext, RequestOperation, ResourceTarget,
    SqlDiagnostic,
};

/// 将当前请求标记为会改变状态或产生外部副作用的命令。
pub fn command(name: &'static str, description: &'static str, resource: &'static str) {
    RequestLogContext::with_current(|context| {
        context.set_operation(
            RequestOperation::command_static(name)
                .with_description_static(description)
                .with_resource_static(resource),
        );
    });
}

/// 使用运行时字符串将当前请求标记为命令。
pub fn command_owned(
    name: impl Into<String>,
    description: impl Into<String>,
    resource: impl Into<String>,
) {
    RequestLogContext::with_current(|context| {
        context.set_operation(
            RequestOperation::command(name)
                .with_description(description)
                .with_resource(resource),
        );
    });
}

/// 将当前请求标记为只读查询。
pub fn query(name: &'static str, description: &'static str, resource: &'static str) {
    RequestLogContext::with_current(|context| {
        context.set_operation(
            RequestOperation::query_static(name)
                .with_description_static(description)
                .with_resource_static(resource),
        );
    });
}

/// 使用运行时字符串将当前请求标记为查询。
pub fn query_owned(
    name: impl Into<String>,
    description: impl Into<String>,
    resource: impl Into<String>,
) {
    RequestLogContext::with_current(|context| {
        context.set_operation(
            RequestOperation::query(name)
                .with_description(description)
                .with_resource(resource),
        );
    });
}

/// 记录当前操作影响的一个资源目标。
pub fn target(kind: impl Into<String>, id: impl Display) {
    RequestLogContext::with_current(|context| {
        context.add_target(ResourceTarget::new(kind).with_id(id.to_string()));
    });
}

/// 记录一个包含额外安全属性的资源目标。
pub fn target_resource(target: ResourceTarget) {
    RequestLogContext::with_current(|context| context.add_target(target));
}

/// 以字符串形式记录一项已成功提交的字段变化。
pub fn field_change(field: impl Into<String>, before: impl Display, after: impl Display) {
    RequestLogContext::with_current(|context| {
        context.add_change(FieldChange::new(field, before, after));
    });
}

/// 保留 JSON 原始类型记录一项已提交变化,适用于数字、布尔值、字符串和 `Value`。
pub fn change(
    field: impl Into<String>,
    before: impl Into<serde_json::Value>,
    after: impl Into<serde_json::Value>,
) {
    RequestLogContext::with_current(|context| {
        context.add_change(FieldChange::from_values(field, before, after));
    });
}

/// 以字符串形式记录一项尚未确认提交的尝试变化。
pub fn attempted_change(field: impl Into<String>, before: impl Display, after: impl Display) {
    RequestLogContext::with_current(|context| {
        context.add_attempted_change(FieldChange::new(field, before, after));
    });
}

/// 保留原始 JSON 类型地记录一项已成功提交的字段变化。
///
/// 返回 `Ok(true)` 表示已写入当前请求上下文,`Ok(false)` 表示当前不在
/// 完整请求日志的异步作用域内。只有存在当前上下文时才执行 JSON 序列化。
///
/// # Errors
///
/// 修改前或修改后的值无法序列化为 JSON 时返回错误。
pub fn json_field_change<T, U>(
    field: impl Into<String>,
    before: T,
    after: U,
) -> Result<bool, serde_json::Error>
where
    T: Serialize,
    U: Serialize,
{
    let Some(context) = RequestLogContext::try_current() else {
        return Ok(false);
    };
    let change = FieldChange::from_json(field, before, after)?;
    context.add_change(change);
    Ok(true)
}

/// 保留原始 JSON 类型地记录一项尝试变化。
///
/// # Errors
///
/// 修改前或修改后的值无法序列化为 JSON 时返回错误。
pub fn json_attempted_change<T, U>(
    field: impl Into<String>,
    before: T,
    after: U,
) -> Result<bool, serde_json::Error>
where
    T: Serialize,
    U: Serialize,
{
    let Some(context) = RequestLogContext::try_current() else {
        return Ok(false);
    };
    context.add_attempted_change(FieldChange::from_json(field, before, after)?);
    Ok(true)
}

/// 记录当前请求的一条失败诊断。
pub fn diagnostic(diagnostic: Diagnostic) {
    RequestLogContext::with_current(|context| context.record_diagnostic(diagnostic));
}

/// 根据类别、名称和错误快速记录失败诊断。
pub fn failure(kind: DiagnosticKind, name: impl Into<String>, error: impl Display) {
    diagnostic(Diagnostic::new(kind, name, error));
}

/// 记录当前请求的一条 SQL 失败诊断。
pub fn sql_error(diagnostic: SqlDiagnostic) {
    RequestLogContext::with_current(|context| context.record_sql_error(diagnostic));
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;
    use crate::observability::{OperationKind, context::scope_request_log};

    #[tokio::test]
    async fn helpers_collect_structured_request_audit_information() {
        let context = RequestLogContext::new();

        scope_request_log(context.clone(), async {
            command("article.save", "保存文章", "article");
            target("article", 1001);
            field_change("title", "旧标题", "新标题");
            assert!(
                json_field_change("visibility", false, true).expect("JSON 字段变化应当可序列化")
            );
        })
        .await;

        let snapshot = context.structured_snapshot();
        let operation = snapshot.operation.expect("应当记录当前操作");
        assert_eq!(operation.name, "article.save");
        assert_eq!(operation.kind, OperationKind::Command);
        assert_eq!(snapshot.targets[0].id.as_deref(), Some("1001"));
        assert_eq!(snapshot.changes[0].before, json!("旧标题"));
        assert_eq!(snapshot.changes[1].after, json!(true));
    }

    #[tokio::test]
    async fn helpers_are_noop_without_request_logging_scope() {
        query("article.list", "查询文章", "article");
        target("article", 1001);
        field_change("title", "旧标题", "新标题");

        assert!(
            !json_field_change("visibility", false, true)
                .expect("没有请求上下文时不应执行 JSON 序列化")
        );
    }
}