wordval-web 1.0.13

Wordval web layer: router, middleware, extractors, responses, session-based authentication
Documentation
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! 请求访问日志中间件
//!
//! 记录请求路径、状态码、耗时,输出到 tracing(终端/文件/ELK)。
//! 如需操作审计日志(含请求参数、响应体、脱敏、写库),
//! 请通过 `App::with_middleware_hook` 注入项目级中间件。

use axum::body::{to_bytes, Body};
use axum::http::{header, StatusCode};
use axum::{extract::Request, response::Response};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Instant;
use tower::{Layer, Service};
use tracing::{info, warn};

/// 调试模式下 body 打印的最大长度(超出截断显示,不影响实际传输)
const PRINT_BODY_MAX: usize = 4096;

/// 调试模式收集请求/响应体的硬上限(防止大 body 被无界缓冲导致 OOM)
const MAX_BUFFER_BODY: usize = 16 * 1024 * 1024;

/// 已声明长度超过缓冲上限时的占位文本(body 原样透传,不收集)
const BODY_OVER_LIMIT_NOTE: &str = "(body 超过缓冲上限,未打印)";

/// 请求访问日志中间件:记录请求路径 + 状态码 + 耗时
///
/// 通过 config.toml 中 `[middleware]` 下的 `request_log` 和 `request_log_config` 控制开关和参数。
/// `print_body = true` 时进入调试模式:额外打印请求参数(query + body)与响应体,
/// 开启会完整收集 body 再重建(有内存/序列化开销),生产环境建议关闭。
/// `report_multiline = true` 时改为多行 Action Report(URL/参数/结果/耗时分行对齐),
/// 人读更直观但日志量与 IO 压力更大,生产环境建议关闭。
#[derive(Clone)]
pub struct RequestLogLayer {
    /// 不记录日志的路径列表。
    /// Arc 共享:`Router::layer` 对每个路由端点 clone 本层,裸 Vec 会被
    /// 深拷贝出 E 份字符串列表;Arc 使逐端点 clone 退化为引用计数 +1。
    pub exclude_paths: Arc<Vec<String>>,
    /// 是否记录请求耗时
    pub log_duration: bool,
    /// 调试模式:打印请求参数与响应体(默认关闭)
    pub print_body: bool,
    /// 多行 Action Report 格式(默认关闭,单行更省日志量)
    pub report_multiline: bool,
}

impl Default for RequestLogLayer {
    fn default() -> Self {
        Self {
            exclude_paths: Arc::new(vec!["/health".into(), "/favicon.ico".into()]),
            log_duration: true,
            print_body: false,
            report_multiline: false,
        }
    }
}

impl RequestLogLayer {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn exclude_paths(mut self, paths: Vec<String>) -> Self {
        self.exclude_paths = Arc::new(paths);
        self
    }
}

impl<S> Layer<S> for RequestLogLayer {
    type Service = RequestLogService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        RequestLogService {
            inner,
            exclude_paths: self.exclude_paths.clone(),
            log_duration: self.log_duration,
            print_body: self.print_body,
            report_multiline: self.report_multiline,
        }
    }
}

#[derive(Clone)]
/// 请求日志服务——记录请求路径、状态码、耗时(调试模式可打印请求参数与响应体)
pub struct RequestLogService<S> {
    /// 下游服务
    inner: S,
    /// 不记录日志的路径列表(Arc 共享,克隆廉价)
    exclude_paths: Arc<Vec<String>>,
    /// 是否记录请求耗时
    log_duration: bool,
    /// 调试模式:打印请求参数与响应体
    print_body: bool,
    /// 多行 Action Report 格式
    report_multiline: bool,
}

