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
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 配置模块
//!
//! 使用 confers 库进行配置管理,支持:
//! - TOML 配置文件
//! - 环境变量覆盖 (CRAWLRS__ 前缀)
//! - 类型安全的配置解析
//! - 内置验证

use sdforge::validator::Validate;
use serde::{Deserialize, Serialize};

// 重新导出子模块中的类型
pub use super::app::{
    ConcurrencySettings, DatabaseSettings, RateLimitingSettings, RetentionSettings, ServerSettings,
    WebSocketSettings,
};
pub use super::engines::{
    EngineSettings, FlareSolverrCdpSettings, FlareSolverrSettings, FlareSolverrTlsSettings,
    PlaywrightEngineSettings,
};
pub use super::fluxweir::FluxweirSettings;
pub use super::llm::{LLMSettings, LlmChunkingSettings};
pub use super::logging::{ConsoleLoggingSettings, FileLoggingSettings, LoggingSettings};
pub use super::rag::RagSettings;
pub use super::search::{
    BingSearchSettings, ExaEngineSettings, FallbackEngineConfig, SearchFallbackConfig,
    SearchSettings, TavilyEngineSettings,
};

// 主配置结构

/// 应用程序配置设置
///
/// 包含数据库、服务器、速率限制和并发控制等所有配置项
///
/// # 使用示例
///
/// ```ignore
/// use crawlrs::config::Settings;
///
/// fn main -> Result<, Box<dyn std::error::Error>> {
///     let settings = Settings::load?;
///     println!("Server will run on {}:{}", settings.server.host, settings.server.port);
///     Ok()
/// }
/// ```
#[derive(Debug, Clone, Deserialize, Serialize, Validate, confers::Config)]
#[validate(crate = "sdforge::validator")]
#[config(env_prefix = "CRAWLRS__", validate)]
pub struct Settings {
    /// 服务器配置
    pub server: ServerSettings,

    /// 数据库配置
    pub database: DatabaseSettings,

    /// CORS 配置
    pub cors: CorsSettings,

    /// 速率限制配置
    pub rate_limiting: RateLimitingSettings,

    /// 并发控制配置
    pub concurrency: ConcurrencySettings,

    /// 数据保留配置
    pub retention: RetentionSettings,

    /// Webhook 配置
    pub webhook: WebhookSettings,

    /// Bing Search API 配置
    pub bing_search: BingSearchSettings,

    /// 搜索配置(引擎注册、超时与重试)
    pub search: SearchSettings,

    /// LLM 配置
    pub llm: LLMSettings,

    /// RAG 能力配置(嵌入 + 重排,默认全关)。
    /// provider 组合校验走 [`RagSettings::validate_providers`](启动期 fail-fast),
    /// 不挂 validator 的 nested 约束。
    pub rag: RagSettings,

    /// fluxweir 网关集成配置(默认全关;校验走 [`FluxweirSettings::validate`])。
    /// 启用后统一 LLM/嵌入/重排出站出口(见变更 `fluxweir-llm-gateway`)。
    pub fluxweir: FluxweirSettings,

    /// HTTP 代理配置
    pub proxy: ProxySettings,

    /// 引擎配置
    pub engines: EngineSettings,

    /// Markdown 转换配置(html2md-converter-chain 变更)
    pub markdown: MarkdownSettings,

    /// robots.txt 遵从配置
    #[validate(nested)]
    pub robots: RobotsSettings,

    /// Per-host 礼貌爬取与 AutoThrottle 配置(驱动 EngineRouter::host_discipline)
    #[validate(nested)]
    pub politeness: PolitenessSettings,

    /// Session 身份三件套配置(驱动 EngineRouter::session)
    #[validate(nested)]
    pub session: SessionSettings,

    /// 日志配置
    pub logging: LoggingSettings,

    /// Worker 配置
    pub workers: WorkerSettings,

    /// Sitemap 流式请求源配置(F11;消费方由 feature `sitemap` 门控)
    ///
    /// `serde(default)` 兼容旧 config 文件缺 `[sitemap]` 节
    /// (同 `observability` 节先例)。
    #[serde(default)]
    pub sitemap: SitemapSettings,

    /// Crawl 级行为配置(软 404 指纹等,F11)
    ///
    /// `serde(default)` 兼容旧 config 文件缺 `[crawl]` 节。
    #[serde(default)]
    pub crawl: CrawlSettings,

    /// 超时配置
    #[validate(nested)]
    pub timeouts: TimeoutSettings,

    /// 缓存配置
    pub cache: CacheSettings,

    /// WebSocket 连接治理配置(R-ws-task-status-003)
    ///
    /// `serde(default)` 兼容旧 config 文件缺 `[websocket]` 节
    /// (同 `sitemap` 节先例)。
    #[serde(default)]
    pub websocket: WebSocketSettings,

    /// 可信代理配置
    pub trusted_proxies: TrustedProxySettings,

    /// 可观测性配置(失败现场快照等)
    ///
    /// `serde(default)` 兼容旧 config 文件缺 `[observability]` 节
    /// (同 `fail_closed` / MRT 字段先例)。
    #[serde(default)]
    pub observability: ObservabilitySettings,

    /// 认证配置(garrison JWT 密钥等)
    pub auth: AuthSettings,

    /// 国际化配置(i18n)
    pub i18n: I18nSettings,

    /// 提取降级重试阶梯质量门配置(F7)
    ///
    /// `serde(default)` 兼容旧 config 文件缺 `[content_extraction]` 节
    /// (同 `sitemap` / `crawl` 节先例)。
    #[serde(default)]
    pub content_extraction: ContentExtractionSettings,

    /// ID 生成配置(NebulaId 迁移;`serde(default)` 兼容旧配置缺 `[id]` 节)
    #[serde(default)]
    pub id: IdSettings,
}

// ID 生成配置(NebulaId)

/// NebulaId ID 生成配置。
///
/// 默认算法 `uuid_v8`(生成 UUID 兼容值,DB `UUID` 列与 API JSON 契约零改动);
/// `snowflake`/`segment` 未编译进本构建,配置即启动报错(需启用对应 nebulaid
/// 特性)。`workspace`/`group` 为调用
/// `IdGenerator::generate(workspace, group, biz_tag)` 时的默认标识,`biz_tag`
/// 由各业务域在生成点传入。
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__ID__")]
pub struct IdSettings {
    /// 算法:`uuid_v8`(默认;本构建唯一已编译算法,其它值启动即报错)。
    #[config(default = "uuid_v8".to_string())]
    pub algorithm: String,

    /// 默认 workspace 标识。
    #[config(default = "crawlrs".to_string())]
    pub workspace: String,

    /// 默认 group 标识。
    #[config(default = "default".to_string())]
    pub group: String,
}

// CORS 配置

/// robots.txt 遵从配置
///
/// 控制 robots.txt 的识别与应用:
/// - `user_agent`:robots.txt 匹配与抓取使用的 User-Agent(crawl 与
///   `/v1/scrape` 的 robots 检查共用)
/// - `scrape_respect_robots`:`/v1/scrape` 单页抓取是否**默认**遵从
///   robots.txt。默认 `false`(单页抓取定位为直接取页接口,向后兼容);
///   请求级 `options.respect_robots` 可覆盖此全局默认。
///   robots.txt 自身获取失败时 fail-open(放行,与 crawl 路径一致)。
/// - `fail_closed`:robots.txt 获取失败(重试耗尽)时的兜底策略。默认
///   `false` 维持 fail-open;`true` 时判禁并将失败标记按短 TTL(60s)写入
///   缓存,避免对不可达目标站反复打 robots 请求。
#[derive(Debug, Clone, Deserialize, Serialize, Validate, confers::Config)]
#[validate(crate = "sdforge::validator")]
#[config(env_prefix = "CRAWLRS__ROBOTS__")]
pub struct RobotsSettings {
    /// robots.txt 匹配与抓取使用的 User-Agent
    #[config(default = "crawlrs-bot/1.0".to_string())]
    #[validate(length(min = 1, max = 128))]
    pub user_agent: String,

    /// `/v1/scrape` 是否默认遵从 robots.txt(请求级 respect_robots 可覆盖)
    #[config(default = false)]
    pub scrape_respect_robots: bool,

    /// robots.txt 获取失败(重试耗尽)时是否判禁(fail-closed)。
    /// 默认 `false` 维持 fail-open 放行(向后兼容)。
    ///
    /// `serde(default)` 兼容旧 config/default.toml 缺键(同 MRT 字段先例)。
    #[serde(default)]
    #[config(default = false)]
    pub fail_closed: bool,

    /// robots.txt 缓存 TTL(秒)
    #[config(default = 3600)]
    pub cache_ttl_secs: u64,

    /// robots.txt 获取失败重试次数
    #[config(default = 5)]
    pub fetch_max_retries: u32,

    /// 重试初始退避(秒)
    #[config(default = 2)]
    pub fetch_initial_backoff_secs: u64,

    /// 重试最大退避(秒)
    #[config(default = 10)]
    pub fetch_max_backoff_secs: u64,
}

/// Markdown 转换器选择(`[markdown]` 段)
///
/// `converter = "alchemize"`(默认)自研 html 引擎直通(htmd 基础链 + 自研深链,
/// 内建空输出防呆/诚实降级/math `$TeX$` 保真路由);
/// `converter = "htmd"` htmd 单转换器直通(诊断/对比用,无兜底语义)。
/// moli-html2md 链已退役(见 CHANGELOG Unreleased)。
/// 非法值在配置校验期报错(`invalid_markdown_converter` 并列出合法值)。
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum MarkdownConverterKind {
    /// alchemize html 引擎直通(默认;内建兜底)
    #[default]
    Alchemize,
    /// htmd 单转换器直通(诊断用)
    Htmd,
}

/// Markdown 转换配置
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__MARKDOWN__")]
pub struct MarkdownSettings {
    /// 转换器选择:alchemize(默认)| htmd(直通诊断)
    #[config(default = "alchemize".to_string())]
    pub converter: String,
}

impl MarkdownSettings {
    /// 解析转换器枚举(配置校验/装配层调用;非法值在装配期 fail-closed)
    pub fn converter_kind(&self) -> Result<MarkdownConverterKind, String> {
        match self.converter.to_ascii_lowercase().as_str() {
            "alchemize" => Ok(MarkdownConverterKind::Alchemize),
            "htmd" => Ok(MarkdownConverterKind::Htmd),
            other => Err(format!(
                "invalid [markdown].converter = {other:?}; expected \"alchemize\" or \"htmd\""
            )),
        }
    }
}

