crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 失败现场快照(吸收点 F4,参考 Crawlee `ErrorSnapshotter`)
//!
//! 抓取被判定为反爬/限速时,把响应现场(HTML + 响应元数据 + 可选截图)
//! 按错误签名键去重存档,供事后诊断 WAF 拦截页形态。
//!
//! 设计约束:
//! - **旁路观测**:内部任何 IO 失败 `log::debug` 后静默返回,绝不影响抓取主流程
//!   (调用方无需 `?`);快照器未配置(`Option::None`)时调用点零成本短路;
//!   全部落盘经 `spawn_blocking` 执行,不阻塞 tokio worker 线程
//! - **签名去重**:同签名键第二次命中只自增计数并刷新 `.meta.json` 的 count,
//!   不重写 `.html`/`.jpg`(对齐 Crawlee 去重语义)
//! - **磁盘护栏(滚动)**:全目录文件数达 `max_total` 后按最旧优先滚动删除腾位,
//!   目录文件数有界;签名键内存表达 `MAX_TRACKED_KEYS` 上限,超限仅计指标
//! - **权限收紧**:快照文件以 0600 落盘(unix;其他平台走进程默认 umask)
//!
//! 落盘形态(`{key}` = sha256(url|status|reason) 前 30 hex + 消毒 reason 前 30 字符):
//! - `{key}.html`:响应体
//! - `{key}.meta.json`:url / status / reason / count / timestamp / headers
//! - `{key}.jpg`:screenshot 为 `Some` 时 base64 解码写入(仅透传已有值,不额外触发截图)
//!
//! 敏感信息提示:响应体可能含目标页敏感内容,目录访问权限与保留期由运维治理。

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

/// 签名键内存表(`counts`)的容量上限:键含 URL,长期被反爬拦截的爬取下
/// 不同 URL 无界增长会泄漏内存;达上限后新键仅计指标,不再入表/落盘
const MAX_TRACKED_KEYS: usize = 10_000;

use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine as _;
use dashmap::DashMap;
use sha2::{Digest, Sha256};

use crate::common::metrics_shim::counter;
use crate::config::settings::ObservabilitySettings;

/// 一次失败现场的快照输入
///
/// `content` / `screenshot` 持有所有权:落盘任务可直接移入 `spawn_blocking`,
/// 不在 async worker 线程上做整份正文拷贝或 base64 解码。其余字段仅用于
/// 签名键与 meta 构建,保持借用。
pub struct SnapshotInput<'a> {
    /// 请求 URL(签名键成分)
    pub url: &'a str,
    /// 响应状态码(签名键成分)
    pub status_code: u16,
    /// 失败原因(签名键成分 + meta.json 字段)
    pub reason: &'a str,
    /// 响应体(`.html` 落盘内容)
    pub content: String,
    /// 响应头(meta.json 字段)
    pub headers: &'a HashMap<String, String>,
    /// 截图 base64(`Some` 时解码写 `.jpg`;仅浏览器引擎已产出时非空)
    pub screenshot: Option<String>,
}

/// 失败现场快照器:错误签名键去重存档
///
/// - `snapshot`:同键首次落盘 `.html` + `.meta.json`(+ 可选 `.jpg`),
///   后续命中只自增计数并刷新 meta 的 count
/// - 内部全 `DashMap` + `AtomicU64`,无锁线程安全;`snapshot(&self)` 可并发调用
/// - 磁盘按 `max_total` 滚动有界;签名键内存表按 `MAX_TRACKED_KEYS` 封顶
#[derive(Debug)]
pub struct FailureSnapshotter {
    /// 快照落盘目录
    dir: PathBuf,
    /// 签名键 → 命中次数(去重计数)
    counts: DashMap<String, u64>,
    /// 净写入操作数(写入次数 − 逐出次数;重复命中刷新 meta 也计一次),
    /// 用于监控,不是目录文件数(文件数由 `max_total` 扫描守卫)
    total_written: AtomicU64,
    /// 全目录快照文件总数上限
    max_total: usize,
    /// 落盘互斥:只串行化「首写」路径(`count == 1`,含目录扫描与滚动逐出)。
    ///
    /// 并发首写在无锁情况下会同时看到目录已满并重复逐出,导致计数与磁盘漂移;
    /// 重复命中只刷新 meta.json、不碰逐出游标,走无锁路径。锁在
    /// `spawn_blocking` 内获取(同步上下文),不跨 await 持有;base64 解码在
    /// 锁外执行。
    persist_lock: Arc<parking_lot::Mutex<()>>,
}

