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
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Limiteron 服务实现
//!
//! 使用 limiteron 库实现速率限制、并发控制和配额管理功能

use std::sync::Arc;

use ahash::AHashMap;
use async_trait::async_trait;
use chrono::Utc;
use limiteron::prelude::*;
use limiteron::storage::{BanStorage, MemoryBanStorage, MemoryStorage, Storage};
use log::{debug, warn};

use crate::domain::repositories::{
    credits_repository::CreditsRepository,
    task_repository::TaskRepository,
    tasks_backlog_repository::{TasksBacklog, TasksBacklogRepository},
};
use crate::domain::services::rate_limiting_service::{
    BacklogService, ConcurrencyConfig, ConcurrencyControlService, ConcurrencyResult, QuotaService,
    RateLimitConfig, RateLimitResult, RateLimitService, RateLimitingError, RateLimitingService,
};

// dbnexus 适配器仅 db-postgres + dbnexus 同时启用时可用
// (db-postgres 透传 limiteron?/postgres,limiteron 的适配器导出挂 postgres/sqlite/mysql 门控)
#[cfg(all(feature = "db-postgres", feature = "platform"))]
use limiteron::adapters::{DBNexusBanStorageAdapter, DBNexusStorageAdapter};

/// 限流存储句柄:携带后端选择与其所需资源。
///
/// - [`StorageHandle::Memory`]:进程内存储(默认,历史行为)
/// - [`StorageHandle::Database`]:limiteron dbnexus Postgres 适配器,
///   api/worker 双进程共享限流计数与封禁记录,重启不丢失
///
/// `Database` 变体仅在 `db-postgres` + `dbnexus` 构建下存在;
/// 其他数据库构建(sqlite/mysql)暂不支持(limiteron 适配器的 DDL 为 Postgres 方言)。
#[derive(Clone, Default)]
pub enum StorageHandle {
    /// 进程内内存存储
    #[default]
    Memory,
    /// Postgres 共享存储(db-postgres + dbnexus 构建)
    #[cfg(all(feature = "db-postgres", feature = "platform"))]
    Database(Arc<dbnexus::DbPool>),
}

/// 限流服务配置
#[derive(Debug, Clone)]
pub struct RateLimitingConfig {
    /// 限流配置
    pub rate_limit: RateLimitConfig,
    /// 并发控制配置
    pub concurrency: ConcurrencyConfig,
    /// 积压任务处理间隔(秒)
    pub backlog_process_interval_seconds: u64,
    /// 限流记录过期时间(秒)
    pub rate_limit_ttl_seconds: u64,
}

/// API Key 标识符提取器:从 [`RequestContext::user_id`] 提取限流标识。
///
/// limiteron 默认标识链从 X-User-Id/X-API-Key header 与 client_ip 提取,而
/// crawlrs 的服务间调用上下文(`build_request_context`)这三者全为空——
/// Governor 报 "Failed to extract identifier" 后按 fail-open 放行,限流在
/// 活体形同虚设(配置 60rpm 实测 0 次 429 的根因)。crawlrs 已将 API Key
/// 写入 `user_id` 字段,本提取器直接取该字段作为按 key 计量的桶标识。
struct ApiUserIdIdentifierExtractor;

impl limiteron::matchers::IdentifierExtractor for ApiUserIdIdentifierExtractor {
    fn extract(&self, context: &RequestContext) -> Option<Identifier> {
        context
            .user_id
            .as_ref()
            .map(|u| Identifier::UserId(u.clone()))
    }

    fn name(&self) -> &str {
        "ApiUserIdIdentifierExtractor"
    }
}

impl Default for RateLimitingConfig {
    fn default() -> Self {
        Self {
            rate_limit: RateLimitConfig::default(),
            concurrency: ConcurrencyConfig::default(),
            backlog_process_interval_seconds: 30,
            rate_limit_ttl_seconds: 3600,
        }
    }
}

/// Limiteron 服务实现
///
/// 使用 limiteron 库实现速率限制、并发控制和配额管理
#[derive(Clone)]
pub struct LimiteronService {
    /// Limiteron Governor 实例
    governor: Arc<Governor>,
    /// 限流服务配置
    config: RateLimitingConfig,
    /// 任务仓库
    task_repository: Arc<dyn TaskRepository>,
    /// 积压任务仓库
    tasks_backlog_repository: Arc<dyn TasksBacklogRepository>,
    /// 积分仓库
    credits_repository: Arc<dyn CreditsRepository>,
}

/// 日志脱敏:SHA-256 前 12 位(禁止输出原始 key 片段)。
fn hash_key_prefix(key: &str) -> String {
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(key.as_bytes());
    format!("sha256:{}", &hex::encode(digest)[..12])
}

impl LimiteronService {
    /// 创建新的 LimiteronService
    ///
    /// # Arguments
    ///
    /// * `task_repository` - 任务仓库
    /// * `tasks_backlog_repository` - 积压任务仓库
    /// * `credits_repository` - 积分仓库
    /// * `config` - 限流服务配置
    /// * `storage` - 存储后端句柄(memory / postgres 共享存储)
    pub async fn new(
        task_repository: Arc<dyn TaskRepository>,
        tasks_backlog_repository: Arc<dyn TasksBacklogRepository>,
        credits_repository: Arc<dyn CreditsRepository>,
        config: RateLimitingConfig,
        storage: StorageHandle,
    ) -> Result<Self, RateLimitingError> {
        let (storage, ban_storage, l1_enabled) = Self::build_storage(storage).await?;

        let flow_config = Self::build_flow_control_config(&config)?;

        let governor = Governor::builder()
            .with_config(flow_config)
            .with_storage(storage)
            .with_ban_storage(ban_storage)
            .with_identifier_extractor(Arc::new(ApiUserIdIdentifierExtractor))
            // Memory 后端无需 L1(后端本身就是内存);Database 后端启用 L1
            // 挡住高频键的 DB 往返
            .with_l1_cache_enabled(l1_enabled)
            .build()
            .await
            .map_err(|e| RateLimitingError::ConfigurationError(e.to_string()))?;

        Ok(Self {
            governor: Arc::new(governor),
            config,
            task_repository,
            tasks_backlog_repository,
            credits_repository,
        })
    }