/// Per-host 礼貌爬取与 AutoThrottle 配置(吸收点 F1/F5)
///
/// 驱动 `EngineRouter::host_discipline`(此前硬编码 `with_defaults`,无配置面)。
/// 键值语义与 `config/default.toml` `[politeness]` 节一一对应:
/// - `autothrottle_enabled = false`(默认):per-host 间隔恒定 `min_interval_ms`,
///   行为与引入 AutoThrottle 之前一致(对齐 Scrapy AUTOTHROTTLE_ENABLED 默认关)
/// - `backoff_base_secs`/`backoff_max_secs`:429 指数退避
///   `min(base × 2^连击数, max)`;`base = 0` 退回固定 `cooldown_default_secs` 冷却
/// - `stalled_threshold`:连续 RateLimited 达阈值置 stalled,触发身份/代理切换
#[derive(Debug, Clone, Deserialize, Serialize, Validate, confers::Config)]
#[validate(crate = "sdforge::validator")]
#[config(env_prefix = "CRAWLRS__POLITENESS__")]
pub struct PolitenessSettings {
    /// 相邻同 host 请求最小间隔(毫秒)——AutoThrottle 收敛下界
    #[config(default = 1000)]
    #[validate(range(min = 0, max = 3_600_000))]
    pub min_interval_ms: u64,

    /// AutoThrottle 收敛上界(毫秒)
    #[config(default = 60_000)]
    #[validate(range(min = 1, max = 3_600_000))]
    pub max_interval_ms: u64,

    /// 429 无 Retry-After 时的兜底冷却(秒;legacy 固定冷却模式)
    #[config(default = 60)]
    #[validate(range(min = 0, max = 86_400))]
    pub cooldown_default_secs: u64,

    /// 裸 403 连击阈值(达到后置 tls_suspect 升级 TLS 指纹)
    #[config(default = 3)]
    #[validate(range(min = 1, max = 100))]
    pub bare403_threshold: u32,

    /// AutoThrottle 开关:false 时 min_interval 恒定(现状行为);
    /// true 后按观测延迟 EMA 收敛 per-host 间隔
    #[config(default = false)]
    pub autothrottle_enabled: bool,

    /// 延迟收敛目标并发度:target_interval = 观测延迟 / target_concurrency
    #[config(default = 8)]
    #[validate(range(min = 1, max = 1024))]
    pub target_concurrency: u32,

    /// 429 指数连击底值(秒);0 = 关闭指数退避(退回固定冷却)
    #[config(default = 2)]
    #[validate(range(min = 0, max = 3600))]
    pub backoff_base_secs: u64,

    /// 429 指数连击封顶(秒)
    #[config(default = 60)]
    #[validate(range(min = 1, max = 86_400))]
    pub backoff_max_secs: u64,

    /// 停滞检测:连续 RateLimited 达该次数置 stalled;0 = 关闭
    #[config(default = 3)]
    #[validate(range(min = 0, max = 100))]
    pub stalled_threshold: u32,

    /// 放行时刻抖动比例(0.0-1.0):实际放行在预约槽位上 ±ratio×interval
    /// 随机化,打散请求指纹规律;0 = 确定性时刻表(现状)
    #[config(default = 0.0)]
    pub jitter_ratio: f64,
}

/// Session 身份三件套配置(吸收点 F2)
///
/// 将代理 + UA/TLS 档 + Cookie 绑定为单一会话身份,按 error_score 记分退休
/// (驱动 `EngineRouter::session`)。键值语义与 `config/default.toml`
/// `[session]` 节一一对应:
/// - `enabled = false`(默认):保持现状盲轮换(`pick_seeded`),灰度开启
/// - `max_sessions`:身份池容量上限(内存护栏;超限降级为临时身份)
/// - `max_error_score`:error_score ≥ 阈值退休(mark_bad +1.0 / mark_good -0.5,
///   下限 0)
/// - `max_uses` / `max_age_secs`:单身份使用次数 / 寿命上限
/// - `cookie_cache_max_bytes`:每身份 Cookie 头缓存上限(超出丢最旧条目)
#[derive(Debug, Clone, Deserialize, Serialize, Validate, confers::Config)]
#[validate(crate = "sdforge::validator")]
#[config(env_prefix = "CRAWLRS__SESSION__")]
pub struct SessionSettings {
    /// 默认关:保持现状盲轮换,灰度开启
    #[config(default = false)]
    pub enabled: bool,

    /// 池内最大身份数(内存护栏)
    #[config(default = 16)]
    #[validate(range(min = 1, max = 10_000))]
    pub max_sessions: usize,

    /// error_score ≥ 阈值退休(mark_bad +1.0 / mark_good -0.5,下限 0)
    #[config(default = 3.0)]
    #[validate(range(min = 0.0, max = 1_000_000.0))]
    pub max_error_score: f64,

    /// 单身份最大使用次数
    #[config(default = 100)]
    #[validate(range(min = 1, max = 1_000_000))]
    pub max_uses: u64,

    /// 身份最长寿命(秒)
    #[config(default = 1800)]
    #[validate(range(min = 0, max = 86_400))]
    pub max_age_secs: u64,

    /// 每身份 Cookie 头缓存上限(字节;手动 Set-Cookie 累积,超出丢最旧条目)
    #[config(default = 16384)]
    #[validate(range(min = 64, max = 1_048_576))]
    pub cookie_cache_max_bytes: usize,
}

/// CORS 配置设置
///
/// 配置跨域资源共享(CORS)策略
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__CORS__")]
pub struct CorsSettings {
    /// 允许的跨域来源列表(逗号分隔)
    #[config(default = "*".to_string())]
    pub allowed_origins: String,
}

impl CorsSettings {
    /// 解析后的来源列表(唯一真源;CORS 层与 429 辅助函数共用)。
    pub fn allowed_origins_list(&self) -> Vec<String> {
        self.allowed_origins
            .split(',')
            .map(str::trim)
            .filter(|origin| !origin.is_empty())
            .map(str::to_string)
            .collect()
    }
}

// Webhook 配置

/// Webhook配置设置
///
/// 配置 Webhook 功能的参数
///
/// # 字段说明
///
/// * `secret` - Webhook 签名密钥,用于验证请求真实性(敏感信息,仅 crate 可见)
///
/// # 安全提示
///
/// `secret` 字段包含 Webhook 签名密钥,泄露可能导致伪造请求。
/// 该字段仅对 crate 可见,外部模块应使用 `secret()` 方法访问。
#[derive(Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__WEBHOOK__")]
pub struct WebhookSettings {
    /// Webhook签名密钥 (敏感信息)
    /// 注意:此字段包含敏感信息,仅 crate 内部可访问
    pub(crate) secret: String,

    /// 最大重试次数
    #[config(default = 5)]
    pub max_retries: u32,

    /// 批处理大小
    #[config(default = 1000)]
    pub batch_size: usize,
}

/// 手写 `Debug`:`secret` 输出 `[REDACTED]`(CWE-532);非敏感参数保持可见。
impl std::fmt::Debug for WebhookSettings {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WebhookSettings")
            .field("secret", &"[REDACTED]")
            .field("max_retries", &self.max_retries)
            .field("batch_size", &self.batch_size)
            .finish()
    }
}

impl WebhookSettings {
    /// 获取 Webhook 签名密钥
    ///
    /// # 安全提示
    ///
    /// 此方法返回 Webhook 签名密钥,调用者应谨慎处理,
    /// 不要记录到日志或暴露给用户。
    pub fn secret(&self) -> &str {
        &self.secret
    }
}

// 认证配置

/// 认证配置设置。
///
/// 配置 garrison 认证鉴权框架的 JWT 密钥等参数。
///
/// # 字段说明
///
/// * `jwt_secret` - JWT 签名密钥(HS256),敏感信息,仅 crate 可见
///
/// # 安全提示
///
/// `jwt_secret` 字段包含 JWT 签名密钥,泄露可能导致 token 伪造。
/// 该字段仅对 crate 可见,外部模块应使用 `jwt_secret()` 方法访问。
/// 密钥长度须 ≥32 字节(HS256 最小要求),弱密钥会在 `build_garrison_config` 中被拒绝。
///
/// # Debug 脱敏
///
/// 手动实现 `Debug`(不派生 `#[derive(Debug)]`),对 `jwt_secret` 字段输出 `"***REDACTED***"`,
/// 防止日志打印 Settings 时泄露密钥(CWE-532 防护)。对齐 [`ProxySettings`] 的 redaction 模式。
#[derive(Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__AUTH__")]
pub struct AuthSettings {
    /// JWT 签名密钥(HS256,敏感信息)。
    ///
    /// 默认空字符串——`auth` feature 启用时,`build_garrison_config("")` 会返回 `Err(EmptySecret)`,
    /// 导致启动 panic(fail-fast),强制运维通过环境变量或配置文件提供强密钥。
    #[config(default = "".to_string())]
    pub(crate) jwt_secret: String,
}

impl std::fmt::Debug for AuthSettings {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthSettings")
            .field("jwt_secret", &"***REDACTED***")
            .finish()
    }
}

impl AuthSettings {
    /// 获取 JWT 签名密钥。
    ///
    /// # 安全提示
    ///
    /// 此方法返回 JWT 签名密钥,调用者应谨慎处理,
    /// 不要记录到日志或暴露给用户。
    pub fn jwt_secret(&self) -> &str {
        &self.jwt_secret
    }
}

// 代理配置

/// 代理轮换策略
///
/// 决定调用方在 ProxyPool 上的默认行为:
/// - `RoundRobin`:每次请求调用 `ProxyPool::next(category)` 取下一个
/// - `Sticky`:按 `session_id` 调用 `ProxyPool::sticky(session_id)` 锁定同一代理
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ProxyStrategy {
    #[default]
    RoundRobin,
    Sticky,
}

/// HTTP代理配置设置
///
/// 配置HTTP代理参数,用于转发爬虫请求。
///
/// 支持多代理轮换池:
/// - `urls`: 代理 URL 列表,可包含 userinfo(日志输出会脱敏)
/// - `strategy`: 轮换策略(RoundRobin / Sticky)
/// - `enabled`: 是否启用代理
/// - `sticky_ttl_seconds`: 粘性会话 TTL(秒),TTL 内同一 session_id 返回同一代理
/// - `cooldown_seconds`: 失败代理默认冷却时长(秒)
#[derive(Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__PROXY__")]
pub struct ProxySettings {
    /// 代理 URL 列表(支持多个代理轮换,按 strategy 决定调度方式)
    #[config(default = Vec::<String>::new())]
    pub urls: Vec<String>,

