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
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Crawl Link Extractor
//!
//! 从 `scrape_worker.rs` 提取的爬取链接处理函数。
//! 包含 robots.txt 检查、完成状态更新和链接提取入队。

mod link_filters;
use link_filters::url_accepted;

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

use anyhow::Result;
use log::{debug, error, info, warn};
use scraper::{Html, Selector};
use serde_json::json;
use url::Url;

use chrono::Utc;

use crate::application::dto::crawl_request::CrawlConfigDto;
use crate::domain::models::{Task, TaskStatus, TaskType};
use crate::domain::repositories::crawl_repository::CrawlRepository;
use crate::domain::repositories::task_repository::TaskRepository;
use crate::engines::engine_client::ScrapeResponse;
use crate::i18n::tr_log_args;
use crate::utils::dedup::{DedupResult, Deduplicator};
use crate::utils::robots::RobotsCheckerTrait;
use crate::workers::crawl::{
    DomainFilter, FilterContext, Frontier, PathDepthScorer, ScoringContext, UrlPatternFilter,
    UrlScorer,
};
use crate::workers::errors::ScrapeWorkerError;

/// 检查 Robots.txt 并返回是否允许访问
///
/// # Arguments
/// * `task` - 目标任务
/// * `robots_checker` - robots.txt 检查器
pub async fn check_robots_txt(
    task: &Task,
    robots_checker: &dyn RobotsCheckerTrait,
    user_agent: &str,
) -> bool {
    if !robots_checker
        .is_allowed(&task.url, user_agent)
        .await
        .unwrap_or(true)
    {
        info!("Access denied by robots.txt for {}", task.url);
        return false;
    }

    if let Some(delay) = robots_checker
        .get_crawl_delay(&task.url, user_agent)
        .await
        .unwrap_or(None)
    {
        info!("Respecting crawl delay of {:?} for {}", delay, task.url);
        tokio::time::sleep(delay).await;
    }

    true
}

/// 更新 Crawl 完成状态(检查是否所有任务都已完成)
///
/// 当 completed + failed == total 时,将 crawl 状态标记为 Completed。
///
/// # Arguments
/// * `crawl_id` - 爬取任务 ID
/// * `crawl_repository` - 爬取仓库
pub async fn update_crawl_completion_status(
    crawl_id: crate::domain::id::Id,
    crawl_repository: &dyn CrawlRepository,
) {
    // 终态规则收敛在仓储单条条件 UPDATE:completed+failed==total 才落终态,
    // completed==0 → Failed;并发取消/完成不被覆盖。
    match crawl_repository.finalize_if_all_terminal(crawl_id).await {
        Ok(true) => info!(
            "Crawl {} marked terminal (all tasks completed/failed)",
            crawl_id
        ),
        Ok(false) => debug!("crawl {} not eligible for terminal transition", crawl_id),
        Err(e) => error!("Failed to finalize crawl {}: {}", crawl_id, e),
    }
}

/// 从抓取响应中提取链接并加入爬取队列
///
/// 三层去重:Bloom 预筛 → DB 校验 → 二次 Bloom 防 race。
/// 最终经 Frontier 评分排序后入队。
///
/// # Arguments
/// * `task` - 当前任务
/// * `response` - 抓取响应
/// * `crawl_id` - 爬取 ID
/// * `current_depth` - 当前深度
/// * `config` - 爬取配置
/// * `repository` - 任务仓库
/// * `crawl_repository` - 爬取仓库
/// * `deduplicator` - URL 去重器
#[allow(clippy::too_many_arguments)]
pub async fn extract_and_queue_links(
    task: &Task,
    response: &ScrapeResponse,
    crawl_id: crate::domain::id::Id,
    current_depth: u32,
    config: &CrawlConfigDto,
    domain_blacklist: &[String],
    repository: &dyn TaskRepository,
    crawl_repository: &dyn CrawlRepository,
    deduplicator: &Arc<parking_lot::RwLock<Deduplicator>>,
) -> Result<()> {
    // 只解析 HTML 内容
    if !response.content_type.contains("text/html") {
        return Ok(());
    }

    let LinkFilters {
        pattern_filter,
        filter_ctx,
        blacklist_filter,
        empty_include_short_circuit,
    } = build_link_filters(task, config, domain_blacklist);

    let unique_links = collect_unique_links(
        task,
        response,
        &pattern_filter,
        empty_include_short_circuit,
        &blacklist_filter,
        &filter_ctx,
    )?;

    info!("Found {} unique links on {}", unique_links.len(), task.url);

    // URL 分层去重
    let (mut to_enqueue, db_check) = partition_by_dedup(&unique_links, deduplicator)?;

    // Frontier 评分排序
    let mut new_urls: Vec<String> = Vec::with_capacity(unique_links.len());
    new_urls.extend(std::mem::take(&mut to_enqueue));

    if !db_check.is_empty() {
        new_urls.extend(resolve_db_check(db_check, repository, deduplicator).await?);
    }

    // Frontier 评分排序入队
    if !new_urls.is_empty() {
        score_and_enqueue(
            new_urls,
            task,
            crawl_id,
            current_depth,
            config,
            repository,
            crawl_repository,
        )
        .await?;
    }

    Ok(())
}

/// 链接过滤链构造结果(include/exclude patterns + 团队域名黑名单 + 空集合短路标志)
struct LinkFilters {
    /// include/exclude pattern 过滤器(include 配置为空集合短路时为 `None`)
    pattern_filter: Option<UrlPatternFilter>,
    /// 过滤上下文
    filter_ctx: FilterContext,
    /// 团队域名黑名单过滤器(payload 未配置黑名单时为 `None`)
    blacklist_filter: Option<DomainFilter>,
    /// include_patterns 配置为空集合时的整体短路标志
    empty_include_short_circuit: bool,
}