    /// 依据存储句柄构建 Governor 的 storage / ban_storage。
    ///
    /// 返回 `(storage, ban_storage, l1_enabled)`;Database 后端启动前先执行
    /// 幂等建表(`CREATE TABLE IF NOT EXISTS`,逐条执行以兼容 sqlx 预编译通道)。
    async fn build_storage(
        handle: StorageHandle,
    ) -> Result<(Arc<dyn Storage>, Arc<dyn BanStorage>, bool), RateLimitingError> {
        #[cfg(all(feature = "db-postgres", feature = "platform"))]
        if let StorageHandle::Database(pool) = &handle {
            Self::ensure_storage_schema(pool).await?;
            log::info!(
                "LimiteronService: using Postgres shared storage (cross-process rate limiting)"
            );
            return Ok((
                Arc::new(DBNexusStorageAdapter::new(pool.clone())),
                Arc::new(DBNexusBanStorageAdapter::new(pool.clone())),
                true,
            ));
        }

        // Memory 分支(含 db-postgres 关闭的构建)不消费 handle,统一借用一次
        // 避免 unused variable(`#[warn]` 级在 CI RUSTFLAGS=-D warnings 下为 error)
        let _ = &handle;

        debug!("LimiteronService: using in-memory storage (single-process semantics)");
        Ok((
            Arc::new(MemoryStorage::new()),
            Arc::new(MemoryBanStorage::new()),
            false,
        ))
    }

    /// 幂等初始化 limiteron 存储表(postgres 方言)。
    ///
    /// `create_all_tables_ddl()` 返回 `;` 连接的多语句串;sqlx 预编译通道
    /// 不支持单次执行多语句,这里按 `;` 拆分逐条执行。
    #[cfg(all(feature = "db-postgres", feature = "platform"))]
    async fn ensure_storage_schema(pool: &Arc<dbnexus::DbPool>) -> Result<(), RateLimitingError> {
        use dbnexus::sea_orm::ConnectionTrait;

        let ddl = limiteron::create_all_tables_ddl();
        let session = pool.get_session("admin").await.map_err(|e| {
            RateLimitingError::ConfigurationError(format!(
                "rate limit storage: failed to get db session: {}",
                e
            ))
        })?;
        let conn = session.connection().map_err(|e| {
            RateLimitingError::ConfigurationError(format!(
                "rate limit storage: failed to get connection: {}",
                e
            ))
        })?;

        for statement in ddl.split(';') {
            let statement = statement.trim();
            if statement.is_empty() {
                continue;
            }
            conn.execute_unprepared(statement).await.map_err(|e| {
                RateLimitingError::ConfigurationError(format!(
                    "rate limit storage: schema init failed: {}",
                    e
                ))
            })?;
        }
        Ok(())
    }

    /// 从配置构建 FlowControlConfig
    fn build_flow_control_config(
        config: &RateLimitingConfig,
    ) -> Result<FlowControlConfig, RateLimitingError> {
        use limiteron::config::{Action, ActionConfig, GlobalConfig, LimiterConfig, Matcher, Rule};

        // 构建用户限流规则(使用 User matcher 匹配 API Key)
        let user_rule = Rule {
            id: "user_rate_limit".to_string(),
            name: "User Rate Limit".to_string(),
            priority: 100,
            matchers: vec![Matcher::User {
                user_ids: vec!["*".to_string()],
            }],
            limiters: vec![LimiterConfig::TokenBucket {
                capacity: config.rate_limit.bucket_capacity.unwrap_or(100) as u64,
                refill_rate: (config.rate_limit.requests_per_second as u64).max(1),
            }],
            action: ActionConfig {
                on_exceed: Action::Reject,
                ban: None,
            },
        };

        // 构建 IP 限流规则
        // 使用 "0.0.0.0/0" 匹配所有 IPv4 地址(limiteron 不接受 "*" 作为 IP 范围)
        let ip_rule = Rule {
            id: "ip_rate_limit".to_string(),
            name: "IP Rate Limit".to_string(),
            priority: 90,
            matchers: vec![Matcher::Ip {
                ip_ranges: vec!["0.0.0.0/0".to_string()],
            }],
            limiters: vec![LimiterConfig::TokenBucket {
                capacity: config.rate_limit.bucket_capacity.unwrap_or(50) as u64,
                refill_rate: ((config.rate_limit.requests_per_second / 2) as u64).max(1),
            }],
            action: ActionConfig {
                on_exceed: Action::Reject,
                ban: None,
            },
        };

        let flow_config = FlowControlConfig {
            version: "0.1.0".to_string(),
            global: GlobalConfig::default(),
            rules: vec![user_rule, ip_rule],
        };

        Ok(flow_config)
    }

    /// 构建请求上下文
    fn build_request_context(&self, api_key: &str, endpoint: &str) -> RequestContext {
        RequestContext {
            ip: None,
            user_id: Some(api_key.to_string()), // 使用 API Key 作为 user_id
            api_key: Some(api_key.to_string()),
            path: endpoint.to_string(),
            method: "GET".to_string(),
            headers: AHashMap::new(),
            query_params: AHashMap::new(),
            client_ip: None,
            mac: None,
            device_id: None,
        }
    }
}

#[async_trait]
impl RateLimitService for LimiteronService {
    async fn check_rate_limit(
        &self,
        api_key: &str,
        endpoint: &str,
    ) -> Result<RateLimitResult, RateLimitingError> {
        debug!(
            "LimiteronService: Checking rate limit for API key: {}..., endpoint: {}",
            hash_key_prefix(api_key),
            endpoint
        );

        if !self.config.rate_limit.enabled {
            debug!("LimiteronService: Rate limiting is disabled globally");
            return Ok(RateLimitResult::Allowed);
        }

        let context = self.build_request_context(api_key, endpoint);

        // 使用 Governor 检查限流
        match self.governor.check(&context).await {
            Ok(Decision::Allowed(_)) => {
                debug!("LimiteronService: Rate limit check passed");
                Ok(RateLimitResult::Allowed)
            }
            Ok(Decision::Rejected(reason)) => {
                warn!(
                    "LimiteronService: Rate limit exceeded for API key: {}...: {:?}",
                    hash_key_prefix(api_key),
                    reason
                );
                Ok(RateLimitResult::Denied {
                    reason: reason.reason.clone(),
                })
            }
            Ok(Decision::Banned(ban_info)) => {
                warn!(
                    "LimiteronService: API key {}... is banned: {}",
                    hash_key_prefix(api_key),
                    ban_info.reason()
                );
                Ok(RateLimitResult::Denied {
                    reason: format!("Banned: {}", ban_info.reason()),
                })
            }
            Err(e) => {
                warn!(
                    "LimiteronService: Rate limit check error for API key: {}...: {}",
                    hash_key_prefix(api_key),
                    e
                );
                // 审查 M6:后端错误上抛,由调用方按 RATE_LIMIT_FAIL_OPEN
                // 统一决策(handler 侧默认 fail-closed → 503);不得在此
                // 静默放行,否则 fail-closed 分支永远不可达。
                Err(RateLimitingError::Other(anyhow::anyhow!(
                    "rate limit backend error: {e}"
                )))
            }
        }
    }

    async fn get_team_rate_limit_config(
        &self,
        _team_id: crate::domain::id::Id,
    ) -> Result<RateLimitConfig, RateLimitingError> {
        Ok(self.config.rate_limit.clone())
    }