    /// 代理轮换策略
    #[serde(default)]
    pub strategy: ProxyStrategy,

    /// 是否启用代理
    #[config(default = false)]
    pub enabled: bool,

    /// 粘性会话 TTL(秒)
    ///
    /// `ProxyStrategy::Sticky` 时,TTL 内同一 `session_id` 返回同一代理;
    /// TTL 过期或代理冷却中时重选。
    /// 默认 60 秒(从 di/modules.rs 硬编码移入配置)。
    #[config(default = 60)]
    #[serde(default = "default_sticky_ttl_seconds")]
    pub sticky_ttl_seconds: u64,

    /// 失败代理默认冷却时长(秒)
    ///
    /// `mark_failure` 后代理进入冷却,在此期间不被 `next` / `sticky` 选中。
    /// 默认 30 秒(从 di/modules.rs 硬编码移入配置)。
    #[config(default = 30)]
    #[serde(default = "default_cooldown_seconds")]
    pub cooldown_seconds: u64,
}

/// serde 默认值:粘性会话 TTL(与 `#[config(default = 60)]` 保持一致)
fn default_sticky_ttl_seconds() -> u64 {
    60
}

/// serde 默认值:失败代理冷却时长(与 `#[config(default = 30)]` 保持一致)
fn default_cooldown_seconds() -> u64 {
    30
}

impl std::fmt::Debug for ProxySettings {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // 安全:urls 可能含 user:pass@host 凭证,Debug 输出统一脱敏
        f.debug_struct("ProxySettings")
            .field("urls", &"***REDACTED***")
            .field("strategy", &self.strategy)
            .field("enabled", &self.enabled)
            .field("sticky_ttl_seconds", &self.sticky_ttl_seconds)
            .field("cooldown_seconds", &self.cooldown_seconds)
            .finish()
    }
}

impl ProxySettings {
    /// 获取代理 URL 列表
    pub fn urls(&self) -> &[String] {
        &self.urls
    }

    /// 获取代理轮换策略
    pub fn strategy(&self) -> ProxyStrategy {
        self.strategy
    }
}

// Worker 配置

/// Worker配置设置
///
/// 配置后台Worker进程的数量和类型
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__WORKERS__")]
pub struct WorkerSettings {
    /// Worker数量配置
    pub count: WorkerCount,
    /// 优雅退出宽限期(秒)
    ///
    /// 收到 SIGTERM/SIGINT 后,worker 停止接受新任务并等待进行中任务完成的
    /// 最大时长;超时后强制退出并回滚未完成任务。默认 30 秒。
    #[config(default = 30)]
    pub graceful_shutdown_seconds: u64,
    /// 断点续爬 seen 预热补充(F3 差量):true 时 `warmup_deduplicator` 在
    /// tasks 表之后追加灌入 scrape_results 表 distinct URL(覆盖 tasks.url
    /// 之外的重定向 final_url)。默认 false:结果表含保留期内全部抓取
    /// URL,量大,按站点需要显式开启。
    ///
    /// `serde(default)` 兼容旧 config 文件缺键(同 `fail_closed` 字段先例)。
    #[serde(default)]
    #[config(default = false)]
    pub dedup_warmup_include_results: bool,
}

/// Worker数量配置
///
/// 支持固定数量或自动检测CPU核心数
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum WorkerCount {
    Auto(String),
    Fixed(usize),
}

impl Default for WorkerCount {
    fn default() -> Self {
        WorkerCount::Auto("auto".to_string())
    }
}

impl WorkerCount {
    /// 解析为实际的worker数量
    pub fn resolve(&self) -> usize {
        match self {
            WorkerCount::Auto(s) if s.eq_ignore_ascii_case("auto") => {
                let logical_cores = std::thread::available_parallelism()
                    .map(|n| n.get())
                    .unwrap_or(4);
                logical_cores * 2
            }
            WorkerCount::Fixed(n) => *n,
            _ => 5,
        }
    }
}

// Sitemap 与 Crawl 配置(F11)

/// Sitemap 流式请求源配置(吸收点 F11)
///
/// 键值语义与 `config/default.toml` `[sitemap]` 节一一对应:
/// - `enabled`:流式请求源(frontier 喂入)开关;`/v1/map` 端点本身不受此键控制
/// - `max_urls`:单次 map 任务最多消费的 URL 数(防无限站点图)
/// - `max_concurrent_sub_sitemaps`:子 sitemap 并发展开上限
/// - `channel_capacity`:mpsc 背压边界(解析端在通道满时暂停)
/// - `fetch_timeout_secs`:单个 sitemap 文档拉取超时
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__SITEMAP__")]
pub struct SitemapSettings {
    /// 流式请求源开关(frontier 喂入);map 端点不受此键控制
    #[serde(default)]
    #[config(default = false)]
    pub enabled: bool,

    /// 单次 map 任务最多消费的 URL 数
    #[serde(default = "default_sitemap_max_urls")]
    #[config(default = 50_000)]
    pub max_urls: usize,

    /// 子 sitemap 并发展开上限
    #[serde(default = "default_sitemap_max_concurrent_sub_sitemaps")]
    #[config(default = 4)]
    pub max_concurrent_sub_sitemaps: usize,

    /// 流式通道容量(背压边界)
    #[serde(default = "default_sitemap_channel_capacity")]
    #[config(default = 4096)]
    pub channel_capacity: usize,

    /// 单个 sitemap 文档拉取超时(秒)
    #[serde(default = "default_sitemap_fetch_timeout_secs")]
    #[config(default = 30)]
    pub fetch_timeout_secs: u64,
}

/// serde 默认值:单次 map 消费上限(与 `#[config(default = 50_000)]` 保持一致)
fn default_sitemap_max_urls() -> usize {
    50_000
}

/// serde 默认值:子 sitemap 并发上限(与 `#[config(default = 4)]` 保持一致)
fn default_sitemap_max_concurrent_sub_sitemaps() -> usize {
    4
}

/// serde 默认值:流式通道容量(与 `#[config(default = 4096)]` 保持一致)
fn default_sitemap_channel_capacity() -> usize {
    4096
}

/// serde 默认值:sitemap 拉取超时(与 `#[config(default = 30)]` 保持一致)
fn default_sitemap_fetch_timeout_secs() -> u64 {
    30
}

/// Crawl 级行为配置(吸收点 F11:软 404 指纹)
///
/// 键值语义与 `config/default.toml` `[crawl]` 节一一对应:
/// - `soft404_enabled`:软 404 学习/命中开关
/// - `soft404_max_fingerprints`:指纹库容量(超出按插入序淘汰最旧)
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__CRAWL__")]
pub struct CrawlSettings {
    /// 软 404 学习/命中开关:true 时从 404/410 响应学习空壳指纹,
    /// 命中同指纹的 200 SPA 壳按软 404 处理(不落结果)
    #[serde(default = "default_soft404_enabled")]
    #[config(default = true)]
    pub soft404_enabled: bool,

    /// 指纹库容量上限
    #[serde(default = "default_soft404_max_fingerprints")]
    #[config(default = 10_000)]
    pub soft404_max_fingerprints: usize,
}

/// serde 默认值:软 404 开关(与 `#[config(default = true)]` 保持一致)
fn default_soft404_enabled() -> bool {
    true
}

/// serde 默认值:指纹库容量(与 `#[config(default = 10_000)]` 保持一致)
fn default_soft404_max_fingerprints() -> usize {
    10_000
}

// 超时配置

/// 超时配置设置
///
/// 配置各种操作的超时时间
///
/// # 安全验证
///
/// `engines` 字段添加 `#[validate(nested)]`,使 `Settings::validate` 递归
/// 调用 `EngineTimeoutSettings::validate`,覆盖所有 `#[validate(range(min=1, max=600))]`
/// 约束。其余子结构(workers/retry/cache)无 range 约束,不需要 nested。
#[derive(Debug, Clone, Deserialize, Serialize, Validate, confers::Config)]
#[validate(crate = "sdforge::validator")]
#[config(env_prefix = "CRAWLRS__TIMEOUTS__")]
pub struct TimeoutSettings {
    /// Worker相关超时
    pub workers: WorkerTimeoutSettings,

    /// 引擎相关超时
    #[validate(nested)]
    pub engines: EngineTimeoutSettings,

    /// 重试策略超时
    pub retry: RetryTimeoutSettings,

    /// 缓存TTL设置
    pub cache: CacheTimeoutSettings,
}

/// Worker超时设置
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__TIMEOUTS__WORKERS__")]
pub struct WorkerTimeoutSettings {
    /// Webhook worker处理间隔(秒)
    #[config(default = 5)]
    pub webhook_interval_seconds: u64,

    /// Backlog worker处理间隔(秒)
    #[config(default = 30)]
    pub backlog_interval_seconds: u64,
}

/// 引擎超时设置
///
/// # 安全验证
///
/// 所有超时字段均添加 `#[validate(range(min = 1, max = 600))]` 约束:
/// - `min = 1`:防止配置为 0 秒导致 `tokio::time::timeout(Duration::ZERO, ...)`
///   立即超时,触发瀑布式 fallback 直到所有引擎失败,造成 DoS
/// - `max = 600`:防止配置过大值(10 分钟已足够覆盖最慢的浏览器引擎)
#[derive(Debug, Clone, Deserialize, Serialize, Validate, confers::Config)]
#[validate(crate = "sdforge::validator")]
#[config(env_prefix = "CRAWLRS__TIMEOUTS__ENGINES__")]
pub struct EngineTimeoutSettings {
    /// 默认请求超时(秒)
    #[config(default = 30)]
    #[validate(range(min = 1, max = 600))]
    pub default_timeout_seconds: u64,

    /// Playwright引擎超时(秒)
    #[config(default = 30)]
    #[validate(range(min = 1, max = 600))]
    pub playwright_timeout_seconds: u64,

    /// FlareSolverr超时(秒)
    #[config(default = 30)]
    #[validate(range(min = 1, max = 600))]
    pub flaresolverr_timeout_seconds: u64,

    /// HTTP fetch 引擎 MRT(Maximum Response Time,秒)。
    ///
    /// 用于 `ReqwestEngine` 单引擎最大响应时间。router 顺序 fallback 路径
    /// 用 `min(remaining, fetch_seconds)` 包裹单引擎调用,超时即切下一引擎。
    /// 默认 5 秒(HTTP fetch 引擎比浏览器引擎快)。
    #[config(default = 5)]
    #[serde(default = "default_fetch_seconds")]
    #[validate(range(min = 1, max = 600))]
    pub fetch_seconds: u64,

