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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//! 幂等执行支撑模块(用 `#[wordval::idempotent]` 宏按需标注 handler)
//!
//! 本模块是 `#[idempotent]` 宏展开的运行时支撑(`idempotent_run` 在宏
//! 展开处被直接调用),不是套在全链路上的 tower 中间件,因此不属于
//! [`crate::middleware`]。
//!
//! 客户端在请求头中携带 `x-idempotency-key`,
//! 服务端保证同一 key 的请求只执行一次,
//! 重复请求直接返回缓存的首次响应结果。
//!
//! # 语义边界(重要)
//!
//! 本实现提供 **HTTP 层尽力而为的防重放**,不承诺业务层面的 exactly-once:
//! - 幂等键绑定请求指纹(方法 + 路径 + query + 请求体摘要),相同 key 不同
//!   内容返回 409,防止错误复用旧响应;
//! - 幂等作用域绑定 principal + tenant + method + path,匿名请求直接拒绝,
//!   防止跨客户端重放其他用户的缓存响应;
//! - 声明锁带 fingerprint 与 TTL,业务超过锁 TTL 仍可能并发执行第二次;
//! - 涉及资金、库存、订单的唯一性必须以数据库唯一键/事务兜底。
//!
//! # 使用方式
//!
//! ```ignore
//! use wordval::prelude::*;
//!
//! #[wordval::post("/api/order/create")]
//! #[wordval::idempotent(ttl = 3600)]
//! async fn create_order(Json(p): Json<CreateOrderReq>) -> ResResult<Order> {
//!     // ... 同一 x-idempotency-key 只执行一次,重复请求直接返回首次结果
//! }
//! ```

use axum::http::StatusCode;
use axum::{
    body::Body,
    extract::Request,
    response::{IntoResponse, Response},
};
use std::future::Future;
use std::time::Duration;
use wordval_cache::Cache;
use wordval_core::api::ApiError;

use crate::middleware::error_response;
use crate::middleware::CurrentUser;
use crate::resources::try_cache;
use crate::tenant::TenantContext;

/// 声明锁 TTL(秒):处理中标记的存活时长,到期后自动释放。
/// 注意:业务执行超过该时长时锁会过期,另一个相同请求可能重新获得锁并再次执行。
const CLAIM_TTL_SECS: u64 = 30;
/// 轮询等待最大重试次数
const POLL_RETRIES: u32 = 30;
/// 每次轮询间隔
const POLL_INTERVAL: Duration = Duration::from_millis(100);
/// 可被幂等缓存的最大响应体大小;超过该值的响应返回但不入缓存
const MAX_CACHE_BODY: usize = 1024 * 1024;
/// 缓冲响应体的硬上限;超过该值返回 500,不返回截断后的残缺响应
const MAX_BUFFER_BODY: usize = 16 * 1024 * 1024;
/// 幂等键最大长度;超过该长度的键不参与幂等,请求直接透传
const MAX_KEY_LEN: usize = 128;
/// 参与请求指纹的请求体大小上限;超过该上限不参与幂等(直接执行)
const MAX_FINGERPRINT_BODY: usize = 1024 * 1024;

/// 重放响应时禁止恢复的响应头(请求/连接/凭据相关,绝不允许跨请求重放)
const FORBIDDEN_REPLAY_HEADERS: &[&str] = &[
    "set-cookie",
    "set-cookie2",
    "authorization",
    "proxy-authorization",
    "x-request-id",
    "content-length",
    "transfer-encoding",
    "connection",
    "keep-alive",
];

#[derive(serde::Serialize, serde::Deserialize)]
struct CachedResponse {
    status: u16,
    content_type: String,
    /// 首次请求的指纹(重放时校验,指纹不同返回 409)
    #[serde(default)]
    fingerprint: String,
    /// 安全 allowlist 之外的响应头(重放时恢复;连接/凭据语义头绝不缓存)
    #[serde(default)]
    headers: Vec<(String, String)>,
    /// 原始响应体字节的 base64 编码(支持二进制响应,如图片/Excel 导出)
    body: String,
}

impl CachedResponse {
    fn encode_body(bytes: &[u8]) -> String {
        wordval_utils::Crypto::encode_base64(bytes)
    }