    async fn update_team_rate_limit_config(
        &self,
        _team_id: crate::domain::id::Id,
        _config: RateLimitConfig,
    ) -> Result<(), RateLimitingError> {
        // 目前不支持动态更新配置
        // 未来可以添加动态配置更新逻辑
        Ok(())
    }

    async fn cleanup_expired_rate_limits(&self) -> Result<u64, RateLimitingError> {
        // Limiteron 使用内存/数据库存储,自动处理过期
        // 这里返回 0 表示没有需要清理的记录
        Ok(0)
    }
}

#[async_trait]
impl ConcurrencyControlService for LimiteronService {
    async fn check_team_concurrency(
        &self,
        team_id: crate::domain::id::Id,
        task_id: crate::domain::id::Id,
    ) -> Result<ConcurrencyResult, RateLimitingError> {
        if !self.config.concurrency.enabled {
            return Ok(ConcurrencyResult::Allowed);
        }

        debug!(
            "LimiteronService: Checking team concurrency for team: {}, task: {}",
            team_id, task_id
        );

        let task = match self.task_repository.find_by_id(task_id).await {
            Ok(Some(t)) => t,
            Ok(None) => {
                warn!("LimiteronService: Task not found: {}", task_id);
                return Err(RateLimitingError::DatabaseError);
            }
            Err(e) => {
                log::error!("LimiteronService: Database error finding task: {:?}", e);
                return Err(RateLimitingError::DatabaseError);
            }
        };

        // 检查团队当前并发数
        let current_concurrency = self.get_team_current_concurrency(team_id).await?;

        if current_concurrency < self.config.concurrency.max_concurrent_per_team {
            debug!(
                "LimiteronService: Team {} concurrency check passed (current: {}, max: {})",
                team_id, current_concurrency, self.config.concurrency.max_concurrent_per_team
            );
            Ok(ConcurrencyResult::Allowed)
        } else {
            debug!(
                "LimiteronService: Team {} concurrency limit reached, queueing task",
                team_id
            );

            let backlog = crate::domain::repositories::tasks_backlog_repository::TasksBacklog::new(
                task_id,
                team_id,
                task.task_type.to_string(),
                task.priority,
                task.payload,
                task.expires_at.map(|dt| dt.with_timezone(&Utc)),
            );

            match self.tasks_backlog_repository.create(&backlog).await {
                Ok(saved_backlog) => Ok(ConcurrencyResult::Queued {
                    backlog_id: saved_backlog.id,
                }),
                Err(e) => {
                    log::error!("LimiteronService: Database error creating backlog: {:?}", e);
                    Err(RateLimitingError::DatabaseError)
                }
            }
        }
    }

    async fn release_team_concurrency_slot(
        &self,
        team_id: crate::domain::id::Id,
        _task_id: crate::domain::id::Id,
    ) -> Result<(), RateLimitingError> {
        debug!(
            "LimiteronService: Releasing concurrency slot for team: {}",
            team_id
        );

        self.process_backlog_tasks(team_id).await?;

        Ok(())
    }

    async fn get_team_current_concurrency(
        &self,
        _team_id: crate::domain::id::Id,
    ) -> Result<u32, RateLimitingError> {
        // 在实际实现中,应该从存储中获取当前并发数
        // 这里暂时返回 0,生产环境需要从数据库获取
        Ok(0)
    }

    async fn get_team_concurrency_config(
        &self,
        _team_id: crate::domain::id::Id,
    ) -> Result<ConcurrencyConfig, RateLimitingError> {
        Ok(self.config.concurrency.clone())
    }

    async fn update_team_concurrency_config(
        &self,
        _team_id: crate::domain::id::Id,
        _config: ConcurrencyConfig,
    ) -> Result<(), RateLimitingError> {
        // 目前不支持动态更新配置
        Ok(())
    }
}

#[async_trait]
impl BacklogService for LimiteronService {
    async fn process_backlog_tasks(
        &self,
        team_id: crate::domain::id::Id,
    ) -> Result<u32, RateLimitingError> {
        debug!(
            "LimiteronService: Processing backlog tasks for team: {}",
            team_id
        );

        let pending_backlogs = self.load_pending_backlogs(team_id).await?;

        let mut processed_count = 0;

        for backlog in pending_backlogs {
            if self.expire_backlog_item(&backlog).await {
                continue;
            }

            // 尝试获取并发槽位
            let current_concurrency = self.get_team_current_concurrency(team_id).await?;

            if current_concurrency < self.config.concurrency.max_concurrent_per_team {
                // 成功获取槽位,更新任务状态
                if self.complete_backlog_item(&backlog).await {
                    processed_count += 1;
                }
            } else {
                // 无法获取槽位,停止处理
                break;
            }
        }

        debug!(
            "LimiteronService: Processed {} backlog tasks for team: {}",
            processed_count, team_id
        );

        Ok(processed_count)
    }
}

impl LimiteronService {
    /// 拉取待处理的 backlog(每批最多 10 条)。
    async fn load_pending_backlogs(
        &self,
        team_id: crate::domain::id::Id,
    ) -> Result<Vec<TasksBacklog>, RateLimitingError> {
        match self
            .tasks_backlog_repository
            .get_pending_tasks(Some(team_id), Some(10))
            .await
        {
            Ok(backlogs) => Ok(backlogs),
            Err(e) => {
                log::error!(
                    "LimiteronService: Database error getting pending tasks: {:?}",
                    e
                );
                Err(RateLimitingError::DatabaseError)
            }
        }
    }

    /// 过期 backlog:标记过期并落库;返回 true 表示应跳过该条目。
    async fn expire_backlog_item(&self, backlog: &TasksBacklog) -> bool {
        if !backlog.is_expired() {
            return false;
        }

        let mut expired_backlog = backlog.clone();
        if let Err(e) = expired_backlog.mark_expired() {
            log::error!("LimiteronService: Error marking backlog expired: {}", e);
            return true;
        }

        if let Err(e) = self.tasks_backlog_repository.update(&expired_backlog).await {
            log::error!("LimiteronService: Database error updating backlog: {:?}", e);
        }
        true
    }

    /// 已获取槽位:将 Queued 任务置为 Active 并完成 backlog;返回是否计入 processed。
    async fn complete_backlog_item(&self, backlog: &TasksBacklog) -> bool {
        // 成功获取槽位,更新任务状态
        if let Ok(Some(mut task)) = self.task_repository.find_by_id(backlog.task_id).await {
            if task.status == crate::domain::models::TaskStatus::Queued {
                task.status = crate::domain::models::TaskStatus::Active;
                task.started_at = Some(chrono::Utc::now());
                task.lock_token = None;
                task.lock_expires_at = Some(chrono::Utc::now() + chrono::Duration::seconds(300));

                if let Err(e) = self.task_repository.update(&task).await {
                    log::error!("LimiteronService: Database error updating task: {:?}", e);
                    return false;
                }
            }
        }

        let mut updated_backlog = backlog.clone();
        if let Err(e) = updated_backlog.mark_completed() {
            log::error!("LimiteronService: Error marking backlog completed: {}", e);
            return false;
        }

        if let Err(e) = self.tasks_backlog_repository.update(&updated_backlog).await {
            log::error!("LimiteronService: Database error updating backlog: {:?}", e);
            return false;
        }

        true
    }
}

