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
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Sitemap 流式请求源(F11):sitemap 作为 crawl 的一等 URL 发现源
//!
//! 消费 `MapUseCase::execute_streaming` 的 `<loc>` 有界通道,逐 URL 过
//! FilterChain(include/exclude 通配 + 域名黑名单)与分层去重
//! (Bloom 预筛 → DB 精确校验,语义对齐 `extract_and_queue_links`)后
//! 入队为 crawl Task 行(depth = 1,config 原样继承种子任务)。
//!
//! # 断点续爬(与 F3 共用 DB 持久)
//!
//! 每入队一批持久化进度指针 `{sitemap_url, consumed}` 到 `cache_service`;
//! worker 重启后种子任务被重新认领并再次进入喂入路径,从指针处继续。
//! 喂入完成(流耗尽)后删除指针。
//!
//! # seek 精度与正确性边界
//!
//! - `Urlset` 流保序:指针 `consumed=N` 时精确跳过前 N 条,从第 N+1 条继续。
//! - `SitemapIndex` 流的子 sitemap 并发展开、到达顺序天然不定:两次消费的
//!   顺序无法对齐,seek 会跳错条目。此场景不 seek,改为全量重喂,重复由
//!   分层去重兜底(已入队 loc 在 dedup/DB 中命中被跳过)——正确性由
//!   dedup + DB 校验保证,指针只加速保序的 Urlset 场景。
//!
//! 入队批与指针持久化非原子:create 成功、指针写回前崩溃 → 恢复后指针
//! 滞后,重复 loc 走 dedup/DB 被挡(安全方向:多检不漏喂)。
//!
//! # 失败显性化
//!
//! 拉取失败向上传播,由调用方打 error 日志并说明后果(crawl 继续以页面
//! 链接发现运行);sitemap 404 是合法状态(站点无 sitemap),返回零入队
//! 而非错误。

mod sitemap_batch;
use sitemap_batch::{build_sitemap_task, dedup_filtered_batch, filter_batch_urls};

use std::sync::Arc;

use serde::{Deserialize, Serialize};
use url::Url;

use crate::application::dto::map_request::MapRequestDto;
use crate::application::use_cases::map_use_case::{
    MapUseCase, SitemapFetcher, SitemapKind, SitemapStream, SitemapStreamOptions,
};
use crate::domain::repositories::crawl_repository::CrawlRepository;
use crate::domain::repositories::task_repository::TaskRepository;
use crate::infrastructure::oxcache::CacheService;
use crate::utils::dedup::Deduplicator;
use crate::workers::crawl::{DomainFilter, FilterContext, UrlPatternFilter};

#[cfg(test)]
use crate::domain::models::{Task, TaskStatus, TaskType};
#[cfg(test)]
use serde_json::json;
#[cfg(test)]
use std::collections::HashSet;

/// 批大小:每消费这么多 loc 执行一次过滤/去重/入队/指针持久化
const FEED_BATCH_SIZE: usize = 500;

/// 喂入进度指针:记录消费中的 sitemap 文档与已消费 `<loc>` 数
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SitemapFeedPointer {
    /// 正在消费的 sitemap 文档 URL
    pub sitemap_url: String,
    /// 该文档已消费(喂入判定完毕)的 `<loc>` 数
    pub consumed: usize,
}

/// 喂入结果统计
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct SitemapFeedStats {
    /// 入队的 crawl Task 行数
    pub enqueued: usize,
    /// 被 FilterChain 拒绝的 loc 数
    pub filtered_out: usize,
    /// 被去重跳过(DB 确认已存在)的 loc 数
    pub duplicates_skipped: usize,
    /// 从通道消费的 loc 总数(含 seek 跳过与重复)
    pub consumed: usize,
    /// 恢复起点(Urlset 流从指针跳过的条数;无指针 / Index 流为 None)
    pub resumed_from: Option<usize>,
}

/// 入队 Task 行的种子上下文(继承种子任务的归属与配置)
#[derive(Debug, Clone)]
pub struct SeedTaskContext {
    pub team_id: crate::domain::id::Id,
    pub api_key_id: crate::domain::id::Id,
    pub crawl_id: crate::domain::id::Id,
    /// 子任务 priority(对齐 `extract_and_queue_links`:继承种子任务)
    pub priority: i32,
    /// 种子任务 payload 中的 `config`(原样透传,保持与链接提取侧同构)
    pub config_json: serde_json::Value,
}

/// 指针的 cache key(每 crawl 一条)
pub fn sitemap_feed_pointer_key(crawl_id: crate::domain::id::Id) -> String {
    format!("crawl:sitemap-feed:{crawl_id}")
}

/// 从 crawl 种子 URL 派生默认 sitemap 地址:`scheme://host[:port]/sitemap.xml`
pub fn derive_sitemap_url(seed_url: &str) -> Option<String> {
    let parsed = Url::parse(seed_url).ok()?;
    let host = parsed.host_str()?;
    let origin = match parsed.port() {
        Some(port) => format!("{}://{host}:{port}", parsed.scheme()),
        None => format!("{}://{host}", parsed.scheme()),
    };
    Some(format!("{origin}/sitemap.xml"))
}