/// 构造链接过滤链(include/exclude patterns + 团队域名黑名单)
///
/// 自 [`extract_and_queue_links`] 提取,过滤规则构造顺序与日志逐字保留。
/// 返回 [`LinkFilters`]。
fn build_link_filters(
    task: &Task,
    config: &CrawlConfigDto,
    domain_blacklist: &[String],
) -> LinkFilters {
    // 循环外构造一次 UrlPatternFilter
    let empty_include_short_circuit =
        matches!(&config.include_patterns, Some(patterns) if patterns.is_empty());
    let pattern_filter = if empty_include_short_circuit {
        None
    } else {
        Some(UrlPatternFilter::new(
            config.include_patterns.clone().unwrap_or_default(),
            config.exclude_patterns.clone().unwrap_or_default(),
        ))
    };
    let filter_ctx = FilterContext::default();

    // 团队 domain_blacklist 由 worker 从 crawl.config 读取后传入;
    // 黑名单优先级高于 include/exclude patterns——命中即丢弃。
    let blacklist_filter = if domain_blacklist.is_empty() {
        None
    } else {
        info!(
            "Crawl task {} enforcing domain blacklist with {} entries",
            task.id,
            domain_blacklist.len()
        );
        Some(DomainFilter::denylist_normalized(domain_blacklist.to_vec()))
    };

    LinkFilters {
        pattern_filter,
        filter_ctx,
        blacklist_filter,
        empty_include_short_circuit,
    }
}

/// 从 HTML 响应收集绝对链接并按过滤链去重
///
/// 自 [`extract_and_queue_links`] 提取,过滤判定顺序与短路行为逐字保留
/// (单链接判定见 [`url_accepted`]):
/// 黑名单 → include/exclude patterns → include 为空集合时整体短路。
fn collect_unique_links(
    task: &Task,
    response: &ScrapeResponse,
    pattern_filter: &Option<UrlPatternFilter>,
    empty_include_short_circuit: bool,
    blacklist_filter: &Option<DomainFilter>,
    filter_ctx: &FilterContext,
) -> Result<HashSet<String>> {
    let document = Html::parse_document(&response.content);
    let selector =
        Selector::parse("a").map_err(|e| ScrapeWorkerError::SelectorError(e.to_string()))?;
    // 以响应 final_url(重定向后地址)为解析基准,并把种子 host 与
    // final host 都纳入允许集;允许子域(www./docs.)但拒绝父域与兄弟域。
    // 此前仅用 task.url 精确匹配,种子被 302 到 www 后页面内链接全部被丢弃。
    let join_base = response
        .final_url
        .as_deref()
        .and_then(|u| Url::parse(u).ok())
        .unwrap_or(Url::parse(&task.url)?);
    let seed_host = Url::parse(&task.url)
        .ok()
        .and_then(|u| u.host_str().map(str::to_ascii_lowercase));
    let mut allowed_hosts: Vec<String> = seed_host.clone().into_iter().collect();
    // final host 仅在与会话种子相关(等同/互为子域)时纳入允许集。
    // 否则 302 到任意外部域会把外站变成可爬根,扩大 crawl 范围。
    if let Some(final_host) = response
        .final_url
        .as_deref()
        .and_then(|u| Url::parse(u).ok())
        .and_then(|u| u.host_str().map(str::to_ascii_lowercase))
    {
        let related = seed_host
            .as_ref()
            .map(|seed| host_matches(&final_host, seed) || host_matches(seed, &final_host))
            .unwrap_or(false);
        if related {
            allowed_hosts.push(final_host);
        } else {
            log::debug!(
                "redirect final host {} unrelated to seed host; not expanding crawl scope",
                final_host
            );
        }
    }
    allowed_hosts.sort();
    allowed_hosts.dedup();

    let mut links = HashSet::new();

    for element in document.select(&selector) {
        if let Some(href) = element.value().attr("href") {
            if let Ok(absolute_url) = join_base.join(href) {
                let same_host = absolute_url
                    .host_str()
                    .map(str::to_ascii_lowercase)
                    .map(|host| allowed_hosts.iter().any(|root| host_matches(&host, root)))
                    .unwrap_or(false);
                if !same_host {
                    continue;
                }
                let url_str = absolute_url.to_string();

                // 子链接与根 URL 同口径限长(DTO 上限 2048)。
                // 超长 URL 会让 PostgreSQL btree 唯一索引插入失败
                // (index row size exceeds maximum),且非重复冲突会中止
                // 整个链接提取步骤。
                if url_str.len() > 2048 {
                    log::debug!("skip oversized child url ({} bytes)", url_str.len());
                    continue;
                }

                if url_accepted(
                    &url_str,
                    &task.url,
                    pattern_filter,
                    empty_include_short_circuit,
                    blacklist_filter,
                    filter_ctx,
                ) {
                    links.insert(url_str);
                }
            }
        }
    }
    Ok(links)
}

/// host 是否等于 root 或为 root 的子域(`www.example.com` ∈ `example.com`)。
fn host_matches(host: &str, root: &str) -> bool {
    host == root
        || (host.len() > root.len() + 1
            && host.ends_with(root)
            && host.as_bytes()[host.len() - root.len() - 1] == b'.')
}