#[async_trait]
impl QuotaService for LimiteronService {
    async fn check_and_deduct_quota(
        &self,
        team_id: crate::domain::id::Id,
        amount: i64,
        transaction_type: crate::domain::models::CreditsTransactionType,
        description: String,
        reference_id: Option<crate::domain::id::Id>,
    ) -> Result<(), RateLimitingError> {
        debug!(
            "LimiteronService: Checking and deducting quota for team: {}, amount: {}",
            team_id, amount
        );

        let balance = match self.credits_repository.get_balance(team_id).await {
            Ok(balance) => balance,
            Err(e) => {
                log::error!("LimiteronService: Credits error getting balance: {:?}", e);
                return Err(RateLimitingError::CreditsError);
            }
        };

        if balance < amount {
            return Err(RateLimitingError::RateLimitExceeded(format!(
                "Insufficient credits: required {}, available {}",
                amount, balance
            )));
        }

        // 扣除积分
        match self
            .credits_repository
            .deduct_credits(team_id, amount, transaction_type, description, reference_id)
            .await
        {
            Ok(_) => {
                debug!(
                    "LimiteronService: Quota deducted successfully for team: {}",
                    team_id
                );
                Ok(())
            }
            Err(e) => {
                log::error!("LimiteronService: Credits error deducting: {:?}", e);
                Err(RateLimitingError::CreditsError)
            }
        }
    }

    async fn refund_quota(
        &self,
        team_id: crate::domain::id::Id,
        amount: i64,
        description: String,
        reference_id: Option<crate::domain::id::Id>,
    ) -> Result<(), RateLimitingError> {
        debug!(
            "LimiteronService: Refunding quota for team: {}, amount: {}",
            team_id, amount
        );

        match self
            .credits_repository
            .add_credits(
                team_id,
                amount,
                crate::domain::models::CreditsTransactionType::Refund,
                description,
                reference_id,
            )
            .await
        {
            Ok(_) => {
                debug!(
                    "LimiteronService: Quota refunded successfully for team: {}",
                    team_id
                );
                Ok(())
            }
            Err(e) => {
                log::error!("LimiteronService: Credits error refunding: {:?}", e);
                Err(RateLimitingError::CreditsError)
            }
        }
    }

    async fn get_quota_balance(
        &self,
        team_id: crate::domain::id::Id,
    ) -> Result<i64, RateLimitingError> {
        match self.credits_repository.get_balance(team_id).await {
            Ok(balance) => Ok(balance),
            Err(e) => {
                log::error!("LimiteronService: Credits error getting balance: {:?}", e);
                Err(RateLimitingError::CreditsError)
            }
        }
    }
}

/// 为 LimiteronService 实现组合 trait RateLimitingService(向后兼容)
#[async_trait]
impl RateLimitingService for LimiteronService {}

#[cfg(test)]
mod tests {
    use super::*;
    use limiteron::config::{LimiterConfig, Matcher};
    use std::str::FromStr;

    // RateLimitingConfig::default tests

    #[test]
    fn test_rate_limiting_config_default_values() {
        let config = RateLimitingConfig::default();
        assert_eq!(config.backlog_process_interval_seconds, 30);
        assert_eq!(config.rate_limit_ttl_seconds, 3600);
        assert!(config.rate_limit.enabled);
        assert!(config.concurrency.enabled);
    }

    // build_flow_control_config tests

    #[test]
    fn test_build_flow_control_config_default() {
        let config = RateLimitingConfig::default();
        let flow_config = LimiteronService::build_flow_control_config(&config).unwrap();

        assert_eq!(flow_config.version, "0.1.0");
        assert_eq!(flow_config.rules.len(), 2);

        // user_rate_limit rule
        assert_eq!(flow_config.rules[0].id, "user_rate_limit");
        assert_eq!(flow_config.rules[0].name, "User Rate Limit");
        assert_eq!(flow_config.rules[0].priority, 100);

        // ip_rate_limit rule
        assert_eq!(flow_config.rules[1].id, "ip_rate_limit");
        assert_eq!(flow_config.rules[1].name, "IP Rate Limit");
        assert_eq!(flow_config.rules[1].priority, 90);
    }

    #[test]
    fn test_build_flow_control_config_custom_bucket_capacity() {
        let mut config = RateLimitingConfig::default();
        config.rate_limit.bucket_capacity = Some(200);
        config.rate_limit.requests_per_second = 20;

        let flow_config = LimiteronService::build_flow_control_config(&config).unwrap();

        // With custom bucket_capacity=200, the user rule capacity should be 200
        let user_limiter = &flow_config.rules[0].limiters[0];
        match user_limiter {
            LimiterConfig::TokenBucket { capacity, .. } => {
                assert_eq!(*capacity, 200);
            }
            _ => panic!("Expected TokenBucket limiter for user rule"),
        }
    }

    #[test]
    fn test_build_flow_control_config_none_bucket_capacity_uses_defaults() {
        let mut config = RateLimitingConfig::default();
        config.rate_limit.bucket_capacity = None;

        let flow_config = LimiteronService::build_flow_control_config(&config).unwrap();

        // With None bucket_capacity, user rule defaults to 100, ip rule to 50
        let user_limiter = &flow_config.rules[0].limiters[0];
        match user_limiter {
            LimiterConfig::TokenBucket { capacity, .. } => {
                assert_eq!(*capacity, 100);
            }
            _ => panic!("Expected TokenBucket limiter for user rule"),
        }

        let ip_limiter = &flow_config.rules[1].limiters[0];
        match ip_limiter {
            LimiterConfig::TokenBucket { capacity, .. } => {
                assert_eq!(*capacity, 50);
            }
            _ => panic!("Expected TokenBucket limiter for ip rule"),
        }
    }

    #[test]
    fn test_build_flow_control_config_ip_range_is_valid_cidr() {
        // Regression test: previously used "*" which limiteron Governor rejects
        let config = RateLimitingConfig::default();
        let flow_config = LimiteronService::build_flow_control_config(&config).unwrap();

        let ip_rule = &flow_config.rules[1];
        assert_eq!(ip_rule.id, "ip_rate_limit");
        for matcher in &ip_rule.matchers {
            match matcher {
                Matcher::Ip { ip_ranges } => {
                    for range in ip_ranges {
                        // Each IP range must be a valid CIDR (not "*")
                        assert_ne!(
                            range, "*",
                            "IP range must not be wildcard '*', use CIDR notation"
                        );
                        // Validate it parses as a valid IP network
                        ipnetwork::IpNetwork::from_str(range).unwrap_or_else(|_| {
                            panic!("IP range '{}' is not a valid CIDR notation", range)
                        });
                    }
                }
                _ => panic!("Expected Ip matcher for ip_rate_limit rule"),
            }
        }
    }