impl FailureSnapshotter {
    /// 指定目录与文件总数上限创建快照器
    ///
    /// 目录在首次 `snapshot` 时惰性创建;创建失败按旁路观测静默降级。
    pub fn new(dir: impl Into<PathBuf>, max_total: usize) -> Self {
        Self {
            dir: dir.into(),
            counts: DashMap::new(),
            total_written: AtomicU64::new(0),
            max_total: max_total.max(1),
            persist_lock: Arc::new(parking_lot::Mutex::new(())),
        }
    }

    /// 从 `[observability]` 配置构造
    ///
    /// `failure_snapshot_dir` 为空串 = 禁用(返回 `None`,全链路零成本)。
    pub fn from_config(settings: &ObservabilitySettings) -> Option<Arc<Self>> {
        if settings.failure_snapshot_dir.is_empty() {
            return None;
        }
        Some(Arc::new(Self::new(
            settings.failure_snapshot_dir.clone(),
            settings.failure_snapshot_max_total,
        )))
    }

    /// 记录一次失败现场(旁路观测,永不失败)
    ///
    /// 同签名键第二次命中只自增计数并刷新 `.meta.json` 的 count,
    /// 不重写 `.html`/`.jpg`;目录文件数达 `max_total` 后按最旧优先滚动
    /// 删除腾位(新签名仍可观测)。内部 IO 失败 `log::debug` 后静默返回。
    ///
    /// 全部文件 IO 经 `spawn_blocking` 执行,调用方(async 路由路径)的
    /// tokio worker 线程不被阻塞。
    pub async fn snapshot(&self, input: SnapshotInput<'_>) {
        let key = Self::signature_key(input.url, input.status_code, input.reason);
        // 命中计数先于磁盘判断:内存表达 `MAX_TRACKED_KEYS` 上限,
        // 超限后新键仅计指标(含 URL 的键不无限驻留内存)
        let Some(count) = self.track_hit(&key) else {
            return;
        };

        // meta.json 每次命中都刷新(小文件):count 反映累计命中次数;
        // 刷新同时续期 mtime,滚动删除时活跃键的 meta 不会被优先淘汰
        let meta = serde_json::json!({
            "url": input.url,
            "status": input.status_code,
            "reason": input.reason,
            "count": count,
            "timestamp": chrono::Utc::now().to_rfc3339(),
            "headers": input.headers,
        });

        let dir = self.dir.clone();
        let key_closure = key.clone();
        // 持有字段直接移入阻塞任务:async 线程上不做正文拷贝
        let content = input.content;
        let screenshot_b64 = input.screenshot;
        let max_total = self.max_total;
        let persist_lock = self.persist_lock.clone();

        let outcome = tokio::task::spawn_blocking(move || {
            Self::persist_hit(
                dir,
                key_closure,
                count,
                content,
                screenshot_b64,
                meta,
                max_total,
                persist_lock,
            )
        })
        .await;

        self.record_persist_outcome(outcome);
    }

    /// 应用落盘结果:写入/逐出 delta 以单次 CAS 计入 `total_written`;
    /// `spawn_blocking` join 失败按旁路观测记录 debug 日志。
    fn record_persist_outcome(&self, outcome: Result<(u64, u64), tokio::task::JoinError>) {
        match outcome {
            Ok((written, evicted)) => {
                if written > 0 || evicted > 0 {
                    // 单次 CAS 应用「写入/逐出」delta:先 add 再 load+sub 是非原子三段式,
                    // 并发命中会让计数漂移。计数器语义 = 净写入操作数(重复命中刷新
                    // meta.json 也计一次),不是目录文件数。
                    let _ = self.total_written.try_update(
                        Ordering::Relaxed,
                        Ordering::Relaxed,
                        |cur| Some(cur.saturating_add(written).saturating_sub(evicted)),
                    );
                }
            }
            Err(e) => log::debug!(
                "{}",
                crate::i18n::tr_log_args("snapshot-join-failed", &[("error", e.to_string())],)
            ),
        }
    }