/// 布隆分层去重:`DefinitelyNew` 直接入队,`MaybeExisting` 转 DB 校验
///
/// 自 [`extract_and_queue_links`] 提取,写锁临界区与错误语义逐字保留
/// (首个去重错误立即返回,锁随作用域释放)。
fn partition_by_dedup(
    unique_links: &HashSet<String>,
    deduplicator: &Arc<parking_lot::RwLock<Deduplicator>>,
) -> Result<(Vec<String>, Vec<String>)> {
    let mut to_enqueue: Vec<String> = Vec::with_capacity(unique_links.len());
    let mut db_check: Vec<String> = Vec::with_capacity(unique_links.len());

    {
        let mut dedup = deduplicator.write();
        for link in unique_links {
            match dedup.check_and_insert(link) {
                Ok(DedupResult::DefinitelyNew { normalized }) => {
                    to_enqueue.push(normalized);
                }
                Ok(DedupResult::MaybeExisting { normalized, .. }) => {
                    db_check.push(normalized);
                }
                Err(e) => {
                    return Err(anyhow::anyhow!(
                        "URL dedup check failed for {}: {}",
                        link,
                        e
                    ));
                }
            }
        }
    }

    Ok((to_enqueue, db_check))
}

/// DB 校验布隆疑似项:确认不存在则无条件 insert + 入队
///
/// 自 [`extract_and_queue_links`] 提取,排序/去重与二次 insert 注释逐字保留。
async fn resolve_db_check(
    mut db_check: Vec<String>,
    repository: &dyn TaskRepository,
    deduplicator: &Arc<parking_lot::RwLock<Deduplicator>>,
) -> Result<Vec<String>> {
    db_check.sort_unstable();
    db_check.dedup();

    let existing_urls = repository.find_existing_urls(&db_check).await?;
    let existing_url_set: HashSet<String> = existing_urls.into_iter().collect();

    let mut to_db_insert: Vec<&String> = Vec::with_capacity(db_check.len());
    for normalized in &db_check {
        if !existing_url_set.contains(normalized) {
            to_db_insert.push(normalized);
        }
    }

    let mut to_db_enqueue: Vec<String> = Vec::with_capacity(to_db_insert.len());
    if !to_db_insert.is_empty() {
        let mut dedup = deduplicator.write();
        // DB 已确认这些 URL 不存在——布隆阳性必为假阳性,必须无条件
        // insert + 入队。禁止再走 check_and_insert:首轮检查已置位布隆,
        // 二次检查必然复现 MaybeExisting,会把 DB 确认的新 URL 静默丢弃
        // (永久漏抓)。
        for normalized in &to_db_insert {
            dedup.insert(normalized);
            to_db_enqueue.push(normalized.to_string());
        }
    }

    Ok(to_db_enqueue)
}

/// Frontier 评分入队 + 按策略(DFS/BFS)生成子任务落库
///
/// 自 [`extract_and_queue_links`] 提取,评分日志、优先级策略与任务构造逐字保留。
#[allow(clippy::too_many_arguments)]
async fn score_and_enqueue(
    new_urls: Vec<String>,
    task: &Task,
    crawl_id: crate::domain::id::Id,
    current_depth: u32,
    config: &CrawlConfigDto,
    repository: &dyn TaskRepository,
    crawl_repository: &dyn CrawlRepository,
) -> Result<()> {
    // 停止瞬间仍在飞的子任务会继续入队新链接;入队侧再校验
    // 一次父 crawl 终态,避免取消之后又产生新行。
    // 仅需状态:投影读取,避免每页拉回 crawl.config。
    if let Ok(Some(progress)) = crawl_repository.find_progress_by_id(crawl_id).await {
        if crate::application::use_cases::crawl_state_machine::is_terminal(&progress.status) {
            log::info!(
                "crawl {} is terminal; skip enqueueing {} discovered link(s)",
                crawl_id,
                new_urls.len()
            );
            return Ok(());
        }
    }

    let frontier = build_scored_frontier(&new_urls, task);

    // DFS/BFS 策略判断提到循环外:`to_lowercase` 每次调用都分配新 String,
    // 不必逐 URL 重复计算
    let is_dfs_strategy = config
        .strategy
        .as_deref()
        .map(|s| s.to_lowercase() == "dfs")
        .unwrap_or(false);

    while let Some(scored) = frontier.pop() {
        // 归一化可能放大 URL(例如 query 中的 '+' 被重新编码为 '%20')。
        // 入队前按最终字符串再查一次 2048 字节,避免 PG btree 元组超限。
        if scored.url.len() > 2048 {
            log::debug!(
                "skip oversized normalized child url: {} bytes (limit 2048)",
                scored.url.len()
            );
            continue;
        }
        // 出队按 priority ASC(小值先出)。
        // DFS(栈语义):子链接键 = 父 priority - (子深度),i32 负空间
        // 保证默认 priority=0 与超深链路下仍严格随深度递减
        // (此前 saturating_sub(1) 在 priority=0 或深链路塌缩回 BFS)。
        // BFS(层序):继承父 priority。
        let priority = child_priority(task.priority, is_dfs_strategy, current_depth);

        let new_task =
            build_child_crawl_task(task, crawl_id, current_depth, config, priority, scored.url);

        match repository.create(&new_task).await {
            Ok(_) => {
                // 只有真正插入成功才计数;冲突跳过不计数,
                // 否则 total_tasks 虚高,completed+failed==total 永不成立,
                // crawl 会永远停在 running。
                crawl_repository.increment_total_tasks(crawl_id).await?;
            }
            Err(e) => {
                // 类型化唯一冲突(RepositoryError::Conflict)
                // = 并发窗口已入队,跳过;其他错误原样上抛。
                if e.is_unique_conflict() {
                    log::debug!("skip duplicate child task url={}", new_task.url);
                } else {
                    return Err(e.into());
                }
            }
        }
    }

    Ok(())
}