    /// TLS 指纹引擎 MRT(秒)。
    ///
    /// 用于 `FlareSolverrEngine::Tls` 模式单引擎最大响应时间。
    /// 默认 15 秒(TLS 指纹对抗比完整浏览器快)。
    #[config(default = 15)]
    #[serde(default = "default_tls_seconds")]
    #[validate(range(min = 1, max = 600))]
    pub tls_seconds: u64,

    /// CDP/浏览器引擎 MRT(秒)。
    ///
    /// 用于 `PlaywrightEngine` 和 `FlareSolverrEngine::{Cdp, Full}` 模式
    /// 单引擎最大响应时间。默认 30 秒(覆盖完整浏览器启动 + JS 渲染)。
    #[config(default = 30)]
    #[serde(default = "default_cdp_seconds")]
    #[validate(range(min = 1, max = 600))]
    pub cdp_seconds: u64,
}

/// serde 默认值:HTTP fetch 引擎 MRT(与 `#[config(default = 5)]` 保持一致)
fn default_fetch_seconds() -> u64 {
    5
}

/// serde 默认值:TLS 指纹引擎 MRT(与 `#[config(default = 15)]` 保持一致)
fn default_tls_seconds() -> u64 {
    15
}

/// serde 默认值:CDP/浏览器引擎 MRT(与 `#[config(default = 30)]` 保持一致)
fn default_cdp_seconds() -> u64 {
    30
}

/// 重试超时设置
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__TIMEOUTS__RETRY__")]
pub struct RetryTimeoutSettings {
    /// 初始退避时间(秒)
    #[config(default = 1)]
    pub initial_backoff_seconds: u64,

    /// 最大退避时间(秒)
    #[config(default = 60)]
    pub max_backoff_seconds: u64,
}

/// 缓存超时设置
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__TIMEOUTS__CACHE__")]
pub struct CacheTimeoutSettings {
    /// 默认TTL(秒)
    #[config(default = 600)]
    pub default_ttl_seconds: u64,

    /// 内存缓存TTL(秒)
    #[config(default = 600)]
    pub memory_ttl_seconds: u64,
}

// Cache Configuration

/// 缓存类型配置
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__CACHE__TYPES__")]
pub struct CacheTypeSettings {
    #[config(default = 300)]
    pub ttl_seconds: u64,
    #[config(default = 10000)]
    pub max_size: u64,
}

/// 统一缓存配置(oxcache)
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__CACHE__")]
pub struct CacheSettings {
    /// 是否启用缓存
    #[config(default = true)]
    pub enabled: bool,

    /// 缓存后端:`memory`(缺省,进程内)| `redis`(多实例共享)。
    ///
    /// `redis` 需编译 `cache-redis` feature 且配置 `redis_url`,缺一即
    /// 启动拒绝(fail-closed,见 [`CacheSettings::validate_backend`])。
    #[serde(default = "default_cache_backend")]
    #[config(default = "memory".to_string())]
    pub backend: String,

    /// Redis 连接串(`backend=redis` 时必填;建议 `rediss://`,非 TLS
    /// 需 `OXCACHE_ALLOW_INSECURE_REDIS=I_UNDERSTAND_THE_RISKS` 显式放行)。
    #[serde(default)]
    #[config(default = "".to_string())]
    pub redis_url: String,

    /// L1 内存缓存配置
    pub memory: MemoryCacheSettings,

    /// 各缓存类型特定配置
    pub types: CacheTypeSpecificSettings,
}

/// serde 默认值:缓存后端(与 `#[config(default = "memory")]` 保持一致)
fn default_cache_backend() -> String {
    "memory".to_string()
}

impl CacheSettings {
    /// 启动期 fail-closed 校验(R-redis-shared-cache-001)。
    ///
    /// - `backend=redis` 且 `cache-redis` feature 未编译 → 配置错误;
    /// - `backend=redis` 且 `redis_url` 缺失 → 配置错误;
    /// - 未知 backend 值 → 配置错误(不静默回退 memory);
    /// - `backend=memory`(缺省)恒通过。
    pub fn validate_backend(&self) -> Result<(), sdforge::validator::ValidationError> {
        match self.backend.as_str() {
            "memory" => Ok(()),
            "redis" => self.validate_redis_backend(),
            _ => Err(sdforge::validator::ValidationError::new(
                "cache_backend_unknown",
            )),
        }
    }

    /// `backend=redis` 的能力校验:编译期能力缺口不能靠配置绕过。
    #[cfg(not(feature = "cache-redis"))]
    fn validate_redis_backend(&self) -> Result<(), sdforge::validator::ValidationError> {
        Err(sdforge::validator::ValidationError::new(
            "cache_backend_redis_feature_not_compiled",
        ))
    }

    /// `backend=redis` 的能力校验:feature 已编译时仅要求 URL 存在。
    #[cfg(feature = "cache-redis")]
    fn validate_redis_backend(&self) -> Result<(), sdforge::validator::ValidationError> {
        if self.redis_url.trim().is_empty() {
            return Err(sdforge::validator::ValidationError::new(
                "cache_backend_redis_url_missing",
            ));
        }
        Ok(())
    }
}

/// L1 内存缓存配置(Moka)
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__CACHE__MEMORY__")]
pub struct MemoryCacheSettings {
    /// 最大容量
    #[config(default = 10000)]
    pub capacity: u64,
    /// TTL(秒)
    #[config(default = 300)]
    pub ttl_seconds: u64,
}

/// 各缓存类型特定配置
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__CACHE__TYPES__")]
pub struct CacheTypeSpecificSettings {
    /// 搜索结果缓存配置
    pub search: CacheTypeSettings,

    /// DNS 缓存配置
    pub dns: CacheTypeSettings,

    /// 正则缓存配置
    pub regex: CacheTypeSettings,
}

// 可信代理配置

/// 可信代理配置设置
///
/// 用于安全地提取客户端真实 IP 地址。
/// 仅当请求来自可信代理时才信任 X-Forwarded-For 等请求头。
///
/// # 安全说明
///
/// 如果不配置可信代理,攻击者可以伪造 X-Forwarded-For 头来绕过
/// 基于 IP 的安全控制(如速率限制、访问控制等)。
///
/// # 配置示例
///
/// ```toml
/// [trusted_proxies]
/// enabled = true
/// proxies = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.1"]
/// ```
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__TRUSTED_PROXIES__")]
pub struct TrustedProxySettings {
    /// 是否启用可信代理验证
    ///
    /// - true: 仅当请求来自可信代理时才信任转发头
    /// - false: 总是信任转发头(不安全,仅用于开发环境)
    #[config(default = true)]
    pub enabled: bool,

    /// 可信代理 IP 地址列表
    ///
    /// 支持 CIDR 格式(如 "10.0.0.0/8")和单个 IP(如 "127.0.0.1")
    ///
    /// 默认包含常见的私有 IP 地址范围:
    /// - 10.0.0.0/8 (Class A 私有网络)
    /// - 172.16.0.0/12 (Class B 私有网络)
    /// - 192.168.0.0/16 (Class C 私有网络)
    /// - 127.0.0.1 (本地回环)
    /// - ::1 (IPv6 本地回环)
    #[config(default = vec![
        "10.0.0.0/8".to_string(),
        "172.16.0.0/12".to_string(),
        "192.168.0.0/16".to_string(),
        "127.0.0.1".to_string(),
        "::1".to_string(),
    ])]
    pub proxies: Vec<String>,
}

// 可观测性配置

/// 可观测性配置设置(吸收点 F4,参考 Crawlee ErrorSnapshotter)
///
/// 失败现场快照:错误签名键去重存档(HTML + 响应元数据 + 可选截图)。
/// 键值语义与 `config/default.toml` `[observability]` 节一一对应:
/// - `failure_snapshot_dir`:快照落盘目录;空字符串 = 禁用(默认,不影响现状)
/// - `failure_snapshot_max_total`:全目录快照文件总数上限(超出仅计数不落盘)
///
/// 敏感信息提示:快照响应体可能含目标页敏感内容,目录访问权限与保留期
/// 由运维侧治理(对齐 retention 机制后续扩展)。
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__OBSERVABILITY__")]
pub struct ObservabilitySettings {
    /// 快照落盘目录;空字符串 = 禁用(默认)
    #[serde(default)]
    #[config(default = "".to_string())]
    pub failure_snapshot_dir: String,

    /// 全目录快照文件总数上限(超出丢弃并仅计数)
    #[serde(default = "default_failure_snapshot_max_total")]
    #[config(default = 200)]
    pub failure_snapshot_max_total: usize,
}

/// serde 默认值:快照文件总数上限(与 `#[config(default = 200)]` 保持一致)
fn default_failure_snapshot_max_total() -> usize {
    200
}

// 国际化配置(i18n)

/// 国际化配置设置
///
/// 配置翻译系统的默认语言与支持语言列表。消息目录为编译期内嵌
/// (`src/i18n/catalog.rs`),无运行时翻译文件目录。
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__I18N__")]
pub struct I18nSettings {
    /// 默认 locale(BCP 47 格式,如 "en-US")
    #[config(default = "en-US".to_string())]
    pub default_locale: String,

    /// 支持的 locale 列表
    #[config(default = vec!["en-US".to_string(), "zh-CN".to_string()])]
    pub supported_locales: Vec<String>,
}

/// 验证 i18n 配置有效性
///
/// - `default_locale` 必须是有效 BCP 47 语言标识符
/// - `supported_locales` 必须包含 `default_locale`
pub fn validate_i18n(settings: &I18nSettings) -> Result<(), sdforge::validator::ValidationError> {
    use unic_langid::LanguageIdentifier;

    // default_locale 必须是有效 BCP 47
    settings
        .default_locale
        .parse::<LanguageIdentifier>()
        .map_err(|_| sdforge::validator::ValidationError::new("i18n_invalid_default_locale"))?;

    // supported_locales 每个都必须是有效 BCP 47
    for locale in &settings.supported_locales {
        locale.parse::<LanguageIdentifier>().map_err(|_| {
            sdforge::validator::ValidationError::new("i18n_invalid_supported_locale")
        })?;
    }

    // supported_locales 必须包含 default_locale
    if !settings
        .supported_locales
        .contains(&settings.default_locale)
    {
        return Err(sdforge::validator::ValidationError::new(
            "i18n_default_locale_not_in_supported",
        ));
    }

    Ok(())
}

