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
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

use crate::application::use_cases::create_scrape::CreateScrapeUseCaseTrait;
use crate::domain::repositories::crawl_repository::CrawlRepository;
use crate::domain::repositories::credits_repository::CreditsRepository;
use crate::domain::repositories::scrape_result_repository::ScrapeResultRepository;
use crate::domain::repositories::task_repository::TaskRepository;
use crate::domain::services::searxng::SearxngInstanceService;
use crate::domain::services::team_semaphore::TeamSemaphore;
use crate::domain::services::webhook_service::WebhookService;
use crate::engines::engine_client::EngineClient;
use crate::infrastructure::oxcache::CacheService;
use crate::queue::task_queue::TaskQueue;
// 请求合并器(同 URL 并发只允许首个执行实际抓取)
use crate::workers::coalesce_coordinator::RequestCoalescer;
// CoalesceCoordinator(封装 try_coalesce 逻辑,注入 ScrapeWorker)
use crate::workers::coalesce_coordinator::CoalesceCoordinator;
use crate::workers::expiration_worker::ExpirationWorker;
use crate::workers::scrape_worker::{ScrapeWorker, ScrapeWorkerDeps};
// 优雅退出协调器
use crate::workers::shutdown::ShutdownCoordinator;
use crate::workers::{AbstractWorker, Worker};
use log::{error, info};
use std::sync::Arc;
use tokio::task::JoinHandle;

use crate::config::settings::Settings;
use crate::utils::robots::RobotsCheckerTrait;
// MemoryScheduler 接入 WorkerManager
#[cfg(feature = "metrics")]
use crate::workers::scheduler::memory_scheduler::MemoryScheduler;

/// 工作管理器
pub struct WorkerManager {
    queue: Arc<dyn TaskQueue>,
    repository: Arc<dyn TaskRepository>,
    result_repository: Arc<dyn ScrapeResultRepository>,
    crawl_repository: Arc<dyn CrawlRepository>,
    webhook_service: Arc<dyn WebhookService>,
    credits_repository: Arc<dyn CreditsRepository>,
    engine_client: Arc<EngineClient>,
    create_scrape_use_case: Arc<dyn CreateScrapeUseCaseTrait>,
    team_semaphore: Arc<TeamSemaphore>,
    /// 请求合并器
    ///
    /// 由 `WorkerManagerDeps` 从 `ServicesComponents.request_coalescer` 注入,
    /// 所有 worker 共享同一实例。
    request_coalescer: Arc<RequestCoalescer>,
    /// 请求合并协调器
    ///
    /// 由 `WorkerManager::new` 从 `repository` + `result_repository` +
    /// `request_coalescer` 构造,封装 `try_coalesce` 逻辑。所有 worker 共享
    /// 同一实例(通过 `Arc` clone 注入)。
    coalesce_coordinator: Arc<CoalesceCoordinator>,
    robots_checker: Arc<dyn RobotsCheckerTrait>,
    settings: Arc<Settings>,
    default_concurrency_limit: usize,
    handles: Vec<JoinHandle<()>>,
    /// SearXNG 实例生命周期服务(disabled 时 None,不拉起周期 worker)
    searxng_instances: Option<Arc<dyn SearxngInstanceService>>,
    extraction_service:
        Arc<dyn crate::domain::services::extraction_service::ExtractionServiceTrait>,
    /// 带质量门的内容提取 Facade(所有 worker 共享同一实例)
    #[cfg(feature = "content")]
    content_extractor: Arc<crate::domain::services::content_extractor::ContentExtractionFacade>,
    /// 内存感知调度器
    ///
    /// 由 `WorkerManager::new` 从 `shared_system_monitor()` + `ConcurrencySettings`
    /// 阈值构造,所有 worker 共享同一实例。
    #[cfg(feature = "metrics")]
    memory_scheduler: Arc<MemoryScheduler>,
    /// URL 分层去重器
    ///
    /// 所有 worker 共享同一实例,最大化 Bloom 预筛效果。
    /// `RwLock` 因为 Bloom insert 需 `&mut self`,contains 只需 `&self`。
    deduplicator: Arc<parking_lot::RwLock<crate::utils::dedup::Deduplicator>>,
    /// 高级缓存服务
    ///
    /// 由 `WorkerManagerDeps` 从 `InfrastructureComponents.cache_service` 注入,
    /// 所有 worker 共享同一实例,用于 `process_scrape_task` 读写抓取结果缓存。
    cache_service: Arc<dyn CacheService>,
    /// 优雅退出协调器
    ///
    /// 由 main.rs 创建并通过 `WorkerManagerDeps` 注入,所有 worker 共享同一实例。
    /// `start_workers` 注入到每个 `ScrapeWorker`,关闭信号到达后 worker 循环
    /// 停止接受新任务并在完成当前任务后退出。
    shutdown_coordinator: Arc<ShutdownCoordinator>,
    /// 本进程已启动 worker 的认领身份(worker_id 即任务 lock_token)
    ///
    /// 优雅停机回滚在途任务时据此限定回滚范围,
    /// 防止多副本部署下误回滚其他副本正在执行的任务。
    worker_ids: parking_lot::Mutex<Vec<crate::domain::id::Id>>,
}

/// Worker Manager Dependencies
pub struct WorkerManagerDeps {
    pub queue: Arc<dyn TaskQueue>,
    pub repository: Arc<dyn TaskRepository>,
    pub result_repository: Arc<dyn ScrapeResultRepository>,
    pub crawl_repository: Arc<dyn CrawlRepository>,
    pub webhook_service: Arc<dyn WebhookService>,
    pub credits_repository: Arc<dyn CreditsRepository>,
    pub engine_client: Arc<EngineClient>,
    pub create_scrape_use_case: Arc<dyn CreateScrapeUseCaseTrait>,
    pub team_semaphore: Arc<TeamSemaphore>,
    /// 请求合并器
    pub request_coalescer: Arc<RequestCoalescer>,
    pub robots_checker: Arc<dyn RobotsCheckerTrait>,
    pub http_client: Arc<reqwest::Client>,
    pub extraction_service:
        Arc<dyn crate::domain::services::extraction_service::ExtractionServiceTrait>,
    /// 带质量门的内容提取 Facade(bootstrap 按 `content_extraction` 装配)
    #[cfg(feature = "content")]
    pub content_extractor: Arc<crate::domain::services::content_extractor::ContentExtractionFacade>,
    /// 高级缓存服务
    pub cache_service: Arc<dyn CacheService>,
    /// 优雅退出协调器
    pub shutdown_coordinator: Arc<ShutdownCoordinator>,
    /// SearXNG 实例生命周期服务(`search.searxng.enabled = false` 时为 None)
    pub searxng_instances: Option<Arc<dyn SearxngInstanceService>>,
}