/// 对 URL 评分并按 Frontier 评分排序入队(评分失败记 warn 后跳过)。
fn build_scored_frontier(new_urls: &[String], task: &Task) -> Frontier {
    let scorer = PathDepthScorer::new();
    let scoring_ctx = ScoringContext::default();
    let frontier = Frontier::new();

    for url in new_urls {
        let base_score = scorer.score(url, &scoring_ctx);
        // KG 结构空洞提升因子
        // kg_priority_boost > 1.0 表示 URL 可能填补结构空洞,应获得更高优先级
        let score = (base_score as f64 * scoring_ctx.kg_priority_boost).clamp(0.0, 1.0) as f32;
        match crate::workers::crawl::ScoredUrl::new(url.clone(), score) {
            Ok(scored) => frontier.push(scored),
            Err(e) => {
                warn!(
                    "{}",
                    tr_log_args(
                        "link-score-skip",
                        &[
                            ("task_id", task.id.to_string()),
                            ("error", e.to_string()),
                            ("url", url.as_str().to_string()),
                        ],
                    )
                );
            }
        }
    }

    info!(
        "{}",
        tr_log_args(
            "link-frontier-enqueued",
            &[
                ("task_id", task.id.to_string()),
                ("count", frontier.len().to_string()),
                ("domains", frontier.domain_count().to_string()),
            ],
        )
    );

    frontier
}

/// 子链接优先级:DFS 按深度递减(栈语义),BFS 继承父优先级。
fn child_priority(parent_priority: i32, is_dfs_strategy: bool, current_depth: u32) -> i32 {
    if is_dfs_strategy {
        let depth_key = (current_depth.min(1_000_000) as i32).saturating_add(1);
        parent_priority.saturating_sub(depth_key)
    } else {
        parent_priority
    }
}