    // Mock repositories for trait impl tests

    use crate::domain::models::credits_model::{CreditsTransaction, CreditsTransactionType};
    use crate::domain::models::task_domain::{TaskStatus, TaskType};
    use crate::domain::models::task_model::Task;
    use crate::domain::repositories::credits_repository::{
        CreditsRepository, CreditsRepositoryError,
    };
    use crate::domain::repositories::task_repository::{
        RepositoryError, TaskQueryParams, TaskRepository,
    };
    use crate::domain::repositories::tasks_backlog_repository::{
        TasksBacklog, TasksBacklogRepository, TasksBacklogStatus,
    };
    use crate::domain::services::rate_limiting_service::{
        BacklogService, ConcurrencyControlService, QuotaService, RateLimitService,
    };
    use chrono::Utc;
    use std::collections::HashSet;
    use std::sync::Mutex;

    /// Configurable mock TaskRepository1
    struct MockTaskRepository {
        /// Behavior mode for find_by_id (avoids needing RepositoryError: Clone)
        find_mode: FindByIdMode,
        /// Task to return when find_mode == ReturnTask
        task: Option<Task>,
        /// Whether update should fail
        update_should_fail: bool,
        /// Number of times update was called
        update_calls: Mutex<u32>,
    }

    enum FindByIdMode {
        Task,
        None,
        Error,
    }

    impl MockTaskRepository {
        fn with_task(task: Task) -> Self {
            Self {
                find_mode: FindByIdMode::Task,
                task: Some(task),
                update_should_fail: false,
                update_calls: Mutex::new(0),
            }
        }
        fn with_no_task() -> Self {
            Self {
                find_mode: FindByIdMode::None,
                task: None,
                update_should_fail: false,
                update_calls: Mutex::new(0),
            }
        }
        fn with_db_error() -> Self {
            Self {
                find_mode: FindByIdMode::Error,
                task: None,
                update_should_fail: false,
                update_calls: Mutex::new(0),
            }
        }
        fn with_failing_update(task: Task) -> Self {
            Self {
                find_mode: FindByIdMode::Task,
                task: Some(task),
                update_should_fail: true,
                update_calls: Mutex::new(0),
            }
        }
        fn update_call_count(&self) -> u32 {
            *self.update_calls.lock().unwrap()
        }
    }