/// 读取指针。cache 缺失 / 解析失败 / 指向不同 sitemap(源已变)→ None;
/// 指针是加速不是正确性依赖,任何异常都安全回退到全量重喂 + 去重兜底。
async fn load_pointer(
    cache: &dyn CacheService,
    crawl_id: crate::domain::id::Id,
    sitemap_url: &str,
) -> Option<usize> {
    let raw = cache
        .get(&sitemap_feed_pointer_key(crawl_id))
        .await
        .ok()??;
    match serde_json::from_str::<SitemapFeedPointer>(&raw) {
        Ok(p) if p.sitemap_url == sitemap_url => Some(p.consumed),
        Ok(p) => {
            log::warn!(
                "{}",
                crate::i18n::tr_log_args(
                    "sitemap-pointer-mismatch",
                    &[
                        ("crawl_id", crawl_id.to_string(),),
                        ("pointer_url", p.sitemap_url.as_str().to_string(),),
                        ("sitemap_url", sitemap_url.to_string()),
                    ],
                )
            );
            None
        }
        Err(e) => {
            log::warn!(
                "{}",
                crate::i18n::tr_log_args(
                    "sitemap-pointer-corrupt",
                    &[
                        ("crawl_id", crawl_id.to_string(),),
                        ("error", e.to_string()),
                    ],
                )
            );
            None
        }
    }
}

/// 消费 sitemap 流并入队 crawl 任务(组件入口)
///
/// 拉取失败向上传播(调用方显性上报);404 → 零入队的合法结果。
#[allow(clippy::too_many_arguments)]
pub async fn feed_sitemap_as_tasks(
    fetcher: Arc<dyn SitemapFetcher>,
    sitemap_url: String,
    options: SitemapStreamOptions,
    include_patterns: Option<Vec<String>>,
    exclude_patterns: Option<Vec<String>>,
    domain_blacklist: Vec<String>,
    seed: SeedTaskContext,
    dedup: &Arc<parking_lot::RwLock<Deduplicator>>,
    task_repo: &dyn TaskRepository,
    crawl_repo: &dyn CrawlRepository,
    cache: &dyn CacheService,
    pointer_ttl_secs: u64,
) -> anyhow::Result<SitemapFeedStats> {
    let stream = open_sitemap_stream(fetcher, &sitemap_url, options).await?;
    let mut rx = stream.rx;

    // seek 决策:仅 Urlset 流(保序)精确跳过;Index 流不 seek(见模块文档)
    let mut stats = SitemapFeedStats::default();
    let seek =
        resolve_seek_position(cache, seed.crawl_id, &sitemap_url, stream.kind, &mut stats).await;

    // include 为显式空列表 = 全部拒绝(对齐 extract_and_queue_links 短路语义;
    // 与 UrlPatternFilter 的「空 include = 无限制」不同,必须单独短路)
    let (pattern_filter, blacklist_filter, filter_ctx, empty_include_short_circuit) =
        build_feed_filters(include_patterns, exclude_patterns, domain_blacklist);

    feed_sitemap_stream(
        &mut rx,
        seek,
        &mut stats,
        pattern_filter.as_ref(),
        blacklist_filter.as_ref(),
        &filter_ctx,
        empty_include_short_circuit,
        &seed,
        &sitemap_url,
        dedup,
        task_repo,
        crawl_repo,
        cache,
        pointer_ttl_secs,
    )
    .await?;

    // 喂入完成:指针使命结束(404/空流零消费时无指针可清)
    if stats.consumed > 0 {
        let _ = cache.delete(&sitemap_feed_pointer_key(seed.crawl_id)).await;
    }
    Ok(stats)
}

/// 打开流式 sitemap 消费端点(自 [`feed_sitemap_as_tasks`] 提取)
async fn open_sitemap_stream(
    fetcher: Arc<dyn SitemapFetcher>,
    sitemap_url: &str,
    options: SitemapStreamOptions,
) -> anyhow::Result<SitemapStream> {
    let use_case = MapUseCase::new(fetcher);
    let dto = MapRequestDto {
        url: sitemap_url.to_string(),
        include_patterns: None,
        exclude_patterns: None,
        limit: None,
    };
    use_case
        .execute_streaming(&dto, options)
        .await
        .map_err(|e| anyhow::anyhow!(e.to_string()))
}

/// seek 位置决策(自 [`feed_sitemap_as_tasks`] 提取):仅 Urlset 流(保序)精确跳过
async fn resolve_seek_position(
    cache: &dyn CacheService,
    crawl_id: crate::domain::id::Id,
    sitemap_url: &str,
    kind: SitemapKind,
    stats: &mut SitemapFeedStats,
) -> Option<usize> {
    match load_pointer(cache, crawl_id, sitemap_url).await {
        Some(consumed) if consumed > 0 => {
            if kind == SitemapKind::Urlset {
                stats.resumed_from = Some(consumed);
                Some(consumed)
            } else {
                log::info!(
                    "{}",
                    crate::i18n::tr_log_args(
                        "sitemap-resume-without-seek",
                        &[
                            ("crawl_id", crawl_id.to_string(),),
                            ("consumed", (consumed as i64).to_string()),
                        ],
                    )
                );
                None
            }
        }
        _ => None,
    }
}