/// 构造子爬取任务(payload 记录 crawl_id / depth / config)。
fn build_child_crawl_task(
    task: &Task,
    crawl_id: crate::domain::id::Id,
    current_depth: u32,
    config: &CrawlConfigDto,
    priority: i32,
    url: String,
) -> Task {
    Task {
        id: crate::domain::id::Id::generate(),
        task_type: TaskType::Crawl,
        status: TaskStatus::Queued,
        priority,
        team_id: task.team_id,
        api_key_id: task.api_key_id,
        url,
        payload: json!({
            "crawl_id": crawl_id.to_string(),
            "depth": current_depth + 1,
            "config": config,
        }),
        retry_count: 0,
        attempt_count: 0,
        max_retries: 3,
        scheduled_at: None,
        created_at: Utc::now(),
        started_at: None,
        completed_at: None,
        crawl_id: Some(crawl_id),
        updated_at: Utc::now(),
        lock_token: None,
        lock_expires_at: None,
        expires_at: None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::models::Crawl;
    use crate::domain::models::CrawlStatus;
    use crate::domain::repositories::task_repository::RepositoryError;
    use std::sync::atomic::{AtomicU32, Ordering};

    fn make_task(url: &str) -> Task {
        Task {
            id: crate::domain::id::Id::generate(),
            task_type: TaskType::Crawl,
            status: TaskStatus::Queued,
            priority: 0,
            team_id: crate::domain::id::Id::generate(),
            api_key_id: crate::domain::id::Id::generate(),
            url: url.to_string(),
            payload: json!({}),
            retry_count: 0,
            attempt_count: 0,
            max_retries: 3,
            scheduled_at: None,
            created_at: Utc::now(),
            started_at: None,
            completed_at: None,
            crawl_id: None,
            updated_at: Utc::now(),
            lock_token: None,
            lock_expires_at: None,
            expires_at: None,
        }
    }

    // Mock types

    struct MockRobotsChecker {
        allowed: bool,
    }

    #[async_trait::async_trait]
    impl RobotsCheckerTrait for MockRobotsChecker {
        async fn is_allowed(&self, _url: &str, _user_agent: &str) -> Result<bool> {
            Ok(self.allowed)
        }
        async fn get_crawl_delay(
            &self,
            _url: &str,
            _user_agent: &str,
        ) -> Result<Option<std::time::Duration>> {
            Ok(None)
        }
    }

    #[derive(Default)]
    struct MockCrawlRepo {
        update_status_count: AtomicU32,
    }

    /// Configurable crawl repo that can return a specific crawl from find_by_id
    struct ConfigurableCrawlRepo {
        crawl: Option<Crawl>,
        update_status_count: AtomicU32,
        last_status: std::sync::Mutex<Option<CrawlStatus>>,
    }

    impl ConfigurableCrawlRepo {
        fn with_crawl(c: Crawl) -> Self {
            Self {
                crawl: Some(c),
                update_status_count: AtomicU32::new(0),
                last_status: std::sync::Mutex::new(None),
            }
        }

        fn last_status(&self) -> Option<CrawlStatus> {
            *self.last_status.lock().expect("status mutex poisoned")
        }
    }

    #[async_trait::async_trait]
    impl CrawlRepository for ConfigurableCrawlRepo {
        async fn create(&self, crawl: &Crawl) -> Result<Crawl, RepositoryError> {
            Ok(crawl.clone())
        }
        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<Crawl>, RepositoryError> {
            Ok(self.crawl.clone())
        }
        async fn update(&self, crawl: &Crawl) -> Result<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: CrawlStatus,
        ) -> Result<(), RepositoryError> {
            *self.last_status.lock().expect("status mutex poisoned") = Some(status);
            self.update_status_count.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }

        async fn update_status_guarded(
            &self,
            _id: crate::domain::id::Id,
            status: CrawlStatus,
        ) -> Result<bool, RepositoryError> {
            if self.crawl.as_ref().is_some_and(|c| {
                matches!(
                    c.status,
                    CrawlStatus::Completed | CrawlStatus::Failed | CrawlStatus::Cancelled
                )
            }) {
                return Ok(false);
            }
            *self.last_status.lock().expect("status mutex poisoned") = Some(status);
            self.update_status_count.fetch_add(1, Ordering::SeqCst);
            Ok(true)
        }
        async fn finalize_if_all_terminal(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<bool, RepositoryError> {
            let Some(c) = self.crawl.as_ref() else {
                return Ok(false);
            };
            if matches!(
                c.status,
                crate::domain::models::CrawlStatus::Completed
                    | crate::domain::models::CrawlStatus::Failed
                    | crate::domain::models::CrawlStatus::Cancelled
            ) {
                return Ok(false);
            }
            if c.total_tasks() > 0 && c.completed_tasks() + c.failed_tasks() == c.total_tasks() {
                let status = if c.completed_tasks() == 0 {
                    crate::domain::models::CrawlStatus::Failed
                } else {
                    crate::domain::models::CrawlStatus::Completed
                };
                *self.last_status.lock().expect("status mutex poisoned") = Some(status);
                self.update_status_count.fetch_add(1, Ordering::SeqCst);
                Ok(true)
            } else {
                Ok(false)
            }
        }
        async fn increment_total_tasks(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<(), RepositoryError> {
            Ok(())
        }
        async fn find_by_team_id_paginated(
            &self,
            _team_id: crate::domain::id::Id,
            _limit: u32,
            _offset: u32,
        ) -> Result<Vec<Crawl>, RepositoryError> {
            Ok(vec![])
        }
        async fn count_by_team_id(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
    }

    #[async_trait::async_trait]
    impl CrawlRepository for MockCrawlRepo {
        async fn create(&self, crawl: &Crawl) -> Result<Crawl, RepositoryError> {
            Ok(crawl.clone())
        }
        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<Crawl>, RepositoryError> {
            Ok(None)
        }
        async fn update(&self, crawl: &Crawl) -> Result<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: CrawlStatus,
        ) -> Result<(), RepositoryError> {
            self.update_status_count.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
        async fn increment_total_tasks(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<(), RepositoryError> {
            Ok(())
        }
        async fn find_by_team_id_paginated(
            &self,
            _team_id: crate::domain::id::Id,
            _limit: u32,
            _offset: u32,
        ) -> Result<Vec<Crawl>, RepositoryError> {
            Ok(vec![])
        }
        async fn count_by_team_id(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
    }

    // check_robots_txt

    #[tokio::test]
    async fn test_check_robots_txt_allowed_returns_true() {
        let task = make_task("https://example.com");
        let checker = MockRobotsChecker { allowed: true };
        assert!(check_robots_txt(&task, &checker, "crawlrs-bot/1.0").await);
    }

    #[tokio::test]
    async fn test_check_robots_txt_denied_returns_false() {
        let task = make_task("https://example.com");
        let checker = MockRobotsChecker { allowed: false };
        assert!(!check_robots_txt(&task, &checker, "crawlrs-bot/1.0").await);
    }

    // update_crawl_completion_status

    #[tokio::test]
    async fn test_update_crawl_completion_status_crawl_not_found() {
        // MockCrawlRepo.find_by_id returns Ok(None) → logs error, no panic
        let repo = MockCrawlRepo::default();
        update_crawl_completion_status(crate::domain::id::Id::generate(), &repo).await;
        // No assertion needed — just verify it doesn't panic
    }

    // extract_and_queue_links

    use crate::application::dto::crawl_request::CrawlConfigDto;
    use crate::domain::repositories::crawl_repository::CrawlRepository;
    use crate::domain::repositories::task_repository::TaskQueryParams;
    use crate::engines::engine_client::ScrapeResponse;
    use crate::utils::dedup::Deduplicator;
    use std::collections::HashSet;

    struct CountingTaskRepo {
        create_count: AtomicU32,
        /// 记录入队任务的 priority(P01 DFS/BFS 语义验证用)
        captured_priorities: std::sync::Mutex<Vec<i32>>,
    }
    impl CountingTaskRepo {
        fn new() -> Self {
            Self {
                create_count: AtomicU32::new(0),
                captured_priorities: std::sync::Mutex::new(Vec::new()),
            }
        }
    }

    #[async_trait::async_trait]
    impl TaskRepository for CountingTaskRepo {
        async fn create(&self, task: &Task) -> Result<Task, RepositoryError> {
            self.create_count.fetch_add(1, Ordering::SeqCst);
            self.captured_priorities.lock().unwrap().push(task.priority);
            Ok(Task::new(
                crate::domain::id::Id::generate(),
                TaskType::Crawl,
                crate::domain::id::Id::generate(),
                crate::domain::id::Id::generate(),
                String::new(),
                json!({}),
            ))
        }
        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::new(
                crate::domain::id::Id::generate(),
                TaskType::Crawl,
                crate::domain::id::Id::generate(),
                crate::domain::id::Id::generate(),
                String::new(),
                json!({}),
            ))
        }
        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(HashSet::new())
        }
        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: 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)
        }
    }

    fn make_response(content_type: &str, content: &str) -> ScrapeResponse {
        ScrapeResponse {
            js_degraded: None,
            captured_responses: Vec::new(),
            content: content.to_string(),
            status_code: 200,
            content_type: content_type.to_string(),
            headers: Default::default(),
            screenshot: None,
            response_time_ms: 100,
            final_url: None,
            markdown: None,
        }
    }

    fn default_config() -> CrawlConfigDto {
        CrawlConfigDto {
            max_depth: 2,
            include_patterns: None,
            exclude_patterns: None,
            strategy: None,
            crawl_delay_ms: None,
            max_concurrency: None,
            max_pages: None,
            proxy: None,
            headers: None,
            extraction_rules: None,
            extraction_prompt: None,
            extraction_schema: None,
        }
    }

    #[tokio::test]
    async fn test_extract_links_non_html_returns_early() {
        let task = make_task("https://example.com");
        let response = make_response("application/json", r#"{"key": "value"}"#);
        let repo = CountingTaskRepo::new();
        let crawl_repo = MockCrawlRepo::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));
        let config = default_config();

        extract_and_queue_links(
            &task,
            &response,
            crate::domain::id::Id::generate(),
            0,
            &config,
            &[],
            &repo,
            &crawl_repo,
            &dedup,
        )
        .await
        .unwrap();
        assert_eq!(
            repo.create_count.load(Ordering::SeqCst),
            0,
            "non-HTML should not extract links"
        );
    }

    #[tokio::test]
    async fn test_extract_links_html_with_links() {
        let task = make_task("https://example.com/page");
        let html = r#"<html><body>
            <a href="https://example.com/other">Other</a>
            <a href="https://example.com/another">Another</a>
        </body></html>"#;
        let response = make_response("text/html", html);
        let repo = CountingTaskRepo::new();
        let crawl_repo = MockCrawlRepo::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));
        let config = default_config();

        extract_and_queue_links(
            &task,
            &response,
            crate::domain::id::Id::generate(),
            0,
            &config,
            &[],
            &repo,
            &crawl_repo,
            &dedup,
        )
        .await
        .unwrap();
        assert!(
            repo.create_count.load(Ordering::SeqCst) > 0,
            "should enqueue found links"
        );
    }

    #[tokio::test]
    async fn test_extract_links_skips_self_link() {
        let task = make_task("https://example.com/page");
        let html = r#"<html><body>
            <a href="https://example.com/page">Self</a>
            <a href="https://example.com/other">Other</a>
        </body></html>"#;
        let response = make_response("text/html", html);
        let repo = CountingTaskRepo::new();
        let crawl_repo = MockCrawlRepo::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));
        let config = default_config();

        extract_and_queue_links(
            &task,
            &response,
            crate::domain::id::Id::generate(),
            0,
            &config,
            &[],
            &repo,
            &crawl_repo,
            &dedup,
        )
        .await
        .unwrap();
        // Self-link should be skipped, only "other" should be enqueued
        assert_eq!(
            repo.create_count.load(Ordering::SeqCst),
            1,
            "self-link should be skipped"
        );
    }

    #[tokio::test]
    async fn test_extract_links_empty_include_patterns_short_circuit() {
        let task = make_task("https://example.com/page");
        let html = r#"<html><body><a href="https://example.com/other">Other</a></body></html>"#;
        let response = make_response("text/html", html);
        let repo = CountingTaskRepo::new();
        let crawl_repo = MockCrawlRepo::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));
        let mut config = default_config();
        config.include_patterns = Some(vec![]); // empty → short circuit

        extract_and_queue_links(
            &task,
            &response,
            crate::domain::id::Id::generate(),
            0,
            &config,
            &[],
            &repo,
            &crawl_repo,
            &dedup,
        )
        .await
        .unwrap();
        assert_eq!(
            repo.create_count.load(Ordering::SeqCst),
            0,
            "empty include_patterns should block all links"
        );
    }

    #[tokio::test]
    async fn test_extract_links_with_dfs_strategy() {
        let task = make_task("https://example.com/page");
        let html = r#"<html><body>
            <a href="https://example.com/other">Other</a>
        </body></html>"#;
        let response = make_response("text/html", html);
        let repo = CountingTaskRepo::new();
        let crawl_repo = MockCrawlRepo::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));
        let mut config = default_config();
        config.strategy = Some("dfs".to_string());

        extract_and_queue_links(
            &task,
            &response,
            crate::domain::id::Id::generate(),
            0,
            &config,
            &[],
            &repo,
            &crawl_repo,
            &dedup,
        )
        .await
        .unwrap();
        // DFS strategy should still enqueue links (with priority + 1)
        assert!(
            repo.create_count.load(Ordering::SeqCst) > 0,
            "DFS strategy should enqueue links"
        );
    }

    /// P01 回归钉:DFS 子链接 priority 必须小于父任务(出队 priority ASC
    /// → 深层先出,栈语义);BFS 子链接必须大于父任务(层序)。
    /// 修复前 DFS 用 saturating_add,实际行为是 BFS,策略标签与行为相反。
    #[tokio::test]
    async fn test_dfs_child_priority_below_parent_and_bfs_above() {
        async fn run_with_strategy(strategy: Option<&str>, html: &str) -> Vec<i32> {
            let mut task = make_task("https://example.com/page");
            task.priority = 5;
            let response = make_response("text/html", html);
            let repo = CountingTaskRepo::new();
            let crawl_repo = MockCrawlRepo::default();
            let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));
            let mut config = default_config();
            config.strategy = strategy.map(str::to_string);

            extract_and_queue_links(
                &task,
                &response,
                crate::domain::id::Id::generate(),
                0,
                &config,
                &[],
                &repo,
                &crawl_repo,
                &dedup,
            )
            .await
            .unwrap();
            let priorities = repo.captured_priorities.lock().unwrap().clone();
            priorities
        }

        let html = r#"<html><body>
            <a href="https://example.com/child">Child</a>
        </body></html>"#;

        let dfs = run_with_strategy(Some("dfs"), html).await;
        assert!(
            dfs.iter().all(|&p| p < 5),
            "dfs child priority must be BELOW parent (5), got {dfs:?}"
        );
        let bfs = run_with_strategy(Some("bfs"), html).await;
        assert!(
            bfs.iter().all(|&p| p >= 5),
            "bfs child priority must be >= parent (5), got {bfs:?}"
        );
    }

    #[tokio::test]
    async fn test_extract_links_with_exclude_patterns() {
        let task = make_task("https://example.com/page");
        let html = r#"<html><body>
            <a href="https://example.com/good">Good</a>
            <a href="https://example.com/bad">Bad</a>
        </body></html>"#;
        let response = make_response("text/html", html);
        let repo = CountingTaskRepo::new();
        let crawl_repo = MockCrawlRepo::default();
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));
        let mut config = default_config();
        config.exclude_patterns = Some(vec![".*bad.*".to_string()]);

        extract_and_queue_links(
            &task,
            &response,
            crate::domain::id::Id::generate(),
            0,
            &config,
            &[],
            &repo,
            &crawl_repo,
            &dedup,
        )
        .await
        .unwrap();
        // Only "good" link should be enqueued (bad excluded)
        assert_eq!(
            repo.create_count.load(Ordering::SeqCst),
            1,
            "excluded pattern links should be filtered"
        );
    }

    // update_crawl_completion_status (all paths)

    #[tokio::test]
    async fn test_update_crawl_completion_status_all_done_marks_completed() {
        // completed(3) + failed(2) == total(5) → should call update_status
        let crawl = Crawl::with_all_fields(
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            "test".into(),
            "https://example.com".into(),
            "https://example.com".into(),
            CrawlStatus::Processing,
            json!({}),
            5,
            3,
            2,
            Utc::now(),
            Utc::now(),
            None,
        );
        let repo = ConfigurableCrawlRepo::with_crawl(crawl);
        update_crawl_completion_status(crate::domain::id::Id::generate(), &repo).await;
        assert_eq!(
            repo.update_status_count.load(Ordering::SeqCst),
            1,
            "should mark completed when all tasks done"
        );
    }

    #[tokio::test]
    async fn test_update_crawl_completion_status_all_failed_marks_failed() {
        // completed(0) + failed(5) == total(5) → 全部失败必须标 Failed,
        // 不能 completed + 空结果(防静默假成功)
        let crawl = Crawl::with_all_fields(
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            "test".into(),
            "https://example.com".into(),
            "https://example.com".into(),
            CrawlStatus::Processing,
            json!({}),
            5,
            0,
            5,
            Utc::now(),
            Utc::now(),
            None,
        );
        let repo = ConfigurableCrawlRepo::with_crawl(crawl);
        update_crawl_completion_status(crate::domain::id::Id::generate(), &repo).await;
        assert_eq!(repo.update_status_count.load(Ordering::SeqCst), 1);
        assert_eq!(
            repo.last_status(),
            Some(CrawlStatus::Failed),
            "all-failed crawl must be marked Failed"
        );
    }

    #[tokio::test]
    async fn test_update_crawl_completion_status_not_yet_done() {
        // completed(1) + failed(0) != total(5) → should NOT call update_status
        let crawl = Crawl::with_all_fields(
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            "test".into(),
            "https://example.com".into(),
            "https://example.com".into(),
            CrawlStatus::Processing,
            json!({}),
            5,
            1,
            0,
            Utc::now(),
            Utc::now(),
            None,
        );
        let repo = ConfigurableCrawlRepo::with_crawl(crawl);
        update_crawl_completion_status(crate::domain::id::Id::generate(), &repo).await;
        assert_eq!(
            repo.update_status_count.load(Ordering::SeqCst),
            0,
            "should not mark completed when tasks pending"
        );
    }

    #[tokio::test]
    async fn test_update_crawl_completion_status_find_error() {
        // find_by_id returns Err → logs error, no panic
        struct ErrorCrawlRepo;
        #[async_trait::async_trait]
        impl CrawlRepository for ErrorCrawlRepo {
            async fn create(&self, crawl: &Crawl) -> Result<Crawl, RepositoryError> {
                Ok(crawl.clone())
            }
            async fn find_by_id(
                &self,
                _id: crate::domain::id::Id,
            ) -> Result<Option<Crawl>, RepositoryError> {
                Err(RepositoryError::Database(anyhow::anyhow!("db error")))
            }
            async fn update(&self, crawl: &Crawl) -> Result<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: CrawlStatus,
            ) -> Result<(), RepositoryError> {
                Ok(())
            }
            async fn increment_total_tasks(
                &self,
                _id: crate::domain::id::Id,
            ) -> Result<(), RepositoryError> {
                Ok(())
            }
            async fn find_by_team_id_paginated(
                &self,
                _team_id: crate::domain::id::Id,
                _limit: u32,
                _offset: u32,
            ) -> Result<Vec<Crawl>, RepositoryError> {
                Ok(vec![])
            }
            async fn count_by_team_id(
                &self,
                _team_id: crate::domain::id::Id,
            ) -> Result<u64, RepositoryError> {
                Ok(0)
            }
        }
        let repo = ErrorCrawlRepo;
        update_crawl_completion_status(crate::domain::id::Id::generate(), &repo).await;
        // No panic = success
    }

    // DB check path (MaybeExisting → find_existing_urls → second dedup)

    /// Mock task repo that returns existing URLs from find_existing_urls
    struct ExistingUrlTaskRepo {
        create_count: AtomicU32,
        existing_urls: HashSet<String>,
    }
    impl ExistingUrlTaskRepo {
        fn new_with_existing(urls: Vec<String>) -> Self {
            Self {
                create_count: AtomicU32::new(0),
                existing_urls: urls.into_iter().collect(),
            }
        }
    }
    #[async_trait::async_trait]
    impl TaskRepository for ExistingUrlTaskRepo {
        async fn create(&self, _task: &Task) -> Result<Task, RepositoryError> {
            self.create_count.fetch_add(1, Ordering::SeqCst);
            Ok(Task::new(
                crate::domain::id::Id::generate(),
                TaskType::Crawl,
                crate::domain::id::Id::generate(),
                crate::domain::id::Id::generate(),
                String::new(),
                json!({}),
            ))
        }
        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::new(
                crate::domain::id::Id::generate(),
                TaskType::Crawl,
                crate::domain::id::Id::generate(),
                crate::domain::id::Id::generate(),
                String::new(),
                json!({}),
            ))
        }
        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> {
            // Return only URLs that are in our "existing" set
            Ok(urls
                .iter()
                .filter(|u| self.existing_urls.contains(u.as_str()))
                .cloned()
                .collect())
        }
        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: 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)
        }
    }

    #[tokio::test]
    async fn test_extract_links_db_check_path_with_preinserted_urls() {
        let task = make_task("https://example.com/page");
        let html = r#"<html><body>
            <a href="https://example.com/new-link">New</a>
        </body></html>"#;
        let response = make_response("text/html", html);

        // Pre-insert the URL into deduplicator to trigger MaybeExisting path
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));
        {
            let mut d = dedup.write();
            d.insert("https://example.com/new-link");
        }

        // Repo says URL already exists → should skip (DB check finds it existing)
        let repo =
            ExistingUrlTaskRepo::new_with_existing(
                vec!["https://example.com/new-link".to_string()],
            );
        let crawl_repo = MockCrawlRepo::default();
        let config = default_config();

        extract_and_queue_links(
            &task,
            &response,
            crate::domain::id::Id::generate(),
            0,
            &config,
            &[],
            &repo,
            &crawl_repo,
            &dedup,
        )
        .await
        .unwrap();
        // URL found在 existing_urls 中 → to_db_insert 为空 → 不 create
        assert_eq!(
            repo.create_count.load(Ordering::SeqCst),
            0,
            "existing URLs should not be enqueued via DB check path"
        );
    }

    #[tokio::test]
    async fn test_extract_links_db_check_path_existing_url_skipped() {
        let task = make_task("https://example.com/page");
        let html = r#"<html><body>
            <a href="https://example.com/existing-link">Existing</a>
        </body></html>"#;
        let response = make_response("text/html", html);

        // Pre-insert to trigger MaybeExisting
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));
        {
            let mut d = dedup.write();
            d.insert("https://example.com/existing-link");
        }

        // Repo says this URL already exists → should NOT enqueue
        let repo = ExistingUrlTaskRepo::new_with_existing(vec![
            "https://example.com/existing-link".to_string(),
        ]);
        let crawl_repo = MockCrawlRepo::default();
        let config = default_config();

        extract_and_queue_links(
            &task,
            &response,
            crate::domain::id::Id::generate(),
            0,
            &config,
            &[],
            &repo,
            &crawl_repo,
            &dedup,
        )
        .await
        .unwrap();
        assert_eq!(
            repo.create_count.load(Ordering::SeqCst),
            0,
            "existing URLs should not be enqueued"
        );
    }

    /// P09 回归钉:布隆阳性 + DB 确认"不存在"的 URL 必须入队,不得静默丢弃。
    ///
    /// 修复前:二次 check_and_insert 必然复现 MaybeExisting(首轮已置位布隆),
    /// 走 continue 分支丢弃——to_db_enqueue 恒为空,假阳性变成永久漏抓。
    #[tokio::test]
    async fn test_extract_links_bloom_false_positive_enqueued_after_db_miss() {
        let task = make_task("https://example.com/page");
        let html = r#"<html><body>
            <a href="https://example.com/fresh-link">Fresh</a>
        </body></html>"#;
        let response = make_response("text/html", html);

        // 预插入目标 URL 使布隆阳性 → 触发 MaybeExisting / DB 校验路径
        let dedup = Arc::new(parking_lot::RwLock::new(Deduplicator::new()));
        {
            let mut d = dedup.write();
            d.insert("https://example.com/fresh-link");
        }

        // DB 判定该 URL 不存在(existing 集为空)→ 修复后必须入队
        let repo = ExistingUrlTaskRepo::new_with_existing(vec![]);
        let crawl_repo = MockCrawlRepo::default();
        let config = default_config();

        extract_and_queue_links(
            &task,
            &response,
            crate::domain::id::Id::generate(),
            0,
            &config,
            &[],
            &repo,
            &crawl_repo,
            &dedup,
        )
        .await
        .unwrap();
        assert_eq!(
            repo.create_count.load(Ordering::SeqCst),
            1,
            "DB-confirmed-new URL must be enqueued despite bloom positive (false positive must not cause missed URLs)"
        );
    }
}