    fn decode_body(&self) -> Vec<u8> {
        wordval_utils::Crypto::decode_base64(&self.body).unwrap_or_default()
    }
}

fn build_response(cached: CachedResponse) -> Response<Body> {
    let body = cached.decode_body();
    let mut builder = Response::builder()
        .status(StatusCode::from_u16(cached.status).unwrap_or(StatusCode::OK))
        .header("Content-Type", cached.content_type.as_str());
    // 恢复缓存的安全响应头(Set-Cookie、认证头、request ID 等请求相关头
    // 已在缓存时剔除,绝不通用重放)。
    // 缓存数据可能损坏(非法头名/值):跳过非法项而非 panic
    for (name, value) in &cached.headers {
        if let (Ok(n), Ok(v)) = (
            axum::http::HeaderName::from_bytes(name.as_bytes()),
            axum::http::HeaderValue::from_str(value),
        ) {
            builder = builder.header(n, v);
        }
    }
    // body 构造几乎不会失败;即使 builder 因头值损坏报错也兜底返回裸 body,绝不 panic
    builder
        .body(Body::from(body.clone()))
        .unwrap_or_else(|_| Response::new(Body::from(body)))
}

// ── 幂等核心逻辑(#[idempotent] 宏运行时使用)──────────────────────

/// 从请求头提取幂等键;空键/超长键返回 None(不参与幂等,直接透传)
fn extract_idem_key(req: &Request) -> Option<String> {
    req.headers()
        .get("x-idempotency-key")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string())
        .filter(|s| !s.is_empty() && s.len() <= MAX_KEY_LEN)
}

/// 幂等作用域 = 认证身份 + 租户 + 方法 + 路径;
/// 匿名(未登录)请求返回 None——禁止匿名幂等,防止跨客户端响应复用。
fn extract_scope(req: &Request) -> Option<String> {
    let user = req.extensions().get::<CurrentUser>()?;
    let tenant = req
        .extensions()
        .get::<TenantContext>()
        .and_then(|t| t.tenant_id)
        .map(|t| format!("t{}", t))
        .unwrap_or_else(|| "t-".to_string());
    Some(format!(
        "u{}:{}:{}:{}",
        user.id,
        tenant,
        req.method().as_str(),
        req.uri().path()
    ))
}

/// 请求指纹:方法 + 路径 + query + 请求体字节摘要。
/// 缓冲整个请求体(硬上限 `MAX_BUFFER_BODY`)后原样恢复,供宏重放提取器。
///
/// 体积超过 `MAX_FINGERPRINT_BODY` 时不参与幂等(返回 `None`),但请求体仍
/// 完整恢复,透传执行业务不受影响;仅当超过缓冲硬上限才丢弃 body。
///
/// 摘要经 [`Crypto::sha256_parts`] 分段喂入:`method:path:query:` 与 body
/// 各为一段,中间不拼接——body 最大 1MB,hex 展开拼串要 2×body 的中间分配,
/// 分段哈希后仅剩 64 字符的 hex 摘要。
async fn compute_fingerprint(req: Request) -> (Option<String>, Request) {
    let (parts, body) = req.into_parts();
    match axum::body::to_bytes(body, MAX_BUFFER_BODY).await {
        Ok(bytes) => {
            let fingerprint = if bytes.len() <= MAX_FINGERPRINT_BODY {
                let header = format!(
                    "{}:{}:{}:",
                    parts.method.as_str(),
                    parts.uri.path(),
                    parts.uri.query().unwrap_or("")
                );
                Some(wordval_utils::Crypto::sha256_parts(&[
                    header.as_bytes(),
                    &bytes,
                ]))
            } else {
                // 体过大不参与幂等,但 body 已缓冲,原样恢复供透传执行
                None
            };
            (fingerprint, Request::from_parts(parts, Body::from(bytes)))
        }
        // 请求体超过缓冲硬上限:丢弃 body 透传(提取器将自行报错)
        Err(_) => (None, Request::from_parts(parts, Body::empty())),
    }
}

