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
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
// Copyright (c) 2025 Kirky.X
//
// Licensed under the Apache License, Version 2.0
// See LICENSE file in the project root for full license information.

//! `/v1/map` 业务用例:从站点 sitemap 发现 URL(bdd-acceptance-hardening R-map-002/003)。
//!
//! 语义(specs/map-endpoint):
//! - 抓取 `{origin}/sitemap.xml`,解析 `<urlset>` 的 `<loc>` 保序返回
//! - `<sitemapindex>` 递归一层,子 sitemap 上限 5 个
//! - `<loc>` 去重保首次出现位置;sitemap 404 返回空 links(合法状态)
//! - include 白名单 → exclude 黑名单 → limit 截断
//! - 抓取经 `SitemapFetcher` 端口(生产实现 `EngineSitemapFetcher` 走 reqwest 引擎,
//!   XML 无需渲染),端口化使业务逻辑可脱离引擎单测

use std::collections::HashSet;
use std::sync::Arc;

use async_trait::async_trait;

use crate::application::dto::map_request::MapRequestDto;
use crate::engines::engine_client::EngineClient;
use crate::engines::types::ScrapeRequest;

/// 单次抓取结果
pub struct SitemapFetch {
    pub status: u16,
    pub body: String,
}

/// 用例级错误(handler 映射:TargetUnreachable / SitemapStatus →
/// 502 MAP_TARGET_UNREACHABLE;OriginUnparsable / Internal → 400)
#[derive(Debug, thiserror::Error)]
pub enum MapError {
    #[error("target unreachable: {0}")]
    TargetUnreachable(String),
    /// sitemap 源返回非 2xx 状态(结构化携带状态码,供 handler 按请求 locale 翻译)
    #[error("sitemap returned status {0}")]
    SitemapStatus(u16),
    /// URL 无法解析出 origin(结构化携带原始 URL,供 handler 翻译)
    #[error("cannot parse origin from {0}")]
    OriginUnparsable(String),
    #[error("internal: {0}")]
    Internal(String),
}

/// sitemap 文档根元素类型
#[cfg(feature = "sitemap")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SitemapKind {
    /// `<urlset>`:`<loc>` 为页面 URL
    Urlset,
    /// `<sitemapindex>`:`<loc>` 为子 sitemap URL(递归一层展开)
    SitemapIndex,
}

/// 流式 sitemap 流:文档类型 + 逐 `<loc>` 产出的有界通道
///
/// 解析端在通道满时暂停(背压),消费端按解析顺序逐条 `recv`。
#[cfg(feature = "sitemap")]
pub struct SitemapStream {
    /// 根元素类型(由文档根元素判定;空文档按 Urlset 处理)
    pub kind: SitemapKind,
    /// `<loc>` 文本流(保序)
    pub rx: tokio::sync::mpsc::Receiver<String>,
}

#[cfg(feature = "sitemap")]
impl SitemapStream {
    /// 立即耗尽的空流(sitemap 404 合法状态)
    pub fn empty() -> Self {
        let (tx, rx) = tokio::sync::mpsc::channel(1);
        drop(tx);
        Self {
            kind: SitemapKind::Urlset,
            rx,
        }
    }
}

/// `MapUseCase::execute_streaming` 的运行参数(来自 `settings.sitemap`)
#[cfg(feature = "sitemap")]
#[derive(Debug, Clone)]
pub struct SitemapStreamOptions {
    /// mpsc 背压边界(`sitemap.channel_capacity`)
    pub channel_capacity: usize,
    /// 单次 map 消费上限(`sitemap.max_urls`,防无限站点图)
    pub max_urls: usize,
    /// 子 sitemap 并发展开上限(`sitemap.max_concurrent_sub_sitemaps`)
    pub max_concurrent_sub_sitemaps: usize,
    /// 已归一化的团队域名黑名单:子 sitemap URL 在抓取前过滤。
    #[doc(hidden)]
    pub domain_blacklist: Vec<String>,
}

/// sitemap 抓取端口(测试用 mock 替换)
#[async_trait]
pub trait SitemapFetcher: Send + Sync {
    async fn fetch(&self, url: &str) -> Result<SitemapFetch, MapError>;

    /// 流式拉取:解析端遇 `<loc>` 即送入容量 `channel_capacity` 的有界通道,
    /// 通道满即 await(背压)。
    ///
    /// 语义:404 → `Ok(空流)`(无 sitemap 是合法状态);其余 ≥400 / 传输失败
    /// → `Err(TargetUnreachable)`;其余非 200(含 3xx 重定向页)→ `Ok(空流)`,
    /// 不解析非 sitemap 内容(与 [`MapUseCase::execute`] 子 sitemap 的严格 200 口径对齐)。
    ///
    /// 默认实现为整串 fetch + 一次解析的回退路径;生产实现
    /// ([`EngineSitemapFetcher`])覆盖为 quick-xml 增量解析。
    #[cfg(feature = "sitemap")]
    async fn fetch_streaming(
        &self,
        url: &str,
        channel_capacity: usize,
    ) -> Result<SitemapStream, MapError> {
        let fetched = self.fetch(url).await?;
        if let Some(verdict) = classify_sitemap_status(fetched.status) {
            return verdict;
        }
        let kind = if is_sitemap_index(&fetched.body) {
            SitemapKind::SitemapIndex
        } else {
            SitemapKind::Urlset
        };
        let (tx, rx) = tokio::sync::mpsc::channel(channel_capacity.max(1));
        tokio::spawn(async move {
            for loc in parse_locs(&fetched.body) {
                if tx.send(loc).await.is_err() {
                    break;
                }
            }
        });
        Ok(SitemapStream { kind, rx })
    }
}

/// 生产实现:经 EngineClient(reqwest 引擎)抓取
///
/// `timeout` 来自 `settings.sitemap.fetch_timeout_secs`(单文档拉取超时)。
pub struct EngineSitemapFetcher {
    client: Arc<EngineClient>,
    timeout: std::time::Duration,
}

impl EngineSitemapFetcher {
    pub fn new(client: Arc<EngineClient>, timeout: std::time::Duration) -> Self {
        Self { client, timeout }
    }
}

#[async_trait]
impl SitemapFetcher for EngineSitemapFetcher {
    async fn fetch(&self, url: &str) -> Result<SitemapFetch, MapError> {
        let request = ScrapeRequest::new(url.to_string()).timeout(self.timeout);
        let response = self
            .client
            .scrape(&request)
            .await
            .map_err(|e| MapError::TargetUnreachable(e.to_string()))?;
        Ok(SitemapFetch {
            status: response.status_code,
            body: response.content,
        })
    }