/// Worker Manager Configuration
pub struct WorkerManagerConfig {
    pub settings: Arc<Settings>,
    pub default_concurrency_limit: usize,
}

impl WorkerManager {
    pub fn new(deps: WorkerManagerDeps, config: WorkerManagerConfig) -> Self {
        // 构造内存感知调度器
        //
        // 复用 `shared_system_monitor()` 全局单例(init_metrics 启动时已初始化),
        // 从 `ConcurrencySettings` 读取阈值(pressure/critical/timeout)。
        #[cfg(feature = "metrics")]
        let memory_scheduler = {
            use crate::infrastructure::observability::metrics::{
                shared_system_monitor, SystemMonitorTrait,
            };
            Arc::new(MemoryScheduler::new(
                shared_system_monitor() as Arc<dyn SystemMonitorTrait>,
                config.settings.concurrency.mem_pressure_threshold,
                config.settings.concurrency.mem_critical_threshold,
                std::time::Duration::from_secs(
                    config.settings.concurrency.critical_timeout_seconds,
                ),
            ))
        };

        // 在 move 前构造 CoalesceCoordinator,共享 repository +
        // result_repository + request_coalescer(所有 worker 共享同一实例)
        let coalesce_coordinator = Arc::new(CoalesceCoordinator::new(
            deps.repository.clone(),
            deps.result_repository.clone(),
            deps.request_coalescer.clone(),
        ));

        Self {
            queue: deps.queue,
            repository: deps.repository,
            result_repository: deps.result_repository,
            crawl_repository: deps.crawl_repository,
            webhook_service: deps.webhook_service,
            credits_repository: deps.credits_repository,
            engine_client: deps.engine_client,
            create_scrape_use_case: deps.create_scrape_use_case,
            team_semaphore: deps.team_semaphore,
            coalesce_coordinator,
            request_coalescer: deps.request_coalescer,
            robots_checker: deps.robots_checker,
            settings: config.settings,
            default_concurrency_limit: config.default_concurrency_limit,
            handles: Vec::new(),
            extraction_service: deps.extraction_service,
            #[cfg(feature = "content")]
            content_extractor: deps.content_extractor,
            #[cfg(feature = "metrics")]
            memory_scheduler,
            // 所有 worker 共享 Deduplicator 实例
            // 共享 Bloom 让已爬 URL 在任一 worker 触发后立即对其他 worker 可见,
            // 最大化降 DB 查询量效果。
            deduplicator: Arc::new(parking_lot::RwLock::new(
                crate::utils::dedup::Deduplicator::new(),
            )),
            // 所有 worker 共享 CacheService 实例
            cache_service: deps.cache_service,
            searxng_instances: deps.searxng_instances,
            shutdown_coordinator: deps.shutdown_coordinator,
            worker_ids: parking_lot::Mutex::new(Vec::new()),
        }
    }

    /// 从 DB 分页预热去重器(P10 + F3 差量)
    ///
    /// 重启后进程内布隆/HashSet 全空,所有链接会走 `DefinitelyNew` 快路径
    /// 绕过 DB 校验 → 全站重爬。启动时把 tasks 表的 distinct URL 灌回
    /// Deduplicator(幂等:重复灌入只影响布隆位图,HashSet 自动去重);
    /// `workers.dedup_warmup_include_results = true` 时追加灌入
    /// scrape_results 表 distinct URL(覆盖 tasks.url 之外的重定向
    /// final_url)。
    ///
    /// 失败显性化:任一页失败打 error 日志(含后果说明)并中止对应阶段。
    /// tasks 阶段失败 → 以空去重状态继续运行(预热是优化,不阻塞可用性);
    /// results 阶段失败 → 保留 tasks 阶段已灌入的状态,不回滚不 panic。
    async fn warmup_deduplicator(&self) {
        const PAGE_SIZE: u32 = 5000;

        // tasks 表阶段(恒定执行)
        match self
            .warmup_dedup_from(|after| self.repository.list_distinct_urls(PAGE_SIZE, after))
            .await
        {
            Ok(total) if total > 0 => {
                info!("Deduplicator warmed up with {total} distinct URLs from previous runs");
            }
            Ok(_) => {}
            Err((after_url, e)) => {
                error!(
                    "Deduplicator warmup failed at cursor {after_url:?}: {e}; \
                     continuing with EMPTY dedup state — already-crawled URLs \
                     will be re-crawled this run"
                );
                return;
            }
        }

        // scrape_results 表阶段(F3 差量,默认关:结果表含保留期内全部
        // 抓取 URL,量大;显式开启后覆盖重定向 final_url)
        if !self.settings.workers.dedup_warmup_include_results {
            return;
        }
        match self
            .warmup_dedup_from(|after| self.result_repository.list_distinct_urls(PAGE_SIZE, after))
            .await
        {
            Ok(total) if total > 0 => {
                info!(
                    "Deduplicator warmup: +{total} distinct URLs from scrape_results \
                     (redirect targets included)"
                );
            }
            Ok(_) => {}
            Err((after_url, e)) => {
                error!(
                    "Deduplicator warmup failed on scrape_results phase at cursor \
                     {after_url:?}: {e}; keeping URLs already warmed from tasks — \
                     redirect final_urls may be re-crawled this run"
                );
            }
        }
    }

    /// keyset 分页灌入单一仓库的 distinct URL(`url > 上一页末条`),
    /// 返回灌入总数;失败时携带失败时刻的游标(供日志定位)。
    async fn warmup_dedup_from<F, Fut, E>(&self, mut fetch: F) -> Result<usize, (Option<String>, E)>
    where
        F: FnMut(Option<String>) -> Fut,
        Fut: std::future::Future<Output = Result<Vec<String>, E>>,
    {
        const PAGE_SIZE: u32 = 5000;
        let mut after_url: Option<String> = None;
        let mut total: usize = 0;

        loop {
            let urls = match fetch(after_url.clone()).await {
                Ok(urls) => urls,
                Err(e) => return Err((after_url, e)),
            };

            let page_len = urls.len();
            if page_len > 0 {
                let mut dedup = self.deduplicator.write();
                dedup.extend(urls.iter().map(String::as_str));
                total += page_len;
                after_url = urls.into_iter().last();
            }
            if page_len < PAGE_SIZE as usize {
                break;
            }
        }

        Ok(total)
    }

    /// 启动工作进程
    ///
    /// 创建并启动指定数量的工作进程
    ///
    /// # 参数
    ///
    /// * `count` - 要启动的工作进程数量
    pub async fn start_workers(&mut self, count: usize) {
        // P10:去重状态启动预热——从 DB 分页灌入已爬 URL,
        // 否则重启后布隆全空,所有链接走 DefinitelyNew 快路径 → 全站重爬
        self.warmup_deduplicator().await;

        self.spawn_expiration_worker();
        self.spawn_searxng_workers();
        self.spawn_coalescer_purge();

        for _ in 0..count {
            self.spawn_scrape_worker();
        }
    }