    /// 命中计数与容量上限检查。
    ///
    /// 返回 `None` 表示签名键表已满,调用方直接返回(仅计指标)。
    fn track_hit(&self, key: &str) -> Option<u64> {
        let count = match self.counts.get_mut(key) {
            Some(mut c) => {
                *c += 1;
                *c
            }
            None => {
                if self.counts.len() >= MAX_TRACKED_KEYS {
                    counter!("crawlrs_failure_snapshot_total").increment(1);
                    return None;
                }
                self.counts.insert(key.to_string(), 1);
                1
            }
        };
        counter!("crawlrs_failure_snapshot_total").increment(1);
        Some(count)
    }

    /// 阻塞落盘:重复命中只刷新 meta.json;首写持锁做目录扫描与滚动逐出。
    #[allow(clippy::too_many_arguments)]
    fn persist_hit(
        dir: PathBuf,
        key: String,
        count: u64,
        content: String,
        screenshot_b64: Option<String>,
        meta: serde_json::Value,
        max_total: usize,
        persist_lock: Arc<parking_lot::Mutex<()>>,
    ) -> (u64, u64) {
        // 重复命中只刷新 meta.json,不使用截图:count > 1 时跳过解码(省 CPU)
        let screenshot = if count == 1 {
            screenshot_b64
                .as_deref()
                .map(|s| BASE64.decode(s))
                .transpose()
                .ok()
                .flatten()
        } else {
            None
        };
        // 仅首写(count == 1)需要互斥:它做目录扫描与逐出;重复命中只刷新
        // meta.json,不碰逐出游标,无需加锁。
        let _guard = (count == 1).then(|| persist_lock.lock());
        persist_snapshot(
            &dir,
            &key,
            count,
            &content,
            screenshot.as_deref(),
            &meta,
            max_total,
        )
    }

    /// 错误签名键 = sha256(url|status|reason) 前 30 hex + 消毒 reason 前 30 字符
    ///
    /// 消毒仅保留 `[a-zA-Z0-9_-]`(剥路径分隔符/控制字符),保证键可安全作文件名。
    fn signature_key(url: &str, status_code: u16, reason: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(url.as_bytes());
        hasher.update(b"|");
        hasher.update(status_code.to_string().as_bytes());
        hasher.update(b"|");
        hasher.update(reason.as_bytes());
        let hex = hex::encode(hasher.finalize());

        let mut key = String::with_capacity(60);
        key.push_str(&hex[..30]);
        key.extend(
            reason
                .chars()
                .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
                .take(30),
        );
        key
    }

    /// 查询某签名键的命中次数(测试与监控用)
    pub fn hit_count(&self, key: &str) -> Option<u64> {
        self.counts.get(key).map(|c| *c)
    }

    /// 查询净写入操作数(写入次数 − 逐出次数;重复命中刷新 meta 也计一次)。
    ///
    /// 测试与监控用;不是目录文件数(文件数由 `max_total` 扫描守卫)。
    pub fn total_written(&self) -> u64 {
        self.total_written.load(Ordering::Relaxed)
    }
}