    /// quick-xml 增量解析:遇 `<loc>` 即 `send`,通道满即 await(背压)。
    /// XML 中途解析失败时保留已产出的部分结果(`warn!` 显性化后终止流),
    /// 不因尾部畸形标签丢弃整份 sitemap。
    #[cfg(feature = "sitemap")]
    async fn fetch_streaming(
        &self,
        url: &str,
        channel_capacity: usize,
    ) -> Result<SitemapStream, MapError> {
        let request = ScrapeRequest::new(url.to_string()).timeout(self.timeout);
        let response = self
            .client
            .scrape(&request)
            .await
            .map_err(|e| MapError::TargetUnreachable(e.to_string()))?;
        if let Some(verdict) = classify_sitemap_status(response.status_code) {
            return verdict;
        }
        Ok(spawn_loc_stream(response.content, channel_capacity))
    }
}

/// 非 200 状态的流式口径:404 → 空流(无 sitemap 是合法状态);其余 ≥400 →
/// `Err(SitemapStatus)`;其余非 200(3xx 重定向页)→ 空流,不解析非 sitemap
/// 内容(与 execute 子 sitemap 的严格 200 口径对齐)。返回 `None` 表示 200,
/// 继续解析。
#[cfg(feature = "sitemap")]
fn classify_sitemap_status(status: u16) -> Option<Result<SitemapStream, MapError>> {
    if status == 404 {
        return Some(Ok(SitemapStream::empty()));
    }
    if status >= 400 {
        return Some(Err(MapError::SitemapStatus(status)));
    }
    if status != 200 {
        // 3xx 未跟随重定向时 body 是重定向页而非 sitemap:按空流处理,
        // 与 execute 子 sitemap 的严格 200 口径对齐。
        return Some(Ok(SitemapStream::empty()));
    }
    None
}

/// quick-xml 增量解析:遇 `<loc>` 即 `send`,通道满即 await(背压)。
/// XML 中途解析失败时保留已产出的部分结果(`warn!` 显性化后终止流),
/// 不因尾部畸形标签丢弃整份 sitemap。
///
/// 解析循环在独立任务中运行并持有 XML 所有权;函数先返回接收端,生产端
/// 才能在通道满时安全等待消费方 `recv`,不会因接收端尚未交付而永久阻塞。
#[cfg(feature = "sitemap")]
fn spawn_loc_stream(xml: String, channel_capacity: usize) -> SitemapStream {
    let kind = if is_sitemap_index(&xml) {
        SitemapKind::SitemapIndex
    } else {
        SitemapKind::Urlset
    };
    let (tx, rx) = tokio::sync::mpsc::channel(channel_capacity.max(1));
    tokio::spawn(stream_loc_events(xml, tx));

    SitemapStream { kind, rx }
}

/// 解析循环任务体:遇 `<loc>` 即 `send`,通道满即 await(背压)。
#[cfg(feature = "sitemap")]
async fn stream_loc_events(xml: String, tx: tokio::sync::mpsc::Sender<String>) {
    use quick_xml::events::Event;

    let mut reader = quick_xml::Reader::from_str(&xml);
    let mut in_loc = false;
    let mut loc_text = String::new();
    loop {
        match reader.read_event() {
            Ok(Event::Start(e)) => {
                if is_loc_name(e.name().local_name().as_ref()) {
                    in_loc = true;
                    loc_text.clear();
                }
            }
            Ok(Event::Text(t)) if in_loc => push_loc_text(&mut loc_text, &t),
            Ok(Event::End(e)) => {
                if in_loc && is_loc_name(e.name().local_name().as_ref()) {
                    in_loc = false;
                    if emit_completed_loc(&tx, &loc_text).await {
                        // 消费端已关闭:停止解析
                        break;
                    }
                }
            }
            Ok(Event::Eof) => break,
            Ok(_) => {}
            Err(e) => {
                log::warn!(
                    "sitemap XML parse error: {e}; keeping partial results already produced"
                );
                break;
            }
        }
    }
}

/// `<loc>` 元素名判定(大小写不敏感)。
#[cfg(feature = "sitemap")]
fn is_loc_name(local_name: &str) -> bool {
    local_name.eq_ignore_ascii_case("loc")
}

/// 解码并追加 `<loc>` 文本;实体解码失败记 warn 并跳过该片段。
#[cfg(feature = "sitemap")]
fn push_loc_text(loc_text: &mut String, t: &quick_xml::events::BytesText<'_>) {
    match quick_xml::escape::unescape(&t.xml10_content()) {
        Ok(unescaped) => loc_text.push_str(&unescaped),
        Err(e) => {
            log::warn!("sitemap loc entity unescape failed: {e}");
        }
    }
}

/// 收尾一个 `<loc>`:空 loc 跳过;返回 `true` 表示消费端已关闭、应停止解析。
#[cfg(feature = "sitemap")]
async fn emit_completed_loc(tx: &tokio::sync::mpsc::Sender<String>, loc_text: &str) -> bool {
    let loc = loc_text.trim();
    !loc.is_empty() && tx.send(loc.to_string()).await.is_err()
}

/// `/v1/map` 结果
pub struct MapResult {
    pub links: Vec<String>,
}

/// `/v1/map` 用例
pub struct MapUseCase {
    fetcher: Arc<dyn SitemapFetcher>,
}

/// 子 sitemap 递归上限(specs/map-endpoint R-map-002)
const MAX_SUB_SITEMAPS: usize = 5;

impl MapUseCase {
    pub fn new(fetcher: Arc<dyn SitemapFetcher>) -> Self {
        Self { fetcher }
    }

    pub async fn execute(&self, dto: &MapRequestDto) -> Result<MapResult, MapError> {
        let origin =
            extract_origin(&dto.url).ok_or_else(|| MapError::OriginUnparsable(dto.url.clone()))?;

        let first = self.fetcher.fetch(&format!("{origin}/sitemap.xml")).await?;
        if first.status == 404 {
            // 站点无 sitemap 是合法状态:空结果而非错误
            return Ok(MapResult { links: Vec::new() });
        }
        if first.status >= 400 {
            return Err(MapError::SitemapStatus(first.status));
        }
        if first.status != 200 {
            // 3xx 未跟随重定向时 body 是重定向页而非 sitemap:空结果,
            // 与 execute_streaming 的严格 200 口径一致。
            return Ok(MapResult { links: Vec::new() });
        }

        let mut locs = parse_locs(&first.body);
        if is_sitemap_index(&first.body) {
            // 递归一层:取前 MAX_SUB_SITEMAPS 个子 sitemap 展开
            locs = self.expand_sitemap_index(locs).await?;
        }

        Ok(MapResult {
            links: finalize_links(locs, dto),
        })
    }