// body 收集需要具体 body 类型(axum Router 实际为 Request<Body>)
impl<S> Service<Request<Body>> for RequestLogService<S>
where
    S: Service<Request<Body>, Response = Response> + Clone + Send + 'static,
    S::Future: Send + 'static,
    // 调试模式收集响应体时 `Result` 跨 await 存活,要求错误类型 Send
    S::Error: Send,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut req: Request<Body>) -> Self::Future {
        let path = req.uri().path().to_string();
        let should_log = !self.exclude_paths.contains(&path);

        let replacement = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, replacement);

        // 排除路径(如 /health):直接透传,不做计时/收集/分配,
        // 避免健康检查等高频端点在调试模式下白白缓冲 body
        if !should_log {
            return Box::pin(async move { inner.call(req).await });
        }

        let method = req.method().clone();
        // 统一从 ClientIdentity 层解析的扩展读取客户端 IP,避免与限流层
        // 使用不同代理策略产生不一致的 IP 结论
        let ip = req
            .extensions()
            .get::<super::client_identity::ClientIp>()
            .map(|c| c.0.clone())
            .unwrap_or_else(|| "unknown".to_string());
        // 请求 ID 优先读 RequestId 扩展(入站非法 ID 已被 RequestId 层替换)
        let req_id = req
            .extensions()
            .get::<super::request_id::RequestId>()
            .map(|r| r.0.clone())
            .or_else(|| {
                req.headers()
                    .get("x-request-id")
                    .and_then(|v| v.to_str().ok())
                    .map(|s| s.to_string())
            })
            .unwrap_or_else(|| "-".to_string());
        let log_duration = self.log_duration;
        let print_body = self.print_body;
        let report_multiline = self.report_multiline;
        // query 仅调试模式/多行报告需要,单行模式不分配
        let query_str = if print_body || report_multiline {
            req.uri().query().map(|q| q.to_string()).unwrap_or_default()
        } else {
            String::new()
        };
        let start = Instant::now();

        Box::pin(async move {
            // 调试模式:先完整收集请求体(打印时截断,缓冲设硬上限防 OOM),
            // 收集成功后原样重建请求;未知长度超限时短路 413(见 collect_request_body)
            let req_snippet = if print_body {
                match collect_request_body(&mut req, MAX_BUFFER_BODY).await {
                    Ok(snippet) => snippet,
                    Err(resp) => {
                        warn!(
                            request_id = %req_id, ip = %ip,
                            "{method} {path} -> 413 (调试日志请求体超出缓冲上限)"
                        );
                        return Ok(resp);
                    }
                }
            } else {
                String::new()
            };

            let mut result = inner.call(req).await;

            // 调试模式:完整收集响应体(打印时截断,缓冲设硬上限防 OOM),
            // 收集成功后原样重建响应
            let resp_snippet = if print_body {
                match &mut result {
                    Ok(resp) => collect_response_body(resp, MAX_BUFFER_BODY).await,
                    Err(_) => String::new(),
                }
            } else {
                String::new()
            };

            let elapsed = start.elapsed();
            // 耗时裸文本(多行报告不带括号,单行保留括号包裹)
            let duration_ms = elapsed.as_millis();
            let duration_str = if log_duration {
                format!("{duration_ms}ms")
            } else {
                String::new()
            };

            // ── 多行 Action Report(report_multiline=true)──
            if report_multiline {
                let (status_text, is_err) = match &result {
                    Ok(response) => {
                        let reason = response
                            .status()
                            .canonical_reason()
                            .unwrap_or("");
                        (
                            format!("{} {}", response.status().as_u16(), reason),
                            false,
                        )
                    }
                    Err(_e) => ("ERR".to_string(), true),
                };
                let report = build_report(
                    method.as_str(),
                    &path,
                    &query_str,
                    &status_text,
                    &duration_str,
                    &ip,
                    &req_id,
                    &req_snippet,
                    &resp_snippet,
                    print_body,
                );
                if is_err {
                    warn!(request_id = %req_id, ip = %ip, "{report}");
                } else {
                    info!(request_id = %req_id, ip = %ip, "{report}");
                }
                return result;
            }

            // ── 单行模式(默认):状态码前置、耗时括号包裹,一行一目了然 ──
            let duration_paren = if duration_str.is_empty() {
                String::new()
            } else {
                format!(" ({duration_str})")
            };
            // 调试模式:请求参数 = query + body,响应体单独一段
            let req_debug = if print_body && (!query_str.is_empty() || !req_snippet.is_empty()) {
                if query_str.is_empty() {
                    format!(" req={req_snippet}")
                } else if req_snippet.is_empty() {
                    format!(" req=?{query_str}")
                } else {
                    format!(" req=?{query_str} {req_snippet}")
                }
            } else {
                String::new()
            };
            let resp_debug = if print_body && !resp_snippet.is_empty() {
                format!(" resp={resp_snippet}")
            } else {
                String::new()
            };
            match &result {
                Ok(response) => {
                    let status = response.status().as_u16();
                    if status >= 500 {
                        warn!(
                            request_id = %req_id, ip = %ip,
                            "{method} {path} -> {status}{duration_paren}{req_debug}{resp_debug}"
                        );
                    } else {
                        info!(
                            request_id = %req_id, ip = %ip,
                            "{method} {path} -> {status}{duration_paren}{req_debug}{resp_debug}"
                        );
                    }
                }
                Err(_e) => {
                    warn!(
                        request_id = %req_id, ip = %ip,
                        "{method} {path} -> ERR{duration_paren}{req_debug}{resp_debug}"
                    );
                }
            }
            result
        })
    }
}

/// body 调试文本:二进制安全、超长截断(字符边界安全)
///
/// 先按字节预算截断再做 lossy:非法 UTF-8 的大 body(上限 `MAX_BUFFER_BODY`
/// 16MB)不再整段替换分配——日志本就只取前 `PRINT_BODY_MAX` 个字符。
/// UTF-8 每字符至多 4 字节,`4 × PRINT_BODY_MAX` 字节足以产出全部
/// `PRINT_BODY_MAX` 个字符(含逐字节 U+FFFD 替换的最坏情形)。
/// 截断提示改为**原始字节数**(lossy 替换会虚增非法序列的长度)。
fn body_snippet(bytes: &[u8]) -> String {
    if bytes.len() <= PRINT_BODY_MAX {
        return String::from_utf8_lossy(bytes).into_owned();
    }
    let cut = bytes.len().min(PRINT_BODY_MAX * 4);
    let text = String::from_utf8_lossy(&bytes[..cut]);
    let truncated: String = text.chars().take(PRINT_BODY_MAX).collect();
    format!("{truncated}...(truncated {})", bytes.len())
}