    #[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> {
            match self.find_mode {
                FindByIdMode::Task => Ok(self.task.clone()),
                FindByIdMode::None => Ok(None),
                FindByIdMode::Error => {
                    Err(RepositoryError::Database(anyhow::anyhow!("mock db error")))
                }
            }
        }
        async fn update(&self, task: &Task) -> Result<Task, RepositoryError> {
            *self.update_calls.lock().unwrap() += 1;
            if self.update_should_fail {
                return Err(RepositoryError::Database(anyhow::anyhow!(
                    "mock update failed"
                )));
            }
            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 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)
        }
    }

    /// Configurable mock TasksBacklogRepository
    struct MockBacklogRepository {
        /// Pending tasks to return from get_pending_tasks
        pending_tasks: Mutex<Vec<TasksBacklog>>,
        /// Whether create should fail
        create_should_fail: bool,
        /// Whether update should fail
        update_should_fail: bool,
        /// Whether get_pending_tasks should fail
        get_pending_should_fail: bool,
        /// Created backlogs (for assertion)
        created_backlogs: Mutex<Vec<TasksBacklog>>,
        /// Updated backlogs (for assertion)
        updated_backlogs: Mutex<Vec<TasksBacklog>>,
    }

    impl MockBacklogRepository {
        fn new() -> Self {
            Self {
                pending_tasks: Mutex::new(vec![]),
                create_should_fail: false,
                update_should_fail: false,
                get_pending_should_fail: false,
                created_backlogs: Mutex::new(vec![]),
                updated_backlogs: Mutex::new(vec![]),
            }
        }
        fn with_pending(tasks: Vec<TasksBacklog>) -> Self {
            Self {
                pending_tasks: Mutex::new(tasks),
                create_should_fail: false,
                update_should_fail: false,
                get_pending_should_fail: false,
                created_backlogs: Mutex::new(vec![]),
                updated_backlogs: Mutex::new(vec![]),
            }
        }
        fn with_failing_create() -> Self {
            Self {
                pending_tasks: Mutex::new(vec![]),
                create_should_fail: true,
                update_should_fail: false,
                get_pending_should_fail: false,
                created_backlogs: Mutex::new(vec![]),
                updated_backlogs: Mutex::new(vec![]),
            }
        }
        fn with_failing_update() -> Self {
            Self {
                pending_tasks: Mutex::new(vec![]),
                create_should_fail: false,
                update_should_fail: true,
                get_pending_should_fail: false,
                created_backlogs: Mutex::new(vec![]),
                updated_backlogs: Mutex::new(vec![]),
            }
        }
        fn with_failing_get_pending() -> Self {
            Self {
                pending_tasks: Mutex::new(vec![]),
                create_should_fail: false,
                update_should_fail: false,
                get_pending_should_fail: true,
                created_backlogs: Mutex::new(vec![]),
                updated_backlogs: Mutex::new(vec![]),
            }
        }
        fn created_backlogs(&self) -> Vec<TasksBacklog> {
            self.created_backlogs.lock().unwrap().clone()
        }
        fn updated_backlogs(&self) -> Vec<TasksBacklog> {
            self.updated_backlogs.lock().unwrap().clone()
        }
    }

    #[async_trait]
    impl TasksBacklogRepository for MockBacklogRepository {
        async fn create(&self, backlog: &TasksBacklog) -> Result<TasksBacklog, RepositoryError> {
            if self.create_should_fail {
                return Err(RepositoryError::Database(anyhow::anyhow!(
                    "mock create failed"
                )));
            }
            self.created_backlogs.lock().unwrap().push(backlog.clone());
            Ok(backlog.clone())
        }
        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<TasksBacklog>, RepositoryError> {
            Ok(None)
        }
        async fn find_by_task_id(
            &self,
            _task_id: crate::domain::id::Id,
        ) -> Result<Option<TasksBacklog>, RepositoryError> {
            Ok(None)
        }
        async fn update(&self, backlog: &TasksBacklog) -> Result<TasksBacklog, RepositoryError> {
            if self.update_should_fail {
                return Err(RepositoryError::Database(anyhow::anyhow!(
                    "mock update failed"
                )));
            }
            self.updated_backlogs.lock().unwrap().push(backlog.clone());
            Ok(backlog.clone())
        }
        async fn delete(&self, _id: crate::domain::id::Id) -> Result<(), RepositoryError> {
            Ok(())
        }
        async fn get_pending_tasks(
            &self,
            _team_id: Option<crate::domain::id::Id>,
            _limit: Option<u64>,
        ) -> Result<Vec<TasksBacklog>, RepositoryError> {
            if self.get_pending_should_fail {
                return Err(RepositoryError::Database(anyhow::anyhow!(
                    "mock get_pending failed"
                )));
            }
            Ok(self.pending_tasks.lock().unwrap().clone())
        }
        async fn get_expired_tasks(
            &self,
            _limit: Option<u64>,
        ) -> Result<Vec<TasksBacklog>, RepositoryError> {
            Ok(vec![])
        }
        async fn count_by_status(
            &self,
            _team_id: Option<crate::domain::id::Id>,
            _status: TasksBacklogStatus,
        ) -> Result<i64, RepositoryError> {
            Ok(0)
        }
        async fn update_status_batch(
            &self,
            _ids: &[crate::domain::id::Id],
            _status: TasksBacklogStatus,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
    }

    /// Configurable mock CreditsRepository
    struct MockCreditsRepository {
        balance: Mutex<i64>,
        get_balance_should_fail: bool,
        deduct_should_fail: bool,
        deduct_calls: Mutex<u32>,
    }

    impl MockCreditsRepository {
        fn with_balance(balance: i64) -> Self {
            Self {
                balance: Mutex::new(balance),
                get_balance_should_fail: false,
                deduct_should_fail: false,
                deduct_calls: Mutex::new(0),
            }
        }
        fn with_failing_get_balance() -> Self {
            Self {
                balance: Mutex::new(0),
                get_balance_should_fail: true,
                deduct_should_fail: false,
                deduct_calls: Mutex::new(0),
            }
        }
        fn with_failing_deduct(balance: i64) -> Self {
            Self {
                balance: Mutex::new(balance),
                get_balance_should_fail: false,
                deduct_should_fail: true,
                deduct_calls: Mutex::new(0),
            }
        }
        fn deduct_call_count(&self) -> u32 {
            *self.deduct_calls.lock().unwrap()
        }
    }

    #[async_trait]
    impl CreditsRepository for MockCreditsRepository {
        async fn get_balance(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<i64, CreditsRepositoryError> {
            if self.get_balance_should_fail {
                return Err(CreditsRepositoryError::DatabaseError("mock".to_string()));
            }
            Ok(*self.balance.lock().unwrap())
        }
        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> {
            *self.deduct_calls.lock().unwrap() += 1;
            if self.deduct_should_fail {
                return Err(CreditsRepositoryError::DatabaseError("mock".to_string()));
            }
            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(initial_balance)
        }
    }

    /// Build a LimiteronService with configurable mocks
    async fn make_service_with_mocks(
        task_repo: Arc<MockTaskRepository>,
        backlog_repo: Arc<MockBacklogRepository>,
        credits_repo: Arc<MockCreditsRepository>,
        config: RateLimitingConfig,
    ) -> LimiteronService {
        LimiteronService::new(
            task_repo as Arc<dyn TaskRepository>,
            backlog_repo as Arc<dyn TasksBacklogRepository>,
            credits_repo as Arc<dyn CreditsRepository>,
            config,
            // 测试统一走 Memory 后端(Database 后端需要真实 Postgres,由集成测试覆盖)
            StorageHandle::Memory,
        )
        .await
        .expect("Failed to build LimiteronService")
    }

    fn make_task(
        task_id: crate::domain::id::Id,
        team_id: crate::domain::id::Id,
        status: TaskStatus,
    ) -> Task {
        let mut task = Task::new(
            task_id,
            TaskType::Scrape,
            team_id,
            crate::domain::id::Id::generate(),
            "https://example.com".to_string(),
            serde_json::json!({}),
        );
        task.status = status;
        task
    }

    fn make_pending_backlog(
        task_id: crate::domain::id::Id,
        team_id: crate::domain::id::Id,
    ) -> TasksBacklog {
        TasksBacklog::new(
            task_id,
            team_id,
            "scrape".to_string(),
            1,
            serde_json::json!({}),
            None,
        )
    }

    fn make_expired_backlog(
        task_id: crate::domain::id::Id,
        team_id: crate::domain::id::Id,
    ) -> TasksBacklog {
        TasksBacklog::new(
            task_id,
            team_id,
            "scrape".to_string(),
            1,
            serde_json::json!({}),
            Some(Utc::now() - chrono::Duration::hours(1)),
        )
    }

    // RateLimitService trait tests

    #[tokio::test]
    async fn test_check_rate_limit_disabled_short_circuits_to_allowed() {
        let mut config = RateLimitingConfig::default();
        config.rate_limit.enabled = false;

        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            config,
        )
        .await;

        let result = service.check_rate_limit("k", "/v1/extract").await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), RateLimitResult::Allowed);
    }

    #[tokio::test]
    async fn test_check_rate_limit_enforces_bucket_after_capacity() {
        // 回归(活体 0 次 429):默认标识链在 crawlrs 服务间上下文全空,
        // Governor "Failed to extract identifier" 走 fail-open,限流形同虚设。
        // ApiUserIdIdentifierExtractor 从 user_id 提取标识后,打满令牌桶
        // (默认容量 100,refill 10/s)必须出现 Denied。
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let mut allowed = 0;
        let mut denied = 0;
        for _ in 0..150 {
            match service.check_rate_limit("key-a", "/v1/map").await.unwrap() {
                RateLimitResult::Allowed => allowed += 1,
                RateLimitResult::Denied { .. } | RateLimitResult::RetryAfter { .. } => denied += 1,
            }
        }
        // refill 10/s 会少量回补,允许少量抖动,但拒绝必须出现
        assert!(allowed >= 90, "容量内请求应放行,实际 allowed={allowed}");
        assert!(denied > 0, "超出桶容量后必须 Denied,实际 denied={denied}");

        // NOTE: memory flow-rule 语义——DecisionNode 每 rule 持有一个 limiter
        // 实例,桶按 rule 全局共享(per-key 隔离需走 storage 路径);key-b 在
        // key-a 打满后同样 Denied,固化该现行为以防回归认知。
        let other = service.check_rate_limit("key-b", "/v1/map").await.unwrap();
        assert!(
            matches!(other, RateLimitResult::Denied { .. }),
            "共享规则桶语义下 key-b 应同样被拒,实际 {other:?}"
        );
    }

    #[tokio::test]
    async fn test_get_team_rate_limit_config_returns_clone() {
        let config = RateLimitingConfig::default();
        let expected = config.rate_limit.clone();

        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            config,
        )
        .await;

        let result = service
            .get_team_rate_limit_config(crate::domain::id::Id::generate())
            .await;
        assert!(result.is_ok());
        let got = result.unwrap();
        // RateLimitConfig doesn't derive PartialEq — compare key fields instead
        assert_eq!(got.enabled, expected.enabled);
        assert_eq!(got.requests_per_second, expected.requests_per_second);
        assert_eq!(got.requests_per_minute, expected.requests_per_minute);
        assert_eq!(got.requests_per_hour, expected.requests_per_hour);
        assert_eq!(got.bucket_capacity, expected.bucket_capacity);
    }

    #[tokio::test]
    async fn test_update_team_rate_limit_config_returns_ok() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .update_team_rate_limit_config(
                crate::domain::id::Id::generate(),
                RateLimitConfig::default(),
            )
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_cleanup_expired_rate_limits_returns_zero() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service.cleanup_expired_rate_limits().await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);
    }

    // ConcurrencyControlService trait tests

    #[tokio::test]
    async fn test_check_team_concurrency_disabled_returns_allowed() {
        let mut config = RateLimitingConfig::default();
        config.concurrency.enabled = false;

        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            config,
        )
        .await;

        let result = service
            .check_team_concurrency(
                crate::domain::id::Id::generate(),
                crate::domain::id::Id::generate(),
            )
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), ConcurrencyResult::Allowed);
    }

    #[tokio::test]
    async fn test_check_team_concurrency_task_not_found_returns_db_error() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .check_team_concurrency(
                crate::domain::id::Id::generate(),
                crate::domain::id::Id::generate(),
            )
            .await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            RateLimitingError::DatabaseError
        ));
    }

    #[tokio::test]
    async fn test_check_team_concurrency_find_by_id_db_error_returns_db_error() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_db_error()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .check_team_concurrency(
                crate::domain::id::Id::generate(),
                crate::domain::id::Id::generate(),
            )
            .await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            RateLimitingError::DatabaseError
        ));
    }

    #[tokio::test]
    async fn test_check_team_concurrency_under_limit_returns_allowed() {
        // get_team_current_concurrency returns 0, max_concurrent_per_team default 10 → Allowed
        let task_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_task(make_task(
                task_id,
                team_id,
                TaskStatus::Queued,
            ))),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service.check_team_concurrency(team_id, task_id).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), ConcurrencyResult::Allowed);
    }

    #[tokio::test]
    async fn test_check_team_concurrency_at_limit_queues_backlog() {
        // Force current_concurrency >= max_concurrent_per_team by setting max=0
        let mut config = RateLimitingConfig::default();
        config.concurrency.max_concurrent_per_team = 0;

        let task_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let backlog_repo = Arc::new(MockBacklogRepository::new());
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_task(make_task(
                task_id,
                team_id,
                TaskStatus::Queued,
            ))),
            backlog_repo.clone(),
            Arc::new(MockCreditsRepository::with_balance(100)),
            config,
        )
        .await;

        let result = service.check_team_concurrency(team_id, task_id).await;
        assert!(result.is_ok());
        match result.unwrap() {
            ConcurrencyResult::Queued { backlog_id } => {
                // Verify backlog was created with our task
                let created = backlog_repo.created_backlogs();
                assert_eq!(created.len(), 1);
                assert_eq!(created[0].task_id, task_id);
                assert_eq!(created[0].team_id, team_id);
                assert_eq!(created[0].id, backlog_id);
            }
            other => panic!("Expected Queued, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_check_team_concurrency_at_limit_backlog_create_fails_returns_db_error() {
        let mut config = RateLimitingConfig::default();
        config.concurrency.max_concurrent_per_team = 0;

        let task_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_task(make_task(
                task_id,
                team_id,
                TaskStatus::Queued,
            ))),
            Arc::new(MockBacklogRepository::with_failing_create()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            config,
        )
        .await;

        let result = service.check_team_concurrency(team_id, task_id).await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            RateLimitingError::DatabaseError
        ));
    }

    #[tokio::test]
    async fn test_release_team_concurrency_slot_calls_process_backlog() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .release_team_concurrency_slot(
                crate::domain::id::Id::generate(),
                crate::domain::id::Id::generate(),
            )
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_release_team_concurrency_slot_backlog_error_propagates() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::with_failing_get_pending()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .release_team_concurrency_slot(
                crate::domain::id::Id::generate(),
                crate::domain::id::Id::generate(),
            )
            .await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            RateLimitingError::DatabaseError
        ));
    }

    #[tokio::test]
    async fn test_get_team_current_concurrency_returns_zero() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .get_team_current_concurrency(crate::domain::id::Id::generate())
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);
    }

    #[tokio::test]
    async fn test_get_team_concurrency_config_returns_clone() {
        let config = RateLimitingConfig::default();
        let expected = config.concurrency.clone();

        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            config,
        )
        .await;

        let result = service
            .get_team_concurrency_config(crate::domain::id::Id::generate())
            .await;
        assert!(result.is_ok());
        let got = result.unwrap();
        // ConcurrencyConfig doesn't derive PartialEq — compare key fields instead
        assert_eq!(got.enabled, expected.enabled);
        assert_eq!(got.max_concurrent_tasks, expected.max_concurrent_tasks);
        assert_eq!(
            got.max_concurrent_per_team,
            expected.max_concurrent_per_team
        );
        assert_eq!(got.lock_timeout_seconds, expected.lock_timeout_seconds);
        assert_eq!(got.strategy, expected.strategy);
    }

    #[tokio::test]
    async fn test_update_team_concurrency_config_returns_ok() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .update_team_concurrency_config(
                crate::domain::id::Id::generate(),
                ConcurrencyConfig::default(),
            )
            .await;
        assert!(result.is_ok());
    }

    // BacklogService trait tests

    #[tokio::test]
    async fn test_process_backlog_tasks_get_pending_fails_returns_db_error() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::with_failing_get_pending()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .process_backlog_tasks(crate::domain::id::Id::generate())
            .await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            RateLimitingError::DatabaseError
        ));
    }

    #[tokio::test]
    async fn test_process_backlog_tasks_empty_returns_zero() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .process_backlog_tasks(crate::domain::id::Id::generate())
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);
    }

    #[tokio::test]
    async fn test_process_backlog_tasks_expired_marks_expired_and_updates() {
        let task_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let expired = make_expired_backlog(task_id, team_id);
        let backlog_repo = Arc::new(MockBacklogRepository::with_pending(vec![expired]));
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            backlog_repo.clone(),
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service.process_backlog_tasks(team_id).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0); // expired branch doesn't increment processed_count

        // Verify the expired backlog was updated
        let updated = backlog_repo.updated_backlogs();
        assert_eq!(updated.len(), 1);
        assert_eq!(updated[0].status, TasksBacklogStatus::Expired);
    }

    #[tokio::test]
    async fn test_process_backlog_tasks_expired_update_failure_continues() {
        let task_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let expired = make_expired_backlog(task_id, team_id);
        let backlog_repo = Arc::new(MockBacklogRepository::with_failing_update());
        *backlog_repo.pending_tasks.lock().unwrap() = vec![expired];
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            backlog_repo,
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        // Should not propagate error (logged and continue)
        let result = service.process_backlog_tasks(team_id).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);
    }

    #[tokio::test]
    async fn test_process_backlog_tasks_task_find_by_id_err_continues() {
        // Pending (non-expired) backlog, but find_by_id returns Err
        let task_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let backlog = make_pending_backlog(task_id, team_id);
        let backlog_repo = Arc::new(MockBacklogRepository::with_pending(vec![backlog]));
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_db_error()),
            backlog_repo,
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service.process_backlog_tasks(team_id).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);
    }

    #[tokio::test]
    async fn test_process_backlog_tasks_task_not_found_skips_update() {
        // Pending backlog, find_by_id returns Ok(None) → skip task update branch
        let task_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let backlog = make_pending_backlog(task_id, team_id);
        // NOTE: source bug — mark_completed on a Pending backlog fails, so
        // processed_count never increments. We assert the observed behavior.
        let backlog_repo = Arc::new(MockBacklogRepository::with_pending(vec![backlog]));
        let task_repo = Arc::new(MockTaskRepository::with_no_task());
        let service = make_service_with_mocks(
            task_repo,
            backlog_repo,
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service.process_backlog_tasks(team_id).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0); // mark_completed fails on Pending → 0
    }

    #[tokio::test]
    async fn test_process_backlog_tasks_task_not_queued_skips_status_update() {
        // Task found but status != Queued → skip the update-task branch
        let task_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let backlog = make_pending_backlog(task_id, team_id);
        let backlog_repo = Arc::new(MockBacklogRepository::with_pending(vec![backlog]));
        let task_repo = Arc::new(MockTaskRepository::with_task(make_task(
            task_id,
            team_id,
            TaskStatus::Active,
        )));
        let service = make_service_with_mocks(
            task_repo.clone(),
            backlog_repo,
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service.process_backlog_tasks(team_id).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0); // mark_completed still fails on Pending → 0
        assert_eq!(task_repo.update_call_count(), 0); // task.update not called
    }

    #[tokio::test]
    async fn test_process_backlog_tasks_task_queued_calls_task_update() {
        // Task is Queued → task.update called (succeeds) → mark_completed fails → 0
        let task_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let backlog = make_pending_backlog(task_id, team_id);
        let backlog_repo = Arc::new(MockBacklogRepository::with_pending(vec![backlog]));
        let task_repo = Arc::new(MockTaskRepository::with_task(make_task(
            task_id,
            team_id,
            TaskStatus::Queued,
        )));
        let service = make_service_with_mocks(
            task_repo.clone(),
            backlog_repo,
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service.process_backlog_tasks(team_id).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0); // mark_completed fails on Pending → 0
        assert_eq!(task_repo.update_call_count(), 1); // task.update WAS called
    }

    #[tokio::test]
    async fn test_process_backlog_tasks_task_update_failure_continues() {
        // Task is Queued, but task.update fails → continue (no increment)
        let task_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let backlog = make_pending_backlog(task_id, team_id);
        let backlog_repo = Arc::new(MockBacklogRepository::with_pending(vec![backlog]));
        let task_repo = Arc::new(MockTaskRepository::with_failing_update(make_task(
            task_id,
            team_id,
            TaskStatus::Queued,
        )));
        let service = make_service_with_mocks(
            task_repo.clone(),
            backlog_repo,
            Arc::new(MockCreditsRepository::with_balance(100)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service.process_backlog_tasks(team_id).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);
        assert_eq!(task_repo.update_call_count(), 1);
    }

    #[tokio::test]
    async fn test_process_backlog_tasks_concurrency_at_limit_breaks() {
        // Force break branch: max_concurrent_per_team = 0 so 0 < 0 is false → break immediately
        let mut config = RateLimitingConfig::default();
        config.concurrency.max_concurrent_per_team = 0;

        let task_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let backlog = make_pending_backlog(task_id, team_id);
        let backlog_repo = Arc::new(MockBacklogRepository::with_pending(vec![backlog]));
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            backlog_repo,
            Arc::new(MockCreditsRepository::with_balance(100)),
            config,
        )
        .await;

        let result = service.process_backlog_tasks(team_id).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0); // break before any processing
    }

    // QuotaService trait tests

    #[tokio::test]
    async fn test_check_and_deduct_quota_get_balance_fails_returns_credits_error() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_failing_get_balance()),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .check_and_deduct_quota(
                crate::domain::id::Id::generate(),
                10,
                CreditsTransactionType::Scrape,
                "test".to_string(),
                None,
            )
            .await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            RateLimitingError::CreditsError
        ));
    }

    #[tokio::test]
    async fn test_check_and_deduct_quota_insufficient_balance_returns_exceeded() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(5)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .check_and_deduct_quota(
                crate::domain::id::Id::generate(),
                10,
                CreditsTransactionType::Scrape,
                "test".to_string(),
                None,
            )
            .await;
        assert!(result.is_err());
        match result.unwrap_err() {
            RateLimitingError::RateLimitExceeded(msg) => {
                assert!(msg.contains("Insufficient credits"));
                assert!(msg.contains("required 10"));
                assert!(msg.contains("available 5"));
            }
            other => panic!("Expected RateLimitExceeded, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_check_and_deduct_quota_exact_balance_succeeds() {
        let credits_repo = Arc::new(MockCreditsRepository::with_balance(10));
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            credits_repo.clone(),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .check_and_deduct_quota(
                crate::domain::id::Id::generate(),
                10,
                CreditsTransactionType::Scrape,
                "test".to_string(),
                None,
            )
            .await;
        assert!(result.is_ok());
        assert_eq!(credits_repo.deduct_call_count(), 1);
    }

    #[tokio::test]
    async fn test_check_and_deduct_quota_deduct_fails_returns_credits_error() {
        let credits_repo = Arc::new(MockCreditsRepository::with_failing_deduct(100));
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            credits_repo.clone(),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .check_and_deduct_quota(
                crate::domain::id::Id::generate(),
                10,
                CreditsTransactionType::Scrape,
                "test".to_string(),
                None,
            )
            .await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            RateLimitingError::CreditsError
        ));
        assert_eq!(credits_repo.deduct_call_count(), 1);
    }

    #[tokio::test]
    async fn test_get_quota_balance_get_balance_fails_returns_credits_error() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_failing_get_balance()),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .get_quota_balance(crate::domain::id::Id::generate())
            .await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            RateLimitingError::CreditsError
        ));
    }

    #[tokio::test]
    async fn test_get_quota_balance_success_returns_balance() {
        let service = make_service_with_mocks(
            Arc::new(MockTaskRepository::with_no_task()),
            Arc::new(MockBacklogRepository::new()),
            Arc::new(MockCreditsRepository::with_balance(42)),
            RateLimitingConfig::default(),
        )
        .await;

        let result = service
            .get_quota_balance(crate::domain::id::Id::generate())
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
    }
}