    /// 启动过期清理工作器(使用新模板模式)
    fn spawn_expiration_worker(&mut self) {
        let expiration_processor = Arc::new(ExpirationWorker::new(
            self.repository.clone(),
            self.result_repository.clone(),
            self.settings.retention.scrape_results_days,
        ));
        let expiration_worker =
            AbstractWorker::new(expiration_processor, std::time::Duration::from_secs(3600));
        self.handles.push(tokio::spawn(async move {
            expiration_worker.run().await;
        }));
    }

    /// SearXNG 双周期 worker(enabled 门控与 spawn_common_workers 一致):
    /// 采集轮 PG advisory lock 防重、探活幂等,api/worker 双进程并发安全。
    fn spawn_searxng_workers(&mut self) {
        if let Some(searxng) = self.searxng_instances.clone() {
            let collector = AbstractWorker::new(
                Arc::new(
                    crate::workers::searxng_collector_worker::SearxngCollectorWorker::new(
                        searxng.clone(),
                    ),
                ),
                std::time::Duration::from_secs(
                    self.settings.search.searxng.collector.interval_seconds,
                ),
            );
            self.handles.push(tokio::spawn(async move {
                collector.run().await;
            }));

            let health = AbstractWorker::new(
                Arc::new(crate::workers::searxng_health_worker::SearxngHealthWorker::new(searxng)),
                std::time::Duration::from_secs(
                    self.settings.search.searxng.health.interval_seconds,
                ),
            );
            self.handles.push(tokio::spawn(async move {
                health.run().await;
            }));
        }
    }

    /// 定期调度 RequestCoalescer::purge_stale
    ///
    /// worker panic / 死锁可能导致 CoalesceGuard 未 Drop,使 in-flight 条目
    /// 永久驻留 DashMap 阻塞同 URL 后续请求。每 60s 调用 purge_stale 清理
    /// 僵死条目(STALE_TIMEOUT=120s),并通过 broadcast 通知等待方重试。
    fn spawn_coalescer_purge(&mut self) {
        let coalescer_for_purge = self.request_coalescer.clone();
        let shutdown_for_purge = self.shutdown_coordinator.clone();
        self.handles.push(tokio::spawn(async move {
            let mut interval = tokio::time::interval(std::time::Duration::from_secs(60));
            interval.tick().await; // 跳过首次立即触发
            loop {
                interval.tick().await;
                // 检查关闭信号,避免关闭后继续无意义循环
                if shutdown_for_purge.is_shutting_down() {
                    info!("purge_stale loop exiting due to shutdown");
                    break;
                }
                let purged = coalescer_for_purge.purge_stale();
                if purged > 0 {
                    info!("purge_stale cleaned up {} zombie coalesce entries", purged);
                }
            }
        }));
    }

    /// 构造并启动单个 ScrapeWorker(注入共享 deduplicator 与优雅退出协调器)。
    fn spawn_scrape_worker(&mut self) {
        let worker = ScrapeWorker::new(ScrapeWorkerDeps {
            repository: self.repository.clone(),
            result_repository: self.result_repository.clone(),
            crawl_repository: self.crawl_repository.clone(),
            webhook_service: self.webhook_service.clone(),
            credits_repository: self.credits_repository.clone(),
            engine_client: self.engine_client.clone(),
            create_scrape_use_case: self.create_scrape_use_case.clone(),
            team_semaphore: self.team_semaphore.clone(),
            coalesce_coordinator: self.coalesce_coordinator.clone(),
            robots_checker: self.robots_checker.clone(),
            settings: self.settings.clone(),
            default_concurrency_limit: self.default_concurrency_limit,
            extraction_service: self.extraction_service.clone(),
            #[cfg(feature = "content")]
            content_extractor: self.content_extractor.clone(),
            cache_service: self.cache_service.clone(),
            #[cfg(feature = "metrics")]
            memory_scheduler: self.memory_scheduler.clone(),
        })
        // 注入共享优雅退出协调器
        .with_shutdown_coordinator(self.shutdown_coordinator.clone())
        // 注入共享 deduplicator(替换 ScrapeWorker::new 内部默认实例)
        .with_deduplicator_opt(Some(self.deduplicator.clone()));

        // 记录本 worker 的认领身份(lock_token),供停机回滚限定范围
        self.worker_ids.lock().push(worker.worker_id());

        let queue = self.queue.clone();
        // We spawn the worker loop on a separate task to avoid blocking the main thread
        // or the loop that spawns workers.
        let handle = tokio::spawn(async move {
            worker.run(queue).await;
        });
        self.handles.push(handle);
    }

    /// 本进程所有已启动 worker 的认领身份(worker_id == 任务 lock_token)。
    ///
    /// 供优雅停机回滚(`rollback_pending_tasks`)限定回滚范围:
    /// 只回滚本进程认领的在途任务。
    pub fn worker_ids(&self) -> Vec<crate::domain::id::Id> {
        self.worker_ids.lock().clone()
    }

    /// 触发优雅退出
    ///
    /// 等价于信号监听任务(`listen_unix_signals`)收到 SIGTERM/SIGINT 后
    /// 调用 `ShutdownCoordinator::trigger()`。置位后各 worker 循环停止接受
    /// 新任务,完成当前任务后退出。
    pub fn begin_shutdown(&self) {
        self.shutdown_coordinator.trigger();
    }

    /// 等待关闭并优雅终止所有工作进程
    ///
    /// 依赖注入的 `ShutdownCoordinator`:
    /// - `wait_for_completion()` 阻塞等待关闭信号,并在关闭后给进行中的任务
    ///   至多 `graceful_period` 的宽限期完成
    /// - 宽限期结束后 abort 所有剩余句柄(含不检查关闭 flag 的辅助 worker:
    ///   expiration / purge_stale 等无限循环),强制退出。
    pub async fn wait_for_shutdown(&mut self) {
        let _ = self.shutdown_coordinator.wait_for_completion().await;

        info!("Shutting down workers...");
        let handles = std::mem::take(&mut self.handles);
        for handle in &handles {
            handle.abort();
        }
        // abort 后 await 所有 handles,确保任务真正退出
        // 带 5s 超时防止某个 handle 卡死阻塞关闭流程
        for handle in handles {
            let _ = tokio::time::timeout(std::time::Duration::from_secs(5), async {
                let _ = handle.await;
            })
            .await;
        }

        info!("Workers shut down successfully");
    }
}