/// 调试模式收集请求体:成功返回截断片段并原样重建请求。
///
/// - 已声明 content-length 且超过 `cap`:不消费 body 原样透传;
/// - 未知长度(分块)body 超限:`to_bytes` 已消费流、原 body 无法重建,
///   返回 413 短路响应——静默换成空体会让 handler 收到“合法的空请求”
///   而破坏业务数据,必须把问题显式暴露给调用方。
async fn collect_request_body(req: &mut Request<Body>, cap: usize) -> Result<String, Response> {
    let taken = std::mem::take(req);
    let (parts, body) = taken.into_parts();
    let declared_len = parts
        .headers
        .get(header::CONTENT_LENGTH)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.parse::<usize>().ok());
    if declared_len.is_some_and(|n| n > cap) {
        *req = Request::from_parts(parts, body);
        return Ok(BODY_OVER_LIMIT_NOTE.to_string());
    }
    match to_bytes(body, cap).await {
        Ok(bytes) => {
            let snippet = body_snippet(&bytes);
            *req = Request::from_parts(parts, Body::from(bytes));
            Ok(snippet)
        }
        Err(e) => {
            tracing::error!(
                err = %e,
                "调试日志收集请求体超出缓冲上限({cap}B),body 已不可恢复,返回 413"
            );
            Err(Response::builder()
                .status(StatusCode::PAYLOAD_TOO_LARGE)
                .header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
                .body(Body::from("request body too large"))
                .expect("固定 413 响应构建不会失败"))
        }
    }
}

/// 调试模式收集响应体:成功返回截断片段并原样重建响应,响应始终可用。
///
/// - 已声明 content-length 且超过 `cap`:不消费 body;
/// - 未知长度 body 超限:原 body 已不可恢复——移除失实的 content-length
///   (否则客户端按旧长度挂起等待),响应体为空并以 error 日志显式暴露。
async fn collect_response_body(resp: &mut Response, cap: usize) -> String {
    let declared_len = resp
        .headers()
        .get(header::CONTENT_LENGTH)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.parse::<usize>().ok());
    if declared_len.is_some_and(|n| n > cap) {
        return BODY_OVER_LIMIT_NOTE.to_string();
    }
    let body = std::mem::replace(resp.body_mut(), Body::empty());
    match to_bytes(body, cap).await {
        Ok(bytes) => {
            let snippet = body_snippet(&bytes);
            *resp.body_mut() = Body::from(bytes);
            snippet
        }
        Err(e) => {
            tracing::error!(
                err = %e,
                "调试日志收集响应体超出缓冲上限({cap}B),响应体已不可恢复"
            );
            resp.headers_mut().remove(header::CONTENT_LENGTH);
            "(响应体超过缓冲上限,已丢失)".to_string()
        }
    }
}

/// 多行 Action Report:URL / 参数 / 结果 / 耗时 / 时间 / IP / 请求 ID 分行对齐展示
///
/// 仅 `report_multiline = true` 时启用(人读友好,但每请求多行日志 + 对齐空格,
/// 日志量与 IO 压力更大,生产环境建议保持默认单行)。
// 参数即报告的各日志字段,与格式化输出一一对应,结构体化反而增加透传样板,故豁免
#[allow(clippy::too_many_arguments)]
fn build_report(
    method: &str,
    path: &str,
    query: &str,
    status_text: &str,
    duration: &str,
    ip: &str,
    req_id: &str,
    req_snippet: &str,
    resp_snippet: &str,
    print_body: bool,
) -> String {
    const LINE: &str = "=============================== REQUEST ===============================";
    let mut s = format!("{LINE}\n");
    // 第一行:状态码 + 完整 URL(含 query)
    s.push_str(&format!("  {status_text:8}  {method} {path}"));
    if !query.is_empty() {
        s.push_str(&format!("?{query}"));
    }
    // 请求时间(本地时间,毫秒精度)
    let now = wordval_utils::Date::now_local().format("%Y-%m-%d %H:%M:%S%.3f");
    s.push_str(&format!("\n  TIME     {now}"));
    // 耗时 / 来源 / 链路 ID
    let duration_part = if duration.is_empty() {
        String::new()
    } else {
        format!("{duration:>8}")
    };
    s.push_str(&format!("\n  DURATION {duration_part}   IP {ip:>15}   REQ-ID {req_id}"));
    // 请求参数与响应体(仅 print_body 调试模式)
    if print_body && !req_snippet.is_empty() {
        s.push_str(&format!("\n  BODY     {req_snippet}"));
    }
    if print_body && !resp_snippet.is_empty() {
        s.push_str(&format!("\n  RESULT   {resp_snippet}"));
    }
    s.push('\n');
    s.push_str(LINE);
    s
}