/// 落盘一次快照(阻塞上下文调用,供 `spawn_blocking` 承载)
///
/// 返回 `(写入文件数, 滚动删除文件数)`。目录文件数达 `max_total` 时按
/// mtime 最旧优先逐个删除腾位;重复命中(count > 1)只刷新 meta,
/// 不做目录扫描。任何失败 `log::debug` 后静默返回(旁路观测语义)。
fn persist_snapshot(
    dir: &Path,
    key: &str,
    count: u64,
    content: &str,
    screenshot: Option<&[u8]>,
    meta: &serde_json::Value,
    max_total: usize,
) -> (u64, u64) {
    let mut written = 0u64;
    let mut evicted = 0u64;

    if let Err(e) = fs::create_dir_all(dir) {
        log::debug!(
            "{}",
            crate::i18n::tr_log_args(
                "snapshot-dir-create-failed",
                &[("dir", dir.display().to_string()), ("error", e.to_string()),],
            )
        );
        return (0, 0);
    }

    if count == 1 {
        // 首次命中才落盘响应体与截图(重复命中不重写,对齐 Crawlee 去重语义);
        // 需要新增文件前先滚动腾位
        let needed: u64 = 1 + u64::from(screenshot.is_some()) + 1; // html + jpg? + meta
        evicted += evict_oldest(dir, needed, max_total);

        let html_path = dir.join(format!("{key}.html"));
        match write_private(&html_path, content.as_bytes()) {
            Ok(()) => written += 1,
            Err(e) => log_snapshot_write_failed(&html_path, &e),
        }
        if let Some(bytes) = screenshot {
            let jpg_path = dir.join(format!("{key}.jpg"));
            match write_private(&jpg_path, bytes) {
                Ok(()) => written += 1,
                Err(e) => log_snapshot_write_failed(&jpg_path, &e),
            }
        }
    }

    // meta.json 每次命中都刷新(小文件):count 反映累计命中次数
    let meta_path = dir.join(format!("{key}.meta.json"));
    match serde_json::to_string_pretty(meta)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
        .and_then(|raw| write_private(&meta_path, raw.as_bytes()))
    {
        Ok(()) => written += 1,
        Err(e) => log_snapshot_write_failed(&meta_path, &e),
    }
    (written, evicted)
}

/// 快照写盘失败的旁路 debug 日志(启动期全局束 locale)
fn log_snapshot_write_failed(path: &Path, error: &std::io::Error) {
    log::debug!(
        "{}",
        crate::i18n::tr_log_args(
            "snapshot-write-failed",
            &[
                ("path", path.display().to_string()),
                ("error", error.to_string()),
            ],
        )
    );
}

/// 目录文件数逼近 `max_total` 时按 mtime 最旧优先删除,为 `needed` 个新文件腾位
///
/// 返回实际删除的文件数。文件级逐个删除(不按 key 分组):活跃键的
/// meta 因每次命中刷新 mtime,天然不会被优先淘汰。目录读取失败视为
/// 无需腾位(后续写盘失败按旁路静默)。
fn evict_oldest(dir: &Path, needed: u64, max_total: usize) -> u64 {
    let entries = match fs::read_dir(dir) {
        Ok(rd) => rd,
        Err(e) => {
            log::debug!(
                "{}",
                crate::i18n::tr_log_args(
                    "snapshot-read-dir-failed",
                    &[("dir", dir.display().to_string()), ("error", e.to_string()),],
                )
            );
            return 0;
        }
    };
    let mut files: Vec<(std::time::SystemTime, PathBuf)> = entries
        .filter_map(|e| e.ok())
        .filter_map(|e| {
            let meta = e.metadata().ok()?;
            if !meta.is_file() {
                return None;
            }
            Some((meta.modified().ok()?, e.path()))
        })
        .collect();
    let target = (max_total as u64).saturating_sub(needed);
    if (files.len() as u64) <= target {
        return 0;
    }
    files.sort_by_key(|(mtime, _)| *mtime);
    let total = files.len() as u64;
    let mut evicted = 0u64;
    for (_, path) in files {
        if total.saturating_sub(evicted) <= target {
            break;
        }
        match fs::remove_file(&path) {
            Ok(()) => evicted += 1,
            Err(e) => log::debug!(
                "{}",
                crate::i18n::tr_log_args(
                    "snapshot-evict-failed",
                    &[
                        ("path", path.display().to_string()),
                        ("error", e.to_string()),
                    ],
                )
            ),
        }
    }
    evicted
}

/// 以受限权限写文件:unix 下 0600(快照含目标站响应原文,属敏感数据);
/// 其他平台退化为进程默认 umask
#[cfg(unix)]
fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    use std::io::Write;
    use std::os::unix::fs::OpenOptionsExt;
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .mode(0o600)
        .open(path)?;
    file.write_all(bytes)
}