/// 快速路径:响应已缓存且指纹一致则重放;指纹不一致返回 None(由调用方返回 409)
async fn try_fast_path(
    cache: &wordval_cache::SharedCache,
    resp_key: &str,
    fingerprint: &str,
) -> Option<Response> {
    match cache.get::<CachedResponse>(resp_key).await {
        Ok(Some(cached)) if cached.fingerprint == fingerprint => Some(build_response(cached)),
        // 缓存读取失败或指纹不匹配:None(调用方区分处理)
        _ => None,
    }
}

/// 快速路径上的指纹冲突:key 已被其他请求内容占用
async fn fingerprint_conflict(
    cache: &wordval_cache::SharedCache,
    resp_key: &str,
    fingerprint: &str,
) -> bool {
    match cache.get::<CachedResponse>(resp_key).await {
        Ok(Some(cached)) => cached.fingerprint != fingerprint,
        _ => false,
    }
}

/// 原子声明处理锁;锁 value 为请求指纹,用于冲突判定。
/// 返回 `Ok(true)` 获得执行权;`Ok(false)` 锁被其他请求持有;
/// `Err` 表示缓存故障(按 fail-closed 处理,不静默执行)。
async fn try_claim_lock(
    cache: &wordval_cache::SharedCache,
    lock_key: &str,
    fingerprint: &str,
) -> Result<bool, String> {
    cache
        .set_nx(lock_key, &fingerprint.to_string(), CLAIM_TTL_SECS)
        .await
        .map_err(|e| e.to_string())
}

/// 锁被其他请求持有时轮询等待其完成并写入缓存
async fn poll_for_response(cache: &wordval_cache::SharedCache, resp_key: &str) -> Option<Response> {
    for _ in 0..POLL_RETRIES {
        tokio::time::sleep(POLL_INTERVAL).await;
        if let Ok(Some(cached)) = cache.get::<CachedResponse>(resp_key).await {
            return Some(build_response(cached));
        }
    }
    None
}

/// 等待超时——返回冲突响应
fn conflict_response() -> Response {
    error_response(ApiError::conflict("请求正在处理中,请稍后重试"))
}

/// 幂等键已被其他请求内容占用——返回冲突响应
fn fingerprint_conflict_response() -> Response {
    error_response(ApiError::conflict(
        "幂等键已被其他请求内容使用,请更换 x-idempotency-key",
    ))
}

/// 匿名请求禁止幂等——返回 401
fn anonymous_rejected_response() -> Response {
    error_response(ApiError::unauthorized("幂等操作需要登录"))
}

/// 执行完成后的收尾:缓冲响应体,体积可控则写入缓存,随后释放锁并原样返回。
///
/// 响应体超过硬上限时释放锁并返回 500(业务已执行,客户端重试可能再次执行,
/// 因此文档不承诺 exactly-once,关键业务必须依赖数据库唯一约束)。
async fn cache_and_return(
    cache: &wordval_cache::SharedCache,
    resp_key: &str,
    lock_key: &str,
    fingerprint: &str,
    ttl_secs: u64,
    parts: axum::http::response::Parts,
    body: Body,
) -> Response {
    let status = parts.status.as_u16();
    let ctype = parts
        .headers
        .get("Content-Type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/json; charset=utf-8")
        .to_string();
    // 只缓存安全响应头;连接语义头与凭据相关头绝不缓存重放
    let headers: Vec<(String, String)> = parts
        .headers
        .iter()
        .filter(|(n, _)| !FORBIDDEN_REPLAY_HEADERS.contains(&n.as_str()))
        .map(|(n, v)| {
            (
                n.as_str().to_string(),
                v.to_str().unwrap_or_default().to_string(),
            )
        })
        .collect();

    // 以硬上限缓冲响应体;超过上限视为异常:释放锁并返回错误响应
    match axum::body::to_bytes(body, MAX_BUFFER_BODY).await {
        Ok(bytes) => {
            // 仅缓存体积可控的响应;超大响应原样返回但不入缓存
            if bytes.len() <= MAX_CACHE_BODY {
                let cached = CachedResponse {
                    status,
                    content_type: ctype,
                    fingerprint: fingerprint.to_string(),
                    headers,
                    body: CachedResponse::encode_body(&bytes),
                };
                // 完成结果必须先于锁释放写入,且必须检查写入错误——
                // 写入失败时返回 500,不能删除唯一执行证据后静默成功
                if let Err(e) = cache.set_ex(resp_key, &cached, ttl_secs).await {
                    let _ = cache.del(lock_key).await;
                    tracing::error!("幂等响应缓存写入失败: {}", e);
                    return error_response(ApiError::internal("幂等处理失败,请重试"));
                }
            }
            // 释放锁,允许后续重复请求直接走缓存
            let _ = cache.del(lock_key).await;
            // Bytes 克隆廉价(引用计数),无需 to_vec 全量复制
            Response::from_parts(parts, Body::from(bytes))
        }
        Err(_) => {
            // 响应体超过缓冲上限:释放锁并返回 500
            let _ = cache.del(lock_key).await;
            error_response(ApiError::internal("响应体过大,无法完成幂等处理"))
        }
    }
}