/// 构造 FilterChain 组件(自 [`feed_sitemap_as_tasks`] 提取)
fn build_feed_filters(
    include_patterns: Option<Vec<String>>,
    exclude_patterns: Option<Vec<String>>,
    domain_blacklist: Vec<String>,
) -> (
    Option<UrlPatternFilter>,
    Option<DomainFilter>,
    FilterContext,
    bool,
) {
    // include 为显式空列表 = 全部拒绝(对齐 extract_and_queue_links 短路语义;
    // 与 UrlPatternFilter 的「空 include = 无限制」不同,必须单独短路)
    let empty_include_short_circuit =
        matches!(&include_patterns, Some(patterns) if patterns.is_empty());
    let pattern_filter = if empty_include_short_circuit {
        None
    } else {
        Some(UrlPatternFilter::new(
            include_patterns.unwrap_or_default(),
            exclude_patterns.unwrap_or_default(),
        ))
    };
    let blacklist_filter = if domain_blacklist.is_empty() {
        None
    } else {
        Some(DomainFilter::denylist_normalized(domain_blacklist))
    };
    let filter_ctx = FilterContext::default();
    (
        pattern_filter,
        blacklist_filter,
        filter_ctx,
        empty_include_short_circuit,
    )
}

/// 消费 sitemap 流并按批入队(自 [`feed_sitemap_as_tasks`] 提取)
#[allow(clippy::too_many_arguments)]
async fn feed_sitemap_stream(
    rx: &mut tokio::sync::mpsc::Receiver<String>,
    seek: Option<usize>,
    stats: &mut SitemapFeedStats,
    pattern_filter: Option<&UrlPatternFilter>,
    blacklist_filter: Option<&DomainFilter>,
    filter_ctx: &FilterContext,
    empty_include_short_circuit: bool,
    seed: &SeedTaskContext,
    sitemap_url: &str,
    dedup: &Arc<parking_lot::RwLock<Deduplicator>>,
    task_repo: &dyn TaskRepository,
    crawl_repo: &dyn CrawlRepository,
    cache: &dyn CacheService,
    pointer_ttl_secs: u64,
) -> anyhow::Result<()> {
    let mut batch: Vec<String> = Vec::with_capacity(FEED_BATCH_SIZE.min(64));
    while let Some(loc) = rx.recv().await {
        if let Some(seek_n) = seek {
            if stats.consumed < seek_n {
                stats.consumed += 1;
                continue;
            }
        }
        stats.consumed += 1;
        batch.push(loc);
        // 先入批再 flush:flush 时指针 consumed 精确覆盖本批全部已处理 loc
        // (先 flush 后 push 会让指针超前于实际处理,崩溃恢复时漏喂边界 loc)
        if batch.len() >= FEED_BATCH_SIZE {
            flush_batch(
                &mut batch,
                stats,
                pattern_filter,
                blacklist_filter,
                filter_ctx,
                empty_include_short_circuit,
                seed,
                sitemap_url,
                dedup,
                task_repo,
                crawl_repo,
                cache,
                pointer_ttl_secs,
            )
            .await?;
        }
    }
    if !batch.is_empty() {
        flush_batch(
            &mut batch,
            stats,
            pattern_filter,
            blacklist_filter,
            filter_ctx,
            empty_include_short_circuit,
            seed,
            sitemap_url,
            dedup,
            task_repo,
            crawl_repo,
            cache,
            pointer_ttl_secs,
        )
        .await?;
    }

    Ok(())
}