// 提取降级重试阶梯质量门配置

/// 提取降级重试阶梯质量门配置(吸收点 F7;消费方 `ContentExtractionFacade`)
///
/// 键值语义与 `config/default.toml` `[content_extraction]` 节一一对应:
/// - `min_word_count`:正文词数低于该值时继续尝试下一通道(否则按 confidence 短路)
/// - `replacement_length_ratio`:候选替换裁决,新结果字符数 ≥ 当前 × 该比例才采纳
/// - `prose_min_sentence_words`:prose 硬门槛,句子平均词数下限
/// - `prose_max_link_density`:prose 硬门槛,链接密度上限
#[derive(Debug, Clone, Deserialize, Serialize, confers::Config)]
#[config(env_prefix = "CRAWLRS__CONTENT_EXTRACTION__")]
pub struct ContentExtractionSettings {
    /// 短结果升级阈值(词数)
    #[serde(default = "default_content_extraction_min_word_count")]
    #[config(default = 150)]
    pub min_word_count: usize,

    /// 候选替换裁决长度比(trafilatura 同款)
    #[serde(default = "default_content_extraction_replacement_length_ratio")]
    #[config(default = 1.5)]
    pub replacement_length_ratio: f64,

    /// prose 硬门槛(defuddle):句子平均词数下限
    #[serde(default = "default_content_extraction_prose_min_sentence_words")]
    #[config(default = 7.0)]
    pub prose_min_sentence_words: f64,

    /// prose 硬门槛:链接密度上限
    #[serde(default = "default_content_extraction_prose_max_link_density")]
    #[config(default = 0.7)]
    pub prose_max_link_density: f64,
}

/// serde 默认值:短结果升级阈值(与 `#[config(default = 150)]` 保持一致)
fn default_content_extraction_min_word_count() -> usize {
    150
}

/// serde 默认值:替换裁决长度比(与 `#[config(default = 1.5)]` 保持一致)
fn default_content_extraction_replacement_length_ratio() -> f64 {
    1.5
}

/// serde 默认值:句均词数下限(与 `#[config(default = 7.0)]` 保持一致)
fn default_content_extraction_prose_min_sentence_words() -> f64 {
    7.0
}

/// serde 默认值:链接密度上限(与 `#[config(default = 0.7)]` 保持一致)
fn default_content_extraction_prose_max_link_density() -> f64 {
    0.7
}

// 自定义验证函数已拆分到子模块:`config::security::validate_security`、
// `config::validation::validate_values`。