impl Drop for WorkerManager {
    fn drop(&mut self) {
        // Abort all worker handles to prevent them from running after the manager is dropped
        for handle in &self.handles {
            handle.abort();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ========== WorkerManagerConfig construction ==========

    #[test]
    fn test_worker_manager_config_construction() {
        let settings = Arc::new(Settings::default());
        let config = WorkerManagerConfig {
            settings: settings.clone(),
            default_concurrency_limit: 10,
        };
        assert_eq!(config.default_concurrency_limit, 10);
        assert_eq!(Arc::strong_count(&config.settings), 2);
    }

    #[test]
    fn test_worker_manager_config_with_different_concurrency() {
        let settings = Arc::new(Settings::default());
        let config = WorkerManagerConfig {
            settings,
            default_concurrency_limit: 50,
        };
        assert_eq!(config.default_concurrency_limit, 50);
    }

    #[test]
    fn test_worker_manager_config_concurrency_zero() {
        let settings = Arc::new(Settings::default());
        let config = WorkerManagerConfig {
            settings,
            default_concurrency_limit: 0,
        };
        assert_eq!(config.default_concurrency_limit, 0);
    }

    #[test]
    fn test_worker_manager_config_settings_shared() {
        let settings = Arc::new(Settings::default());
        let config1 = WorkerManagerConfig {
            settings: settings.clone(),
            default_concurrency_limit: 5,
        };
        let config2 = WorkerManagerConfig {
            settings: settings.clone(),
            default_concurrency_limit: 15,
        };
        // Both configs share the same Arc<Settings>
        assert!(Arc::ptr_eq(&config1.settings, &config2.settings));
    }

    // ========== EngineClient construction ==========

    #[test]
    fn test_engine_client_can_be_constructed() {
        let client = EngineClient::new();
        // Verify it can be cloned (required by WorkerManager)
        let _cloned = client.clone();
    }

    // ========== TeamSemaphore construction (in-memory, no external service) ==========

    #[test]
    fn test_team_semaphore_can_be_constructed() {
        // TeamSemaphore is an in-memory primitive — no external service required.
        let sem = TeamSemaphore::new(10);
        // Verify behavior: acquiring a permit should succeed (limit is 10)
        let team_id = crate::domain::id::Id::generate();
        assert!(sem.try_acquire(team_id).is_some());
    }

    #[test]
    fn test_team_semaphore_clone_shares_state() {
        let sem = TeamSemaphore::new(1);
        let cloned = sem.clone();
        // Both clones share the same internal DashMap
        let team_id = crate::domain::id::Id::generate();
        // Acquire from original — exhausts the single permit
        let _permit = sem
            .try_acquire(team_id)
            .expect("first acquire should succeed");
        // Cloned should also see the exhausted state (shared internal map)
        assert!(cloned.try_acquire(team_id).is_none());
    }

    // ========== WorkerManagerDeps field types verification ==========
    // Note: Full construction of WorkerManagerDeps requires mocking 9+ traits,
    // which is impractical for unit tests. We verify the struct can be referenced
    // and its fields have the expected types.

    #[test]
    fn test_worker_manager_deps_struct_exists() {
        // Verify the struct can be referenced (compile-time check)
        fn _assert_deps_type(_deps: WorkerManagerDeps) {}
        // This function existing proves the struct is accessible
    }

    #[test]
    fn test_worker_manager_config_struct_exists() {
        fn _assert_config_type(_config: WorkerManagerConfig) {}
    }

    #[test]
    fn test_worker_manager_struct_exists() {
        fn _assert_manager_type(_manager: WorkerManager) {}
    }

    // ========== WorkerManagerConfig additional tests ==========

    #[test]
    fn test_worker_manager_config_large_concurrency() {
        let settings = Arc::new(Settings::default());
        let config = WorkerManagerConfig {
            settings,
            default_concurrency_limit: usize::MAX,
        };
        assert_eq!(config.default_concurrency_limit, usize::MAX);
    }

    #[test]
    fn test_worker_manager_config_one_concurrency() {
        let settings = Arc::new(Settings::default());
        let config = WorkerManagerConfig {
            settings,
            default_concurrency_limit: 1,
        };
        assert_eq!(config.default_concurrency_limit, 1);
    }

    #[test]
    fn test_worker_manager_config_settings_arc_count_increases() {
        let settings = Arc::new(Settings::default());
        let initial_count = Arc::strong_count(&settings);
        let _config = WorkerManagerConfig {
            settings: settings.clone(),
            default_concurrency_limit: 10,
        };
        let after_count = Arc::strong_count(&settings);
        assert_eq!(after_count, initial_count + 1);
    }

    #[test]
    fn test_worker_manager_config_settings_arc_count_decreces_on_drop() {
        let settings = Arc::new(Settings::default());
        {
            let _config = WorkerManagerConfig {
                settings: settings.clone(),
                default_concurrency_limit: 10,
            };
            assert!(Arc::strong_count(&settings) > 1);
        }
        // After config goes out of scope, count should decrease
        assert_eq!(Arc::strong_count(&settings), 1);
    }

    #[test]
    fn test_multiple_configs_sharing_same_settings() {
        let settings = Arc::new(Settings::default());
        let configs: Vec<WorkerManagerConfig> = (0..5)
            .map(|i| WorkerManagerConfig {
                settings: settings.clone(),
                default_concurrency_limit: i * 10,
            })
            .collect();
        // All configs should share the same Arc
        for config in &configs {
            assert!(Arc::ptr_eq(&config.settings, &settings));
        }
        assert_eq!(configs.len(), 5);
        assert_eq!(configs[0].default_concurrency_limit, 0);
        assert_eq!(configs[4].default_concurrency_limit, 40);
    }

    // ========== EngineClient additional tests ==========

    #[test]
    fn test_engine_client_clone_preserves_identity() {
        let client = EngineClient::new();
        let cloned = client.clone();
        // Both should be usable independently
        let _another_clone = cloned.clone();
    }

    #[test]
    fn test_engine_client_multiple_instances() {
        let client1 = EngineClient::new();
        let client2 = EngineClient::new();
        // Both should be independently usable
        let _both = (client1, client2);
    }

    // ========== Settings default values ==========

    #[test]
    fn test_settings_default_is_constructible() {
        let settings1 = Settings::default();
        let settings2 = Settings::default();
        // Each Settings::default() should create an independent instance
        let _ = (settings1, settings2);
    }

    #[test]
    fn test_settings_can_be_cloned() {
        let settings = Settings::default();
        let _cloned = settings.clone();
    }

    // ========== TeamSemaphore additional tests ==========

    #[tokio::test]
    async fn test_team_semaphore_acquire_returns_permit() {
        let sem = TeamSemaphore::new(3);
        let team_id = crate::domain::id::Id::generate();
        let permit = sem.acquire(team_id).await;
        assert!(permit.is_ok());
    }

    #[test]
    fn test_team_semaphore_try_acquire_respects_limit() {
        let sem = TeamSemaphore::new(1);
        let team_id = crate::domain::id::Id::generate();
        let p1 = sem.try_acquire(team_id);
        assert!(p1.is_some());
        // Limit is 1, second acquire should fail
        let p2 = sem.try_acquire(team_id);
        assert!(p2.is_none());
    }

    // ========== WorkerManagerDeps field verification ==========

    #[test]
    fn test_worker_manager_deps_has_expected_fields() {
        // Compile-time verification that WorkerManagerDeps has the expected fields
        // by constructing it field-by-field (partially, to verify field names)
        let settings = Arc::new(Settings::default());

        // Verify WorkerManagerConfig fields
        let config = WorkerManagerConfig {
            settings: settings.clone(),
            default_concurrency_limit: 10,
        };
        // Access fields to verify they exist
        let _limit = config.default_concurrency_limit;
        let _settings_ref = &config.settings;
    }

    // ========== WorkerManager Drop behavior ==========

    #[test]
    fn test_worker_manager_drop_aborts_handles() {
        // WorkerManager::new requires full deps which is impractical to construct.
        // Instead, verify that the type requires Drop (has a non-trivial destructor)
        // by checking std::mem::needs_drop at compile time.
        assert!(std::mem::needs_drop::<WorkerManager>());
    }

    // ========== WorkerManagerConfig Send + Sync verification ==========

    #[test]
    fn test_worker_manager_config_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<WorkerManagerConfig>();
    }

    #[test]
    fn test_worker_manager_config_arc_settings_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Arc<Settings>>();
    }