    /// 递归一层展开 sitemap index:取前 `MAX_SUB_SITEMAPS` 个子 sitemap,
    /// 子 sitemap 瞬态错误或 ≥400 状态重试一次,仍失败则放弃该子 sitemap
    async fn expand_sitemap_index(&self, mut locs: Vec<String>) -> Result<Vec<String>, MapError> {
        let children: Vec<String> = locs.iter().take(MAX_SUB_SITEMAPS).cloned().collect();
        locs.clear();
        for child in children {
            // 连接级瞬态错误(如 keep-alive 连接被对端关闭)与 ≥400 状态各重试一次
            // (4xx/5xx 也可能瞬态:网关抖动;404 已在上方转为空流);仍失败则按既有
            // 语义放弃该子 sitemap 的内容(不计为整体失败)
            let fetched = match self.fetcher.fetch(&child).await {
                Ok(f) => Some(f),
                // 连接级瞬态错误 / ≥400 状态重试一次(ok 语义:仍失败则放弃该子 sitemap)
                Err(MapError::TargetUnreachable(_)) | Err(MapError::SitemapStatus(_)) => {
                    self.fetcher.fetch(&child).await.ok()
                }
                Err(e) => return Err(e),
            };
            if let Some(fetched) = fetched {
                if fetched.status == 200 {
                    locs.extend(parse_locs(&fetched.body));
                }
            }
        }

        Ok(locs)
    }

    /// 流式执行(F11:sitemap 一等请求源的产出口)
    ///
    /// 从 `{origin}/sitemap.xml` 流式解析并经有界通道逐条产出 `<loc>`:
    /// - `Urlset`:loc 直接转发,`max_urls` 为消费上限护栏
    /// - `SitemapIndex`:递归一层,取前 `MAX_SUB_SITEMAPS` 个子 sitemap,
    ///   并发展开 ≤ `options.max_concurrent_sub_sitemaps`;子 sitemap 瞬态
    ///   失败重试一次仍失败则放弃该子 sitemap(对齐 [`Self::execute`] 语义)
    ///
    /// 返回的 [`SitemapStream`] 携带根元素类型(消费方的断点 seek 决策依赖:
    /// Urlset 流保序可精确 seek,Index 流并发展开顺序不定只能靠去重兜底),
    /// `rx` 供消费方逐条处理(HTTP handler 聚合为 [`MapResult`];请求源路径
    /// 可直接消费做 dedup/过滤/入队)。过滤(dedup/include/exclude/limit)
    /// 由消费方按需应用(HTTP 路径用 [`finalize_links`])。
    #[cfg(feature = "sitemap")]
    pub async fn execute_streaming(
        &self,
        dto: &MapRequestDto,
        options: SitemapStreamOptions,
    ) -> Result<SitemapStream, MapError> {
        let origin =
            extract_origin(&dto.url).ok_or_else(|| MapError::OriginUnparsable(dto.url.clone()))?;

        let mut first = self
            .fetcher
            .fetch_streaming(&format!("{origin}/sitemap.xml"), options.channel_capacity)
            .await?;

        match first.kind {
            SitemapKind::Urlset => Ok(SitemapStream {
                kind: SitemapKind::Urlset,
                rx: forward_capped(first.rx, options),
            }),
            SitemapKind::SitemapIndex => {
                // 递归一层:取前 MAX_SUB_SITEMAPS 个子 sitemap
                let children = collect_index_children(&mut first.rx).await;
                Ok(self.expand_index_stream(children, options))
            }
        }
    }

    /// `SitemapIndex` 并发展开:子 sitemap 各自限流重试抓取,loc 汇入一个
    /// 有界通道(`max_urls` 为消费上限护栏,`max_concurrent_sub_sitemaps`
    /// 为并发上限)。
    ///
    /// 返回的流在全部子任务结束后自然闭合(tx 归零);子任务 panic 记
    /// `warn!` 后继续等待其余子任务(不静默消失)。
    #[cfg(feature = "sitemap")]
    fn expand_index_stream(
        &self,
        children: Vec<String>,
        options: SitemapStreamOptions,
    ) -> SitemapStream {
        use tokio::sync::mpsc;
        use tokio::task::JoinSet;

        let (tx, rx) = mpsc::channel(options.channel_capacity.max(1));
        let semaphore = Arc::new(tokio::sync::Semaphore::new(
            options.max_concurrent_sub_sitemaps.max(1),
        ));
        let sent = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let mut set: JoinSet<()> = JoinSet::new();
        for child in children {
            // index 里的子 sitemap 也是服务端请求:与顶层同口径过滤。
            if let Some(reason) =
                crate::domain::services::team_service::domain_in_normalized_denylist(
                    &child,
                    &options.domain_blacklist,
                )
            {
                log::warn!("skip blacklisted child sitemap: {reason}");
                continue;
            }
            let fetcher = self.fetcher.clone();
            let tx = tx.clone();
            let semaphore = semaphore.clone();
            let sent = sent.clone();
            set.spawn(forward_child_sitemap(
                fetcher,
                child,
                options.clone(),
                tx,
                semaphore,
                sent,
            ));
        }
        drop(tx);
        // 全部子任务结束后 tx 归零,rx 端 recv 返回 None。
        // 子任务 panic 不让它静默消失:记 warn 后继续等待其余子任务。
        spawn_child_task_monitor(set);
        SitemapStream {
            kind: SitemapKind::SitemapIndex,
            rx,
        }
    }
}