/// 以受限权限写文件(非 unix 平台:进程默认 umask)
#[cfg(not(unix))]
fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    fs::write(path, bytes)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::fs;
    use std::path::Path;
    use std::sync::LazyLock;

    static EMPTY_HEADERS: LazyLock<HashMap<String, String>> = LazyLock::new(HashMap::new);

    fn temp_snapshotter(max_total: usize) -> (FailureSnapshotter, PathBuf) {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("snapshots");
        (FailureSnapshotter::new(dir.clone(), max_total), dir)
    }

    fn sample_input<'a>(
        url: &'a str,
        status: u16,
        reason: &'a str,
        content: &'a str,
        screenshot: Option<&'a str>,
    ) -> SnapshotInput<'a> {
        SnapshotInput {
            url,
            status_code: status,
            reason,
            content: content.to_string(),
            headers: &EMPTY_HEADERS,
            screenshot: screenshot.map(str::to_owned),
        }
    }

    fn dir_file_count(dir: &Path) -> usize {
        fs::read_dir(dir).expect("read_dir").count()
    }

    fn read_meta(dir: &Path, key: &str) -> serde_json::Value {
        let raw = fs::read_to_string(dir.join(format!("{key}.meta.json"))).expect("meta.json");
        serde_json::from_str(&raw).expect("meta json parse")
    }

    /// 显式设置单个文件的 mtime。文件系统时间戳粒度粗于测试的连续写入间隔
    /// (实测 16 连写仅 2 个不同时间戳),「最旧优先」的淘汰顺序必须由测试
    /// 自己钉住,否则断言退化为 read_dir 随机序。
    fn set_mtime(path: &Path, t: std::time::SystemTime) {
        std::fs::File::options()
            .write(true)
            .open(path)
            .unwrap_or_else(|e| panic!("open {}: {e}", path.display()))
            .set_modified(t)
            .unwrap_or_else(|e| panic!("set_modified {}: {e}", path.display()));
    }

    /// 第 i 个签名的合成时间(远早于当前墙钟,且按写入序严格递增)。
    fn stamped_time(i: u64) -> std::time::SystemTime {
        std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000 + i)
    }

    fn stamp_signature(dir: &Path, key: &str, i: u64) {
        let t = stamped_time(i);
        set_mtime(&dir.join(format!("{key}.html")), t);
        set_mtime(&dir.join(format!("{key}.meta.json")), t);
    }

    // ========== 滚动淘汰(F4 护栏验收) ==========

    /// 滚动淘汰:目录文件数达 max_total 后最旧优先删除,新签名仍可观测。
    #[tokio::test]
    async fn rolling_eviction_keeps_dir_bounded_and_newest_observable() {
        let dir = std::env::temp_dir().join(format!("crawlrs-snap-test-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let snap = FailureSnapshotter::new(&dir, 6); // 6 文件 = 3 个签名(html+meta 各一)
        let headers = HashMap::new();

        // 写 8 个不同签名(16 文件)→ 滚动后仅保留最新 3 个签名的文件
        for i in 0..8 {
            let url = format!("https://x.com/err/{i}");
            let reason = format!("rate limited {i}");
            snap.snapshot(SnapshotInput {
                url: &url,
                status_code: 429,
                reason: &reason,
                content: "429".to_string(),
                headers: &headers,
                screenshot: None,
            })
            .await;
            let key = FailureSnapshotter::signature_key(&url, 429, &reason);
            stamp_signature(&dir, &key, i);
        }

        let file_count = std::fs::read_dir(&dir).unwrap().count();
        assert!(
            file_count <= 6,
            "目录文件数应 ≤ max_total=6,实际 {file_count}"
        );
        // 最旧的签名(err/0)已被淘汰
        let oldest_key =
            FailureSnapshotter::signature_key("https://x.com/err/0", 429, "rate limited 0");
        assert!(
            !dir.join(format!("{oldest_key}.meta.json")).exists(),
            "最旧签名的 meta 应被滚动删除"
        );
        // 最新的签名(err/7)仍可观测
        let newest_key =
            FailureSnapshotter::signature_key("https://x.com/err/7", 429, "rate limited 7");
        assert!(
            dir.join(format!("{newest_key}.meta.json")).exists(),
            "最新签名的 meta 应保留"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    // ========== 签名键 ==========

    /// 不同 reason 生成不同签名键(URL+status 相同)
    #[test]
    fn different_reason_yields_different_key() {
        let k1 = FailureSnapshotter::signature_key("https://x.com/a", 403, "cloudflare challenge");
        let k2 = FailureSnapshotter::signature_key("https://x.com/a", 403, "rate limited");
        assert_ne!(k1, k2);
        // 同输入键稳定
        assert_eq!(
            FailureSnapshotter::signature_key("https://x.com/a", 403, "cloudflare challenge"),
            k1
        );
    }

    /// 消息含路径分隔符/控制字符时键被消毒(不含 / \ 与不可打印字符)
    #[test]
    fn signature_key_sanitizes_path_separators_and_control_chars() {
        let key = FailureSnapshotter::signature_key(
            "https://x.com/a",
            403,
            "bad/../../etc\\passwd\n\t chall§enge",
        );
        assert!(!key.contains('/'), "key must not contain /: {key}");
        assert!(!key.contains('\\'), "key must not contain \\: {key}");
        assert!(
            key.chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
            "key must be filename-safe: {key}"
        );
        // 键长 = 30 hex + ≤30 消毒消息
        assert!(key.chars().count() <= 60);
    }

    // ========== 去重存档 ==========

    /// 同签名两次 snapshot:目录内文件数不变,meta.json 的 count=2
    #[tokio::test]
    async fn same_signature_second_hit_keeps_file_count_and_updates_meta_count() {
        let (snapshotter, dir) = temp_snapshotter(200);
        let url = "https://x.com/challenge";
        let reason = "cloudflare challenge detected";
        snapshotter
            .snapshot(sample_input(url, 403, reason, "<html>cf</html>", None))
            .await;
        let key = FailureSnapshotter::signature_key(url, 403, reason);
        let count_after_first = dir_file_count(&dir);
        assert!(count_after_first >= 2, "first hit writes html + meta");

        snapshotter
            .snapshot(sample_input(url, 403, reason, "<html>cf</html>", None))
            .await;
        assert_eq!(
            dir_file_count(&dir),
            count_after_first,
            "second hit must not create new files"
        );
        assert_eq!(snapshotter.hit_count(&key), Some(2));
        assert_eq!(read_meta(&dir, &key)["count"], 2, "meta count must be 2");
    }

    /// 不同 reason 生成不同快照(各自落盘)
    #[tokio::test]
    async fn different_reason_writes_distinct_snapshots() {
        let (snapshotter, dir) = temp_snapshotter(200);
        snapshotter
            .snapshot(sample_input(
                "https://x.com/a",
                403,
                "reason-one",
                "<html>1</html>",
                None,
            ))
            .await;
        snapshotter
            .snapshot(sample_input(
                "https://x.com/a",
                403,
                "reason-two",
                "<html>2</html>",
                None,
            ))
            .await;
        assert!(dir
            .join(format!(
                "{}.html",
                FailureSnapshotter::signature_key("https://x.com/a", 403, "reason-one")
            ))
            .exists());
        assert!(dir
            .join(format!(
                "{}.html",
                FailureSnapshotter::signature_key("https://x.com/a", 403, "reason-two")
            ))
            .exists());
    }

    /// meta.json 携带 url / status / reason / headers
    #[tokio::test]
    async fn meta_json_carries_response_metadata() {
        let (snapshotter, dir) = temp_snapshotter(200);
        let mut headers = HashMap::new();
        headers.insert("server".to_string(), "cloudflare".to_string());
        let input = SnapshotInput {
            url: "https://x.com/meta",
            status_code: 429,
            reason: "rate limited",
            content: "<html>429</html>".to_string(),
            headers: &headers,
            screenshot: None,
        };
        snapshotter.snapshot(input).await;
        let key = FailureSnapshotter::signature_key("https://x.com/meta", 429, "rate limited");
        let meta = read_meta(&dir, &key);
        assert_eq!(meta["url"], "https://x.com/meta");
        assert_eq!(meta["status"], 429);
        assert_eq!(meta["reason"], "rate limited");
        assert_eq!(meta["headers"]["server"], "cloudflare");
        assert_eq!(meta["count"], 1);
    }

    // ========== 磁盘护栏(滚动删除) ==========

    /// 达 max_total 后新签名滚动淘汰最旧文件腾位:目录文件数有界、新键可观测
    #[tokio::test]
    async fn max_total_rolls_oldest_files_to_admit_new_snapshot() {
        let (snapshotter, dir) = temp_snapshotter(2);
        let key_one = FailureSnapshotter::signature_key("https://x.com/one", 403, "r1");
        snapshotter
            .snapshot(sample_input(
                "https://x.com/one",
                403,
                "r1",
                "<html>1</html>",
                None,
            ))
            .await;
        assert_eq!(snapshotter.total_written(), 2, "html + meta = 2 files");
        assert!(dir.join(format!("{key_one}.html")).exists());
        stamp_signature(&dir, &key_one, 0);

        // 护栏已满:新签名滚动删除最旧(key-one 的 html/meta),写入自身文件
        let key_two = FailureSnapshotter::signature_key("https://x.com/two", 403, "r2");
        snapshotter
            .snapshot(sample_input(
                "https://x.com/two",
                403,
                "r2",
                "<html>2</html>",
                None,
            ))
            .await;
        stamp_signature(&dir, &key_two, 1);
        assert_eq!(
            dir_file_count(&dir),
            2,
            "rolling keeps directory bounded at max_total"
        );
        assert!(
            !dir.join(format!("{key_one}.html")).exists(),
            "oldest snapshot files evicted"
        );
        assert!(
            dir.join(format!("{key_two}.html")).exists(),
            "new snapshot admitted after eviction"
        );
        assert_eq!(snapshotter.hit_count(&key_two), Some(1), "new key counted");
        assert_eq!(
            snapshotter.total_written(),
            2,
            "cursor nets writes/evictions"
        );
    }

    /// 落盘文件权限收紧:unix 下 0600(敏感响应原文不得 world-readable)
    #[cfg(unix)]
    #[tokio::test]
    async fn snapshot_files_written_with_owner_only_permissions() {
        use std::os::unix::fs::PermissionsExt;
        let (snapshotter, dir) = temp_snapshotter(200);
        snapshotter
            .snapshot(sample_input(
                "https://x.com/perm",
                403,
                "waf",
                "<html/>",
                None,
            ))
            .await;
        let key = FailureSnapshotter::signature_key("https://x.com/perm", 403, "waf");
        for name in [format!("{key}.html"), format!("{key}.meta.json")] {
            let mode = fs::metadata(dir.join(&name))
                .expect("snapshot file exists")
                .permissions()
                .mode();
            assert_eq!(
                mode & 0o777,
                0o600,
                "{name} must be owner-only, got {:o}",
                mode & 0o777
            );
        }
    }

    /// 签名键内存表达 `MAX_TRACKED_KEYS` 上限:超限后新键不入表(仅计指标),
    /// 既有键不受影响
    #[tokio::test]
    async fn counts_map_caps_distinct_keys() {
        let (snapshotter, _dir) = temp_snapshotter(1);
        let first_key = FailureSnapshotter::signature_key("https://x.com/k0", 403, "r");
        for i in 0..=MAX_TRACKED_KEYS {
            snapshotter
                .snapshot(sample_input(
                    &format!("https://x.com/k{i}"),
                    403,
                    "r",
                    "x",
                    None,
                ))
                .await;
        }
        assert_eq!(
            snapshotter.hit_count(&first_key),
            Some(1),
            "early key still tracked"
        );
        let overflow_key = FailureSnapshotter::signature_key(
            &format!("https://x.com/k{MAX_TRACKED_KEYS}"),
            403,
            "r",
        );
        assert_eq!(
            snapshotter.hit_count(&overflow_key),
            None,
            "key beyond cap must not enter the map"
        );
    }

    // ========== 截图透传 ==========

    /// screenshot=Some 时 .jpg 落盘且 base64 解码正确
    #[tokio::test]
    async fn screenshot_some_writes_decoded_jpg() {
        let (snapshotter, dir) = temp_snapshotter(200);
        // "aGVsbG8=" = "hello"
        snapshotter
            .snapshot(sample_input(
                "https://x.com/shot",
                403,
                "waf",
                "<html>shot</html>",
                Some("aGVsbG8="),
            ))
            .await;
        let key = FailureSnapshotter::signature_key("https://x.com/shot", 403, "waf");
        let jpg = fs::read(dir.join(format!("{key}.jpg"))).expect("jpg file");
        assert_eq!(jpg, b"hello", "jpg must be base64-decoded bytes");
        assert_eq!(snapshotter.total_written(), 3, "html + meta + jpg");
    }

    /// screenshot=None 时无 .jpg
    #[tokio::test]
    async fn screenshot_none_writes_no_jpg() {
        let (snapshotter, dir) = temp_snapshotter(200);
        snapshotter
            .snapshot(sample_input(
                "https://x.com/noshot",
                403,
                "waf",
                "<html>noshot</html>",
                None,
            ))
            .await;
        let key = FailureSnapshotter::signature_key("https://x.com/noshot", 403, "waf");
        assert!(!dir.join(format!("{key}.jpg")).exists());
        assert!(dir.join(format!("{key}.html")).exists());
    }

    /// 非法 base64 截图静默跳过(不 panic、不写 .jpg)
    #[tokio::test]
    async fn invalid_base64_screenshot_is_silently_skipped() {
        let (snapshotter, dir) = temp_snapshotter(200);
        snapshotter
            .snapshot(sample_input(
                "https://x.com/b64",
                403,
                "waf",
                "<html>b64</html>",
                Some("!!!not-base64!!!"),
            ))
            .await;
        let key = FailureSnapshotter::signature_key("https://x.com/b64", 403, "waf");
        assert!(
            !dir.join(format!("{key}.jpg")).exists(),
            "bad base64: no jpg"
        );
        assert!(
            dir.join(format!("{key}.html")).exists(),
            "html still written"
        );
        assert_eq!(snapshotter.total_written(), 2);
    }

    // ========== 错误显性化(旁路降级) ==========

    /// dir 不可写(路径为普通文件,create_dir_all 必败)时 snapshot 静默返回,无 panic
    #[tokio::test]
    async fn unwritable_dir_returns_silently_no_panic() {
        let tmp = tempfile::tempdir().expect("tempdir");
        // 用普通文件路径冒充目录:create_dir_all 在任意用户(含 root)下都失败
        let file_path = tmp.path().join("not-a-dir");
        fs::write(&file_path, b"occupied").expect("write blocker file");
        let snapshotter = FailureSnapshotter::new(file_path.clone(), 200);

        snapshotter
            .snapshot(sample_input("https://x.com/x", 403, "r", "<html/>", None))
            .await;
        assert_eq!(snapshotter.total_written(), 0, "nothing written");
        assert!(file_path.is_file(), "blocker file untouched");
    }

    // ========== 配置构造 ==========

    /// from_config:目录空串 = None(禁用);非空 = Some
    #[test]
    fn from_config_empty_dir_is_none_and_populated_is_some() {
        let disabled = ObservabilitySettings {
            failure_snapshot_dir: String::new(),
            failure_snapshot_max_total: 200,
        };
        assert!(FailureSnapshotter::from_config(&disabled).is_none());

        let enabled = ObservabilitySettings {
            failure_snapshot_dir: "data/failure_snapshots".to_string(),
            failure_snapshot_max_total: 50,
        };
        let s = FailureSnapshotter::from_config(&enabled).expect("some");
        assert_eq!(s.total_written(), 0);
    }

    // ========== 并发串行化 ==========

    /// 并发 snapshot:落盘互斥保证文件数不超 max_total,且 total_written 与磁盘一致
    #[tokio::test]
    async fn concurrent_snapshots_keep_dir_bounded_and_accounted() {
        let (snapshotter, dir) = temp_snapshotter(4);
        let snapshotter = Arc::new(snapshotter);

        let mut handles = Vec::new();
        for i in 0..16 {
            let snap = snapshotter.clone();
            handles.push(tokio::spawn(async move {
                let url = format!("https://x.com/c{i}");
                let reason = format!("rate limited {i}");
                snap.snapshot(SnapshotInput {
                    url: &url,
                    status_code: 429,
                    reason: &reason,
                    content: format!("<html>{i}</html>"),
                    headers: &EMPTY_HEADERS,
                    screenshot: None,
                })
                .await;
            }));
        }
        for handle in handles {
            handle.await.expect("snapshot task");
        }

        let files = fs::read_dir(&dir).expect("read_dir").count() as u64;
        assert!(
            files <= 4,
            "dir must stay bounded by max_total, got {files}"
        );
        // 本用例每键仅命中一次:净写入操作数 = 目录文件数
        assert_eq!(
            snapshotter.total_written(),
            files,
            "for unique keys the net write counter must equal on-disk file count"
        );
    }
}