    // ========== Concurrency limit boundary values ==========

    #[test]
    fn test_concurrency_limit_boundary_values() {
        let settings = Arc::new(Settings::default());
        // Test various boundary values
        for &limit in &[0usize, 1, 10, 100, 1000] {
            let config = WorkerManagerConfig {
                settings: settings.clone(),
                default_concurrency_limit: limit,
            };
            assert_eq!(config.default_concurrency_limit, limit);
        }
    }

    // ========== WorkerManager Send + Sync verification ==========

    #[test]
    fn test_worker_manager_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<WorkerManager>();
    }

    #[test]
    fn test_worker_manager_deps_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<WorkerManagerDeps>();
    }

    // ========== WorkerManagerConfig memory size ==========

    #[test]
    fn test_worker_manager_config_size_is_reasonable() {
        // WorkerManagerConfig contains an Arc<Settings> and a usize.
        // Arc is pointer-sized (8 bytes on 64-bit), usize is 8 bytes.
        // The struct should be 16 bytes (no padding needed).
        let size = std::mem::size_of::<WorkerManagerConfig>();
        assert!(size > 0);
        assert!(
            size <= 32,
            "WorkerManagerConfig size {} seems too large",
            size
        );
    }

    // ========== WorkerManager handles field verification ==========

    #[test]
    fn test_worker_manager_has_handles_field() {
        // Verify that WorkerManager has a handles field of type Vec<JoinHandle<()>>
        // by checking the type at compile time.
        fn _assert_handles_type(_handles: Vec<JoinHandle<()>>) {}
        // This function existing proves the type is accessible
    }

    // ========== WorkerManagerConfig default_concurrency_limit range ==========

    #[test]
    fn test_concurrency_limit_powers_of_two() {
        let settings = Arc::new(Settings::default());
        for &limit in &[1usize, 2, 4, 8, 16, 32, 64, 128, 256] {
            let config = WorkerManagerConfig {
                settings: settings.clone(),
                default_concurrency_limit: limit,
            };
            assert_eq!(config.default_concurrency_limit, limit);
        }
    }

    // ========== Settings Arc sharing across configs ==========

    #[test]
    fn test_settings_arc_strong_count_with_many_configs() {
        let settings = Arc::new(Settings::default());
        let configs: Vec<_> = (0..10)
            .map(|_| WorkerManagerConfig {
                settings: settings.clone(),
                default_concurrency_limit: 5,
            })
            .collect();
        // 10 configs + original = 11 strong references
        assert_eq!(Arc::strong_count(&settings), 11);
        assert_eq!(configs.len(), 10);
    }

    #[test]
    fn test_settings_arc_count_decreases_after_config_drop() {
        let settings = Arc::new(Settings::default());
        let initial = Arc::strong_count(&settings);
        {
            let _config1 = WorkerManagerConfig {
                settings: settings.clone(),
                default_concurrency_limit: 1,
            };
            let _config2 = WorkerManagerConfig {
                settings: settings.clone(),
                default_concurrency_limit: 2,
            };
            assert_eq!(Arc::strong_count(&settings), initial + 2);
        }
        // After configs are dropped, count returns to initial
        assert_eq!(Arc::strong_count(&settings), initial);
    }

    // ========== WorkerManager Drop impl verification ==========

    #[test]
    fn test_worker_manager_needs_drop_is_true() {
        // WorkerManager implements Drop, so needs_drop should be true
        assert!(std::mem::needs_drop::<WorkerManager>());
    }

    #[test]
    fn test_worker_manager_drop_is_not_noop() {
        // Verify WorkerManager has a non-trivial Drop (handles are aborted on drop).
        // needs_drop is true when the type or any field requires Drop.
        assert!(std::mem::needs_drop::<WorkerManager>());
    }

    // ========== WorkerManager method integration tests ==========
    //
    // The following tests exercise WorkerManager::new(), start_workers(),
    // wait_for_shutdown(), and Drop by constructing a full WorkerManagerDeps
    // with no-op mock implementations of all required traits.

    use crate::application::dto::scrape_request::ScrapeRequestDto;
    use crate::domain::models::{
        Crawl, CrawlStatus, CreditsTransaction, CreditsTransactionType, DomainError, ScrapeResult,
        Task, WebhookEvent,
    };
    use crate::domain::repositories::credits_repository::CreditsRepositoryError;
    use crate::domain::repositories::task_repository::{RepositoryError, TaskQueryParams};
    use crate::domain::services::extraction_service::{ExtractionRule, ExtractionServiceTrait};
    use crate::domain::services::llm::TokenUsage;
    use crate::engines::engine_client::ScrapeResponse;
    use crate::queue::task_queue::QueueError;
    use async_trait::async_trait;
    use serde_json::Value;
    use std::collections::{HashMap, HashSet};

    // ---- No-op mock implementations ----

    struct MockTaskQueue;

    #[async_trait]
    impl TaskQueue for MockTaskQueue {
        async fn enqueue(&self, task: Task) -> Result<Task, QueueError> {
            Ok(task)
        }
        async fn dequeue(
            &self,
            _worker_id: crate::domain::id::Id,
        ) -> Result<Option<Task>, QueueError> {
            Ok(None)
        }
        async fn complete(&self, _task_id: crate::domain::id::Id) -> Result<(), QueueError> {
            Ok(())
        }
        async fn fail(&self, _task_id: crate::domain::id::Id) -> Result<(), QueueError> {
            Ok(())
        }
        async fn cancel(&self, _task_id: crate::domain::id::Id) -> Result<(), QueueError> {
            Ok(())
        }
    }

    /// 可注入预热 URL 的任务仓库 mock
    ///
    /// `warmup_urls` 非空时 `list_distinct_urls` 返回它们(一页内,循环终止),
    /// 空(Default)时返回空页——预热循环一轮即结束,既有用例不受影响。
    #[derive(Default)]
    struct MockTaskRepository {
        warmup_urls: Vec<String>,
    }

    #[async_trait]
    impl TaskRepository for MockTaskRepository {
        async fn create(&self, task: &Task) -> Result<Task, RepositoryError> {
            Ok(task.clone())
        }
        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(None)
        }
        async fn update(&self, task: &Task) -> Result<Task, RepositoryError> {
            Ok(task.clone())
        }
        async fn acquire_next(
            &self,
            _worker_id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(None)
        }
        async fn mark_completed(
            &self,
            _id: crate::domain::id::Id,
            _lock_token: Option<crate::domain::id::Id>,
        ) -> Result<u64, RepositoryError> {
            Ok(1)
        }
        async fn mark_failed(
            &self,
            _id: crate::domain::id::Id,
            _lock_token: Option<crate::domain::id::Id>,
        ) -> Result<u64, RepositoryError> {
            Ok(1)
        }
        async fn mark_cancelled(&self, _id: crate::domain::id::Id) -> Result<u64, RepositoryError> {
            Ok(1)
        }
        async fn exists_by_url(&self, _url: &str) -> Result<bool, RepositoryError> {
            Ok(false)
        }
        async fn find_existing_urls(
            &self,
            _urls: &[String],
        ) -> Result<HashSet<String>, RepositoryError> {
            Ok(HashSet::new())
        }
        async fn list_distinct_urls(
            &self,
            _limit: u32,
            _after_url: Option<String>,
        ) -> Result<Vec<String>, RepositoryError> {
            Ok(self.warmup_urls.clone())
        }
        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)
        }
    }

    /// 可注入预热 URL / 注入失败的 结果仓库 mock
    ///
    /// `warmup_urls` 非空时 `list_distinct_urls` 返回它们(一页内,循环终止),
    /// 空(Default)时返回空页;`fail_list_distinct` 为 true 时返回错误
    /// (F3 results 阶段失败语义验证用)。
    #[derive(Default)]
    struct MockScrapeResultRepository {
        warmup_urls: Vec<String>,
        fail_list_distinct: bool,
    }

    #[async_trait]
    impl ScrapeResultRepository for MockScrapeResultRepository {
        async fn save(&self, _result: ScrapeResult) -> anyhow::Result<()> {
            Ok(())
        }
        async fn find_by_task_id(
            &self,
            _task_id: crate::domain::id::Id,
        ) -> anyhow::Result<Option<ScrapeResult>> {
            Ok(None)
        }
        async fn find_by_task_ids(
            &self,
            _task_ids: &[crate::domain::id::Id],
        ) -> anyhow::Result<Vec<ScrapeResult>> {
            Ok(vec![])
        }
        async fn get_team_avg_response_time(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> anyhow::Result<f64> {
            Ok(0.0)
        }

        async fn cleanup_expired(&self, _retention_days: i64) -> anyhow::Result<u64> {
            Ok(0)
        }

        async fn list_distinct_urls(
            &self,
            _limit: u32,
            _after_url: Option<String>,
        ) -> anyhow::Result<Vec<String>> {
            if self.fail_list_distinct {
                return Err(anyhow::anyhow!("mock results list_distinct_urls failure"));
            }
            Ok(self.warmup_urls.clone())
        }
    }

    struct MockCrawlRepository;

    #[async_trait]
    impl CrawlRepository for MockCrawlRepository {
        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> {
            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)
        }
    }

    struct MockWebhookService;

    #[async_trait]
    impl WebhookService for MockWebhookService {
        async fn send_webhook(&self, _event: &WebhookEvent) -> anyhow::Result<u16> {
            Ok(200)
        }
        async fn trigger_completion(&self, _task: &Task) -> anyhow::Result<()> {
            Ok(())
        }
        async fn trigger_failure(&self, _task: &Task, _error_msg: String) -> anyhow::Result<()> {
            Ok(())
        }
    }

    struct MockCreditsRepository;

    #[async_trait]
    impl CreditsRepository for MockCreditsRepository {
        async fn get_balance(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<i64, CreditsRepositoryError> {
            Ok(0)
        }
        async fn deduct_credits(
            &self,
            _team_id: crate::domain::id::Id,
            _amount: i64,
            _transaction_type: CreditsTransactionType,
            _description: String,
            _reference_id: Option<crate::domain::id::Id>,
        ) -> Result<(), CreditsRepositoryError> {
            Ok(())
        }
        async fn add_credits(
            &self,
            _team_id: crate::domain::id::Id,
            _amount: i64,
            _transaction_type: CreditsTransactionType,
            _description: String,
            _reference_id: Option<crate::domain::id::Id>,
        ) -> Result<i64, CreditsRepositoryError> {
            Ok(0)
        }
        async fn get_transaction_history(
            &self,
            _team_id: crate::domain::id::Id,
            _limit: Option<u32>,
        ) -> Result<Vec<CreditsTransaction>, CreditsRepositoryError> {
            Ok(vec![])
        }
        async fn initialize_team_credits(
            &self,
            _team_id: crate::domain::id::Id,
            _initial_balance: i64,
        ) -> Result<i64, CreditsRepositoryError> {
            Ok(0)
        }
    }

    struct MockCreateScrapeUseCase;

    #[async_trait]
    impl CreateScrapeUseCaseTrait for MockCreateScrapeUseCase {
        async fn execute(
            &self,
            _request_dto: ScrapeRequestDto,
        ) -> Result<ScrapeResponse, DomainError> {
            Err(DomainError::EngineError("mock".to_string()))
        }
    }

    struct MockRobotsChecker;

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

    struct MockExtractionService;

    #[async_trait]
    impl ExtractionServiceTrait for MockExtractionService {
        async fn extract(
            &self,
            _html_content: &str,
            _rules: &HashMap<String, ExtractionRule>,
            _base_url: Option<&str>,
        ) -> anyhow::Result<(Value, TokenUsage)> {
            Ok((Value::Null, TokenUsage::default()))
        }
        async fn extract_with_schema(
            &self,
            _html_content: &str,
            _schema: &Value,
        ) -> anyhow::Result<(Value, TokenUsage)> {
            Ok((Value::Null, TokenUsage::default()))
        }
        fn extract_with_selectors(
            &self,
            _html_content: &str,
            _rules: &HashMap<String, ExtractionRule>,
            _base_url: Option<&str>,
        ) -> anyhow::Result<Value> {
            Ok(Value::Null)
        }
        async fn extract_with_rag(
            &self,
            _html_content: &str,
            _query: &str,
            _schema: &Value,
            _rag_strategy: &crate::domain::services::rag_strategy::RagExtractionStrategy,
        ) -> anyhow::Result<(Value, TokenUsage)> {
            Ok((Value::Null, TokenUsage::default()))
        }
    }

    // ---- Helpers ----

    fn make_deps() -> WorkerManagerDeps {
        WorkerManagerDeps {
            queue: Arc::new(MockTaskQueue),
            repository: Arc::new(MockTaskRepository::default()),
            result_repository: Arc::new(MockScrapeResultRepository::default()),
            crawl_repository: Arc::new(MockCrawlRepository),
            webhook_service: Arc::new(MockWebhookService),
            credits_repository: Arc::new(MockCreditsRepository),
            engine_client: Arc::new(EngineClient::new()),
            create_scrape_use_case: Arc::new(MockCreateScrapeUseCase),
            team_semaphore: Arc::new(TeamSemaphore::new(10)),
            request_coalescer: Arc::new(
                crate::workers::coalesce_coordinator::RequestCoalescer::new(),
            ),
            robots_checker: Arc::new(MockRobotsChecker),
            http_client: Arc::new(reqwest::Client::new()),
            extraction_service: Arc::new(MockExtractionService),
            #[cfg(feature = "content")]
            content_extractor: Arc::new(
                crate::domain::services::content_extractor::ContentExtractionFacade::new(None),
            ),
            cache_service: Arc::new(NoopCacheService) as Arc<dyn CacheService>,
            shutdown_coordinator: Arc::new(ShutdownCoordinator::default()),
            searxng_instances: None,
        }
    }

    /// Noop CacheService for testing
    ///
    /// 所有操作返回 Ok(None)/Ok(()),不实际存储数据。
    /// 用于 `WorkerManagerDeps` 构造时满足 `cache_service` 字段类型要求。
    struct NoopCacheService;

    #[async_trait::async_trait]
    impl CacheService for NoopCacheService {
        fn get(
            &self,
            _key: &str,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = anyhow::Result<Option<String>>> + Send + '_>,
        > {
            Box::pin(async { Ok(None) })
        }

        fn set(
            &self,
            _key: &str,
            _value: &str,
            _ttl_seconds: u64,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send + '_>>
        {
            Box::pin(async { Ok(()) })
        }

        fn delete(
            &self,
            _key: &str,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send + '_>>
        {
            Box::pin(async { Ok(()) })
        }

        fn exists(
            &self,
            _key: &str,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<bool>> + Send + '_>>
        {
            Box::pin(async { Ok(false) })
        }
    }

    fn make_config() -> WorkerManagerConfig {
        WorkerManagerConfig {
            settings: Arc::new(Settings::default()),
            default_concurrency_limit: 10,
        }
    }

    // ---- WorkerManager::new tests ----

    #[tokio::test]
    async fn test_worker_manager_new_assigns_fields() {
        let manager = WorkerManager::new(make_deps(), make_config());
        assert_eq!(manager.default_concurrency_limit, 10);
        assert!(
            manager.handles.is_empty(),
            "new() should start with no handles"
        );
    }

    // ---- P10:去重状态启动预热 ----

    #[tokio::test]
    async fn test_warmup_deduplicator_loads_previous_urls() {
        let repo = Arc::new(MockTaskRepository {
            warmup_urls: vec![
                "https://example.com/a".to_string(),
                "https://example.com/b".to_string(),
                "https://example.com/c".to_string(),
            ],
        });
        let mut deps = make_deps();
        deps.repository = repo;
        let manager = WorkerManager::new(deps, make_config());

        assert_eq!(manager.deduplicator.read().len(), 0);
        manager.warmup_deduplicator().await;

        let dedup = manager.deduplicator.read();
        assert_eq!(dedup.len(), 3, "warmup must load all distinct URLs");
        // 预热后已爬 URL 不再 DefinitelyNew——否则重启后会全站重爬
        let result = dedup.check("https://example.com/a").unwrap();
        assert!(
            matches!(
                result,
                crate::utils::dedup::DedupResult::MaybeExisting { .. }
            ),
            "warmed-up URL must be MaybeExisting, got {result:?}"
        );
    }

    /// F3 差量:include_results=true 时 tasks+results 并集灌入
    /// (重叠 URL 由 Deduplicator 的 HashSet 自动去重)
    #[tokio::test]
    async fn test_warmup_include_results_adds_result_urls() {
        let repo = Arc::new(MockTaskRepository {
            warmup_urls: vec![
                "https://example.com/task-a".to_string(),
                "https://example.com/shared".to_string(),
            ],
        });
        let result_repo = Arc::new(MockScrapeResultRepository {
            warmup_urls: vec![
                "https://example.com/shared".to_string(), // 与 tasks 重叠
                "https://redirect.example.com/final-1".to_string(),
                "https://redirect.example.com/final-2".to_string(),
            ],
            fail_list_distinct: false,
        });
        let mut deps = make_deps();
        deps.repository = repo;
        deps.result_repository = result_repo;
        let settings = Settings {
            workers: crate::config::settings::WorkerSettings {
                dedup_warmup_include_results: true,
                ..Default::default()
            },
            ..Default::default()
        };
        let manager = WorkerManager::new(
            deps,
            WorkerManagerConfig {
                settings: Arc::new(settings),
                default_concurrency_limit: 10,
            },
        );

        assert_eq!(manager.deduplicator.read().len(), 0);
        manager.warmup_deduplicator().await;

        let dedup = manager.deduplicator.read();
        assert_eq!(
            dedup.len(),
            4,
            "warmup must cover the tasks∪results union (shared URL counted once)"
        );
        // 重定向 final_url(仅存于结果表)必须进入去重状态
        let result = dedup.check("https://redirect.example.com/final-1").unwrap();
        assert!(
            matches!(
                result,
                crate::utils::dedup::DedupResult::MaybeExisting { .. }
            ),
            "result-table URL must be warmed, got {result:?}"
        );
    }

    /// F3 差量:默认(include_results=false)仅灌 tasks URL——
    /// 回归 P10 快照语义,结果表 URL 不进预热
    #[tokio::test]
    async fn test_warmup_default_excludes_results() {
        let repo = Arc::new(MockTaskRepository {
            warmup_urls: vec![
                "https://example.com/task-a".to_string(),
                "https://example.com/task-b".to_string(),
            ],
        });
        let result_repo = Arc::new(MockScrapeResultRepository {
            warmup_urls: vec![
                "https://redirect.example.com/final-1".to_string(),
                "https://redirect.example.com/final-2".to_string(),
                "https://redirect.example.com/final-3".to_string(),
            ],
            fail_list_distinct: false,
        });
        let mut deps = make_deps();
        deps.repository = repo;
        deps.result_repository = result_repo;
        // make_config() 的 Settings::default() → dedup_warmup_include_results=false
        let manager = WorkerManager::new(deps, make_config());

        manager.warmup_deduplicator().await;

        let dedup = manager.deduplicator.read();
        assert_eq!(
            dedup.len(),
            2,
            "default must warm tasks URLs only (results table excluded)"
        );
        let result = dedup.check("https://redirect.example.com/final-1").unwrap();
        assert!(
            matches!(
                result,
                crate::utils::dedup::DedupResult::DefinitelyNew { .. }
            ),
            "result-table URL must NOT be warmed by default, got {result:?}"
        );
    }

    /// F3 差量:results 阶段查询失败 → error 日志显性化,tasks 已灌入的
    /// 状态保留(不回滚不 panic)
    #[tokio::test]
    async fn test_warmup_results_failure_keeps_tasks_state() {
        let repo = Arc::new(MockTaskRepository {
            warmup_urls: vec![
                "https://example.com/task-a".to_string(),
                "https://example.com/task-b".to_string(),
            ],
        });
        let result_repo = Arc::new(MockScrapeResultRepository {
            warmup_urls: vec![],
            fail_list_distinct: true,
        });
        let mut deps = make_deps();
        deps.repository = repo;
        deps.result_repository = result_repo;
        let settings = Settings {
            workers: crate::config::settings::WorkerSettings {
                dedup_warmup_include_results: true,
                ..Default::default()
            },
            ..Default::default()
        };
        let manager = WorkerManager::new(
            deps,
            WorkerManagerConfig {
                settings: Arc::new(settings),
                default_concurrency_limit: 10,
            },
        );

        // 失败不得 panic:tasks 状态保留
        manager.warmup_deduplicator().await;

        let dedup = manager.deduplicator.read();
        assert_eq!(
            dedup.len(),
            2,
            "tasks-phase state must be retained when results phase fails"
        );
    }

    // ---- start_workers tests ----

    #[tokio::test]
    async fn test_start_workers_zero_count_starts_only_expiration_worker() {
        let mut manager = WorkerManager::new(make_deps(), make_config());
        manager.start_workers(0).await;
        // start_workers(0) 启动:1 个 expiration worker + 1 个 purge_stale 调度任务
        assert_eq!(
            manager.handles.len(),
            2,
            "start_workers(0) should start expiration + purge_stale scheduler"
        );
    }

    #[tokio::test]
    async fn test_start_workers_multiple_count() {
        let mut manager = WorkerManager::new(make_deps(), make_config());
        manager.start_workers(3).await;
        // start_workers(3) 启动:1 expiration + 1 purge_stale + 3 scrape = 5
        assert_eq!(
            manager.handles.len(),
            5,
            "start_workers(3) should start expiration + purge_stale + 3 scrape workers"
        );
    }

    #[tokio::test]
    async fn test_start_workers_handles_are_aborted_on_drop() {
        let mut manager = WorkerManager::new(make_deps(), make_config());
        manager.start_workers(1).await;
        // start_workers(1) 启动:1 expiration + 1 purge_stale + 1 scrape = 3
        assert_eq!(manager.handles.len(), 3);

        // Give workers a moment to start.
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Verify at least one worker is still running (not finished).
        assert!(
            manager.handles.iter().any(|h| !h.is_finished()),
            "at least one worker should be running before drop"
        );

        // Dropping the manager invokes Drop which aborts all handles.
        drop(manager);

        // Re-run with handles extracted to verify abort takes effect.
        let mut manager2 = WorkerManager::new(make_deps(), make_config());
        manager2.start_workers(1).await;
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let handles: Vec<JoinHandle<()>> = std::mem::take(&mut manager2.handles);
        assert!(
            handles.iter().any(|h| !h.is_finished()),
            "workers should be running before abort"
        );

        // Manually abort (mirrors Drop impl behavior).
        for handle in &handles {
            handle.abort();
        }
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        for handle in &handles {
            assert!(
                handle.is_finished(),
                "all handles should be finished after abort"
            );
        }
    }

    // ========== wait_for_shutdown: completes and aborts handles on shutdown trigger ==========
    // Covers the graceful-shutdown branch once the coordinator
    // is triggered (equivalently: SIGTERM/SIGINT received), wait_for_shutdown drains
    // handles within the graceful period and aborts leftovers.
    //
    // 注:不再向当前进程发送 SIGINT。旧的实现依赖 `wait_for_shutdown` 内部
    // `ctrl_c().await` 捕获信号;新实现由外部 `listen_unix_signals` / `begin_shutdown`
    // 触发 coordinator,测试直接调用 `begin_shutdown()` 等价地触发关闭,避免
    // 对测试进程注入信号(会杀死整个测试 harness)。

    #[tokio::test]
    async fn test_wait_for_shutdown_completes_on_trigger() {
        use std::time::Duration;

        let mut manager = WorkerManager::new(make_deps(), make_config());
        manager.start_workers(1).await;
        // start_workers(1) 启动:1 expiration + 1 purge_stale + 1 scrape = 3
        assert_eq!(manager.handles.len(), 3);

        // 触发优雅退出(等价于收到 SIGTERM/SIGINT)
        manager.begin_shutdown();

        // wait_for_shutdown should complete after trigger (not time out)
        let result =
            tokio::time::timeout(Duration::from_secs(5), manager.wait_for_shutdown()).await;

        assert!(
            result.is_ok(),
            "wait_for_shutdown should complete after shutdown trigger"
        );
        // After shutdown, all handles should have been aborted. Give aborted tasks
        // a brief moment to actually finish before checking is_finished().
        tokio::time::sleep(Duration::from_millis(50)).await;
        for handle in &manager.handles {
            assert!(
                handle.is_finished(),
                "handles should be aborted after shutdown"
            );
        }
    }

    #[tokio::test]
    async fn test_begin_shutdown_sets_coordinator_flag() {
        let manager = WorkerManager::new(make_deps(), make_config());
        assert!(!manager.shutdown_coordinator.is_shutting_down());
        manager.begin_shutdown();
        assert!(manager.shutdown_coordinator.is_shutting_down());
    }
}