/// 幂等执行入口(供 `#[wordval::idempotent]` 宏展开调用)
///
/// 从请求头读取 `x-idempotency-key`:无键/超长键直接执行不缓存;
/// 匿名请求(未登录)拒绝幂等;全局缓存未初始化时直接执行,不依赖缓存。
///
/// 业务闭包 `f` 接收**指纹计算后原样恢复的请求**,由宏经 axum `Handler`
/// 重放原始提取器(`Json`/`Path`/`Query` 等)后执行,因此 body 类提取器
/// 与幂等指纹读取不再互相冲突。
pub async fn idempotent_run<R, F, Fut>(ttl_secs: u64, req: Request, f: F) -> Response
where
    R: IntoResponse,
    F: FnOnce(Request) -> Fut,
    Fut: Future<Output = R> + Send + 'static,
{
    let Some(key) = extract_idem_key(&req) else {
        return f(req).await.into_response();
    };

    // 匿名禁止:未登录请求不得使用共享幂等空间
    let Some(scope) = extract_scope(&req) else {
        return anonymous_rejected_response();
    };

    // 请求指纹:方法 + 路径 + query + 请求体摘要(body 超限则不参与幂等)
    let (fingerprint, req) = compute_fingerprint(req).await;
    let Some(fingerprint) = fingerprint else {
        return f(req).await.into_response();
    };

    let Some(cache) = try_cache() else {
        return f(req).await.into_response();
    };

    let path = req.uri().path().to_string();
    let resp_key = format!("idem:resp:{}:{}:{}", scope, path, key);
    let lock_key = format!("idem:lock:{}:{}:{}", scope, path, key);

    // 1) 快速路径:响应已缓存且指纹一致则重放;指纹不同返回 409
    if let Some(resp) = try_fast_path(cache, &resp_key, &fingerprint).await {
        return resp;
    }
    if fingerprint_conflict(cache, &resp_key, &fingerprint).await {
        return fingerprint_conflict_response();
    }

    // 2) 原子声明锁(锁 value = fingerprint;set_nx 保证只有一个请求能成功)
    match try_claim_lock(cache, &lock_key, &fingerprint).await {
        Ok(true) => {
            // 持有锁——执行业务逻辑(重放恢复后的请求)
            let resp = f(req).await.into_response();
            let (parts, body) = resp.into_parts();
            return cache_and_return(
                cache,
                &resp_key,
                &lock_key,
                &fingerprint,
                ttl_secs,
                parts,
                body,
            )
            .await;
        }
        Ok(false) => {
            // 锁被其他请求持有:内容冲突立即 409,相同内容轮询等待
            if fingerprint_conflict(cache, &resp_key, &fingerprint).await {
                return fingerprint_conflict_response();
            }
            if let Some(resp) = poll_for_response(cache, &resp_key).await {
                return resp;
            }
            conflict_response()
        }
        // 缓存故障:fail-closed,不静默执行(避免丢失唯一执行证据)
        Err(e) => {
            tracing::error!("幂等锁声明失败(缓存故障),拒绝请求: {}", e);
            error_response(ApiError::service_unavailable(
                "幂等服务暂不可用,请稍后重试",
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::middleware::CurrentUser;
    use crate::resources::set_cache;
    use axum::body::to_bytes;
    use axum::http::StatusCode;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Once;
    use wordval_cache::{Cache, LocalCache};

    static INIT: Once = Once::new();

    /// 全局只能 set 一次,所有测试共享同一 LocalCache,靠唯一 key/用户隔离
    fn cache() -> &'static wordval_cache::SharedCache {
        INIT.call_once(|| {
            let _ = set_cache(wordval_cache::SharedCache::Local(LocalCache::new(
                100_000,
                3600,
            )));
        });
        try_cache().unwrap()
    }

    fn user(id: i64) -> CurrentUser {
        CurrentUser {
            id,
            username: format!("u{}", id),
            roles: vec![],
            permissions: vec![],
            is_admin: false,
            tenant_id: None,
            store_id: None,
        }
    }

    fn mk_req(key: Option<&str>, body: &[u8], uid: i64) -> Request {
        let mut b = Request::builder()
            .method("POST")
            .uri("/api/x")
            .extension(user(uid));
        if let Some(k) = key {
            b = b.header("x-idempotency-key", k);
        }
        b.body(Body::from(body.to_vec())).unwrap()
    }

    async fn body_str(resp: Response) -> String {
        String::from_utf8_lossy(&to_bytes(resp.into_body(), 32 * 1024 * 1024).await.unwrap())
            .to_string()
    }

    #[tokio::test]
    async fn no_key_and_long_key_passthrough() {
        let c = AtomicUsize::new(0);
        let f = |_| {
            c.fetch_add(1, Ordering::SeqCst);
            async { (StatusCode::OK, "ok") }
        };
        // 无键 → 透传
        let r = idempotent_run(60, mk_req(None, b"{}", 1001), f).await;
        assert_eq!(r.status(), StatusCode::OK);
        // 超长键(>128)→ 透传
        let long = "k".repeat(MAX_KEY_LEN + 1);
        let _ = idempotent_run(60, mk_req(Some(&long), b"{}", 1001), f).await;
        // 空串键 → filter 后视为无键透传
        let _ = idempotent_run(60, mk_req(Some(""), b"{}", 1001), f).await;
        assert_eq!(c.load(Ordering::SeqCst), 3);
    }

    #[tokio::test]
    async fn anonymous_rejected_401() {
        let req = Request::builder()
            .method("POST")
            .uri("/api/x")
            .header("x-idempotency-key", "anon-1")
            .body(Body::from("{}"))
            .unwrap();
        let r = idempotent_run(60, req, |_| async { (StatusCode::OK, "never") }).await;
        assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn first_exec_then_replay_with_header_filtering() {
        let c = AtomicUsize::new(0);
        let exec = |_| {
            c.fetch_add(1, Ordering::SeqCst);
            async {
                (
                    StatusCode::CREATED,
                    [("x-foo", "bar"), ("set-cookie", "session=1")],
                    "{\"ok\":1}".to_string(),
                )
                    .into_response()
            }
        };
        let body = b"{\"a\":1}";
        let r1 = idempotent_run(3600, mk_req(Some("replay-1"), body, 1002), exec).await;
        assert_eq!(r1.status(), StatusCode::CREATED);
        assert_eq!(c.load(Ordering::SeqCst), 1);
        // 二次相同内容 → 重放:不执行业务、状态/自定义头保留、set-cookie 剔除
        let r2 = idempotent_run(3600, mk_req(Some("replay-1"), body, 1002), exec).await;
        assert_eq!(c.load(Ordering::SeqCst), 1, "重放不应执行业务");
        assert_eq!(r2.status(), StatusCode::CREATED);
        assert_eq!(
            r2.headers().get("x-foo").and_then(|v| v.to_str().ok()),
            Some("bar")
        );
        assert!(r2.headers().get("set-cookie").is_none());
        assert!(body_str(r2).await.contains("\"ok\":1"));
    }

    #[tokio::test]
    async fn same_key_different_fingerprint_409() {
        let c = AtomicUsize::new(0);
        let exec = |_| {
            c.fetch_add(1, Ordering::SeqCst);
            async { (StatusCode::OK, "done") }
        };
        let r1 = idempotent_run(3600, mk_req(Some("fp-1"), b"v1", 1003), exec).await;
        assert_eq!(r1.status(), StatusCode::OK);
        // 同键不同 body → 指纹冲突 409,不重复执行
        let r2 = idempotent_run(3600, mk_req(Some("fp-1"), b"v2", 1003), exec).await;
        assert_eq!(r2.status(), StatusCode::CONFLICT);
        assert!(body_str(r2).await.contains("幂等键已被其他请求内容使用"));
        assert_eq!(c.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn huge_request_body_passthrough() {
        let c = AtomicUsize::new(0);
        let big = vec![b'x'; MAX_FINGERPRINT_BODY + 10];
        let r = idempotent_run(60, mk_req(Some("huge-req"), &big, 1004), |_| {
            c.fetch_add(1, Ordering::SeqCst);
            async { (StatusCode::OK, "passed") }
        })
        .await;
        assert_eq!(r.status(), StatusCode::OK);
        assert_eq!(c.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn big_response_executes_but_not_cached() {
        let c = AtomicUsize::new(0);
        let exec = |_| {
            c.fetch_add(1, Ordering::SeqCst);
            async {
                (
                    StatusCode::OK,
                    "y".repeat(MAX_CACHE_BODY + 1_024),
                )
            }
        };
        let body = b"only-once";
        let r1 = idempotent_run(3600, mk_req(Some("big-resp"), body, 1005), exec).await;
        assert_eq!(r1.status(), StatusCode::OK);
        // 超限响应未入缓存 → 二次请求重新执行
        let r2 = idempotent_run(3600, mk_req(Some("big-resp"), body, 1005), exec).await;
        assert_eq!(r2.status(), StatusCode::OK);
        assert_eq!(c.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn over_hard_limit_response_500() {
        let req = mk_req(Some("overflow-1"), b"x", 1006);
        let r = idempotent_run(3600, req, |_| async {
            (StatusCode::OK, "z".repeat(MAX_BUFFER_BODY + 1_024))
        })
        .await;
        assert_eq!(r.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert!(body_str(r).await.contains("响应体过大"));
    }

    #[tokio::test]
    async fn lock_held_polls_until_response_appears() {
        let c = cache();
        // 作用域:用户 1007 + 无租户(t-)+ POST + /api/x
        let scope = "u1007:t-:POST:/api/x";
        let lock_key = format!("idem:lock:{}:/api/x:{}", scope, "poll-1");
        let resp_key = format!("idem:resp:{}:/api/x:{}", scope, "poll-1");
        // 先占用处理锁 → set_nx 失败走轮询分支
        assert!(c.set_nx(&lock_key, &"other-fp".to_string(), 30).await.unwrap());
        // 后台稍后写入响应缓存,模拟持锁请求完成
        let c2 = c.clone();
        let rk = resp_key.clone();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(250)).await;
            let cached = CachedResponse {
                status: 202,
                content_type: "text/plain".into(),
                fingerprint: String::new(),
                headers: vec![("x-foo".into(), "baz".into())],
                body: CachedResponse::encode_body(b"late-resp"),
            };
            c2.set_ex(&rk, &cached, 60).await.unwrap();
        });
        let r = idempotent_run(3600, mk_req(Some("poll-1"), b"p", 1007), |_| async {
            (StatusCode::OK, "SHOULD-NOT-EXECUTE")
        })
        .await;
        // 重放的是后台写入的 202 响应,而非业务闭包的 200
        assert_eq!(r.status(), StatusCode::from_u16(202).unwrap());
        assert_eq!(
            r.headers().get("x-foo").and_then(|v| v.to_str().ok()),
            Some("baz")
        );
        assert!(body_str(r).await.contains("late-resp"));
        let _ = c.del(&lock_key).await;
    }

    #[tokio::test]
    async fn lock_held_poll_timeout_409() {
        let c = cache();
        let scope = "u1008:t-:POST:/api/x";
        let lock_key = format!("idem:lock:{}:/api/x:{}", scope, "wait-1");
        assert!(c.set_nx(&lock_key, &"any".to_string(), 30).await.unwrap());
        let t = tokio::time::Instant::now();
        let r = idempotent_run(3600, mk_req(Some("wait-1"), b"w", 1008), |_| async {
            (StatusCode::OK, "SHOULD-NOT-EXECUTE")
        })
        .await;
        // 轮询超时 → 409,业务未被执行
        assert_eq!(r.status(), StatusCode::CONFLICT);
        assert!(body_str(r).await.contains("请求正在处理中"));
        // 30 次 × 100ms 轮询上限
        assert!(t.elapsed() >= Duration::from_millis(2_500));
        let _ = c.del(&lock_key).await;
    }

    #[tokio::test]
    async fn tenant_scope_isolates_idempotency() {
        let c = AtomicUsize::new(0);
        let exec = |_| {
            c.fetch_add(1, Ordering::SeqCst);
            async { (StatusCode::OK, "t") }
        };
        let body = b"same-bytes";
        let mk = |tid: Option<i64>| {
            Request::builder()
                .method("POST")
                .uri("/api/x")
                .header("x-idempotency-key", "tenants-1")
                .extension(user(1009))
                .extension(TenantContext { tenant_id: tid })
                .body(Body::from(body.to_vec()))
                .unwrap()
        };
        // 同一用户、不同租户 → 幂等作用域不同,各自执行
        let _ = idempotent_run(3600, mk(Some(7)), exec).await;
        let _ = idempotent_run(3600, mk(Some(8)), exec).await;
        assert_eq!(c.load(Ordering::SeqCst), 2);
        // 同租户二次 → 重放不增计数
        let _ = idempotent_run(3600, mk(Some(7)), exec).await;
        assert_eq!(c.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn json_extractor_replayed_after_fingerprint() {
        // 验证 #5 修复机制:闭包收到指纹计算后恢复的请求,经 axum Handler
        // 重放 Json 提取器(body 类提取器与幂等指纹读取不再冲突)
        use axum::extract::Json;
        use axum::handler::Handler;

        async fn inner(Json(p): Json<serde_json::Value>) -> Json<serde_json::Value> {
            Json(p)
        }

        let c = AtomicUsize::new(0);
        let exec = |req: Request| {
            c.fetch_add(1, Ordering::SeqCst);
            Box::pin(async move { Handler::call(inner, req, ()).await })
                as std::pin::Pin<Box<dyn Future<Output = Response> + Send>>
        };
        let body = br#"{"amount":7}"#;
        let mk = || {
            Request::builder()
                .method("POST")
                .uri("/api/x")
                .header("x-idempotency-key", "json-1")
                .header("content-type", "application/json")
                .extension(user(1020))
                .body(Body::from(body.to_vec()))
                .unwrap()
        };
        let r1 = idempotent_run(3600, mk(), exec).await;
        assert_eq!(r1.status(), StatusCode::OK);
        assert!(body_str(r1).await.contains("\"amount\":7"));
        assert_eq!(c.load(Ordering::SeqCst), 1);
        // 二次相同内容 → 重放缓存,不重放提取器、不执行业务
        let r2 = idempotent_run(3600, mk(), exec).await;
        assert_eq!(c.load(Ordering::SeqCst), 1, "重放不应再次执行 Json handler");
        assert!(body_str(r2).await.contains("\"amount\":7"));
    }

    #[test]
    fn extract_idem_key_rules() {
        let mk = |k: Option<&str>| {
            let mut b = Request::builder().method("POST").uri("/");
            if let Some(k) = k {
                b = b.header("x-idempotency-key", k);
            }
            b.body(Body::empty()).unwrap()
        };
        assert_eq!(extract_idem_key(&mk(None)), None);
        assert_eq!(extract_idem_key(&mk(Some(""))), None);
        assert_eq!(extract_idem_key(&mk(Some("abc"))).as_deref(), Some("abc"));
        assert_eq!(extract_idem_key(&mk(Some(&"k".repeat(129)))), None);
        assert!(extract_idem_key(&mk(Some(&"k".repeat(128)))).is_some());
    }

    #[test]
    fn extract_scope_format_with_tenant() {
        let req = Request::builder()
            .method("PUT")
            .uri("/api/y?z=1")
            .extension(user(42))
            .extension(TenantContext { tenant_id: Some(9) })
            .body(Body::empty())
            .unwrap();
        assert_eq!(extract_scope(&req).as_deref(), Some("u42:t9:PUT:/api/y"));
        // 无 TenantContext extension → t-
        let req2 = Request::builder()
            .method("POST")
            .uri("/api/x")
            .extension(user(1))
            .body(Body::empty())
            .unwrap();
        assert_eq!(extract_scope(&req2).as_deref(), Some("u1:t-:POST:/api/x"));
        // 匿名 → None
        let anon = Request::builder()
            .method("POST")
            .uri("/api/x")
            .body(Body::empty())
            .unwrap();
        assert_eq!(extract_scope(&anon), None);
    }

    #[tokio::test]
    async fn compute_fingerprint_restores_body() {
        let req = mk_req(Some("fp-c"), b"ab", 1010);
        let (fp, restored) = compute_fingerprint(req).await;
        let fp = fp.unwrap();
        // 指纹可复现:sha256(method:path:query: + body 原始字节,分段喂入)
        let expect = wordval_utils::Crypto::sha256_parts(&[b"POST:/api/x::", b"ab"]);
        assert_eq!(fp, expect);
        // 请求体已被原样恢复
        assert_eq!(&to_bytes(restored.into_body(), 1024).await.unwrap()[..], b"ab");
    }

    #[tokio::test]
    async fn build_response_fault_tolerant() {
        // 非法头名跳过;保留合法头;100~999 内的非常规码字面透传
        let cached = CachedResponse {
            status: 999,
            content_type: "application/json".into(),
            fingerprint: "f".into(),
            headers: vec![
                ("bad header".into(), "v".into()),
                ("x-ok".into(), "yes".into()),
            ],
            body: CachedResponse::encode_body(b"payload"),
        };
        let resp = build_response(cached);
        assert_eq!(resp.status().as_u16(), 999);
        assert_eq!(
            resp.headers().get("x-ok").and_then(|v| v.to_str().ok()),
            Some("yes")
        );
        assert!(body_str(resp).await.contains("payload"));
        // 超出合法区间的状态码(如 0)→ 回退 200
        let zero = CachedResponse {
            status: 0,
            content_type: "text/plain".into(),
            fingerprint: String::new(),
            headers: vec![],
            body: CachedResponse::encode_body(b"z"),
        };
        assert_eq!(build_response(zero).status(), StatusCode::OK);
        // base64 损坏 → 空 body 不 panic
        let broken = CachedResponse {
            status: 200,
            content_type: "text/plain".into(),
            fingerprint: String::new(),
            headers: vec![],
            body: "!!!not-base64!!!".into(),
        };
        assert_eq!(broken.decode_body(), Vec::<u8>::new());
    }

    #[tokio::test]
    async fn fast_path_and_conflict_helpers() {
        let c = cache();
        let key = "idem:resp:unit-test-key";
        let cached = CachedResponse {
            status: 200,
            content_type: "text/plain".into(),
            fingerprint: "fpA".into(),
            headers: vec![],
            body: CachedResponse::encode_body(b"R"),
        };
        c.set_ex(key, &cached, 60).await.unwrap();
        // 指纹一致 → 重放;不一致 → None 且 conflict=true
        assert!(try_fast_path(c, key, "fpA").await.is_some());
        assert!(try_fast_path(c, key, "fpB").await.is_none());
        assert!(fingerprint_conflict(c, key, "fpB").await);
        assert!(!fingerprint_conflict(c, key, "fpA").await);
        // 未缓存的 key → 两者均 false 路径
        assert!(!fingerprint_conflict(c, "idem:resp:none", "x").await);
        assert!(try_fast_path(c, "idem:resp:none", "x").await.is_none());
        let _ = c.del(key).await;
    }

    #[tokio::test]
    async fn claim_lock_mutual_exclusion() {
        let c = cache();
        let lk = "idem:lock:unit-claim";
        assert!(try_claim_lock(c, lk, "fp1").await.unwrap());
        // 已持锁时再声明 → false(锁被其他请求持有)
        assert!(!try_claim_lock(c, lk, "fp2").await.unwrap());
        let _ = c.del(lk).await;
        // 释放后可重新获得
        assert!(try_claim_lock(c, lk, "fp3").await.unwrap());
        let _ = c.del(lk).await;
    }
}