/// 子 sitemap 转发任务体(自 [`MapUseCase::expand_index_stream`] 提取):
/// 限流 permit → 抓取(一次重试)→ 有界通道转发(消费上限护栏)。
#[cfg(feature = "sitemap")]
async fn forward_child_sitemap(
    fetcher: Arc<dyn SitemapFetcher>,
    child: String,
    options: SitemapStreamOptions,
    tx: tokio::sync::mpsc::Sender<String>,
    semaphore: Arc<tokio::sync::Semaphore>,
    sent: Arc<std::sync::atomic::AtomicUsize>,
) {
    let _permit = semaphore
        .acquire_owned()
        .await
        .expect("semaphore has capacity");
    // 连接级瞬态错误 / ≥400 状态各重试一次,仍失败放弃该子 sitemap
    // (ok 语义,对齐 execute 的子 sitemap 处理)
    let Some(stream) =
        fetch_child_stream_with_retry(&fetcher, &child, options.channel_capacity).await
    else {
        return;
    };
    let mut rx = stream.rx;
    while let Some(loc) = rx.recv().await {
        // 消费上限护栏:check 与 increment 非原子,
        // 并发下最多超发 ≤ 并发数条——护栏安全方向
        if sent.load(std::sync::atomic::Ordering::Relaxed) >= options.max_urls {
            return;
        }
        if tx.send(loc).await.is_err() {
            return;
        }
        sent.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }
}

/// 子 sitemap 流抓取(自 [`MapUseCase::expand_index_stream`] 提取):
/// 连接级瞬态错误 / ≥400 状态各重试一次,仍失败返回 `None`。
#[cfg(feature = "sitemap")]
async fn fetch_child_stream_with_retry(
    fetcher: &Arc<dyn SitemapFetcher>,
    child: &str,
    channel_capacity: usize,
) -> Option<SitemapStream> {
    match fetcher.fetch_streaming(child, channel_capacity).await {
        Ok(s) => Some(s),
        Err(MapError::TargetUnreachable(_)) | Err(MapError::SitemapStatus(_)) => {
            fetcher.fetch_streaming(child, channel_capacity).await.ok()
        }
        Err(_) => None,
    }
}

/// 等待全部子 sitemap 任务结束;panic 记 warn 后继续等待其余任务。
#[cfg(feature = "sitemap")]
fn spawn_child_task_monitor(mut set: tokio::task::JoinSet<()>) {
    tokio::spawn(async move {
        while let Some(res) = set.join_next().await {
            if let Err(e) = res {
                log::warn!("sitemap child task failed: {e}");
            }
        }
    });
}

/// 从根 index 流中收集前 `MAX_SUB_SITEMAPS` 个子 sitemap URL(流尽即止)
#[cfg(feature = "sitemap")]
async fn collect_index_children(rx: &mut tokio::sync::mpsc::Receiver<String>) -> Vec<String> {
    let mut children: Vec<String> = Vec::new();
    while children.len() < MAX_SUB_SITEMAPS {
        match rx.recv().await {
            Some(child) => children.push(child),
            None => break,
        }
    }
    children
}

/// Urlset 流的消费上限转发:最多转发 `max_urls` 条(防无限站点图)
#[cfg(feature = "sitemap")]
fn forward_capped(
    mut rx: tokio::sync::mpsc::Receiver<String>,
    options: SitemapStreamOptions,
) -> tokio::sync::mpsc::Receiver<String> {
    let (tx, out) = tokio::sync::mpsc::channel(options.channel_capacity.max(1));
    tokio::spawn(async move {
        let mut sent = 0usize;
        while sent < options.max_urls {
            match rx.recv().await {
                Some(loc) => {
                    if tx.send(loc).await.is_err() {
                        break;
                    }
                    sent += 1;
                }
                None => break,
            }
        }
    });
    out
}

/// 流式 loc 序列的聚合后处理:include 白名单 → exclude 黑名单 → 去重(保首次
/// 出现位置)→ limit 截断(R-map-003)
///
/// include/exclude 是纯谓词,先过滤后去重输出语义不变,但去重集合从全量
/// locs(max_urls 默认 5 万)缩小到命中白名单的子集。[`MapUseCase::execute`]
/// 与 map_handler 聚合路径共用,保证两条路径的响应语义一致。
pub fn finalize_links(locs: Vec<String>, dto: &MapRequestDto) -> Vec<String> {
    // 先 include 白名单后 exclude 黑名单(R-map-003)
    let mut links = locs;
    if let Some(include) = &dto.include_patterns {
        links.retain(|u| include.iter().any(|p| matches_glob(p, u)));
    }
    if let Some(exclude) = &dto.exclude_patterns {
        links.retain(|u| !exclude.iter().any(|p| matches_glob(p, u)));
    }

    // 去重(保首次出现位置)
    let mut seen: HashSet<String> = HashSet::with_capacity(links.len());
    links.retain(|u| seen.insert(u.clone()));

    // limit 截断
    let limit = dto.limit.unwrap_or(1000) as usize;
    links.truncate(limit);
    links
}

/// 从请求 URL 提取 `scheme://host[:port]` origin
fn extract_origin(url: &str) -> Option<String> {
    let parsed = url::Url::parse(url).ok()?;
    let host = parsed.host_str()?;
    let scheme = parsed.scheme();
    match parsed.port() {
        Some(port) => Some(format!("{scheme}://{host}:{port}")),
        None => Some(format!("{scheme}://{host}")),
    }
}