/// 单批处理:FilterChain 过滤 → 分层去重 → 入队 → 持久化指针
#[allow(clippy::too_many_arguments)]
async fn flush_batch(
    batch: &mut Vec<String>,
    stats: &mut SitemapFeedStats,
    pattern_filter: Option<&UrlPatternFilter>,
    blacklist_filter: Option<&DomainFilter>,
    filter_ctx: &FilterContext,
    empty_include_short_circuit: bool,
    seed: &SeedTaskContext,
    sitemap_url: &str,
    dedup: &Arc<parking_lot::RwLock<Deduplicator>>,
    task_repo: &dyn TaskRepository,
    crawl_repo: &dyn CrawlRepository,
    cache: &dyn CacheService,
    pointer_ttl_secs: u64,
) -> anyhow::Result<()> {
    // sitemap 入队前校验父 crawl 终态,避免停止后继续扩容。
    // 仅需状态:投影读取,避免每批拉回 crawl.config。
    if let Ok(Some(progress)) = crawl_repo.find_progress_by_id(seed.crawl_id).await {
        if crate::application::use_cases::crawl_state_machine::is_terminal(&progress.status) {
            log::info!(
                "crawl {} is terminal; skip enqueueing sitemap batch",
                seed.crawl_id
            );
            return Ok(());
        }
    }

    let new_urls = dedup_filtered_batch(
        filter_batch_urls(
            batch,
            stats,
            pattern_filter,
            blacklist_filter,
            filter_ctx,
            empty_include_short_circuit,
        ),
        dedup,
        task_repo,
        stats,
    )
    .await?;

    for url in &new_urls {
        // 超长 URL 会触发 PostgreSQL btree 唯一索引上限错误,
        // 与根 URL 保持同一 2048 字节口径直接跳过。
        if url.len() > 2048 {
            log::debug!("skip oversized sitemap task url ({} bytes)", url.len());
            continue;
        }
        let task = build_sitemap_task(url, seed);
        match task_repo.create(&task).await {
            Ok(_) => {
                // 只有插入成功才计数;并发窗口的重复 URL 由
                // (crawl_id,url) 唯一索引兜底,跳过而非中止整个 feed。
                crawl_repo.increment_total_tasks(seed.crawl_id).await?;
                stats.enqueued += 1;
            }
            Err(e) => {
                // 类型化唯一冲突判定
                if e.is_unique_conflict() {
                    log::debug!("skip duplicate sitemap task url={}", task.url);
                } else {
                    return Err(e.into());
                }
            }
        }
    }

    // 每批持久化进度指针(断点续爬;此时 batch 已全部处理,consumed 精确)
    let pointer = SitemapFeedPointer {
        sitemap_url: sitemap_url.to_string(),
        consumed: stats.consumed,
    };
    cache
        .set(
            &sitemap_feed_pointer_key(seed.crawl_id),
            &serde_json::to_string(&pointer)?,
            pointer_ttl_secs,
        )
        .await?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::application::use_cases::map_use_case::MapError;
    use crate::domain::repositories::task_repository::RepositoryError;
    use async_trait::async_trait;
    use std::collections::HashMap;
    use std::sync::atomic::{AtomicU32, Ordering};

    // mocks

    /// 内存 CacheService:记录 set/delete 调用(指针持久化断言用)
    #[derive(Default)]
    struct MockCache {
        store: parking_lot::Mutex<HashMap<String, String>>,
        set_keys: parking_lot::Mutex<Vec<String>>,
        deleted: parking_lot::Mutex<Vec<String>>,
    }

    impl MockCache {
        fn set_calls(&self, key: &str) -> usize {
            self.set_keys.lock().iter().filter(|k| *k == key).count()
        }
    }

    #[async_trait::async_trait]
    impl CacheService for MockCache {
        fn get(
            &self,
            key: &str,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = anyhow::Result<Option<String>>> + Send + '_>,
        > {
            let v = self.store.lock().get(key).cloned();
            Box::pin(async move { Ok(v) })
        }
        fn set(
            &self,
            key: &str,
            value: &str,
            _ttl_seconds: u64,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send + '_>>
        {
            self.store.lock().insert(key.to_string(), value.to_string());
            self.set_keys.lock().push(key.to_string());
            Box::pin(async { Ok(()) })
        }
        fn delete(
            &self,
            key: &str,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send + '_>>
        {
            self.store.lock().remove(key);
            self.deleted.lock().push(key.to_string());
            Box::pin(async { Ok(()) })
        }
        fn exists(
            &self,
            key: &str,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<bool>> + Send + '_>>
        {
            let v = self.store.lock().contains_key(key);
            Box::pin(async move { Ok(v) })
        }
    }

    /// 计数任务仓库(记录 create 的 Task 行;可注入 DB 已存在 URL)
    struct CountingTaskRepo {
        created: parking_lot::Mutex<Vec<Task>>,
        existing_urls: HashSet<String>,
    }

    impl CountingTaskRepo {
        fn new() -> Self {
            Self {
                created: parking_lot::Mutex::new(Vec::new()),
                existing_urls: HashSet::new(),
            }
        }
        fn new_with_existing(urls: &[&str]) -> Self {
            Self {
                created: parking_lot::Mutex::new(Vec::new()),
                existing_urls: urls.iter().map(|s| s.to_string()).collect(),
            }
        }
        fn created_urls(&self) -> Vec<String> {
            self.created.lock().iter().map(|t| t.url.clone()).collect()
        }
    }

    #[async_trait]
    impl TaskRepository for CountingTaskRepo {
        async fn create(&self, task: &Task) -> Result<Task, RepositoryError> {
            self.created.lock().push(task.clone());
            Ok(task.clone())
        }
        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(None)
        }
        async fn update(&self, task: &Task) -> Result<Task, RepositoryError> {
            Ok(task.clone())
        }
        async fn acquire_next(
            &self,
            _worker_id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(None)
        }
        async fn mark_completed(
            &self,
            _id: crate::domain::id::Id,
            _lock_token: Option<crate::domain::id::Id>,
        ) -> Result<u64, RepositoryError> {
            Ok(1)
        }
        async fn mark_failed(
            &self,
            _id: crate::domain::id::Id,
            _lock_token: Option<crate::domain::id::Id>,
        ) -> Result<u64, RepositoryError> {
            Ok(1)
        }
        async fn mark_cancelled(&self, _id: crate::domain::id::Id) -> Result<u64, RepositoryError> {
            Ok(1)
        }
        async fn exists_by_url(&self, _url: &str) -> Result<bool, RepositoryError> {
            Ok(false)
        }
        async fn find_existing_urls(
            &self,
            urls: &[String],
        ) -> Result<HashSet<String>, RepositoryError> {
            Ok(urls
                .iter()
                .filter(|u| self.existing_urls.contains(*u))
                .cloned()
                .collect())
        }
        async fn list_distinct_urls(
            &self,
            _limit: u32,
            _after_url: Option<String>,
        ) -> Result<Vec<String>, RepositoryError> {
            Ok(vec![])
        }
        async fn reset_stuck_tasks(
            &self,
            _timeout: chrono::Duration,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
        async fn cancel_tasks_by_crawl_id(
            &self,
            _crawl_id: crate::domain::id::Id,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
        async fn expire_tasks(&self) -> Result<u64, RepositoryError> {
            Ok(0)
        }
        async fn find_by_crawl_id(
            &self,
            _crawl_id: crate::domain::id::Id,
        ) -> Result<Vec<Task>, RepositoryError> {
            Ok(vec![])
        }
        async fn query_tasks(
            &self,
            _params: crate::domain::repositories::task_repository::TaskQueryParams,
        ) -> Result<(Vec<Task>, u64), RepositoryError> {
            Ok((vec![], 0))
        }
        async fn batch_cancel(
            &self,
            _task_ids: Vec<crate::domain::id::Id>,
            _team_id: crate::domain::id::Id,
            _force: bool,
        ) -> Result<
            (
                Vec<crate::domain::id::Id>,
                Vec<(crate::domain::id::Id, String)>,
            ),
            RepositoryError,
        > {
            Ok((vec![], vec![]))
        }
        async fn renew_lock(
            &self,
            _task_id: crate::domain::id::Id,
            _worker_id: crate::domain::id::Id,
            _extend_seconds: i64,
        ) -> Result<bool, RepositoryError> {
            Ok(true)
        }
    }

    /// 计数 crawl 仓库
    #[derive(Default)]
    struct CountingCrawlRepo {
        total_added: AtomicU32,
    }

    #[async_trait]
    impl CrawlRepository for CountingCrawlRepo {
        async fn create(
            &self,
            crawl: &crate::domain::models::Crawl,
        ) -> Result<crate::domain::models::Crawl, RepositoryError> {
            Ok(crawl.clone())
        }
        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<crate::domain::models::Crawl>, RepositoryError> {
            Ok(None)
        }
        async fn update(
            &self,
            crawl: &crate::domain::models::Crawl,
        ) -> Result<crate::domain::models::Crawl, RepositoryError> {
            Ok(crawl.clone())
        }
        async fn increment_completed_tasks(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<(), RepositoryError> {
            Ok(())
        }
        async fn increment_failed_tasks(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<(), RepositoryError> {
            Ok(())
        }
        async fn update_status(
            &self,
            _id: crate::domain::id::Id,
            _status: crate::domain::models::CrawlStatus,
        ) -> Result<(), RepositoryError> {
            Ok(())
        }
        async fn increment_total_tasks(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<(), RepositoryError> {
            self.total_added.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
        async fn find_by_team_id_paginated(
            &self,
            _team_id: crate::domain::id::Id,
            _limit: u32,
            _offset: u32,
        ) -> Result<Vec<crate::domain::models::Crawl>, RepositoryError> {
            Ok(vec![])
        }
        async fn count_by_team_id(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
    }

    /// 静态 sitemap mock:urlset XML 一次返回
    struct StaticSitemapFetcher {
        responses: HashMap<String, (u16, String)>,
    }

    fn urlset_xml(locs: &[String]) -> String {
        let inner: String = locs
            .iter()
            .map(|l| format!("<url><loc>{l}</loc></url>"))
            .collect();
        format!(
            r#"<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">{inner}</urlset>"#
        )
    }

    #[async_trait]
    impl SitemapFetcher for StaticSitemapFetcher {
        async fn fetch(
            &self,
            url: &str,
        ) -> Result<crate::application::use_cases::map_use_case::SitemapFetch, MapError> {
            match self.responses.get(url) {
                Some((status, body)) => {
                    Ok(crate::application::use_cases::map_use_case::SitemapFetch {
                        status: *status,
                        body: body.clone(),
                    })
                }
                None => Err(MapError::TargetUnreachable(format!("no mock for {url}"))),
            }
        }
    }

    fn seed_ctx(crawl_id: crate::domain::id::Id) -> SeedTaskContext {
        SeedTaskContext {
            team_id: crate::domain::id::Id::generate(),
            api_key_id: crate::domain::id::Id::generate(),
            crawl_id,
            priority: 100,
            config_json: json!({"max_depth": 2}),
        }
    }

    fn options(max_urls: usize) -> SitemapStreamOptions {
        SitemapStreamOptions {
            domain_blacklist: Vec::new(),
            channel_capacity: 16,
            max_urls,
            max_concurrent_sub_sitemaps: 2,
        }
    }

    #[allow(clippy::too_many_arguments)]
    async fn feed(
        fetcher: StaticSitemapFetcher,
        sitemap_url: &str,
        include: Option<Vec<String>>,
        exclude: Option<Vec<String>>,
        blacklist: Vec<String>,
        seed: SeedTaskContext,
        dedup: &Arc<parking_lot::RwLock<Deduplicator>>,
        task_repo: &CountingTaskRepo,
        crawl_repo: &CountingCrawlRepo,
        cache: &MockCache,
    ) -> anyhow::Result<SitemapFeedStats> {
        feed_sitemap_as_tasks(
            Arc::new(fetcher),
            sitemap_url.to_string(),
            options(50_000),
            include,
            exclude,
            blacklist,
            seed,
            dedup,
            task_repo,
            crawl_repo,
            cache,
            7 * 24 * 3600,
        )
        .await
    }

    const SITEMAP_URL: &str = "https://a.com/sitemap.xml";

    // tests

    /// 基础喂入:5 个 loc 全部入队为 depth=1 的 crawl Task 行,指针删除(完成)
    #[tokio::test]
    async fn feed_enqueues_task_rows_and_clears_pointer() {
        let locs: Vec<String> = (0..5).map(|i| format!("https://a.com/{i}")).collect();
        let fetcher = StaticSitemapFetcher {
            responses: HashMap::from([(SITEMAP_URL.to_string(), (200u16, urlset_xml(&locs)))]),
        };
        let crawl_id = crate::domain::id::Id::generate();
        let task_repo = CountingTaskRepo::new();
        let crawl_repo = CountingCrawlRepo::default();
        let cache = MockCache::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));

        let stats = feed(
            fetcher,
            SITEMAP_URL,
            None,
            None,
            vec![],
            seed_ctx(crawl_id),
            &dedup,
            &task_repo,
            &crawl_repo,
            &cache,
        )
        .await
        .expect("feed");

        assert_eq!(stats.enqueued, 5);
        assert_eq!(stats.consumed, 5);
        assert_eq!(stats.filtered_out, 0);
        assert_eq!(task_repo.created_urls().len(), 5);
        assert_eq!(crawl_repo.total_added.load(Ordering::SeqCst), 5);

        let created = task_repo.created.lock();
        let first = &created[0];
        assert_eq!(first.task_type, TaskType::Crawl);
        assert_eq!(first.status, TaskStatus::Queued);
        assert_eq!(first.crawl_id, Some(crawl_id));
        assert_eq!(first.payload["crawl_id"], crawl_id.to_string());
        assert_eq!(first.payload["depth"], 1);
        assert_eq!(first.payload["config"], json!({"max_depth": 2}));
        assert_eq!(first.team_id, first.team_id);

        // 喂入完成后指针必须删除(无残留断点)
        assert_eq!(
            cache.deleted.lock().len(),
            1,
            "pointer must be deleted after full feed"
        );
        assert!(!cache
            .store
            .lock()
            .contains_key(&sitemap_feed_pointer_key(crawl_id)));
    }

    /// FilterChain:include 白名单 + exclude 黑名单过滤后再入队
    #[tokio::test]
    async fn feed_applies_include_exclude_filters() {
        let locs: Vec<String> = vec![
            "https://a.com/blog/1".into(),
            "https://a.com/blog/tag/x".into(),
            "https://a.com/page/1".into(),
            "https://a.com/blog/2".into(),
        ];
        let fetcher = StaticSitemapFetcher {
            responses: HashMap::from([(SITEMAP_URL.to_string(), (200u16, urlset_xml(&locs)))]),
        };
        let task_repo = CountingTaskRepo::new();
        let crawl_repo = CountingCrawlRepo::default();
        let cache = MockCache::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));

        let stats = feed(
            fetcher,
            SITEMAP_URL,
            Some(vec!["a\\.com/blog/.*".to_string()]),
            Some(vec!["a\\.com/blog/tag/.*".to_string()]),
            vec![],
            seed_ctx(crate::domain::id::Id::generate()),
            &dedup,
            &task_repo,
            &crawl_repo,
            &cache,
        )
        .await
        .expect("feed");

        assert_eq!(stats.enqueued, 2, "only /blog/* minus /tag/* enqueue");
        assert_eq!(stats.filtered_out, 2);
        let mut urls = task_repo.created_urls();
        urls.sort();
        assert_eq!(urls, vec!["https://a.com/blog/1", "https://a.com/blog/2"]);
    }

    /// include 为空列表 = 全部拒绝(对齐 extract_and_queue_links 短路语义)
    #[tokio::test]
    async fn feed_empty_include_blocks_all() {
        let locs: Vec<String> = (0..3).map(|i| format!("https://a.com/{i}")).collect();
        let fetcher = StaticSitemapFetcher {
            responses: HashMap::from([(SITEMAP_URL.to_string(), (200u16, urlset_xml(&locs)))]),
        };
        let task_repo = CountingTaskRepo::new();
        let crawl_repo = CountingCrawlRepo::default();
        let cache = MockCache::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));

        let stats = feed(
            fetcher,
            SITEMAP_URL,
            Some(vec![]),
            None,
            vec![],
            seed_ctx(crate::domain::id::Id::generate()),
            &dedup,
            &task_repo,
            &crawl_repo,
            &cache,
        )
        .await
        .expect("feed");

        assert_eq!(stats.enqueued, 0);
        assert_eq!(stats.filtered_out, 3);
    }

    /// 域名黑名单绝对拒绝
    #[tokio::test]
    async fn feed_domain_blacklist_blocks() {
        let locs: Vec<String> = vec!["https://a.com/ok".into(), "https://evil.com/bad".into()];
        let fetcher = StaticSitemapFetcher {
            responses: HashMap::from([(SITEMAP_URL.to_string(), (200u16, urlset_xml(&locs)))]),
        };
        let task_repo = CountingTaskRepo::new();
        let crawl_repo = CountingCrawlRepo::default();
        let cache = MockCache::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));

        let stats = feed(
            fetcher,
            SITEMAP_URL,
            None,
            None,
            vec!["evil.com".to_string()],
            seed_ctx(crate::domain::id::Id::generate()),
            &dedup,
            &task_repo,
            &crawl_repo,
            &cache,
        )
        .await
        .expect("feed");

        assert_eq!(task_repo.created_urls(), vec!["https://a.com/ok"]);
        assert_eq!(stats.filtered_out, 1);
    }

    /// 分层去重:进程内 dedup 已见(MaybeExisting)+ DB 确认存在 → 不入队;
    /// DB 确认不存在(布隆假阳性)→ 必须入队
    #[tokio::test]
    async fn feed_dedup_layers_skip_known_urls() {
        let locs: Vec<String> = vec![
            "https://a.com/in-process".into(), // dedup 预插 + DB 说存在 → 跳过
            "https://a.com/bloom-fp".into(),   // dedup 预插 + DB 说不存在 → 入队
            "https://a.com/fresh".into(),      // 全新 → 入队
        ];
        let fetcher = StaticSitemapFetcher {
            responses: HashMap::from([(SITEMAP_URL.to_string(), (200u16, urlset_xml(&locs)))]),
        };
        let task_repo = CountingTaskRepo::new_with_existing(&["https://a.com/in-process"]);
        let crawl_repo = CountingCrawlRepo::default();
        let cache = MockCache::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));
        {
            let mut d = dedup.write();
            d.insert("https://a.com/in-process");
            d.insert("https://a.com/bloom-fp");
        }

        let stats = feed(
            fetcher,
            SITEMAP_URL,
            None,
            None,
            vec![],
            seed_ctx(crate::domain::id::Id::generate()),
            &dedup,
            &task_repo,
            &crawl_repo,
            &cache,
        )
        .await
        .expect("feed");

        assert_eq!(
            stats.enqueued, 2,
            "in-process URL skipped, bloom false positive enqueued"
        );
        assert_eq!(stats.duplicates_skipped, 1);
        let mut urls = task_repo.created_urls();
        urls.sort();
        assert_eq!(urls, vec!["https://a.com/bloom-fp", "https://a.com/fresh"]);
    }

    /// 断点续爬:指针 consumed=3 → 重建全部组件后从第 4 条继续(Urlset 精确 seek)
    #[tokio::test]
    async fn feed_resumes_from_pointer_seek() {
        let locs: Vec<String> = (0..10).map(|i| format!("https://a.com/{i}")).collect();
        let xml = urlset_xml(&locs);
        let crawl_id = crate::domain::id::Id::generate();

        // 第一次:喂入 3 条后"崩溃"(手动写指针模拟断点)
        let cache = MockCache::default();
        let pointer = SitemapFeedPointer {
            sitemap_url: SITEMAP_URL.to_string(),
            consumed: 3,
        };
        cache
            .set(
                &sitemap_feed_pointer_key(crawl_id),
                &serde_json::to_string(&pointer).unwrap(),
                3600,
            )
            .await
            .unwrap();

        // 重启后重建 fetcher/dedup/repo(全新实例),指针仍在 cache
        let fetcher = StaticSitemapFetcher {
            responses: HashMap::from([(SITEMAP_URL.to_string(), (200u16, xml))]),
        };
        let task_repo = CountingTaskRepo::new();
        let crawl_repo = CountingCrawlRepo::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));

        let stats = feed(
            fetcher,
            SITEMAP_URL,
            None,
            None,
            vec![],
            seed_ctx(crawl_id),
            &dedup,
            &task_repo,
            &crawl_repo,
            &cache,
        )
        .await
        .expect("resumed feed");

        assert_eq!(stats.resumed_from, Some(3), "must seek past consumed=3");
        assert_eq!(stats.consumed, 10, "total consumed includes sought locs");
        assert_eq!(stats.enqueued, 7, "only locs 3..10 enqueue after resume");
        assert_eq!(
            task_repo.created_urls(),
            (3..10)
                .map(|i| format!("https://a.com/{i}"))
                .collect::<Vec<_>>()
        );
        // 续爬完成后指针删除
        assert!(!cache
            .store
            .lock()
            .contains_key(&sitemap_feed_pointer_key(crawl_id)));
    }

    /// 指针指向不同 sitemap(源已变)→ 忽略指针从头喂,dedup 兜底
    #[tokio::test]
    async fn feed_ignores_pointer_for_different_sitemap_url() {
        let locs: Vec<String> = vec!["https://a.com/x".into(), "https://a.com/y".into()];
        let fetcher = StaticSitemapFetcher {
            responses: HashMap::from([(SITEMAP_URL.to_string(), (200u16, urlset_xml(&locs)))]),
        };
        let crawl_id = crate::domain::id::Id::generate();
        let cache = MockCache::default();
        let pointer = SitemapFeedPointer {
            sitemap_url: "https://a.com/old-sitemap.xml".to_string(),
            consumed: 99,
        };
        cache
            .set(
                &sitemap_feed_pointer_key(crawl_id),
                &serde_json::to_string(&pointer).unwrap(),
                3600,
            )
            .await
            .unwrap();

        let task_repo = CountingTaskRepo::new();
        let crawl_repo = CountingCrawlRepo::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));

        let stats = feed(
            fetcher,
            SITEMAP_URL,
            None,
            None,
            vec![],
            seed_ctx(crawl_id),
            &dedup,
            &task_repo,
            &crawl_repo,
            &cache,
        )
        .await
        .expect("feed");

        assert_eq!(
            stats.resumed_from, None,
            "mismatched pointer must be ignored"
        );
        assert_eq!(stats.enqueued, 2);
    }

    /// 损坏的指针(非法 JSON)→ 安全回退全量喂入
    #[tokio::test]
    async fn feed_survives_corrupt_pointer() {
        let locs: Vec<String> = vec!["https://a.com/only".into()];
        let fetcher = StaticSitemapFetcher {
            responses: HashMap::from([(SITEMAP_URL.to_string(), (200u16, urlset_xml(&locs)))]),
        };
        let crawl_id = crate::domain::id::Id::generate();
        let cache = MockCache::default();
        cache
            .set(&sitemap_feed_pointer_key(crawl_id), "{{not json", 3600)
            .await
            .unwrap();

        let task_repo = CountingTaskRepo::new();
        let crawl_repo = CountingCrawlRepo::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));

        let stats = feed(
            fetcher,
            SITEMAP_URL,
            None,
            None,
            vec![],
            seed_ctx(crawl_id),
            &dedup,
            &task_repo,
            &crawl_repo,
            &cache,
        )
        .await
        .expect("corrupt pointer must not fail the feed");

        assert_eq!(stats.resumed_from, None);
        assert_eq!(stats.enqueued, 1);
    }

    /// sitemap 404 → 合法状态:零入队非错误
    #[tokio::test]
    async fn feed_sitemap_404_is_legal_empty_result() {
        let fetcher = StaticSitemapFetcher {
            responses: HashMap::from([(SITEMAP_URL.to_string(), (404u16, "not found".into()))]),
        };
        let task_repo = CountingTaskRepo::new();
        let crawl_repo = CountingCrawlRepo::default();
        let cache = MockCache::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));

        let stats = feed(
            fetcher,
            SITEMAP_URL,
            None,
            None,
            vec![],
            seed_ctx(crate::domain::id::Id::generate()),
            &dedup,
            &task_repo,
            &crawl_repo,
            &cache,
        )
        .await
        .expect("404 must be Ok (legal empty)");

        assert_eq!(stats.enqueued, 0);
        assert_eq!(stats.consumed, 0);
    }

    /// 5xx → 错误向上传播(失败显性化)
    #[tokio::test]
    async fn feed_5xx_propagates_error() {
        let fetcher = StaticSitemapFetcher {
            responses: HashMap::from([(SITEMAP_URL.to_string(), (500u16, "boom".into()))]),
        };
        let task_repo = CountingTaskRepo::new();
        let crawl_repo = CountingCrawlRepo::default();
        let cache = MockCache::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));

        let result = feed(
            fetcher,
            SITEMAP_URL,
            None,
            None,
            vec![],
            seed_ctx(crate::domain::id::Id::generate()),
            &dedup,
            &task_repo,
            &crawl_repo,
            &cache,
        )
        .await;

        assert!(result.is_err(), "5xx must propagate as error");
    }

    /// max_urls 护栏:sitemap 有 50 条、上限 10 → 只消费/入队 10 条
    #[tokio::test]
    async fn feed_respects_max_urls_cap() {
        let locs: Vec<String> = (0..50).map(|i| format!("https://a.com/{i}")).collect();
        let fetcher = StaticSitemapFetcher {
            responses: HashMap::from([(SITEMAP_URL.to_string(), (200u16, urlset_xml(&locs)))]),
        };
        let task_repo = CountingTaskRepo::new();
        let crawl_repo = CountingCrawlRepo::default();
        let cache = MockCache::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));

        let stats = feed_sitemap_as_tasks(
            Arc::new(fetcher),
            SITEMAP_URL.to_string(),
            options(10),
            None,
            None,
            vec![],
            seed_ctx(crate::domain::id::Id::generate()),
            &dedup,
            &task_repo,
            &crawl_repo,
            &cache,
            3600,
        )
        .await
        .expect("feed");

        assert_eq!(stats.enqueued, 10);
        assert_eq!(stats.consumed, 10);
    }

    /// 指针持久化:喂入过程至少 set 一次且记录总消费数;完成后 delete
    #[tokio::test]
    async fn feed_persists_pointer_with_consumed_progress() {
        let locs: Vec<String> = (0..7).map(|i| format!("https://a.com/{i}")).collect();
        let fetcher = StaticSitemapFetcher {
            responses: HashMap::from([(SITEMAP_URL.to_string(), (200u16, urlset_xml(&locs)))]),
        };
        let crawl_id = crate::domain::id::Id::generate();
        let task_repo = CountingTaskRepo::new();
        let crawl_repo = CountingCrawlRepo::default();
        let cache = MockCache::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));

        let _ = feed(
            fetcher,
            SITEMAP_URL,
            None,
            None,
            vec![],
            seed_ctx(crawl_id),
            &dedup,
            &task_repo,
            &crawl_repo,
            &cache,
        )
        .await
        .expect("feed");

        let key = sitemap_feed_pointer_key(crawl_id);
        assert!(
            cache.set_calls(&key) >= 1,
            "pointer must be persisted at least once"
        );
        // 完成后删除:指针生命周期 = 喂入过程
        assert!(cache.deleted.lock().contains(&key));
    }

    // derive_sitemap_url

    #[test]
    fn derive_sitemap_url_from_seed() {
        assert_eq!(
            derive_sitemap_url("https://a.com"),
            Some("https://a.com/sitemap.xml".to_string())
        );
        assert_eq!(
            derive_sitemap_url("https://a.com/some/page?q=1"),
            Some("https://a.com/sitemap.xml".to_string())
        );
        assert_eq!(
            derive_sitemap_url("http://localhost:8899"),
            Some("http://localhost:8899/sitemap.xml".to_string())
        );
        assert_eq!(derive_sitemap_url("not-a-url"), None);
    }

    /// 显式 sitemap_url 覆盖派生值(调用契约:sitemap_url=Some 时直接使用,
    /// 仅在缺位时才调 derive——crawl_task 挂接侧 or_else 语义)
    #[test]
    fn explicit_sitemap_url_takes_precedence_by_caller_contract() {
        let explicit = Some("https://cdn.b.com/sitemap-index.xml".to_string());
        let resolved = explicit
            .or_else(|| derive_sitemap_url("https://a.com"))
            .expect("explicit wins");
        assert_eq!(resolved, "https://cdn.b.com/sitemap-index.xml");
    }
}