loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
use std::{io, time::Duration};

use axum::{
    Json, Router,
    routing::{get, post},
};
use loveyu_kit::prelude::*;
use serde::{Deserialize, Serialize};
use tracing_subscriber::fmt::format::JsonFields;
use validify::{Payload, Validify};

#[derive(Serialize)]
struct BenchmarkData {
    id: u64,
    name: &'static str,
    active: bool,
}

#[derive(Serialize)]
struct ManualResponse<T> {
    code: u32,
    data: T,
    msg: String,
}

#[derive(Deserialize)]
struct ManualCreatePayload {
    name: String,
}

#[derive(Deserialize, Payload, Validify)]
struct ToolCreatePayload {
    #[modify(trim)]
    #[validate(length(min = 3, code = "400001", message = "名称长度不能少于 3 个字符"))]
    name: String,
}

const fn benchmark_data() -> BenchmarkData {
    BenchmarkData {
        id: 1,
        name: "benchmark-user",
        active: true,
    }
}

async fn manual_response() -> Json<ManualResponse<BenchmarkData>> {
    Json(ManualResponse {
        code: 200,
        data: benchmark_data(),
        msg: "操作成功".to_owned(),
    })
}

async fn tool_response() -> ApiResponse<BenchmarkData> {
    ApiResponse::new(benchmark_data())
}

async fn manual_validation(
    Json(payload): Json<ManualCreatePayload>,
) -> Json<ManualResponse<String>> {
    // 与 Validify 的 trim 保持相同的数据转换,使压测只比较实现开销。
    let name = payload.name.trim().to_owned();
    Json(ManualResponse {
        code: 200,
        data: name,
        msg: "操作成功".to_owned(),
    })
}

async fn tool_validation(
    Validated(Json(payload)): ValidatedJson<ToolCreatePayload>,
) -> ApiResponse<String> {
    ApiResponse::new(payload.name)
}

fn app() -> Router {
    // 禁止成功事件时仍保留 span、请求上下文和 panic 恢复,用于测量中间件固定成本。
    let logging_without_event = RequestLoggingConfig::new()
        .success_sample_rate(0.0)
        .slow_request_threshold(Duration::MAX)
        .always_log_errors(false);
    let logging_without_event_or_panic = logging_without_event.clone().without_panic_recovery();

    let logging_without_event_router = Router::new()
        .route("/logging/tool-disabled", get(manual_response))
        .with_request_logging_config(logging_without_event);
    let logging_without_event_or_panic_router = Router::new()
        .route("/logging/tool-no-panic", get(manual_response))
        .with_request_logging_config(logging_without_event_or_panic);
    let access_logging_router = Router::new()
        .route("/logging/tool-access", get(manual_response))
        .with_access_logging_config(
            RequestLoggingConfig::new()
                .success_sample_rate(0.0)
                .slow_request_threshold(Duration::MAX)
                .always_log_errors(false)
                .without_panic_recovery(),
        );
    let logging_enabled_router = Router::new()
        .route("/logging/tool-enabled", get(manual_response))
        .with_request_logging();

    Router::new()
        .route("/response/manual", get(manual_response))
        .route("/response/tool", get(tool_response))
        .route("/validation/manual", post(manual_validation))
        .route("/validation/tool", post(tool_validation))
        .route("/logging/manual", get(manual_response))
        .merge(logging_without_event_router)
        .merge(logging_without_event_or_panic_router)
        .merge(access_logging_router)
        .merge(logging_enabled_router)
}

#[tokio::main]
async fn main() {
    // 日志写入 sink:保留 JSON 格式化成本,但排除终端和磁盘吞吐差异。
    let subscriber = tracing_subscriber::fmt()
        .fmt_fields(JsonFields::new())
        .event_format(StructuredJsonFormatter::new())
        .with_writer(io::sink)
        .finish();
    tracing::subscriber::set_global_default(subscriber).expect("初始化压测日志失败");

    let address = std::env::args()
        .nth(1)
        .unwrap_or_else(|| "127.0.0.1:3100".to_owned());
    let listener = tokio::net::TcpListener::bind(&address)
        .await
        .expect("监听压测地址失败");
    println!("压测服务已监听:http://{address}");

    axum::serve(listener, app())
        .await
        .expect("压测服务异常退出");
}