/// 解析 sitemap XML 中全部 `<loc>` 文本(保序)
pub fn parse_locs(xml: &str) -> Vec<String> {
    let document = scraper::Html::parse_fragment(xml);
    document
        .select(&scraper::Selector::parse("loc").expect("valid selector"))
        .map(|el| el.text().collect::<String>().trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

/// 是否为 sitemap index(含子 sitemap 引用的根元素)
fn is_sitemap_index(xml: &str) -> bool {
    // 大小写不敏感地匹配根元素(某些站点输出 <sitemapindex> 大写变体)
    xml.to_ascii_lowercase().contains("<sitemapindex")
}

/// `*`(任意长度)/`?`(单字符)通配匹配(复用 [`crate::utils::glob`] 单实现)
///
/// 注意语义差异:`workers/crawl/filters.rs` 的 `match_pattern` 是
/// regex 优先 + contains 回退,非 glob——两者不可混用。
pub fn matches_glob(pattern: &str, text: &str) -> bool {
    crate::utils::glob::glob_match(pattern, text)
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use std::collections::HashMap;

    // Mock Fetcher

    struct MockFetcher {
        /// url → (status, body)
        responses: HashMap<String, (u16, String)>,
    }

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

    fn urlset(locs: &[&str]) -> 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>"#
        )
    }

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

    fn dto(url: &str) -> MapRequestDto {
        MapRequestDto {
            url: url.to_string(),
            include_patterns: None,
            exclude_patterns: None,
            limit: Some(1000),
        }
    }

    const ORIGIN: &str = "https://a.com";

    // parse_locs

    /// R-map-002:urlset 多 `<loc>` 解析保序。
    #[test]
    fn parse_locs_preserves_order() {
        let xml = urlset(&["https://a.com/1", "https://a.com/2", "https://a.com/3"]);
        assert_eq!(
            parse_locs(&xml),
            vec!["https://a.com/1", "https://a.com/2", "https://a.com/3"]
        );
    }

    /// R-map-002:空 sitemap / 无 loc 返回空。
    #[test]
    fn parse_locs_empty_sitemap() {
        assert!(parse_locs(&urlset(&[])).is_empty());
    }

    // matches_glob

    /// R-map-003:`*`/`?` 通配语义。
    #[test]
    fn matches_glob_semantics() {
        assert!(matches_glob("*/blog/*", "https://a.com/blog/post-1"));
        assert!(!matches_glob("*/blog/*", "https://a.com/page/1"));
        assert!(matches_glob("https://a.com/page/?", "https://a.com/page/1"));
        assert!(!matches_glob(
            "https://a.com/page/?",
            "https://a.com/page/12"
        ));
        assert!(matches_glob("*", "https://anything.example"));
        assert!(matches_glob("https://a.com/*", "https://a.com/"));
    }

    // execute

    /// R-map-002:3 个 loc 的 sitemap 保序返回 3 个 link。
    #[tokio::test]
    async fn execute_returns_locs_in_order() {
        let fetcher = MockFetcher {
            responses: HashMap::from([(
                format!("{ORIGIN}/sitemap.xml"),
                (
                    200u16,
                    urlset(&["https://a.com/1", "https://a.com/2", "https://a.com/3"]),
                ),
            )]),
        };
        let result = MapUseCase::new(Arc::new(fetcher))
            .execute(&dto(ORIGIN))
            .await
            .expect("execute");
        assert_eq!(
            result.links,
            vec!["https://a.com/1", "https://a.com/2", "https://a.com/3"]
        );
    }

    /// R-map-002:重复 loc 去重保首次位置。
    #[tokio::test]
    async fn execute_dedups_keeping_first_position() {
        let fetcher = MockFetcher {
            responses: HashMap::from([(
                format!("{ORIGIN}/sitemap.xml"),
                (
                    200u16,
                    urlset(&["https://a.com/a", "https://a.com/b", "https://a.com/a"]),
                ),
            )]),
        };
        let result = MapUseCase::new(Arc::new(fetcher))
            .execute(&dto(ORIGIN))
            .await
            .expect("execute");
        assert_eq!(result.links, vec!["https://a.com/a", "https://a.com/b"]);
    }

    /// R-map-002:sitemapindex 递归一层,两个子 sitemap 共 5 个 loc 全部返回。
    #[tokio::test]
    async fn execute_recurses_sitemap_index_one_level() {
        let fetcher = MockFetcher {
            responses: HashMap::from([
                (
                    format!("{ORIGIN}/sitemap.xml"),
                    (
                        200u16,
                        sitemap_index(&["https://a.com/s1.xml", "https://a.com/s2.xml"]),
                    ),
                ),
                (
                    "https://a.com/s1.xml".to_string(),
                    (
                        200u16,
                        urlset(&["https://a.com/1", "https://a.com/2", "https://a.com/3"]),
                    ),
                ),
                (
                    "https://a.com/s2.xml".to_string(),
                    (200u16, urlset(&["https://a.com/4", "https://a.com/5"])),
                ),
            ]),
        };
        let result = MapUseCase::new(Arc::new(fetcher))
            .execute(&dto(ORIGIN))
            .await
            .expect("execute");
        assert_eq!(result.links.len(), 5);
        assert_eq!(result.links[0], "https://a.com/1");
        assert_eq!(result.links[4], "https://a.com/5");
    }

    /// R-map-002:子 sitemap 数超过 5 时只取前 5 个。
    #[tokio::test]
    async fn execute_caps_sub_sitemaps_at_five() {
        let children: Vec<String> = (0..7).map(|i| format!("https://a.com/s{i}.xml")).collect();
        let child_refs: Vec<&str> = children.iter().map(|s| s.as_str()).collect();
        let mut responses = HashMap::from([(
            format!("{ORIGIN}/sitemap.xml"),
            (200u16, sitemap_index(&child_refs)),
        )]);
        for i in 0..7 {
            responses.insert(
                format!("https://a.com/s{i}.xml"),
                (200u16, urlset(&[&format!("https://a.com/u{i}")])),
            );
        }
        let fetcher = MockFetcher { responses };
        let result = MapUseCase::new(Arc::new(fetcher))
            .execute(&dto(ORIGIN))
            .await
            .expect("execute");
        assert_eq!(
            result.links.len(),
            5,
            "only first 5 sub sitemaps must be fetched"
        );
        assert!(result.links.contains(&"https://a.com/u0".to_string()));
        assert!(!result.links.contains(&"https://a.com/u5".to_string()));
    }

    /// R-map-003:include 白名单、exclude 黑名单过滤;同时给时先 include 后 exclude。
    #[tokio::test]
    async fn execute_applies_include_then_exclude_patterns() {
        let fetcher = MockFetcher {
            responses: HashMap::from([(
                format!("{ORIGIN}/sitemap.xml"),
                (
                    200u16,
                    urlset(&[
                        "https://a.com/blog/1",
                        "https://a.com/blog/tag/x",
                        "https://a.com/page/1",
                    ]),
                ),
            )]),
        };
        let mut d = dto(ORIGIN);
        d.include_patterns = Some(vec!["*/blog/*".to_string()]);
        d.exclude_patterns = Some(vec!["*/tag/*".to_string()]);
        let result = MapUseCase::new(Arc::new(fetcher))
            .execute(&d)
            .await
            .expect("execute");
        assert_eq!(result.links, vec!["https://a.com/blog/1"]);
    }

    /// R-map-003:limit 截断。
    #[tokio::test]
    async fn execute_truncates_to_limit() {
        let fetcher = MockFetcher {
            responses: HashMap::from([(
                format!("{ORIGIN}/sitemap.xml"),
                (
                    200u16,
                    urlset(&["https://a.com/1", "https://a.com/2", "https://a.com/3"]),
                ),
            )]),
        };
        let mut d = dto(ORIGIN);
        d.limit = Some(2);
        let result = MapUseCase::new(Arc::new(fetcher))
            .execute(&d)
            .await
            .expect("execute");
        assert_eq!(result.links, vec!["https://a.com/1", "https://a.com/2"]);
    }

    /// R-map-002:sitemap 404 → 200 空 links(合法状态,非错误)。
    #[tokio::test]
    async fn execute_returns_empty_links_on_sitemap_404() {
        let fetcher = MockFetcher {
            responses: HashMap::from([(
                format!("{ORIGIN}/sitemap.xml"),
                (404u16, String::from("not found")),
            )]),
        };
        let result = MapUseCase::new(Arc::new(fetcher))
            .execute(&dto(ORIGIN))
            .await
            .expect("execute");
        assert!(result.links.is_empty());
    }

    /// R-map-002:根 sitemap 3xx 重定向页 body 即使含 `<loc>` 也不得解析(严格 200 口径)。
    #[tokio::test]
    async fn execute_non_200_redirect_returns_empty_links() {
        let fetcher = MockFetcher {
            responses: HashMap::from([(
                format!("{ORIGIN}/sitemap.xml"),
                (
                    302u16,
                    urlset(&["https://a.com/redirected-should-not-leak"]),
                ),
            )]),
        };
        let result = MapUseCase::new(Arc::new(fetcher))
            .execute(&dto(ORIGIN))
            .await
            .expect("3xx must be Ok (empty links)");
        assert!(
            result.links.is_empty(),
            "redirect body must not be parsed as sitemap"
        );
    }

    /// R-map-004:目标站 5xx → SitemapStatus(handler 映射 502 MAP_TARGET_UNREACHABLE)。
    #[tokio::test]
    async fn execute_maps_5xx_to_target_unreachable() {
        let fetcher = MockFetcher {
            responses: HashMap::from([(
                format!("{ORIGIN}/sitemap.xml"),
                (500u16, String::from("boom")),
            )]),
        };
        let result = MapUseCase::new(Arc::new(fetcher))
            .execute(&dto(ORIGIN))
            .await;
        assert!(matches!(result, Err(MapError::SitemapStatus(_))));
    }

    /// R-map-001:无效 URL(无法解析 origin)→ OriginUnparsable 错误(DTO 校验是第一道防线)。
    #[tokio::test]
    async fn execute_rejects_unparsable_url() {
        let fetcher = MockFetcher {
            responses: HashMap::new(),
        };
        let result = MapUseCase::new(Arc::new(fetcher))
            .execute(&dto("not-a-url"))
            .await;
        assert!(matches!(result, Err(MapError::OriginUnparsable(_))));
    }

    // execute_streaming(F11 流式路径,sitemap feature)

    #[cfg(feature = "sitemap")]
    mod streaming_tests {
        use super::*;
        use std::sync::atomic::{AtomicUsize, Ordering};

        fn stream_options(
            capacity: usize,
            max_urls: usize,
            concurrency: usize,
        ) -> SitemapStreamOptions {
            SitemapStreamOptions {
                domain_blacklist: Vec::new(),
                channel_capacity: capacity,
                max_urls,
                max_concurrent_sub_sitemaps: concurrency,
            }
        }

        async fn collect(rx: tokio::sync::mpsc::Receiver<String>) -> Vec<String> {
            let mut rx = rx;
            let mut out = Vec::new();
            while let Some(loc) = rx.recv().await {
                out.push(loc);
            }
            out
        }

        /// 回归:loc 数超过通道容量时,解析任务不得在接收端交付前阻塞。
        ///
        /// 旧实现把解析循环内联在 async fn 中、先解析后返回 `rx`:通道满即
        /// 永久挂起。修复后解析在独立任务中运行、函数先返回流。
        #[tokio::test]
        async fn spawn_loc_stream_does_not_block_when_loc_count_exceeds_capacity() {
            let locs: Vec<String> = (0..8).map(|i| format!("https://a.com/{i}")).collect();
            let refs: Vec<&str> = locs.iter().map(String::as_str).collect();
            let stream = spawn_loc_stream(urlset(&refs), 1);
            assert_eq!(stream.kind, SitemapKind::Urlset);

            let received =
                tokio::time::timeout(std::time::Duration::from_secs(5), collect(stream.rx))
                    .await
                    .expect("producer must not deadlock when loc count exceeds capacity");
            assert_eq!(received, locs);
        }

        /// Urlset 流经 execute_streaming 逐条产出且保序(万级 loc)
        #[tokio::test]
        async fn streaming_urlset_yields_ten_thousand_locs_in_order() {
            let locs: Vec<String> = (0..10_000).map(|i| format!("https://a.com/{i}")).collect();
            let refs: Vec<&str> = locs.iter().map(String::as_str).collect();
            let fetcher = MockFetcher {
                responses: HashMap::from([(
                    format!("{ORIGIN}/sitemap.xml"),
                    (200u16, urlset(&refs)),
                )]),
            };
            let rx = MapUseCase::new(Arc::new(fetcher))
                .execute_streaming(&dto(ORIGIN), stream_options(64, 50_000, 4))
                .await
                .expect("execute_streaming");
            assert_eq!(collect(rx.rx).await, locs, "万级 loc 必须逐条且保序产出");
        }

        /// sitemap 404 → 立即耗尽的空流(合法状态,非错误)
        #[tokio::test]
        async fn streaming_sitemap_404_yields_empty_stream() {
            let fetcher = MockFetcher {
                responses: HashMap::from([(
                    format!("{ORIGIN}/sitemap.xml"),
                    (404u16, String::from("not found")),
                )]),
            };
            let rx = MapUseCase::new(Arc::new(fetcher))
                .execute_streaming(&dto(ORIGIN), stream_options(4, 100, 2))
                .await
                .expect("404 must be Ok (empty stream)");
            assert!(collect(rx.rx).await.is_empty());
        }

        /// 3xx 重定向页 body 即使含 `<loc>` 也不得解析(严格 200 口径)
        #[tokio::test]
        async fn streaming_non_200_redirect_yields_empty_stream() {
            let fetcher = MockFetcher {
                responses: HashMap::from([(
                    format!("{ORIGIN}/sitemap.xml"),
                    (
                        302u16,
                        urlset(&["https://a.com/redirected-should-not-leak"]),
                    ),
                )]),
            };
            let rx = MapUseCase::new(Arc::new(fetcher))
                .execute_streaming(&dto(ORIGIN), stream_options(4, 100, 2))
                .await
                .expect("3xx must be Ok (empty stream)");
            assert!(
                collect(rx.rx).await.is_empty(),
                "redirect body must not be parsed as sitemap"
            );
        }

        /// 目标站 5xx / 拉取超时 → SitemapStatus(错误显性化)
        #[tokio::test]
        async fn streaming_maps_5xx_to_target_unreachable() {
            let fetcher = MockFetcher {
                responses: HashMap::from([(
                    format!("{ORIGIN}/sitemap.xml"),
                    (500u16, String::from("boom")),
                )]),
            };
            let result = MapUseCase::new(Arc::new(fetcher))
                .execute_streaming(&dto(ORIGIN), stream_options(4, 100, 2))
                .await;
            assert!(matches!(result, Err(MapError::SitemapStatus(_))));
        }

        /// max_urls 消费上限:100 条 loc 只产出前 10 条
        #[tokio::test]
        async fn streaming_respects_max_urls_cap() {
            let locs: Vec<String> = (0..100).map(|i| format!("https://a.com/{i}")).collect();
            let refs: Vec<&str> = locs.iter().map(String::as_str).collect();
            let fetcher = MockFetcher {
                responses: HashMap::from([(
                    format!("{ORIGIN}/sitemap.xml"),
                    (200u16, urlset(&refs)),
                )]),
            };
            let rx = MapUseCase::new(Arc::new(fetcher))
                .execute_streaming(&dto(ORIGIN), stream_options(4, 10, 2))
                .await
                .expect("execute_streaming");
            let got = collect(rx.rx).await;
            assert_eq!(got.len(), 10, "max_urls=10 must cap the stream at 10");
            assert_eq!(got[0], "https://a.com/0");
            assert_eq!(got[9], "https://a.com/9");
        }

        /// 背压:消费端暂停时,生产端完成量受通道容量约束
        /// (两跳通道的在途上界 = 生产通道 capacity + 转发通道 capacity + 1 手持)
        struct BackpressureFetcher {
            total: usize,
            sent: Arc<AtomicUsize>,
        }

        #[async_trait]
        impl SitemapFetcher for BackpressureFetcher {
            async fn fetch(&self, _url: &str) -> Result<SitemapFetch, MapError> {
                Err(MapError::Internal("unused".to_string()))
            }

            async fn fetch_streaming(
                &self,
                _url: &str,
                channel_capacity: usize,
            ) -> Result<SitemapStream, MapError> {
                let (tx, rx) = tokio::sync::mpsc::channel(channel_capacity.max(1));
                let sent = self.sent.clone();
                let total = self.total;
                tokio::spawn(async move {
                    for i in 0..total {
                        if tx.send(format!("https://a.com/{i}")).await.is_err() {
                            break;
                        }
                        sent.fetch_add(1, Ordering::SeqCst);
                    }
                });
                Ok(SitemapStream {
                    kind: SitemapKind::Urlset,
                    rx,
                })
            }
        }

        #[tokio::test]
        async fn streaming_backpressure_bounds_producer_progress() {
            const TOTAL: usize = 10_000;
            const CAPACITY: usize = 4;
            let sent = Arc::new(AtomicUsize::new(0));
            let fetcher = BackpressureFetcher {
                total: TOTAL,
                sent: sent.clone(),
            };
            let rx = MapUseCase::new(Arc::new(fetcher))
                .execute_streaming(&dto(ORIGIN), stream_options(CAPACITY, TOTAL, 2))
                .await
                .expect("execute_streaming");

            // 消费端暂停:生产端被背压阻塞,完成量远小于总量
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            let stalled = sent.load(Ordering::SeqCst);
            assert!(
                stalled <= 2 * CAPACITY + 1,
                "consumer paused: producer must be bounded by channel capacity, \
                 sent={stalled} (cap={CAPACITY})"
            );

            // 恢复消费:全部 10_000 条按序产出
            let got = collect(rx.rx).await;
            assert_eq!(got.len(), TOTAL, "drain must yield all locs");
            assert_eq!(
                sent.load(Ordering::SeqCst),
                TOTAL,
                "producer must complete after drain"
            );
        }

        /// sitemapindex:并发展开 ≤ max_concurrent_sub_sitemaps、递归一层
        /// 只取前 MAX_SUB_SITEMAPS 个子 sitemap、子 sitemap 失败放弃不计整体失败
        struct IndexMockFetcher {
            /// 子 sitemap url → (status, body)
            children: HashMap<String, (u16, String)>,
            /// 根 index 列出的子 sitemap(有序)
            root_children: Vec<String>,
            in_flight: Arc<AtomicUsize>,
            max_in_flight: Arc<AtomicUsize>,
            child_delay_ms: u64,
        }

        impl IndexMockFetcher {
            fn record_enter(&self) {
                let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
                self.max_in_flight.fetch_max(now, Ordering::SeqCst);
            }

            /// 根 index:按 `root_children` 顺序产出子 sitemap URL 流
            fn root_stream(&self, channel_capacity: usize) -> SitemapStream {
                let (tx, rx) = tokio::sync::mpsc::channel(channel_capacity.max(1));
                let children = self.root_children.clone();
                tokio::spawn(async move {
                    for child in children {
                        if tx.send(child).await.is_err() {
                            break;
                        }
                    }
                });
                SitemapStream {
                    kind: SitemapKind::SitemapIndex,
                    rx,
                }
            }

            /// 子 sitemap:404 → 空流;≥400 → TargetUnreachable;
            /// 200 → 延迟 `child_delay_ms` 后产出 loc 流(记录并发进入)
            async fn child_stream(
                &self,
                url: &str,
                channel_capacity: usize,
            ) -> Result<SitemapStream, MapError> {
                let (status, body) = match self.children.get(url) {
                    Some((s, b)) => (*s, b.clone()),
                    None => return Err(MapError::TargetUnreachable(format!("no mock for {url}"))),
                };
                if status == 404 {
                    return Ok(SitemapStream::empty());
                }
                if status >= 400 {
                    return Err(MapError::TargetUnreachable(format!(
                        "child returned status {status}"
                    )));
                }
                let (tx, rx) = tokio::sync::mpsc::channel(channel_capacity.max(1));
                self.record_enter();
                let in_flight = self.in_flight.clone();
                let delay = self.child_delay_ms;
                tokio::spawn(async move {
                    tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
                    for loc in parse_locs(&body) {
                        if tx.send(loc).await.is_err() {
                            break;
                        }
                    }
                    in_flight.fetch_sub(1, Ordering::SeqCst);
                });
                Ok(SitemapStream {
                    kind: SitemapKind::Urlset,
                    rx,
                })
            }
        }

        #[async_trait]
        impl SitemapFetcher for IndexMockFetcher {
            async fn fetch(&self, _url: &str) -> Result<SitemapFetch, MapError> {
                Err(MapError::Internal("unused".to_string()))
            }

            async fn fetch_streaming(
                &self,
                url: &str,
                channel_capacity: usize,
            ) -> Result<SitemapStream, MapError> {
                const ROOT: &str = "https://a.com/sitemap.xml";
                if url == ROOT {
                    return Ok(self.root_stream(channel_capacity));
                }
                self.child_stream(url, channel_capacity).await
            }
        }

        #[tokio::test]
        async fn streaming_index_recursion_caps_concurrency_and_children() {
            // 7 个子 sitemap(超出 MAX_SUB_SITEMAPS=5 只取前 5),
            // 其中第 2 个(index 1)500 且重试仍 500 → 放弃
            let mut children = HashMap::new();
            let mut root_children = Vec::new();
            for i in 0..7 {
                let url = format!("https://a.com/s{i}.xml");
                let status = if i == 1 { 500u16 } else { 200u16 };
                let body = urlset(&[&format!("https://a.com/u{i}")]);
                children.insert(url.clone(), (status, body));
                root_children.push(url);
            }
            let in_flight = Arc::new(AtomicUsize::new(0));
            let max_in_flight = Arc::new(AtomicUsize::new(0));
            let fetcher = IndexMockFetcher {
                children,
                root_children,
                in_flight: in_flight.clone(),
                max_in_flight: max_in_flight.clone(),
                child_delay_ms: 50,
            };
            let rx = MapUseCase::new(Arc::new(fetcher))
                .execute_streaming(&dto(ORIGIN), stream_options(4, 100, 2))
                .await
                .expect("execute_streaming");

            let got = collect(rx.rx).await;
            // 子 sitemap 0、2、3、4 命中(1 失败放弃,5、6 超出上限不取)
            assert_eq!(
                got,
                vec![
                    "https://a.com/u0",
                    "https://a.com/u2",
                    "https://a.com/u3",
                    "https://a.com/u4",
                ],
                "first 5 children expanded, failed child skipped"
            );
            let peak = max_in_flight.load(Ordering::SeqCst);
            assert!(
                peak >= 2,
                "children must be fetched concurrently (observed peak {peak})"
            );
            assert!(
                peak <= 2,
                "child fetch concurrency must not exceed max_concurrent_sub_sitemaps=2, got {peak}"
            );
        }

        /// 空 sitemapindex(无子 sitemap)→ 立即耗尽的空流
        #[tokio::test]
        async fn streaming_empty_index_yields_empty_stream() {
            let fetcher = MockFetcher {
                responses: HashMap::from([(
                    format!("{ORIGIN}/sitemap.xml"),
                    (200u16, sitemap_index(&[])),
                )]),
            };
            let rx = MapUseCase::new(Arc::new(fetcher))
                .execute_streaming(&dto(ORIGIN), stream_options(4, 100, 2))
                .await
                .expect("execute_streaming");
            assert!(collect(rx.rx).await.is_empty());
        }

        /// 子 sitemap 解析 panic:消费任务记 warn 不中断,主流仍正常收尾
        struct PanicChildFetcher;

        #[async_trait]
        impl SitemapFetcher for PanicChildFetcher {
            async fn fetch(&self, _url: &str) -> Result<SitemapFetch, MapError> {
                Err(MapError::Internal("unused".to_string()))
            }

            async fn fetch_streaming(
                &self,
                url: &str,
                channel_capacity: usize,
            ) -> Result<SitemapStream, MapError> {
                const ROOT: &str = "https://a.com/sitemap.xml";
                if url == ROOT {
                    let (tx, rx) = tokio::sync::mpsc::channel(channel_capacity.max(1));
                    let children = [
                        "https://a.com/panic.xml".to_string(),
                        "https://a.com/ok.xml".to_string(),
                    ];
                    tokio::spawn(async move {
                        for child in children {
                            if tx.send(child).await.is_err() {
                                break;
                            }
                        }
                    });
                    return Ok(SitemapStream {
                        kind: SitemapKind::SitemapIndex,
                        rx,
                    });
                }
                if url.ends_with("/panic.xml") {
                    panic!("mock child panic");
                }
                let (tx, rx) = tokio::sync::mpsc::channel(channel_capacity.max(1));
                tokio::spawn(async move {
                    let _ = tx.send("https://a.com/u-ok".to_string()).await;
                });
                Ok(SitemapStream {
                    kind: SitemapKind::Urlset,
                    rx,
                })
            }
        }

        #[tokio::test]
        async fn streaming_child_panic_does_not_break_stream() {
            let rx = MapUseCase::new(Arc::new(PanicChildFetcher))
                .execute_streaming(&dto(ORIGIN), stream_options(4, 100, 2))
                .await
                .expect("execute_streaming");
            let got = collect(rx.rx).await;
            assert_eq!(
                got,
                vec!["https://a.com/u-ok".to_string()],
                "healthy child must still deliver after a sibling panics"
            );
        }

        /// finalize_links:流式 loc 聚合语义与 execute() 一致
        /// (去重保首现位置 → include → exclude → limit)
        #[test]
        fn finalize_links_matches_execute_semantics() {
            let mut d = dto(ORIGIN);
            d.include_patterns = Some(vec!["*/blog/*".to_string()]);
            d.exclude_patterns = Some(vec!["*/tag/*".to_string()]);
            d.limit = Some(2);
            let links = finalize_links(
                vec![
                    "https://a.com/blog/1".to_string(),
                    "https://a.com/blog/1".to_string(),     // 重复
                    "https://a.com/blog/tag/x".to_string(), // exclude
                    "https://a.com/page/1".to_string(),     // include 不命中
                    "https://a.com/blog/2".to_string(),
                    "https://a.com/blog/3".to_string(),
                ],
                &d,
            );
            assert_eq!(links, vec!["https://a.com/blog/1", "https://a.com/blog/2"]);
        }
    }
}