// Tests

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

    #[test]
    fn test_settings_structure() {
        let settings = Settings {
            server: ServerSettings::default(),
            database: DatabaseSettings::default(),
            cors: CorsSettings::default(),
            rate_limiting: RateLimitingSettings::default(),
            concurrency: ConcurrencySettings::default(),
            retention: RetentionSettings::default(),
            webhook: WebhookSettings::default(),
            bing_search: BingSearchSettings::default(),
            search: SearchSettings::default(),
            llm: LLMSettings::default(),
            rag: RagSettings::default(),
            fluxweir: FluxweirSettings::default(),
            proxy: ProxySettings::default(),
            engines: EngineSettings::default(),
            markdown: MarkdownSettings::default(),
            robots: RobotsSettings::default(),
            logging: LoggingSettings::default(),
            workers: WorkerSettings::default(),
            sitemap: SitemapSettings::default(),
            crawl: CrawlSettings::default(),
            timeouts: TimeoutSettings::default(),
            cache: CacheSettings::default(),
            websocket: WebSocketSettings::default(),
            trusted_proxies: TrustedProxySettings::default(),
            observability: ObservabilitySettings::default(),
            auth: AuthSettings::default(),
            i18n: I18nSettings::default(),
            politeness: PolitenessSettings::default(),
            session: SessionSettings::default(),
            content_extraction: ContentExtractionSettings::default(),
            id: IdSettings::default(),
        };

        assert_eq!(settings.server.port, 8899);
        assert!(settings.rate_limiting.enabled);
        assert!(settings.trusted_proxies.enabled);
        assert_eq!(settings.i18n.default_locale, "en-US");
        assert_eq!(settings.i18n.supported_locales.len(), 2);
        assert_eq!(settings.robots.user_agent, "crawlrs-bot/1.0");
        assert!(!settings.robots.scrape_respect_robots);
        assert!(!settings.robots.fail_closed);
        assert_eq!(settings.politeness.min_interval_ms, 1000);
        assert!(!settings.politeness.autothrottle_enabled);
        assert!(!settings.session.enabled);
    }

    /// SessionSettings 默认值与 config/default.toml `[session]` 节及
    /// 蓝图 configKeys 一一对应(F2)
    #[test]
    fn test_session_settings_defaults_match_spec() {
        let s = SessionSettings::default();
        assert!(!s.enabled, "默认关:保持现状盲轮换,灰度开启");
        assert_eq!(s.max_sessions, 16, "池容量上限(内存护栏)");
        assert_eq!(s.max_error_score, 3.0, "退休分数阈值");
        assert_eq!(s.max_uses, 100, "单身份使用上限");
        assert_eq!(s.max_age_secs, 1800, "身份最长寿命");
        assert_eq!(s.cookie_cache_max_bytes, 16384, "Cookie 缓存上限");
    }

    /// SessionSettings 从 toml 全键反序列化
    #[test]
    fn test_session_settings_toml_parses_all_keys() {
        let toml = r#"
            enabled = true
            max_sessions = 32
            max_error_score = 5.0
            max_uses = 200
            max_age_secs = 3600
            cookie_cache_max_bytes = 32768
        "#;
        let s: SessionSettings = toml::from_str(toml).expect("deserialize");
        assert!(s.enabled);
        assert_eq!(s.max_sessions, 32);
        assert_eq!(s.max_error_score, 5.0);
        assert_eq!(s.max_uses, 200);
        assert_eq!(s.max_age_secs, 3600);
        assert_eq!(s.cookie_cache_max_bytes, 32768);
    }

    /// ContentExtractionSettings 默认值与 config/default.toml `[content_extraction]`
    /// 节及蓝图 configKeys 一一对应(F7)
    #[test]
    fn test_content_extraction_settings_defaults_match_spec() {
        let s = ContentExtractionSettings::default();
        assert_eq!(s.min_word_count, 150, "短结果升级阈值");
        assert!(
            (s.replacement_length_ratio - 1.5).abs() < f64::EPSILON,
            "替换裁决长度比"
        );
        assert!(
            (s.prose_min_sentence_words - 7.0).abs() < f64::EPSILON,
            "句均词数下限"
        );
        assert!(
            (s.prose_max_link_density - 0.7).abs() < f64::EPSILON,
            "链接密度上限"
        );
    }

    /// ContentExtractionSettings 从 toml 全键反序列化
    #[test]
    fn test_content_extraction_settings_toml_parses_all_keys() {
        let toml = r#"
            min_word_count = 200
            replacement_length_ratio = 1.8
            prose_min_sentence_words = 9
            prose_max_link_density = 0.5
        "#;
        let s: ContentExtractionSettings = toml::from_str(toml).expect("deserialize");
        assert_eq!(s.min_word_count, 200);
        assert!((s.replacement_length_ratio - 1.8).abs() < f64::EPSILON);
        assert!((s.prose_min_sentence_words - 9.0).abs() < f64::EPSILON);
        assert!((s.prose_max_link_density - 0.5).abs() < f64::EPSILON);
    }

    /// PolitenessSettings 默认值与 config/default.toml `[politeness]` 节及
    /// 蓝图 configKeys 一一对应(F1/F5)
    #[test]
    fn test_politeness_settings_defaults_match_spec() {
        let p = PolitenessSettings::default();
        assert_eq!(p.min_interval_ms, 1000, "收敛下界对齐 DEFAULT_MIN_INTERVAL");
        assert_eq!(p.max_interval_ms, 60_000, "收敛上界");
        assert_eq!(p.cooldown_default_secs, 60, "对齐 DEFAULT_COOLDOWN");
        assert_eq!(p.bare403_threshold, 3, "对齐 DEFAULT_BARE403_THRESHOLD");
        assert!(!p.autothrottle_enabled, "默认关,保持现网行为不变");
        assert_eq!(p.target_concurrency, 8);
        assert_eq!(p.backoff_base_secs, 2, "429 指数退避底值");
        assert_eq!(p.backoff_max_secs, 60, "指数封顶");
        assert_eq!(p.stalled_threshold, 3);
        assert_eq!(p.jitter_ratio, 0.0, "0=确定性时刻表(现状)");
    }

    /// PolitenessSettings 从 toml 全键反序列化
    #[test]
    fn test_politeness_settings_toml_parses_all_keys() {
        let toml = r#"
            min_interval_ms = 500
            max_interval_ms = 30000
            cooldown_default_secs = 30
            bare403_threshold = 5
            autothrottle_enabled = true
            target_concurrency = 4
            backoff_base_secs = 1
            backoff_max_secs = 120
            stalled_threshold = 2
            jitter_ratio = 0.25
        "#;
        let p: PolitenessSettings = toml::from_str(toml).expect("deserialize");
        assert_eq!(p.min_interval_ms, 500);
        assert_eq!(p.max_interval_ms, 30_000);
        assert_eq!(p.cooldown_default_secs, 30);
        assert_eq!(p.bare403_threshold, 5);
        assert!(p.autothrottle_enabled);
        assert_eq!(p.target_concurrency, 4);
        assert_eq!(p.backoff_base_secs, 1);
        assert_eq!(p.backoff_max_secs, 120);
        assert_eq!(p.stalled_threshold, 2);
        assert!((p.jitter_ratio - 0.25).abs() < f64::EPSILON);
    }

    /// PolitenessSettings → HostDiscipline 参数换算:注入后的纪律组件
    /// 按 min_interval_ms 配置运转(行为断言,不触私有状态;jitter 置 0
    /// 以获得确定性间隔——抖动语义由 host_discipline 专项测试覆盖)
    #[tokio::test]
    async fn test_politeness_settings_to_host_discipline() {
        use crate::utils::host_discipline::HostDiscipline;
        let p = PolitenessSettings {
            min_interval_ms: 250,
            max_interval_ms: 5000,
            cooldown_default_secs: 45,
            bare403_threshold: 2,
            autothrottle_enabled: true,
            target_concurrency: 4,
            backoff_base_secs: 3,
            backoff_max_secs: 90,
            stalled_threshold: 4,
            jitter_ratio: 0.0,
        };
        let d = HostDiscipline::from_politeness(&p);
        d.gate("wire.example.com").await;
        let start = std::time::Instant::now();
        d.gate("wire.example.com").await;
        let elapsed = start.elapsed();
        assert!(
            elapsed >= Duration::from_millis(230),
            "from_politeness must honor min_interval_ms=250, took {elapsed:?}"
        );
        assert!(
            elapsed <= Duration::from_millis(400),
            "gate gap must stay at min_interval, took {elapsed:?}"
        );
    }

    /// RobotsSettings 新增 fail_closed 字段使用 serde(default) 兼容旧 config 文件。
    ///
    /// 验证:旧 toml(如未同步更新的 config/default.toml `[robots]` 节)缺少
    /// `fail_closed` 键时,反序列化回退到 `false`(维持 fail-open),不报错。
    #[test]
    fn test_robots_settings_serde_default_for_fail_closed() {
        // 模拟旧 config 文件:只有原有字段,无 fail_closed
        let old_toml = r#"
            user_agent = "crawlrs-bot/1.0"
            scrape_respect_robots = false
            cache_ttl_secs = 3600
            fetch_max_retries = 5
            fetch_initial_backoff_secs = 2
            fetch_max_backoff_secs = 10
        "#;
        let settings: RobotsSettings = toml::from_str(old_toml).expect("deserialize");
        assert!(
            !settings.fail_closed,
            "缺键时应回退 serde 默认 false(fail-open)"
        );

        // 显式传值可覆盖为 true
        let enabled: RobotsSettings = toml::from_str(
            r#"
            user_agent = "crawlrs-bot/1.0"
            scrape_respect_robots = false
            cache_ttl_secs = 3600
            fetch_max_retries = 5
            fetch_initial_backoff_secs = 2
            fetch_max_backoff_secs = 10
            fail_closed = true
        "#,
        )
        .expect("deserialize override");
        assert!(enabled.fail_closed, "显式 fail_closed=true 应生效");
    }

    /// AuthSettings Debug 输出对 jwt_secret 脱敏(CWE-532 防护)。
    ///
    /// 验证 `format!("{:?}", auth_settings)` 不含密钥明文,仅含 `"***REDACTED***"`。
    /// 防止日志打印 Settings 时泄露 JWT 签名密钥。
    #[test]
    fn test_auth_settings_debug_redacts_jwt_secret() {
        let auth = AuthSettings {
            jwt_secret: "super-secret-jwt-key-32-bytes-or-more!!".to_string(),
        };

        let debug_output = format!("{:?}", auth);
        assert!(
            !debug_output.contains("super-secret-jwt-key-32-bytes-or-more!!"),
            "Debug output must not contain plaintext jwt_secret, got: {debug_output}"
        );
        assert!(
            debug_output.contains("***REDACTED***"),
            "Debug output should contain '***REDACTED***' placeholder, got: {debug_output}"
        );
    }

    /// 防止日志打印 Settings 时泄露 Webhook 签名密钥。
    #[test]
    fn test_webhook_settings_debug_redacts_secret() {
        let settings = WebhookSettings {
            secret: "fixture-webhook-value".to_string(), // pragma: allowlist secret
            max_retries: 7,
            batch_size: 64,
        };
        let debug = format!("{settings:?}");
        assert!(debug.contains("WebhookSettings"), "debug: {debug}");
        assert!(debug.contains("[REDACTED]"), "debug: {debug}");
        assert!(
            !debug.contains("fixture-webhook-value"),
            "secret leaked: {debug}"
        );
        assert!(
            debug.contains("7"),
            "non-sensitive retries visible: {debug}"
        );
        assert!(debug.contains("64"), "non-sensitive batch visible: {debug}");
    }

    /// ObservabilitySettings 默认值与 config/default.toml `[observability]` 节
    /// 一一对应(F4):目录空串 = 禁用,护栏 200 个文件
    #[test]
    fn test_observability_settings_defaults_match_spec() {
        let o = ObservabilitySettings::default();
        assert_eq!(o.failure_snapshot_dir, "", "默认空串 = 禁用,不影响现状");
        assert_eq!(o.failure_snapshot_max_total, 200, "文件总数护栏默认 200");
    }

    /// ObservabilitySettings 从 toml 全键反序列化
    #[test]
    fn test_observability_settings_toml_parses_all_keys() {
        let toml = r#"
            failure_snapshot_dir = "data/failure_snapshots"
            failure_snapshot_max_total = 500
        "#;
        let o: ObservabilitySettings = toml::from_str(toml).expect("deserialize");
        assert_eq!(o.failure_snapshot_dir, "data/failure_snapshots");
        assert_eq!(o.failure_snapshot_max_total, 500);
    }

    /// ObservabilitySettings 缺键兼容:空 toml(模拟旧 config 无键)时
    /// serde(default) 回退默认值(禁用 + 200 护栏),不报错
    #[test]
    fn test_observability_settings_missing_section_falls_back_to_defaults() {
        let o: ObservabilitySettings = toml::from_str("").expect("empty toml with serde defaults");
        assert_eq!(o.failure_snapshot_dir, "");
        assert_eq!(o.failure_snapshot_max_total, 200);
    }

    // WorkerCount tests

    #[test]
    fn test_worker_count_fixed_resolve() {
        let count = WorkerCount::Fixed(8);
        assert_eq!(count.resolve(), 8);
    }

    #[test]
    fn test_worker_count_auto_resolve_positive() {
        let count = WorkerCount::Auto("auto".to_string());
        let resolved = count.resolve();
        assert!(
            resolved > 0,
            "Auto resolve should be positive, got {}",
            resolved
        );
    }

    #[test]
    fn test_worker_count_auto_case_insensitive() {
        let count = WorkerCount::Auto("AUTO".to_string());
        let resolved = count.resolve();
        assert!(resolved > 0, "AUTO should resolve to cpu-based value");
    }

    #[test]
    fn test_worker_count_auto_non_auto_string_falls_to_default() {
        let count = WorkerCount::Auto("not-auto".to_string());
        assert_eq!(count.resolve(), 5);
    }

    #[test]
    fn test_worker_count_default_is_auto() {
        let count = WorkerCount::default();
        assert!(matches!(count, WorkerCount::Auto(_)));
    }

    #[test]
    fn test_worker_count_clone() {
        let count = WorkerCount::Fixed(12);
        let cloned = count.clone();
        assert_eq!(cloned.resolve(), 12);
    }

    #[test]
    fn test_worker_count_serde_fixed() {
        let count = WorkerCount::Fixed(7);
        let json = serde_json::to_string(&count).expect("serialize");
        let back: WorkerCount = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.resolve(), 7);
    }

    #[test]
    fn test_worker_count_serde_auto() {
        let json = "\"auto\"";
        let count: WorkerCount = serde_json::from_str(json).expect("deserialize");
        assert!(matches!(count, WorkerCount::Auto(_)));
    }

    // CorsSettings tests

    #[test]
    fn test_cors_settings_default_allowed_origins() {
        let settings = CorsSettings::default();
        assert_eq!(settings.allowed_origins, "*");
    }

    #[test]
    fn test_cors_settings_construction() {
        let settings = CorsSettings {
            allowed_origins: "https://example.com".to_string(),
        };
        assert_eq!(settings.allowed_origins, "https://example.com");
    }

    #[test]
    fn test_cors_settings_clone() {
        let settings = CorsSettings {
            allowed_origins: "https://test.com,https://api.com".to_string(),
        };
        let cloned = settings.clone();
        assert_eq!(cloned.allowed_origins, settings.allowed_origins);
    }

    #[test]
    fn test_cors_settings_serde_roundtrip() {
        let settings = CorsSettings {
            allowed_origins: "https://roundtrip.com".to_string(),
        };
        let json = serde_json::to_string(&settings).expect("serialize");
        let back: CorsSettings = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.allowed_origins, "https://roundtrip.com");
    }

    // ProxySettings tests

    #[test]
    fn test_proxy_settings_default_empty_urls_and_round_robin_strategy() {
        let settings = ProxySettings::default();
        assert!(settings.urls.is_empty(), "default urls should be empty");
        assert_eq!(settings.strategy, ProxyStrategy::RoundRobin);
        assert!(!settings.enabled);
        // 默认 sticky_ttl=60s, cooldown=30s
        assert_eq!(settings.sticky_ttl_seconds, 60);
        assert_eq!(settings.cooldown_seconds, 30);
    }

    #[test]
    fn test_proxy_settings_urls_and_strategy_accessor() {
        let settings = ProxySettings {
            urls: vec!["http://proxy.example.com:8080".to_string()],
            strategy: ProxyStrategy::Sticky,
            enabled: true,
            sticky_ttl_seconds: 120,
            cooldown_seconds: 45,
        };
        assert_eq!(settings.urls(), &["http://proxy.example.com:8080"]);
        assert_eq!(settings.strategy(), ProxyStrategy::Sticky);
        assert!(settings.enabled);
    }

    #[test]
    fn test_proxy_settings_debug_redacts_urls() {
        let settings = ProxySettings {
            urls: vec!["http://secret:password@proxy:8080".to_string()],
            strategy: ProxyStrategy::RoundRobin,
            enabled: true,
            sticky_ttl_seconds: 60,
            cooldown_seconds: 30,
        };
        let debug_str = format!("{:?}", settings);
        assert!(
            debug_str.contains("***REDACTED***"),
            "urls must be redacted in Debug"
        );
        assert!(
            !debug_str.contains("secret:password"),
            "credentials must not leak to Debug"
        );
        assert!(debug_str.contains("true"), "enabled should be visible");
        assert!(
            debug_str.contains("RoundRobin"),
            "strategy should be visible (non-sensitive)"
        );
    }

    #[test]
    fn test_proxy_settings_clone_preserves_fields() {
        let settings = ProxySettings {
            urls: vec!["http://clone-proxy:9090".to_string()],
            strategy: ProxyStrategy::Sticky,
            enabled: true,
            sticky_ttl_seconds: 90,
            cooldown_seconds: 20,
        };
        let cloned = settings.clone();
        assert_eq!(cloned.urls(), &["http://clone-proxy:9090"]);
        assert_eq!(cloned.strategy(), ProxyStrategy::Sticky);
        assert!(cloned.enabled);
        assert_eq!(cloned.sticky_ttl_seconds, 90);
        assert_eq!(cloned.cooldown_seconds, 20);
    }

    #[test]
    fn test_proxy_settings_serde_roundtrip() {
        let settings = ProxySettings {
            urls: vec!["http://serde-proxy:7070".to_string()],
            strategy: ProxyStrategy::Sticky,
            enabled: false,
            sticky_ttl_seconds: 100,
            cooldown_seconds: 50,
        };
        let json = serde_json::to_string(&settings).expect("serialize");
        let back: ProxySettings = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.urls(), &["http://serde-proxy:7070"]);
        assert_eq!(back.strategy(), ProxyStrategy::Sticky);
        assert!(!back.enabled);
        assert_eq!(back.sticky_ttl_seconds, 100);
        assert_eq!(back.cooldown_seconds, 50);
    }

    /// strategy 字段 serde 用 snake_case:JSON/TOML 中 "round_robin" / "sticky"
    #[test]
    fn test_proxy_settings_strategy_serde_snake_case() {
        // RoundRobin ↔ "round_robin"
        let json = r#"{"urls":[],"strategy":"round_robin","enabled":false}"#;
        let s: ProxySettings = serde_json::from_str(json).expect("deserialize round_robin");
        assert_eq!(s.strategy, ProxyStrategy::RoundRobin);
        let back = serde_json::to_string(&s).expect("serialize");
        assert!(
            back.contains("\"round_robin\""),
            "serialized should be snake_case: {back}"
        );

        // Sticky ↔ "sticky"
        let json = r#"{"urls":[],"strategy":"sticky","enabled":false}"#;
        let s: ProxySettings = serde_json::from_str(json).expect("deserialize sticky");
        assert_eq!(s.strategy, ProxyStrategy::Sticky);
    }

    /// strategy 字段缺失时 serde(default) → RoundRobin
    #[test]
    fn test_proxy_settings_strategy_missing_falls_back_to_default() {
        let json = r#"{"urls":["http://x:8080"],"enabled":true}"#;
        let s: ProxySettings = serde_json::from_str(json).expect("deserialize missing strategy");
        assert_eq!(s.strategy, ProxyStrategy::RoundRobin);
        assert!(s.enabled);
    }

    // WorkerSettings tests

    #[test]
    fn test_worker_settings_default_uses_auto() {
        let settings = WorkerSettings::default();
        assert!(matches!(settings.count, WorkerCount::Auto(_)));
    }

    #[test]
    fn test_worker_settings_construction_fixed() {
        let settings = WorkerSettings {
            count: WorkerCount::Fixed(16),
            graceful_shutdown_seconds: 30,
            dedup_warmup_include_results: false,
        };
        assert_eq!(settings.count.resolve(), 16);
    }

    /// WorkerSettings.dedup_warmup_include_results 默认 false(F3 差量:默认
    /// 不灌结果表,量大需显式开启)
    #[test]
    fn test_worker_settings_dedup_warmup_include_results_default_false() {
        assert!(!WorkerSettings::default().dedup_warmup_include_results);
    }

    /// WorkerSettings 新增 dedup_warmup_include_results 使用 serde(default)
    /// 兼容旧 config 文件:缺键回退 false,显式 true 生效
    #[test]
    fn test_worker_settings_dedup_warmup_include_results_toml() {
        let old_toml = r#"
            count = 5
            graceful_shutdown_seconds = 30
        "#;
        let s: WorkerSettings = toml::from_str(old_toml).expect("deserialize old config");
        assert!(!s.dedup_warmup_include_results, "缺键回退 false");

        let enabled: WorkerSettings = toml::from_str(
            r#"
            count = 5
            graceful_shutdown_seconds = 30
            dedup_warmup_include_results = true
        "#,
        )
        .expect("deserialize override");
        assert!(enabled.dedup_warmup_include_results, "显式 true 生效");
    }

    // SitemapSettings tests(F11)

    /// SitemapSettings 默认值与 config/default.toml `[sitemap]` 节及
    /// 蓝图 configKeys 一一对应
    #[test]
    fn test_sitemap_settings_defaults_match_spec() {
        let s = SitemapSettings::default();
        assert!(!s.enabled, "流式请求源默认关");
        assert_eq!(s.max_urls, 50_000, "单次 map 消费上限");
        assert_eq!(s.max_concurrent_sub_sitemaps, 4, "子 sitemap 并发");
        assert_eq!(s.channel_capacity, 4096, "mpsc 背压边界");
        assert_eq!(s.fetch_timeout_secs, 30, "单文档拉取超时");
    }

    /// SitemapSettings 从 toml 全键反序列化
    #[test]
    fn test_sitemap_settings_toml_parses_all_keys() {
        let toml = r#"
            enabled = true
            max_urls = 1000
            max_concurrent_sub_sitemaps = 2
            channel_capacity = 128
            fetch_timeout_secs = 10
        "#;
        let s: SitemapSettings = toml::from_str(toml).expect("deserialize");
        assert!(s.enabled);
        assert_eq!(s.max_urls, 1000);
        assert_eq!(s.max_concurrent_sub_sitemaps, 2);
        assert_eq!(s.channel_capacity, 128);
        assert_eq!(s.fetch_timeout_secs, 10);
    }

    /// SitemapSettings 缺键兼容:空 toml(模拟旧 config 无 `[sitemap]` 节)
    /// 时 serde(default) 回退默认值,不报错
    #[test]
    fn test_sitemap_settings_missing_section_falls_back_to_defaults() {
        let s: SitemapSettings = toml::from_str("").expect("empty toml with serde defaults");
        assert!(!s.enabled);
        assert_eq!(s.max_urls, 50_000);
    }

    // CrawlSettings tests(F11)

    /// CrawlSettings 默认值与 config/default.toml `[crawl]` 节及
    /// 蓝图 configKeys 一一对应
    #[test]
    fn test_crawl_settings_defaults_match_spec() {
        let c = CrawlSettings::default();
        assert!(c.soft404_enabled, "软 404 默认开");
        assert_eq!(c.soft404_max_fingerprints, 10_000, "指纹库容量");
    }

    /// CrawlSettings 从 toml 全键反序列化 + 缺节兼容
    #[test]
    fn test_crawl_settings_toml_parses_and_falls_back() {
        let c: CrawlSettings = toml::from_str(
            r#"
            soft404_enabled = false
            soft404_max_fingerprints = 100
        "#,
        )
        .expect("deserialize");
        assert!(!c.soft404_enabled);
        assert_eq!(c.soft404_max_fingerprints, 100);

        let fallback: CrawlSettings = toml::from_str("").expect("empty toml with serde defaults");
        assert!(fallback.soft404_enabled);
        assert_eq!(fallback.soft404_max_fingerprints, 10_000);
    }

    // TimeoutSettings tests

    #[test]
    fn test_timeout_settings_default() {
        let settings = TimeoutSettings::default();
        assert_eq!(settings.workers.webhook_interval_seconds, 5);
        assert_eq!(settings.workers.backlog_interval_seconds, 30);
        assert_eq!(settings.engines.default_timeout_seconds, 30);
        assert_eq!(settings.engines.playwright_timeout_seconds, 30);
        assert_eq!(settings.engines.flaresolverr_timeout_seconds, 30);
        assert_eq!(settings.retry.initial_backoff_seconds, 1);
        assert_eq!(settings.retry.max_backoff_seconds, 60);
        assert_eq!(settings.cache.default_ttl_seconds, 600);
        assert_eq!(settings.cache.memory_ttl_seconds, 600);
    }

    // PlaywrightEngineSettings tests

    #[test]
    fn test_playwright_engine_settings_default_capture_off() {
        // F6:XHR 捕获默认关,防止存量部署行为变化与内存放大
        let settings = PlaywrightEngineSettings::default();
        assert!(!settings.capture_xhr);
        assert!(settings.capture_xhr_url_patterns.is_empty());
        assert_eq!(settings.capture_xhr_max_bytes, 262_144);
        assert_eq!(settings.capture_xhr_max_responses, 50);
    }

    #[test]
    fn test_playwright_engine_settings_toml_deserialize() {
        // 与 config/default.toml [engines.playwright] 的键名对齐
        let toml = r#"
capture_xhr = true
capture_xhr_url_patterns = ["*/api/*"]
capture_xhr_max_bytes = 1024
capture_xhr_max_responses = 5
"#;
        let settings: PlaywrightEngineSettings =
            toml::from_str(toml).expect("valid playwright engine toml");
        assert!(settings.capture_xhr);
        assert_eq!(
            settings.capture_xhr_url_patterns,
            vec!["*/api/*".to_string()]
        );
        assert_eq!(settings.capture_xhr_max_bytes, 1024);
        assert_eq!(settings.capture_xhr_max_responses, 5);
    }

    #[test]
    fn test_worker_timeout_settings_construction() {
        let settings = WorkerTimeoutSettings {
            webhook_interval_seconds: 10,
            backlog_interval_seconds: 60,
        };
        assert_eq!(settings.webhook_interval_seconds, 10);
        assert_eq!(settings.backlog_interval_seconds, 60);
    }

    #[test]
    fn test_engine_timeout_settings_construction() {
        let settings = EngineTimeoutSettings {
            default_timeout_seconds: 45,
            playwright_timeout_seconds: 50,
            flaresolverr_timeout_seconds: 55,
            fetch_seconds: 5,
            tls_seconds: 15,
            cdp_seconds: 30,
        };
        assert_eq!(settings.default_timeout_seconds, 45);
        assert_eq!(settings.playwright_timeout_seconds, 50);
        assert_eq!(settings.flaresolverr_timeout_seconds, 55);
        assert_eq!(settings.fetch_seconds, 5);
        assert_eq!(settings.tls_seconds, 15);
        assert_eq!(settings.cdp_seconds, 30);
    }

    /// EngineTimeoutSettings 新增 MRT 字段使用 serde(default) 兼容旧 config 文件。
    ///
    /// 验证:旧 toml/env 中没有 `fetch_seconds` / `tls_seconds` / `cdp_seconds` 字段时,
    /// 反序列化应回退到默认值(fetch=5, tls=15, cdp=30),不报错。
    #[test]
    fn test_engine_timeout_settings_serde_default_for_mrt_fields() {
        // 模拟旧 config 文件:只有原有 3 个字段,无 MRT 字段
        let old_toml = r#"
            default_timeout_seconds = 45
            playwright_timeout_seconds = 50
            flaresolverr_timeout_seconds = 55
        "#;
        let settings: EngineTimeoutSettings = toml::from_str(old_toml).expect("deserialize");
        assert_eq!(settings.default_timeout_seconds, 45);
        assert_eq!(settings.playwright_timeout_seconds, 50);
        assert_eq!(settings.flaresolverr_timeout_seconds, 55);
        // 新字段应回退到 serde 默认值
        assert_eq!(settings.fetch_seconds, 5, "fetch_seconds default");
        assert_eq!(settings.tls_seconds, 15, "tls_seconds default");
        assert_eq!(settings.cdp_seconds, 30, "cdp_seconds default");
    }

    /// EngineTimeoutSettings MRT 字段可被显式覆盖。
    #[test]
    fn test_engine_timeout_settings_mrt_fields_override() {
        let toml = r#"
            default_timeout_seconds = 60
            playwright_timeout_seconds = 45
            flaresolverr_timeout_seconds = 60
            fetch_seconds = 8
            tls_seconds = 20
            cdp_seconds = 45
        "#;
        let settings: EngineTimeoutSettings = toml::from_str(toml).expect("deserialize");
        assert_eq!(settings.fetch_seconds, 8);
        assert_eq!(settings.tls_seconds, 20);
        assert_eq!(settings.cdp_seconds, 45);
    }

    /// EngineTimeoutSettings 的 Validate 派生应拒绝越界值。
    ///
    /// 验证:所有超时字段(含 MRT)必须 >=1 且 <=600 秒。
    /// - 0 秒 → `tokio::time::timeout(Duration::ZERO, ...)` 立即超时 → 瀑布式 fallback 全部失败 → DoS
    /// - 超过 600 秒 → 配置错误(10 分钟已足够覆盖最慢浏览器引擎)
    #[test]
    fn test_engine_timeout_settings_validate_rejects_zero() {
        let settings = EngineTimeoutSettings {
            default_timeout_seconds: 0,
            playwright_timeout_seconds: 30,
            flaresolverr_timeout_seconds: 30,
            fetch_seconds: 5,
            tls_seconds: 15,
            cdp_seconds: 30,
        };
        let result = settings.validate();
        assert!(
            result.is_err(),
            "default_timeout_seconds=0 should be rejected (DoS risk)"
        );
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("default_timeout_seconds"),
            "error should mention field name: {}",
            err
        );
    }

    #[test]
    fn test_engine_timeout_settings_validate_rejects_zero_mrt_fields() {
        // fetch_seconds=0 → tokio::time::timeout(Duration::ZERO) → 立即超时
        let settings = EngineTimeoutSettings {
            default_timeout_seconds: 30,
            playwright_timeout_seconds: 30,
            flaresolverr_timeout_seconds: 30,
            fetch_seconds: 0,
            tls_seconds: 15,
            cdp_seconds: 30,
        };
        assert!(
            settings.validate().is_err(),
            "fetch_seconds=0 should be rejected"
        );

        // tls_seconds=0
        let settings = EngineTimeoutSettings {
            default_timeout_seconds: 30,
            playwright_timeout_seconds: 30,
            flaresolverr_timeout_seconds: 30,
            fetch_seconds: 5,
            tls_seconds: 0,
            cdp_seconds: 30,
        };
        assert!(
            settings.validate().is_err(),
            "tls_seconds=0 should be rejected"
        );

        // cdp_seconds=0
        let settings = EngineTimeoutSettings {
            default_timeout_seconds: 30,
            playwright_timeout_seconds: 30,
            flaresolverr_timeout_seconds: 30,
            fetch_seconds: 5,
            tls_seconds: 15,
            cdp_seconds: 0,
        };
        assert!(
            settings.validate().is_err(),
            "cdp_seconds=0 should be rejected"
        );
    }

    #[test]
    fn test_engine_timeout_settings_validate_rejects_exceeding_max() {
        // 601 秒 → 超过 max=600(10 分钟)
        let settings = EngineTimeoutSettings {
            default_timeout_seconds: 30,
            playwright_timeout_seconds: 30,
            flaresolverr_timeout_seconds: 30,
            fetch_seconds: 601,
            tls_seconds: 15,
            cdp_seconds: 30,
        };
        assert!(
            settings.validate().is_err(),
            "fetch_seconds=601 should be rejected (exceeding max)"
        );
    }

    #[test]
    fn test_engine_timeout_settings_validate_accepts_boundary_values() {
        // 边界值:min=1 和 max=600 都应通过
        let settings = EngineTimeoutSettings {
            default_timeout_seconds: 1,
            playwright_timeout_seconds: 600,
            flaresolverr_timeout_seconds: 1,
            fetch_seconds: 1,
            tls_seconds: 600,
            cdp_seconds: 1,
        };
        assert!(
            settings.validate().is_ok(),
            "boundary values (1 and 600) should pass validation"
        );
    }

    #[test]
    fn test_engine_timeout_settings_validate_accepts_defaults() {
        // 默认值应通过验证
        let settings = EngineTimeoutSettings {
            default_timeout_seconds: 30,
            playwright_timeout_seconds: 30,
            flaresolverr_timeout_seconds: 30,
            fetch_seconds: 5,
            tls_seconds: 15,
            cdp_seconds: 30,
        };
        assert!(
            settings.validate().is_ok(),
            "default values should pass validation"
        );
    }

    #[test]
    fn test_retry_timeout_settings_construction() {
        let settings = RetryTimeoutSettings {
            initial_backoff_seconds: 2,
            max_backoff_seconds: 120,
        };
        assert_eq!(settings.initial_backoff_seconds, 2);
        assert_eq!(settings.max_backoff_seconds, 120);
    }

    #[test]
    fn test_cache_timeout_settings_construction() {
        let settings = CacheTimeoutSettings {
            default_ttl_seconds: 300,
            memory_ttl_seconds: 200,
        };
        assert_eq!(settings.default_ttl_seconds, 300);
        assert_eq!(settings.memory_ttl_seconds, 200);
    }

    // CacheSettings tests

    #[test]
    fn test_cache_settings_default() {
        let settings = CacheSettings::default();
        assert!(settings.enabled);
        assert_eq!(settings.backend, "memory");
        assert_eq!(settings.redis_url, "");
        assert_eq!(settings.memory.capacity, 10000);
        assert_eq!(settings.memory.ttl_seconds, 300);
    }

    #[test]
    fn test_memory_cache_settings_construction() {
        let settings = MemoryCacheSettings {
            capacity: 5000,
            ttl_seconds: 120,
        };
        assert_eq!(settings.capacity, 5000);
        assert_eq!(settings.ttl_seconds, 120);
    }

    #[test]
    fn test_cache_type_settings_construction() {
        let settings = CacheTypeSettings {
            ttl_seconds: 100,
            max_size: 500,
        };
        assert_eq!(settings.ttl_seconds, 100);
        assert_eq!(settings.max_size, 500);
    }

    #[test]
    fn test_cache_settings_serde_roundtrip() {
        let settings = CacheSettings {
            enabled: false,
            backend: "memory".to_string(),
            redis_url: String::new(),
            memory: MemoryCacheSettings {
                capacity: 100,
                ttl_seconds: 50,
            },
            types: CacheTypeSpecificSettings {
                search: CacheTypeSettings {
                    ttl_seconds: 10,
                    max_size: 20,
                },
                dns: CacheTypeSettings {
                    ttl_seconds: 30,
                    max_size: 40,
                },
                regex: CacheTypeSettings {
                    ttl_seconds: 60,
                    max_size: 70,
                },
            },
        };
        let json = serde_json::to_string(&settings).expect("serialize");
        let back: CacheSettings = serde_json::from_str(&json).expect("deserialize");
        assert!(!back.enabled);
        assert_eq!(back.backend, "memory");
        assert_eq!(back.memory.capacity, 100);
        assert_eq!(back.types.search.ttl_seconds, 10);
        assert_eq!(back.types.dns.max_size, 40);
        assert_eq!(back.types.regex.ttl_seconds, 60);
    }

    /// CacheSettings 缺键兼容:旧 toml 无 `backend`/`redis_url` 键时回退
    /// serde 默认(memory + 空串),validate_backend 恒通过
    #[test]
    fn test_cache_settings_missing_keys_fall_back_to_memory() {
        let toml = r#"
            enabled = true
            [memory]
            capacity = 100
            ttl_seconds = 60
            [types.search]
            ttl_seconds = 60
            max_size = 100
            [types.dns]
            ttl_seconds = 300
            max_size = 100
            [types.regex]
            ttl_seconds = 600
            max_size = 50
        "#;
        let s: CacheSettings = toml::from_str(toml).expect("deserialize legacy config");
        assert_eq!(s.backend, "memory");
        assert_eq!(s.redis_url, "");
        assert!(s.validate_backend().is_ok());
    }

    /// validate_backend:缺省 memory 恒通过;未知值拒绝
    #[test]
    fn test_validate_backend_memory_and_unknown() {
        let mut s = CacheSettings::default();
        assert!(s.validate_backend().is_ok());

        s.backend = "memcached".to_string();
        let err = s.validate_backend().expect_err("unknown backend");
        assert_eq!(err.code.to_string(), "cache_backend_unknown");
    }

    /// validate_backend:backend=redis 在未编译 cache-redis 时拒绝,
    /// 与 URL 是否配置无关(编译期能力缺口不能靠配置绕过)
    #[cfg(not(feature = "cache-redis"))]
    #[test]
    fn test_validate_backend_redis_rejected_without_feature() {
        let mut s = CacheSettings {
            backend: "redis".to_string(),
            ..CacheSettings::default()
        };
        let err = s.validate_backend().expect_err("feature not compiled");
        assert_eq!(
            err.code.to_string(),
            "cache_backend_redis_feature_not_compiled"
        );

        s.redis_url = "rediss://127.0.0.1:6379".to_string();
        let err = s.validate_backend().expect_err("url cannot bypass feature");
        assert_eq!(
            err.code.to_string(),
            "cache_backend_redis_feature_not_compiled"
        );
    }

    /// validate_backend:backend=redis 在已编译 cache-redis 时按 URL 判定
    #[cfg(feature = "cache-redis")]
    #[test]
    fn test_validate_backend_redis_requires_url() {
        let mut s = CacheSettings {
            backend: "redis".to_string(),
            ..CacheSettings::default()
        };
        let err = s.validate_backend().expect_err("url missing");
        assert_eq!(err.code.to_string(), "cache_backend_redis_url_missing");

        s.redis_url = "rediss://127.0.0.1:6379".to_string();
        assert!(s.validate_backend().is_ok());
    }
}