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

//! 统一错误类型定义
//!
//! 提供应用程序的统一错误类型,用于处理所有应用级别的错误。
//!
//! # 与 sdforge 的职责划分
//!
//! 17 个领域变体的分类由本模块保有(承载爬虫领域语义,不合并进 sdforge
//! `ApiError` 的 9 变体)。HTTP 状态码映射经变体归一后委托 sdforge
//! `unified::http_status_for`;502/504(Network/Engine/Timeout)为库覆盖集外
//! 残留,显式保留并登记于 docs/ARCHITECTURE.md 自研库反向需求。脱敏双层:
//! 引擎错误串的正则脱敏为本领域特例(库不做正则脱敏),Internal 类
//! (Other/ServiceUnavailable)整体遮蔽语义与 `ApiError::sanitized_message`
//! 对齐(固定遮蔽文案,不透出内部细节)。i18n 经 crawlrs `I18nBundle`
//! (fluent 装载 + locale→default→key 回退链)——sdforge `TranslationStore`
//! 仅支持 JSON 装载且回退链为 locale→en→key,不匹配现有 fluent 资源与
//! 可配置 default 语义,保留差异化实现(缺口已登记)。

#[cfg(any(feature = "platform", feature = "web-axum"))]
use axum::http::StatusCode;
#[cfg(any(feature = "platform", feature = "web-axum"))]
use axum::response::{IntoResponse, Json, Response};
#[cfg(any(feature = "platform", feature = "web-axum"))]
use chrono::Utc;
#[cfg(any(feature = "platform", feature = "web-axum"))]
use log::error;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::Serialize;

use crate::i18n::{I18nBundle, Locale};

/// 应用程序错误类型
///
/// 统一所有应用级别的错误,提供清晰的错误分类和上下文信息
#[derive(Debug, thiserror::Error)]
pub enum CrawlRsError {
    /// 数据库错误。platform 启用时承载 `dbnexus::sea_orm::DbErr`(`#[from]` 自动转换);
    /// 轻量面(agent-lib 等)退化为字符串载荷,不引入 sea-orm。
    /// 匹配处一律用 `Database(_)` 通配载荷,两种构建形态共用同一 match 臂。
    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[error("Database error: {0}")]
    Database(#[from] dbnexus::sea_orm::DbErr),
    #[cfg(not(any(feature = "platform", feature = "web-axum")))]
    #[error("Database error: {0}")]
    Database(String),

    /// 网络错误
    #[error("Network error: {0}")]
    Network(String),

    /// 配置错误
    #[error("Configuration error: {0}")]
    Config(String),

    /// 验证错误
    #[error("Validation error: {0}")]
    Validation(String),

    /// 请求语义无法处理(422:字段缺失/类型不符等结构性校验失败)
    ///
    /// 与 `Validation`(400,值域校验失败)区分:JSON 反序列化成功与否、
    /// 字段结构完整性等"结构正确性"问题按 RFC 9110 归入 422。
    #[error("Unprocessable entity: {0}")]
    Unprocessable(String),

    /// 资源未找到
    #[error("Not found: {0}")]
    NotFound(String),

    /// 认证失败(401,未登录或凭证无效)
    #[error("Authentication failed: {0}")]
    Authentication(String),

    /// 权限拒绝(403,已登录但无权限)
    #[error("Permission denied: {0}")]
    PermissionDenied(String),

    /// 服务不可用(503,下游服务宕机或不可达)
    #[error("Service unavailable: {0}")]
    ServiceUnavailable(String),

    /// 超时错误
    #[error("Timeout: {0}")]
    Timeout(String),

    /// IO 错误
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// JSON 错误
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),

    /// 引擎错误
    #[error("Engine error: {0}")]
    Engine(String),

    /// 缓存错误
    #[error("Cache error: {0}")]
    Cache(String),

    /// 任务错误
    #[error("Task error: {0}")]
    Task(String),

    /// 速率限制错误
    #[error("Rate limit error: {0}")]
    RateLimit(String),

    /// 其他错误
    #[error("Error: {0}")]
    Other(String),
}

impl CrawlRsError {
    /// 将领域错误归一为 sdforge `ApiError` 形态(HTTP 语义分类)。
    ///
    /// sdforge `ApiError` 无 502/504 对应变体(自研库反向需求已登记,见
    /// docs/ARCHITECTURE.md「自研库反向需求」):`Network`/`Engine`/`Timeout`
    /// 三变体返回 `None`,由 [`Self::status_code`] 保留显式状态码。
    /// 其余 14 个变体的 HTTP 状态码改由库映射表单点维护
    /// (`sdforge::error::unified::http_status_for`)。
    #[cfg(any(feature = "platform", feature = "web-axum"))]
    fn to_api_error(&self) -> Option<sdforge::error::ApiError> {
        use sdforge::error::ApiError;
        Some(match self {
            CrawlRsError::Database(_)
            | CrawlRsError::Config(_)
            | CrawlRsError::Io(_)
            | CrawlRsError::Task(_)
            | CrawlRsError::Other(_) => {
                ApiError::internal_error("crawlrs internal error", "internal")
            }
            CrawlRsError::Validation(msg) => ApiError::invalid_input(msg.clone(), None, None),
            CrawlRsError::Json(err) => ApiError::invalid_input(err.to_string(), None, None),
            CrawlRsError::Unprocessable(msg) => ApiError::validation("request", msg.clone()),
            CrawlRsError::NotFound(msg) => ApiError::not_found(msg.clone(), None),
            CrawlRsError::Authentication(msg) => ApiError::authentication_failed(msg.clone()),
            CrawlRsError::PermissionDenied(msg) => ApiError::access_denied(msg.clone(), None),
            CrawlRsError::ServiceUnavailable(_) | CrawlRsError::Cache(_) => {
                ApiError::service_unavailable("crawlrs", None)
            }
            CrawlRsError::RateLimit(_) => ApiError::rate_limit_exceeded(0, 0),
            CrawlRsError::Network(_) | CrawlRsError::Engine(_) | CrawlRsError::Timeout(_) => {
                return None
            }
        })
    }

    /// 获取错误的 HTTP 状态码
    ///
    /// 归一变体经 sdforge `unified::http_status_for` 委托库映射表;
    /// 502/504 为 sdforge 覆盖集外残留(显式保留,缺口见 docs/ARCHITECTURE.md)。
    #[cfg(any(feature = "platform", feature = "web-axum"))]
    pub fn status_code(&self) -> StatusCode {
        if let Some(api_error) = self.to_api_error() {
            return StatusCode::from_u16(sdforge::error::unified::http_status_for(&api_error))
                .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
        }
        match self {
            CrawlRsError::Network(_) | CrawlRsError::Engine(_) => StatusCode::BAD_GATEWAY,
            CrawlRsError::Timeout(_) => StatusCode::GATEWAY_TIMEOUT,
            // to_api_error 对其余变体必然返回 Some;新增变体会先在 to_api_error
            // 的穷尽匹配处编译失败,不会静默落入此臂
            other => unreachable!("status_code residual branch hit by {other:?}"),
        }
    }

    /// 获取错误的代码
    pub fn error_code(&self) -> &'static str {
        match self {
            CrawlRsError::Database(_) => "DATABASE_ERROR",
            CrawlRsError::Network(_) => "EXTERNAL_SERVICE_ERROR",
            CrawlRsError::Config(_) => "CONFIGURATION_ERROR",
            CrawlRsError::Validation(_) => "VALIDATION_ERROR",
            CrawlRsError::Unprocessable(_) => "UNPROCESSABLE_ENTITY",
            CrawlRsError::NotFound(_) => "NOT_FOUND",
            CrawlRsError::Authentication(_) => "AUTHENTICATION_ERROR",
            CrawlRsError::PermissionDenied(_) => "FORBIDDEN",
            CrawlRsError::ServiceUnavailable(_) => "SERVICE_UNAVAILABLE",
            CrawlRsError::Timeout(_) => "TIMEOUT",
            CrawlRsError::Io(_) => "IO_ERROR",
            CrawlRsError::Json(_) => "JSON_ERROR",
            CrawlRsError::Engine(_) => "ENGINE_ERROR",
            CrawlRsError::Cache(_) => "CACHE_ERROR",
            CrawlRsError::Task(_) => "TASK_ERROR",
            CrawlRsError::RateLimit(_) => "RATE_LIMITED",
            CrawlRsError::Other(_) => "INTERNAL_ERROR",
        }
    }

    /// 获取用户可见的错误消息(脱敏后)
    ///
    /// 对外默认出口:启动期 i18n 全局束已初始化时经 Fluent 输出本地化消息
    /// (等价 [`Self::user_message_locale`],locale 为启动检测/配置决议的默认值);
    /// 束未初始化(轻量面构建、单测)时返回英文规范串(双轨基准,FTL 缺失兜底)。
    ///
    /// 此方法不包含敏感的内部实现细节,用于生产环境中的错误响应。
    /// 请求级精确 locale 本地化请使用 `user_message_locale()`。
    pub fn user_message(&self) -> String {
        if let Some((locale, bundle)) = crate::i18n::startup_i18n() {
            return self.user_message_locale(locale, bundle);
        }
        match self {
            CrawlRsError::Database(_) => {
                "Database operation failed. Please try again later.".to_string()
            }
            CrawlRsError::Network(_) => {
                "External service unavailable. Please try again later.".to_string()
            }
            CrawlRsError::Config(_) => "Configuration error. Please contact support.".to_string(),
            CrawlRsError::Validation(msg) => format!("Validation error: {}", msg),
            CrawlRsError::Unprocessable(msg) => format!("Unprocessable entity: {}", msg),
            CrawlRsError::NotFound(msg) => format!("Resource not found: {}", msg),
            CrawlRsError::Authentication(msg) => format!("Authentication failed: {}", msg),
            CrawlRsError::PermissionDenied(msg) => format!("Permission denied: {}", msg),
            CrawlRsError::ServiceUnavailable(_) => {
                "Service unavailable. Please try again later.".to_string()
            }
            CrawlRsError::Timeout(_) => "Request timed out. Please try again later.".to_string(),
            CrawlRsError::Io(_) => "Internal I/O error. Please try again later.".to_string(),
            CrawlRsError::Json(_) => "Invalid JSON format. Please check your request.".to_string(),
            CrawlRsError::Engine(e) => sanitize_engine_error(e),
            CrawlRsError::Cache(_) => {
                "Cache service unavailable. Please try again later.".to_string()
            }
            CrawlRsError::Task(_) => "Task processing error. Please try again later.".to_string(),
            CrawlRsError::RateLimit(_) => {
                "Rate limit exceeded. Please slow down your requests.".to_string()
            }
            CrawlRsError::Other(_) => "Internal server error. Please try again later.".to_string(),
        }
    }

    /// 获取本地化的用户可见错误消息
    ///
    /// 根据请求的 locale 返回对应语言的错误消息。如果翻译 key 不存在,
    /// 回退到 default locale;如果 default locale 也不存在,返回 key 本身。
    pub fn user_message_locale(&self, locale: &Locale, bundle: &I18nBundle) -> String {
        match self {
            CrawlRsError::Database(_) => bundle.translate(locale, "error-database"),
            CrawlRsError::Network(_) => bundle.translate(locale, "error-network"),
            CrawlRsError::Config(_) => bundle.translate(locale, "error-config"),
            CrawlRsError::Validation(msg) => bundle.translate_with_args(
                locale,
                "error-validation",
                &[("message", msg.as_str().to_string())],
            ),
            CrawlRsError::Unprocessable(msg) => bundle.translate_with_args(
                locale,
                "error-validation",
                &[("message", msg.as_str().to_string())],
            ),
            CrawlRsError::NotFound(msg) => bundle.translate_with_args(
                locale,
                "error-not-found",
                &[("resource", msg.as_str().to_string())],
            ),
            CrawlRsError::Authentication(msg) => bundle.translate_with_args(
                locale,
                "error-auth",
                &[("reason", msg.as_str().to_string())],
            ),
            CrawlRsError::PermissionDenied(_) => bundle.translate(locale, "error-permission"),
            CrawlRsError::ServiceUnavailable(_) => {
                bundle.translate(locale, "error-service-unavailable")
            }
            CrawlRsError::Timeout(_) => bundle.translate(locale, "error-timeout"),
            CrawlRsError::Io(_) => bundle.translate(locale, "error-io"),
            CrawlRsError::Json(_) => bundle.translate(locale, "error-json"),
            CrawlRsError::Engine(_) => bundle.translate(locale, "error-engine"),
            CrawlRsError::Cache(_) => bundle.translate(locale, "error-cache"),
            CrawlRsError::Task(_) => bundle.translate(locale, "error-task"),
            CrawlRsError::RateLimit(_) => bundle.translate(locale, "error-rate-limit"),
            CrawlRsError::Other(_) => bundle.translate(locale, "error-internal"),
        }
    }

    /// 获取详细错误信息(用于日志)
    ///
    /// 此方法返回完整的错误详情,包含所有内部实现细节。
    /// 仅用于服务器端日志记录,不应暴露给客户端。
    pub fn detailed_message(&self) -> String {
        self.to_string()
    }

    /// 转换为 API 错误响应格式
    pub fn to_api_error_response(&self) -> ApiErrorResponse {
        ApiErrorResponse {
            code: self.error_code().to_string(),
            message: self.to_string(),
        }
    }
}

/// API 错误响应结构
#[derive(Debug, Serialize)]
pub struct ApiErrorResponse {
    /// 错误代码
    pub code: String,
    /// 错误消息
    pub message: String,
}

/// 应用程序结果类型
///
/// 使用统一的错误类型作为 Result 的错误变体
pub type CrawlRsResult<T> = Result<T, CrawlRsError>;

impl From<CrawlRsError> for ApiErrorResponse {
    fn from(error: CrawlRsError) -> Self {
        error.to_api_error_response()
    }
}

// 错误信息脱敏函数

/// 检查是否应该显示详细错误信息
///
/// 在开发环境中显示详细错误信息便于调试,在生产环境中隐藏敏感信息。
/// 默认情况下隐藏详细错误信息(安全优先)。
#[cfg(any(feature = "platform", feature = "web-axum"))]
fn should_show_detailed_errors() -> bool {
    // 检查多个环境变量以支持不同的配置方式
    let env = std::env::var("CRAWLRS_ENV")
        .or_else(|_| std::env::var("APP_ENVIRONMENT"))
        .or_else(|_| std::env::var("RUST_ENV"))
        .unwrap_or_else(|_| "production".to_string());

    // 只有明确设置为开发环境时才显示详细错误
    env.eq_ignore_ascii_case("development")
        || env.eq_ignore_ascii_case("dev")
        || env.eq_ignore_ascii_case("local")
}

/// 脱敏引擎错误信息
///
/// 移除引擎错误中的敏感信息,包括:
/// - 文件路径
/// - IP 地址
/// - 端口号
/// - URL 中的敏感参数
///
/// 所有 regex 预编译为模块级 Lazy 静态变量,避免每次调用重新编译。
fn sanitize_engine_error(error: &str) -> String {
    static RE_FILE_PATH: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"/[a-zA-Z0-9_/.-]+\.(rs|toml|env|yml|json|txt)").unwrap());
    static RE_LINE_NUMBER: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"[a-zA-Z0-9_/.-]+\.rs:\d+").unwrap());
    static RE_INTERNAL_IP: Lazy<Regex> = Lazy::new(|| {
        Regex::new(
        r"\b(10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[0-1])\.\d{1,3}\.\d{1,3})\b"
    ).unwrap()
    });
    static RE_INTERNAL_SERVICE: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"(localhost|127\.0\.0\.1):\d+").unwrap());
    static RE_PUBLIC_IP: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"\b(?:[0-9]{1,2}|1[01][0-9]|12[0-689]|1[3-9][0-9]|2[0-4][0-9]|25[0-5])\.(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){2}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b").unwrap()
    });
    static RE_URL_PARAMS: Lazy<Regex> = Lazy::new(|| Regex::new(r"\?[^#\s]+").unwrap());
    static RE_URL_CREDS: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"(https?://)[^:]+:[^@]+@").unwrap());
    static RE_DB_PASSWORD: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"(postgres|mysql|mongodb|redis)://[^:]+:[^@]+@").unwrap());
    static RE_API_KEY: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"(?i)(api[_-]?key|token|secret|password|auth)[=:\s]+[^\s&]+").unwrap()
    });

    let mut sanitized = error.to_string();

    sanitized = RE_FILE_PATH
        .replace_all(&sanitized, "[FILE_PATH]")
        .to_string();
    sanitized = RE_LINE_NUMBER
        .replace_all(&sanitized, "[LOCATION]")
        .to_string();
    sanitized = RE_INTERNAL_IP
        .replace_all(&sanitized, "[INTERNAL_IP]")
        .to_string();
    sanitized = RE_INTERNAL_SERVICE
        .replace_all(&sanitized, "$1:[PORT]")
        .to_string();
    sanitized = RE_PUBLIC_IP.replace_all(&sanitized, "[IP]").to_string();
    sanitized = RE_URL_PARAMS
        .replace_all(&sanitized, "?[PARAMS_REDACTED]")
        .to_string();
    sanitized = RE_URL_CREDS
        .replace_all(&sanitized, "$1[CREDENTIALS_REDACTED]@")
        .to_string();
    sanitized = RE_DB_PASSWORD
        .replace_all(&sanitized, "$1://[USER]:[PASSWORD]@")
        .to_string();
    sanitized = RE_API_KEY
        .replace_all(&sanitized, "$1=[REDACTED]")
        .to_string();

    // 如果脱敏后消息为空或太短,返回通用错误消息
    if sanitized.trim().is_empty() || sanitized.len() < 5 {
        return "Engine error occurred".to_string();
    }

    sanitized
}

// IntoResponse 实现

/// 为 CrawlRsError 实现 IntoResponse trait
///
/// 根据环境自动选择返回详细错误信息或脱敏后的错误信息:
/// - 开发环境:返回详细错误信息,便于调试
/// - 生产环境:返回脱敏后的用户友好错误信息,详细错误记录到日志
#[cfg(any(feature = "platform", feature = "web-axum"))]
impl IntoResponse for CrawlRsError {
    fn into_response(self) -> Response {
        let status = self.status_code();
        let error_code = self.error_code();
        let detailed_msg = self.detailed_message();

        error!(
            "Request error occurred error_code={:?} status_code={} error_details={}",
            error_code,
            status.as_u16(),
            detailed_msg
        );

        // 根据环境决定返回给客户端的错误信息
        // 双渲染器统一:走与 response_builder 相同的 ApiResponse 包封
        // (data=null + timestamp + error.{code,message})。error.status 为
        // 冗余字段(HTTP 状态码即权威),随登记簿清零移除。
        let error_response = if should_show_detailed_errors() {
            // 开发环境:返回详细错误信息
            serde_json::json!({
                "success": false,
                "data": serde_json::Value::Null,
                "error": {
                    "code": error_code,
                    "message": detailed_msg,
                },
                "timestamp": Utc::now().to_rfc3339(),
            })
        } else {
            // 生产环境:返回脱敏后的用户友好错误信息
            let user_msg = self.user_message();
            serde_json::json!({
                "success": false,
                "data": serde_json::Value::Null,
                "error": {
                    "code": error_code,
                    "message": user_msg,
                },
                "timestamp": Utc::now().to_rfc3339(),
            })
        };

        (status, Json(error_response)).into_response()
    }
}

/// 从 reqwest::Error 转换为 CrawlRsError::Network
///
/// 保留 `?` 操作符对 reqwest 错误的自动转换能力。
/// 变体 `Network(String)` 不再使用 `#[from]`,因此需要手动实现。
impl From<reqwest::Error> for CrawlRsError {
    fn from(err: reqwest::Error) -> Self {
        CrawlRsError::Network(err.to_string())
    }
}

/// 从 EngineError 转换为 CrawlRsError
///
/// 统一引擎层的错误到应用层错误处理
impl From<crate::engines::engine_client::EngineError> for CrawlRsError {
    fn from(err: crate::engines::engine_client::EngineError) -> Self {
        match err {
            crate::engines::engine_client::EngineError::RequestFailed(msg) => {
                CrawlRsError::Engine(msg)
            }
            crate::engines::engine_client::EngineError::Timeout(duration) => {
                CrawlRsError::Timeout(format!("Request timed out after {:?}", duration))
            }
            crate::engines::engine_client::EngineError::NoEnginesAvailable => {
                CrawlRsError::Engine("No scraping engines available".to_string())
            }
            crate::engines::engine_client::EngineError::MemoryConstrained(msg) => {
                CrawlRsError::Engine(format!("Memory constrained: {}", msg))
            }
            crate::engines::engine_client::EngineError::Unsupported(msg) => {
                CrawlRsError::Engine(format!("Unsupported operation: {}", msg))
            }
            crate::engines::engine_client::EngineError::InvalidUrl(msg) => {
                CrawlRsError::Validation(msg)
            }
            crate::engines::engine_client::EngineError::SsrfProtection(msg) => {
                CrawlRsError::PermissionDenied(format!("SSRF protection triggered: {}", msg))
            }
            crate::engines::engine_client::EngineError::BrowserError(msg) => {
                CrawlRsError::Engine(format!("Browser error: {}", msg))
            }
            crate::engines::engine_client::EngineError::AntiBotDetected(msg) => {
                CrawlRsError::Engine(format!("Anti-bot detected: {}", msg))
            }
            crate::engines::engine_client::EngineError::FeatureToggle(msg) => {
                CrawlRsError::Engine(format!("Feature toggle: {}", msg))
            }
            crate::engines::engine_client::EngineError::Expired => {
                CrawlRsError::Timeout("Request expired".to_string())
            }
            crate::engines::engine_client::EngineError::AllEnginesFailed(msg) => {
                CrawlRsError::Engine(format!("All engines failed: {}", msg))
            }
            crate::engines::engine_client::EngineError::Other(msg) => CrawlRsError::Engine(msg),
            crate::engines::engine_client::EngineError::Internal(msg) => CrawlRsError::Engine(msg),
            // 引擎级 MRT 超时:映射到 Timeout,
            // 错误信息携带 engine 名字 + mrt 时长,便于调用方定位瀑布式 fallback 失败点
            crate::engines::engine_client::EngineError::EngineMrtExceeded { engine, mrt } => {
                CrawlRsError::Timeout(format!(
                    "Engine {} exceeded MRT of {:?} (waterfall fallback exhausted)",
                    engine, mrt
                ))
            }
        }
    }
}

// 通用错误转换宏(从 utils/errors.rs 迁移)

/// 为错误类型生成标准 From 转换(`From<String>` / `From<&str>` / `From<anyhow::Error>`)
///
/// 用法:`impl_basic_error_conversions!(MyError, TargetVariant);`
#[macro_export]
macro_rules! impl_basic_error_conversions {
    ($error_type:ty, $variant:ident) => {
        impl From<String> for $error_type {
            fn from(msg: String) -> Self {
                Self::$variant(msg)
            }
        }

        impl From<&str> for $error_type {
            fn from(msg: &str) -> Self {
                Self::$variant(msg.to_string())
            }
        }

        impl From<anyhow::Error> for $error_type {
            fn from(err: anyhow::Error) -> Self {
                Self::$variant(err.to_string())
            }
        }
    };
}

// 仓库层错误类型(从 utils/errors.rs 迁移)

/// 通用仓库层错误类型
///
/// 注意:与 `domain::repositories::task_repository::RepositoryError` 是不同类型,
/// 后者专用于任务仓库,变体为 `Database(anyhow::Error)` / `NotFound`。
#[derive(Debug, thiserror::Error)]
pub enum RepositoryError {
    #[error("Database error: {0}")]
    DatabaseError(String),

    #[error("Record not found")]
    NotFound,

    #[error("Record already exists")]
    AlreadyExists,

    #[error("Invalid parameter: {0}")]
    InvalidParameter(String),

    #[error("Internal error: {0}")]
    InternalError(String),
}

// Worker 错误类型(从 utils/errors.rs 迁移)

/// Worker 错误类型
#[derive(Debug, thiserror::Error)]
pub enum WorkerError {
    #[error("Repository error: {0}")]
    RepositoryError(String),

    #[error("Rate limiting error: {0}")]
    RateLimitingError(String),

    #[error("Internal error: {0}")]
    InternalError(String),

    #[error("Domain error: {0}")]
    DomainError(String),

    #[error("Service error: {0}")]
    ServiceError(String),

    #[error("Not found: {0}")]
    NotFound(String),
}

impl_basic_error_conversions!(WorkerError, InternalError);

impl From<RepositoryError> for WorkerError {
    fn from(err: RepositoryError) -> Self {
        match err {
            RepositoryError::DatabaseError(msg) => WorkerError::RepositoryError(msg),
            RepositoryError::NotFound => WorkerError::NotFound("Resource not found".to_string()),
            RepositoryError::AlreadyExists => {
                WorkerError::RepositoryError("Resource already exists".to_string())
            }
            RepositoryError::InvalidParameter(msg) => WorkerError::DomainError(msg),
            RepositoryError::InternalError(msg) => WorkerError::InternalError(msg),
        }
    }
}

// From<RepositoryError> for CrawlRsError(通用仓库错误 → 应用错误)

impl From<RepositoryError> for CrawlRsError {
    fn from(err: RepositoryError) -> Self {
        match err {
            // 双态:platform 下重建 DbErr::Custom 保住 Database 变体语义;
            // 轻量面 Database 直接承载字符串。
            #[cfg(any(feature = "platform", feature = "web-axum"))]
            RepositoryError::DatabaseError(msg) => {
                CrawlRsError::Database(dbnexus::sea_orm::DbErr::Custom(msg))
            }
            #[cfg(not(any(feature = "platform", feature = "web-axum")))]
            RepositoryError::DatabaseError(msg) => CrawlRsError::Database(msg),
            RepositoryError::NotFound => CrawlRsError::NotFound("Resource not found".to_string()),
            RepositoryError::AlreadyExists => {
                CrawlRsError::Validation("Resource already exists".to_string())
            }
            RepositoryError::InvalidParameter(msg) => CrawlRsError::Validation(msg),
            RepositoryError::InternalError(msg) => CrawlRsError::Other(msg),
        }
    }
}

// From<task_repository::RepositoryError> for CrawlRsError(任务仓库错误 → 应用错误)

impl From<crate::domain::repositories::task_repository::RepositoryError> for CrawlRsError {
    fn from(err: crate::domain::repositories::task_repository::RepositoryError) -> Self {
        match err {
            crate::domain::repositories::task_repository::RepositoryError::Database(db_err) => {
                CrawlRsError::Other(db_err.to_string())
            }
            crate::domain::repositories::task_repository::RepositoryError::NotFound => {
                CrawlRsError::NotFound("Resource not found".to_string())
            }
            crate::domain::repositories::task_repository::RepositoryError::Conflict { detail } => {
                CrawlRsError::Validation(detail)
            }
        }
    }
}

// From<confers::ConfigError> for CrawlRsError

impl From<confers::ConfigError> for CrawlRsError {
    fn from(err: confers::ConfigError) -> Self {
        CrawlRsError::Config(err.to_string())
    }
}

// From<RobotsCheckerError> for CrawlRsError

impl From<crate::utils::robots::RobotsCheckerError> for CrawlRsError {
    fn from(err: crate::utils::robots::RobotsCheckerError) -> Self {
        CrawlRsError::Other(err.to_string())
    }
}

// 为 CrawlRsError 生成 From<String> / From<&str> / From<anyhow::Error>(映射到 Other 变体)
impl_basic_error_conversions!(CrawlRsError, Other);

// RepositoryResultExt —— 消除重复的 .map_err(|e| WorkerError::RepositoryError(...))

/// 将任意 Display 错误结果转换为 WorkerError::RepositoryError 的扩展 trait
pub trait RepositoryResultExt<T> {
    /// 转换为 WorkerError 格式
    fn repo_err(self) -> Result<T, WorkerError>;
}

impl<T, E: std::fmt::Display> RepositoryResultExt<T> for Result<T, E> {
    fn repo_err(self) -> Result<T, WorkerError> {
        self.map_err(|e| WorkerError::RepositoryError(e.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(any(feature = "platform", feature = "web-axum"))]
    use crate::common::test_support::ENV_MUTEX;
    #[cfg(any(feature = "platform", feature = "web-axum"))]
    use axum::http::StatusCode;
    use std::time::Duration;

    #[test]
    fn test_error_display() {
        let err = CrawlRsError::NotFound("User".to_string());
        assert_eq!(err.to_string(), "Not found: User");
    }

    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[test]
    fn test_status_code_mapping() {
        assert_eq!(
            CrawlRsError::NotFound("test".to_string()).status_code(),
            StatusCode::NOT_FOUND
        );
        assert_eq!(
            CrawlRsError::Validation("test".to_string()).status_code(),
            StatusCode::BAD_REQUEST
        );
        assert_eq!(
            CrawlRsError::PermissionDenied("test".to_string()).status_code(),
            StatusCode::FORBIDDEN
        );
        assert_eq!(
            CrawlRsError::RateLimit("test".to_string()).status_code(),
            StatusCode::TOO_MANY_REQUESTS
        );
    }

    /// 双 cfg 构造器:platform 下载荷为 dbnexus::sea_orm::DbErr,轻量面下为 String——
    /// 使 DB 错误映射测试在两种构建形态下都可编译(2026-09-19 审计)。
    fn make_db_error(msg: &str) -> CrawlRsError {
        #[cfg(any(feature = "platform", feature = "web-axum"))]
        {
            CrawlRsError::Database(dbnexus::sea_orm::DbErr::Custom(msg.to_string()))
        }
        #[cfg(not(any(feature = "platform", feature = "web-axum")))]
        {
            CrawlRsError::Database(msg.to_string())
        }
    }

    #[test]
    fn test_error_code_mapping() {
        // Use a Custom error instead of the specific Conn variant
        let db_err = make_db_error("test connection error");
        assert_eq!(db_err.error_code(), "DATABASE_ERROR");
        assert_eq!(
            CrawlRsError::NotFound("test".to_string()).error_code(),
            "NOT_FOUND"
        );
        assert_eq!(
            CrawlRsError::Validation("test".to_string()).error_code(),
            "VALIDATION_ERROR"
        );
    }

    #[test]
    fn test_to_api_error_response() {
        let err = CrawlRsError::NotFound("User not found".to_string());
        let response = err.to_api_error_response();
        assert_eq!(response.code, "NOT_FOUND");
        assert_eq!(response.message, "Not found: User not found");
    }

    // 错误信息脱敏测试

    #[test]
    fn test_user_message_sanitization() {
        // 数据库错误应该返回通用消息
        let db_err =
            make_db_error("Connection failed to postgres://user:password123@localhost:5432");
        let user_msg = db_err.user_message();
        assert!(!user_msg.contains("password123"));
        assert!(!user_msg.contains("localhost:5432"));
        assert!(user_msg.contains("Database operation failed"));

        // 网络错误应该返回通用消息
        let net_err = crate::utils::error_helpers::map_to_network_error(
            "Connection refused to 10.0.0.1:8080",
        );
        let user_msg = net_err.user_message();
        assert!(!user_msg.contains("10.0.0.1"));
        assert!(user_msg.contains("External service unavailable"));

        // 配置错误应该返回通用消息
        let config_err =
            CrawlRsError::Config("Missing database URL in /home/dev/crawlrs/.env".to_string());
        let user_msg = config_err.user_message();
        assert!(!user_msg.contains("/home/dev/"));
        assert!(user_msg.contains("Configuration error"));

        // 验证错误应该保留用户输入的错误信息
        let validation_err = CrawlRsError::Validation("Email format is invalid".to_string());
        let user_msg = validation_err.user_message();
        assert!(user_msg.contains("Email format is invalid"));
    }

    #[test]
    fn test_detailed_message_preserves_info() {
        let err = make_db_error("Connection failed to postgres://user:password123@localhost:5432");
        let detailed = err.detailed_message();
        // 详细消息应该包含所有信息
        assert!(detailed.contains("postgres://"));
    }

    #[test]
    fn test_sanitize_engine_error_removes_file_paths() {
        let error = "Failed to load config from /home/dev/crawlrs/src/config.rs:42";
        let sanitized = sanitize_engine_error(error);
        assert!(!sanitized.contains("/home/dev/crawlrs/"));
        assert!(sanitized.contains("[FILE_PATH]") || sanitized.contains("[LOCATION]"));
    }

    #[test]
    fn test_sanitize_engine_error_removes_internal_ips() {
        let error = "Connection failed to 10.0.0.1:5432 and 192.168.1.100:8080";
        let sanitized = sanitize_engine_error(error);
        assert!(!sanitized.contains("10.0.0.1"));
        assert!(!sanitized.contains("192.168.1.100"));
        assert!(sanitized.contains("[INTERNAL_IP]"));
    }

    #[test]
    fn test_sanitize_engine_error_removes_ports() {
        let error = "Service at localhost:8080 and 127.0.0.1:5432 failed";
        let sanitized = sanitize_engine_error(error);
        assert!(sanitized.contains("localhost:[PORT]"));
        assert!(sanitized.contains("127.0.0.1:[PORT]"));
    }

    #[test]
    fn test_sanitize_engine_error_removes_credentials() {
        let error = "Failed to connect to postgres://admin:secret123@db.example.com:5432/mydb";
        let sanitized = sanitize_engine_error(error);
        assert!(!sanitized.contains("admin:secret123"));
        assert!(sanitized.contains("[USER]:[PASSWORD]"));
    }

    #[test]
    fn test_sanitize_engine_error_removes_api_keys() {
        let error = "Request failed with api_key=sk-1234567890abcdef and token=xyz789";
        let sanitized = sanitize_engine_error(error);
        assert!(!sanitized.contains("sk-1234567890abcdef"));
        assert!(!sanitized.contains("xyz789"));
        assert!(sanitized.contains("[REDACTED]"));
    }

    #[test]
    fn test_sanitize_engine_error_removes_url_params() {
        let error = "Failed to fetch https://api.example.com/data?secret=abc123&token=xyz";
        let sanitized = sanitize_engine_error(error);
        assert!(!sanitized.contains("secret=abc123"));
        assert!(!sanitized.contains("token=xyz"));
        assert!(sanitized.contains("[PARAMS_REDACTED]"));
    }

    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[test]
    fn test_should_show_detailed_errors_in_dev() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_ENV");
        std::env::remove_var("APP_ENVIRONMENT");
        std::env::remove_var("RUST_ENV");
        std::env::set_var("CRAWLRS_ENV", "development");
        assert!(should_show_detailed_errors());
        std::env::remove_var("CRAWLRS_ENV");
    }

    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[test]
    fn test_should_show_detailed_errors_in_local() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_ENV");
        std::env::remove_var("APP_ENVIRONMENT");
        std::env::remove_var("RUST_ENV");
        std::env::set_var("APP_ENVIRONMENT", "local");
        assert!(should_show_detailed_errors());
        std::env::remove_var("APP_ENVIRONMENT");
    }

    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[test]
    fn test_should_hide_detailed_errors_in_prod() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_ENV");
        std::env::remove_var("APP_ENVIRONMENT");
        std::env::remove_var("RUST_ENV");
        std::env::set_var("CRAWLRS_ENV", "production");
        assert!(!should_show_detailed_errors());
        std::env::remove_var("CRAWLRS_ENV");
    }

    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[test]
    fn test_should_hide_detailed_errors_by_default() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        // 默认应该是生产环境模式(安全优先)
        std::env::remove_var("CRAWLRS_ENV");
        std::env::remove_var("APP_ENVIRONMENT");
        std::env::remove_var("RUST_ENV");
        assert!(!should_show_detailed_errors());
    }

    #[test]
    fn test_sanitize_engine_error_empty_input() {
        let msg = "";
        let sanitized = sanitize_engine_error(msg);
        assert_eq!(sanitized, "Engine error occurred");
    }

    #[test]
    fn test_sanitize_engine_error_very_short_input() {
        let msg = "abc";
        let sanitized = sanitize_engine_error(msg);
        assert_eq!(sanitized, "Engine error occurred");
    }

    #[test]
    fn test_sanitize_engine_error_multiple_patterns() {
        let error =
            "Error at /home/dev/crawlrs/src/main.rs:42 with IP 10.0.0.1 and api_key=secret123";
        let sanitized = sanitize_engine_error(error);
        assert!(sanitized.contains("[FILE_PATH]") || sanitized.contains("[LOCATION]"));
        assert!(sanitized.contains("[INTERNAL_IP]"));
        assert!(sanitized.contains("[REDACTED]"));
    }

    // 完整的状态码映射测试 - 覆盖所有变体

    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[test]
    fn test_status_code_all_variants() {
        // 测试所有错误变体的状态码映射
        assert_eq!(
            CrawlRsError::Network("conn refused".to_string()).status_code(),
            StatusCode::BAD_GATEWAY
        );
        assert_eq!(
            CrawlRsError::Config("missing key".to_string()).status_code(),
            StatusCode::INTERNAL_SERVER_ERROR
        );
        assert_eq!(
            CrawlRsError::Timeout("timed out".to_string()).status_code(),
            StatusCode::GATEWAY_TIMEOUT
        );
        assert_eq!(
            CrawlRsError::Io(std::io::Error::other("io fail")).status_code(),
            StatusCode::INTERNAL_SERVER_ERROR
        );
        assert_eq!(
            CrawlRsError::Json(serde_json::from_str::<serde_json::Value>("bad").unwrap_err())
                .status_code(),
            StatusCode::BAD_REQUEST
        );
        assert_eq!(
            CrawlRsError::Engine("engine fail".to_string()).status_code(),
            StatusCode::BAD_GATEWAY
        );
        assert_eq!(
            CrawlRsError::Cache("cache down".to_string()).status_code(),
            StatusCode::SERVICE_UNAVAILABLE
        );
        assert_eq!(
            CrawlRsError::Task("task error".to_string()).status_code(),
            StatusCode::INTERNAL_SERVER_ERROR
        );
        assert_eq!(
            CrawlRsError::Other("unknown".to_string()).status_code(),
            StatusCode::INTERNAL_SERVER_ERROR
        );
        // Database also maps to INTERNAL_SERVER_ERROR
        assert_eq!(
            make_db_error("db down").status_code(),
            StatusCode::INTERNAL_SERVER_ERROR
        );
        // 新增变体:Authentication(401) / ServiceUnavailable(503)
        assert_eq!(
            CrawlRsError::Authentication("bad token".to_string()).status_code(),
            StatusCode::UNAUTHORIZED
        );
        assert_eq!(
            CrawlRsError::ServiceUnavailable("cache down".to_string()).status_code(),
            StatusCode::SERVICE_UNAVAILABLE
        );
    }

    // 完整的错误代码映射测试 - 覆盖所有变体

    #[test]
    fn test_error_code_all_variants() {
        assert_eq!(
            CrawlRsError::Network("test".to_string()).error_code(),
            "EXTERNAL_SERVICE_ERROR"
        );
        assert_eq!(
            CrawlRsError::Config("test".to_string()).error_code(),
            "CONFIGURATION_ERROR"
        );
        assert_eq!(
            CrawlRsError::PermissionDenied("test".to_string()).error_code(),
            "FORBIDDEN"
        );
        assert_eq!(
            CrawlRsError::Timeout("test".to_string()).error_code(),
            "TIMEOUT"
        );
        assert_eq!(
            CrawlRsError::Io(std::io::Error::other("x")).error_code(),
            "IO_ERROR"
        );
        assert_eq!(
            CrawlRsError::Json(serde_json::from_str::<serde_json::Value>("x").unwrap_err())
                .error_code(),
            "JSON_ERROR"
        );
        assert_eq!(
            CrawlRsError::Engine("test".to_string()).error_code(),
            "ENGINE_ERROR"
        );
        assert_eq!(
            CrawlRsError::Cache("test".to_string()).error_code(),
            "CACHE_ERROR"
        );
        assert_eq!(
            CrawlRsError::Task("test".to_string()).error_code(),
            "TASK_ERROR"
        );
        assert_eq!(
            CrawlRsError::Other("test".to_string()).error_code(),
            "INTERNAL_ERROR"
        );
        assert_eq!(
            CrawlRsError::RateLimit("test".to_string()).error_code(),
            "RATE_LIMITED"
        );
        // 新增变体
        assert_eq!(
            CrawlRsError::Authentication("test".to_string()).error_code(),
            "AUTHENTICATION_ERROR"
        );
        assert_eq!(
            CrawlRsError::ServiceUnavailable("test".to_string()).error_code(),
            "SERVICE_UNAVAILABLE"
        );
    }

    // 完整的 user_message 测试 - 覆盖所有变体

    #[test]
    fn test_user_message_all_variants() {
        // 数据库、网络、配置等通用错误返回固定消息
        assert_eq!(
            CrawlRsError::Network("http://10.0.0.1".to_string()).user_message(),
            "External service unavailable. Please try again later."
        );
        assert_eq!(
            CrawlRsError::Config("/etc/crawlrs/config.toml".to_string()).user_message(),
            "Configuration error. Please contact support."
        );
        assert_eq!(
            CrawlRsError::Timeout("30s".to_string()).user_message(),
            "Request timed out. Please try again later."
        );
        assert_eq!(
            CrawlRsError::Io(std::io::Error::other("x")).user_message(),
            "Internal I/O error. Please try again later."
        );
        assert_eq!(
            CrawlRsError::Json(serde_json::from_str::<serde_json::Value>("x").unwrap_err())
                .user_message(),
            "Invalid JSON format. Please check your request."
        );
        assert_eq!(
            CrawlRsError::Cache("cache down".to_string()).user_message(),
            "Cache service unavailable. Please try again later."
        );
        assert_eq!(
            CrawlRsError::Task("task failed".to_string()).user_message(),
            "Task processing error. Please try again later."
        );
        assert_eq!(
            CrawlRsError::RateLimit("too fast".to_string()).user_message(),
            "Rate limit exceeded. Please slow down your requests."
        );
        assert_eq!(
            CrawlRsError::Other("unknown".to_string()).user_message(),
            "Internal server error. Please try again later."
        );

        // 携带上下文的错误保留原始信息
        let not_found = CrawlRsError::NotFound("user 42".to_string());
        assert!(not_found.user_message().contains("user 42"));

        let perm = CrawlRsError::PermissionDenied("insufficient scope".to_string());
        assert!(perm.user_message().contains("insufficient scope"));

        // 新增变体
        let auth = CrawlRsError::Authentication("bad token".to_string());
        assert!(auth.user_message().contains("Authentication failed"));

        let svc_unavail = CrawlRsError::ServiceUnavailable("cache down".to_string());
        assert!(svc_unavail.user_message().contains("Service unavailable"));

        // 引擎错误经过脱敏处理
        let engine_err = CrawlRsError::Engine(
            "Failed at /home/dev/src/main.rs:42 with api_key=secret".to_string(),
        );
        let msg = engine_err.user_message();
        assert!(!msg.contains("secret"));
        assert!(!msg.contains("/home/dev/"));
    }

    // From<CrawlRsError> for ApiErrorResponse 测试

    #[test]
    fn test_from_app_error_to_api_error_response() {
        let err = CrawlRsError::Validation("field required".to_string());
        let response: ApiErrorResponse = err.into();
        assert_eq!(response.code, "VALIDATION_ERROR");
        assert_eq!(response.message, "Validation error: field required");
    }

    #[test]
    fn test_from_app_error_network_to_api_error_response() {
        let err = CrawlRsError::Network("timeout".to_string());
        let response: ApiErrorResponse = err.into();
        assert_eq!(response.code, "EXTERNAL_SERVICE_ERROR");
        assert!(response.message.contains("timeout"));
    }

    // IntoResponse 测试 - 生产环境和开发环境

    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[tokio::test]
    async fn test_into_response_production_env() {
        let response = {
            let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
            std::env::set_var("CRAWLRS_ENV", "production");
            std::env::remove_var("APP_ENVIRONMENT");
            std::env::remove_var("RUST_ENV");
            CrawlRsError::NotFound("resource 123".to_string()).into_response()
        };

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert_eq!(json["success"], false);
        assert_eq!(json["error"]["code"], "NOT_FOUND");
        assert_eq!(json["data"], serde_json::Value::Null);
        assert!(json.get("timestamp").is_some());
        // 生产环境返回脱敏后的用户消息
        assert!(json["error"]["message"]
            .as_str()
            .unwrap()
            .contains("Resource not found"));
    }

    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[tokio::test]
    async fn test_into_response_development_env() {
        let response = {
            let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
            std::env::set_var("CRAWLRS_ENV", "development");
            CrawlRsError::Validation("bad input".to_string()).into_response()
        };

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert_eq!(json["success"], false);
        assert_eq!(json["error"]["code"], "VALIDATION_ERROR");
        assert_eq!(json["data"], serde_json::Value::Null);
        assert!(json.get("timestamp").is_some());
        // 开发环境返回详细错误信息
        assert!(json["error"]["message"]
            .as_str()
            .unwrap()
            .contains("bad input"));
    }

    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[tokio::test]
    async fn test_into_response_rate_limit() {
        let response = {
            let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
            std::env::set_var("CRAWLRS_ENV", "production");
            std::env::remove_var("APP_ENVIRONMENT");
            std::env::remove_var("RUST_ENV");
            CrawlRsError::RateLimit("too many requests".to_string()).into_response()
        };

        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert_eq!(json["error"]["code"], "RATE_LIMITED");
        assert_eq!(json["data"], serde_json::Value::Null);
        assert!(json.get("timestamp").is_some());
    }

    // From<EngineError> 测试 - 覆盖所有 EngineError 变体

    #[test]
    fn test_from_engine_error_request_failed() {
        let err: CrawlRsError =
            crate::engines::engine_client::EngineError::RequestFailed("conn refused".to_string())
                .into();
        match err {
            CrawlRsError::Engine(msg) => assert!(msg.contains("conn refused")),
            other => panic!("expected Engine variant, got {:?}", other),
        }
    }

    #[test]
    fn test_from_engine_error_timeout() {
        let err: CrawlRsError =
            crate::engines::engine_client::EngineError::Timeout(Duration::from_secs(30)).into();
        match err {
            CrawlRsError::Timeout(msg) => assert!(msg.contains("30")),
            other => panic!("expected Timeout variant, got {:?}", other),
        }
    }

    #[test]
    fn test_from_engine_error_no_engines_available() {
        let err: CrawlRsError =
            crate::engines::engine_client::EngineError::NoEnginesAvailable.into();
        match err {
            CrawlRsError::Engine(msg) => assert!(msg.contains("No scraping engines available")),
            other => panic!("expected Engine variant, got {:?}", other),
        }
    }

    #[test]
    fn test_from_engine_error_invalid_url() {
        let err: CrawlRsError =
            crate::engines::engine_client::EngineError::InvalidUrl("bad url".to_string()).into();
        match err {
            CrawlRsError::Validation(msg) => assert_eq!(msg, "bad url"),
            other => panic!("expected Validation variant, got {:?}", other),
        }
    }

    #[test]
    fn test_from_engine_error_ssrf_protection() {
        let err: CrawlRsError =
            crate::engines::engine_client::EngineError::SsrfProtection("127.0.0.1".to_string())
                .into();
        match err {
            CrawlRsError::PermissionDenied(msg) => {
                assert!(msg.contains("SSRF protection"));
                assert!(msg.contains("127.0.0.1"));
            }
            other => panic!("expected PermissionDenied variant, got {:?}", other),
        }
    }

    #[test]
    fn test_from_engine_error_browser_error() {
        let err: CrawlRsError =
            crate::engines::engine_client::EngineError::BrowserError("crashed".to_string()).into();
        match err {
            CrawlRsError::Engine(msg) => {
                assert!(msg.contains("Browser error"));
                assert!(msg.contains("crashed"));
            }
            other => panic!("expected Engine variant, got {:?}", other),
        }
    }

    #[test]
    fn test_from_engine_error_antibot_detected() {
        let err: CrawlRsError = crate::engines::engine_client::EngineError::AntiBotDetected(
            "Cloudflare challenge".to_string(),
        )
        .into();
        match err {
            CrawlRsError::Engine(msg) => {
                assert!(msg.contains("Anti-bot detected"));
                assert!(msg.contains("Cloudflare challenge"));
            }
            other => panic!("expected Engine variant, got {:?}", other),
        }
    }

    #[test]
    fn test_from_engine_error_expired() {
        let err: CrawlRsError = crate::engines::engine_client::EngineError::Expired.into();
        match err {
            CrawlRsError::Timeout(msg) => assert_eq!(msg, "Request expired"),
            other => panic!("expected Timeout variant, got {:?}", other),
        }
    }

    #[test]
    fn test_from_engine_error_all_engines_failed() {
        let err: CrawlRsError =
            crate::engines::engine_client::EngineError::AllEnginesFailed("all down".to_string())
                .into();
        match err {
            CrawlRsError::Engine(msg) => {
                assert!(msg.contains("All engines failed"));
                assert!(msg.contains("all down"));
            }
            other => panic!("expected Engine variant, got {:?}", other),
        }
    }

    #[test]
    fn test_from_engine_error_other() {
        let err: CrawlRsError =
            crate::engines::engine_client::EngineError::Other("misc".to_string()).into();
        match err {
            CrawlRsError::Engine(msg) => assert_eq!(msg, "misc"),
            other => panic!("expected Engine variant, got {:?}", other),
        }
    }

    #[test]
    fn test_from_engine_error_internal() {
        let err: CrawlRsError =
            crate::engines::engine_client::EngineError::Internal("internal bug".to_string()).into();
        match err {
            CrawlRsError::Engine(msg) => assert_eq!(msg, "internal bug"),
            other => panic!("expected Engine variant, got {:?}", other),
        }
    }

    // From<reqwest::Error> 测试

    #[test]
    fn test_from_reqwest_error_conversion() {
        // reqwest 0.13 + rustls 后端下 Certificate::from_pem 不再立即验证 PEM,
        // 改用无效代理 URL 触发 reqwest::Error。
        let result = reqwest::Proxy::all("not a valid url");
        assert!(result.is_err(), "Proxy::all should reject invalid URL");
        let reqwest_err = result.unwrap_err();
        let app_err: CrawlRsError = reqwest_err.into();
        match app_err {
            CrawlRsError::Network(msg) => assert!(!msg.is_empty()),
            other => panic!("expected Network variant, got {:?}", other),
        }
    }

    // 迁移自 utils/errors.rs:WorkerError / RepositoryError / RepositoryResultExt

    #[test]
    fn test_worker_error_from_string() {
        let err: WorkerError = "something failed".to_string().into();
        assert!(matches!(err, WorkerError::InternalError(msg) if msg == "something failed"));
    }

    #[test]
    fn test_worker_error_from_str() {
        let err: WorkerError = "disk full".into();
        assert!(matches!(err, WorkerError::InternalError(msg) if msg == "disk full"));
    }

    #[test]
    fn test_worker_error_from_anyhow() {
        let err: WorkerError = anyhow::anyhow!("network down").into();
        assert!(matches!(err, WorkerError::InternalError(msg) if msg.contains("network down")));
    }

    #[test]
    fn test_app_error_from_string_via_macro() {
        let err: CrawlRsError = "boom".to_string().into();
        assert!(matches!(err, CrawlRsError::Other(msg) if msg == "boom"));
    }

    #[test]
    fn test_app_error_from_str_via_macro() {
        let err: CrawlRsError = "crash".into();
        assert!(matches!(err, CrawlRsError::Other(msg) if msg == "crash"));
    }

    #[test]
    fn test_app_error_from_anyhow_via_macro() {
        let err: CrawlRsError = anyhow::anyhow!("db timeout").into();
        assert!(matches!(err, CrawlRsError::Other(msg) if msg.contains("db timeout")));
    }

    // From<RepositoryError> for WorkerError

    #[test]
    fn test_worker_error_from_repository_database_error() {
        let err: WorkerError = RepositoryError::DatabaseError("conn refused".to_string()).into();
        assert!(matches!(err, WorkerError::RepositoryError(msg) if msg == "conn refused"));
    }

    #[test]
    fn test_worker_error_from_repository_not_found() {
        let err: WorkerError = RepositoryError::NotFound.into();
        assert!(matches!(err, WorkerError::NotFound(msg) if msg.contains("not found")));
    }

    #[test]
    fn test_worker_error_from_repository_already_exists() {
        let err: WorkerError = RepositoryError::AlreadyExists.into();
        assert!(matches!(err, WorkerError::RepositoryError(msg) if msg.contains("already exists")));
    }

    #[test]
    fn test_worker_error_from_repository_invalid_parameter() {
        let err: WorkerError = RepositoryError::InvalidParameter("bad uuid".to_string()).into();
        assert!(matches!(err, WorkerError::DomainError(msg) if msg == "bad uuid"));
    }

    #[test]
    fn test_worker_error_from_repository_internal_error() {
        let err: WorkerError = RepositoryError::InternalError("oops".to_string()).into();
        assert!(matches!(err, WorkerError::InternalError(msg) if msg == "oops"));
    }

    // From<RepositoryError> for CrawlRsError

    #[test]
    fn test_app_error_from_repository_database_error() {
        let err: CrawlRsError = RepositoryError::DatabaseError("conn refused".to_string()).into();
        // 双态:platform 下为 Database(DbErr::Custom),轻量面为 Database(String)——
        // 统一断言 Database(_) 变体与消息语义
        assert!(matches!(
            err,
            CrawlRsError::Database(ref m) if m.to_string().contains("conn refused")
        ));
    }

    #[test]
    fn test_app_error_from_repository_not_found() {
        let err: CrawlRsError = RepositoryError::NotFound.into();
        assert!(matches!(err, CrawlRsError::NotFound(msg) if msg.contains("not found")));
    }

    #[test]
    fn test_app_error_from_repository_already_exists() {
        let err: CrawlRsError = RepositoryError::AlreadyExists.into();
        assert!(matches!(err, CrawlRsError::Validation(msg) if msg.contains("already exists")));
    }

    #[test]
    fn test_app_error_from_repository_invalid_parameter() {
        let err: CrawlRsError = RepositoryError::InvalidParameter("bad input".to_string()).into();
        assert!(matches!(err, CrawlRsError::Validation(msg) if msg == "bad input"));
    }

    #[test]
    fn test_app_error_from_repository_internal_error() {
        let err: CrawlRsError = RepositoryError::InternalError("oops".to_string()).into();
        assert!(matches!(err, CrawlRsError::Other(msg) if msg == "oops"));
    }

    // From<task_repository::RepositoryError> for CrawlRsError

    #[test]
    fn test_app_error_from_task_repo_database_error() {
        use crate::domain::repositories::task_repository::RepositoryError as TaskRepoError;
        let err: CrawlRsError = TaskRepoError::Database(anyhow::anyhow!("pool exhausted")).into();
        assert!(matches!(err, CrawlRsError::Other(msg) if msg.contains("pool exhausted")));
    }

    #[test]
    fn test_app_error_from_task_repo_not_found() {
        use crate::domain::repositories::task_repository::RepositoryError as TaskRepoError;
        let err: CrawlRsError = TaskRepoError::NotFound.into();
        assert!(matches!(err, CrawlRsError::NotFound(msg) if msg.contains("not found")));
    }

    // From<RobotsCheckerError> for CrawlRsError

    #[test]
    fn test_app_error_from_robots_checker_error() {
        let robots_err =
            crate::utils::robots::RobotsCheckerError::ValidationError("blocked".to_string());
        let err: CrawlRsError = robots_err.into();
        assert!(matches!(err, CrawlRsError::Other(msg) if msg.contains("blocked")));
    }

    // RepositoryResultExt

    #[test]
    fn test_repository_result_ext_ok() {
        let result: Result<i32, &str> = Ok(42);
        assert_eq!(result.repo_err().expect("ok should pass through"), 42);
    }

    #[test]
    fn test_repository_result_ext_err_maps_to_worker_error() {
        let result: Result<i32, &str> = Err("disk failure");
        let err = result.repo_err().unwrap_err();
        assert!(matches!(err, WorkerError::RepositoryError(msg) if msg.contains("disk failure")));
    }

    // 新变体 Authentication / ServiceUnavailable 的 IntoResponse

    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[tokio::test]
    async fn test_app_error_authentication_returns_401() {
        let response = {
            let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
            std::env::remove_var("CRAWLRS_ENV");
            std::env::remove_var("APP_ENVIRONMENT");
            std::env::remove_var("RUST_ENV");
            CrawlRsError::Authentication("bad token".to_string()).into_response()
        };
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"]["code"], "AUTHENTICATION_ERROR");
        assert_eq!(json["data"], serde_json::Value::Null);
        assert!(json.get("timestamp").is_some());
    }

    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[tokio::test]
    async fn test_app_error_service_unavailable_returns_503() {
        let response = {
            let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
            std::env::set_var("CRAWLRS_ENV", "production");
            std::env::remove_var("APP_ENVIRONMENT");
            std::env::remove_var("RUST_ENV");
            let response =
                CrawlRsError::ServiceUnavailable("cache down".to_string()).into_response();
            std::env::remove_var("CRAWLRS_ENV");
            response
        };
        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"]["code"], "SERVICE_UNAVAILABLE");
        assert_eq!(json["data"], serde_json::Value::Null);
        assert!(json.get("timestamp").is_some());
    }

    /// 遍历全部 CrawlRsError 变体,锁定 `user_message_locale`(17 个 match 臂)均产出非空
    /// 本地化文案且 Display 非空(此前仅少量变体被覆盖)。
    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[test]
    fn test_user_message_locale_across_all_variants() {
        use crate::i18n::{I18nBundle, Locale};
        let bundle = I18nBundle::load("en-US", &["en-US", "zh-CN"]).unwrap();
        let en: Locale = "en-US".parse().unwrap();
        let zh: Locale = "zh-CN".parse().unwrap();
        let variants = vec![
            make_db_error("db"),
            CrawlRsError::Network("n".into()),
            CrawlRsError::Config("c".into()),
            CrawlRsError::Validation("v".into()),
            CrawlRsError::Unprocessable("u".into()),
            CrawlRsError::NotFound("nf".into()),
            CrawlRsError::Authentication("a".into()),
            CrawlRsError::PermissionDenied("pd".into()),
            CrawlRsError::ServiceUnavailable("su".into()),
            CrawlRsError::Timeout("t".into()),
            CrawlRsError::Io(std::io::Error::other("io")),
            CrawlRsError::Json(
                serde_json::from_str::<serde_json::Value>("not-json")
                    .expect_err("invalid json must produce serde error"),
            ),
            CrawlRsError::Engine("e".into()),
            CrawlRsError::Cache("ca".into()),
            CrawlRsError::Task("tk".into()),
            CrawlRsError::RateLimit("rl".into()),
            CrawlRsError::Other("o".into()),
        ];
        for v in &variants {
            assert!(
                !v.user_message_locale(&en, &bundle).is_empty(),
                "en empty: {v}"
            );
            assert!(
                !v.user_message_locale(&zh, &bundle).is_empty(),
                "zh empty: {v}"
            );
            assert!(!v.to_string().is_empty());
        }
    }

    /// status_code 委托 sdforge 映射表后与迁移前表逐项相等(17 变体全覆盖)。
    /// sdforge 无 502/504 变体:Network/Engine→502、Timeout→504 为登记的库侧缺口残留。
    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[test]
    fn test_status_code_matches_pre_migration_table() {
        use axum::http::StatusCode;
        let expected: Vec<(CrawlRsError, u16)> = vec![
            (make_db_error("db"), 500),
            (CrawlRsError::Network("n".into()), 502),
            (CrawlRsError::Config("c".into()), 500),
            (CrawlRsError::Validation("v".into()), 400),
            (CrawlRsError::Unprocessable("u".into()), 422),
            (CrawlRsError::NotFound("nf".into()), 404),
            (CrawlRsError::Authentication("a".into()), 401),
            (CrawlRsError::PermissionDenied("pd".into()), 403),
            (CrawlRsError::ServiceUnavailable("su".into()), 503),
            (CrawlRsError::Timeout("t".into()), 504),
            (CrawlRsError::Io(std::io::Error::other("io")), 500),
            (
                CrawlRsError::Json(
                    serde_json::from_str::<serde_json::Value>("not-json")
                        .expect_err("invalid json must produce serde error"),
                ),
                400,
            ),
            (CrawlRsError::Engine("e".into()), 502),
            (CrawlRsError::Cache("ca".into()), 503),
            (CrawlRsError::Task("tk".into()), 500),
            (CrawlRsError::RateLimit("rl".into()), 429),
            (CrawlRsError::Other("o".into()), 500),
        ];
        assert_eq!(expected.len(), 17, "17 个领域变体必须逐一断言");
        for (variant, want) in expected {
            assert_eq!(
                variant.status_code(),
                StatusCode::from_u16(want).unwrap(),
                "status_code mismatch for {variant:?}"
            );
        }
    }

    /// 归一变体(14 个)的状态码必须等于 sdforge `http_status_for` 对归一
    /// `ApiError` 的映射结果——证明库映射表是唯一事实来源。
    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[test]
    fn test_status_code_delegates_to_sdforge_mapping() {
        use axum::http::StatusCode;
        let normalized = vec![
            make_db_error("db"),
            CrawlRsError::Config("c".into()),
            CrawlRsError::Validation("v".into()),
            CrawlRsError::Unprocessable("u".into()),
            CrawlRsError::NotFound("nf".into()),
            CrawlRsError::Authentication("a".into()),
            CrawlRsError::PermissionDenied("pd".into()),
            CrawlRsError::ServiceUnavailable("su".into()),
            CrawlRsError::Io(std::io::Error::other("io")),
            CrawlRsError::Json(
                serde_json::from_str::<serde_json::Value>("not-json")
                    .expect_err("invalid json must produce serde error"),
            ),
            CrawlRsError::Cache("ca".into()),
            CrawlRsError::Task("tk".into()),
            CrawlRsError::RateLimit("rl".into()),
            CrawlRsError::Other("o".into()),
        ];
        assert_eq!(normalized.len(), 14, "14 个归一变体必须逐一断言");
        for variant in &normalized {
            let api_error = variant
                .to_api_error()
                .expect("normalized variant must produce ApiError");
            let want = StatusCode::from_u16(sdforge::error::unified::http_status_for(&api_error))
                .expect("sdforge status must be valid");
            assert_eq!(
                variant.status_code(),
                want,
                "delegation mismatch: {variant:?}"
            );
        }
        // 覆盖集外三变体不得归一(502/504 缺口)
        assert!(CrawlRsError::Network("n".into()).to_api_error().is_none());
        assert!(CrawlRsError::Engine("e".into()).to_api_error().is_none());
        assert!(CrawlRsError::Timeout("t".into()).to_api_error().is_none());
    }

    /// Internal/ServiceUnavailable 类整体遮蔽语义与 sdforge
    /// `ApiError::sanitized_message` 对齐:固定遮蔽文案,不透出内部细节。
    #[test]
    fn test_sanitized_message_semantic_alignment_with_sdforge() {
        // 库侧语义基准:Internal/ServiceUnavailable 丢弃原始 message
        let internal_detail = "connect 10.0.0.1:5432 failed password=sk-secret";
        let masked =
            sdforge::error::ApiError::internal_error(internal_detail, "probe").sanitized_message();
        assert!(!masked.contains("10.0.0.1"));
        assert!(!masked.contains("sk-secret"));
        assert!(!masked.is_empty());

        let svc_detail = "upstream http://user:pw@10.1.2.3:8080 down";
        let svc_masked =
            sdforge::error::ApiError::service_unavailable("upstream", None).sanitized_message();
        assert!(!svc_masked.contains("10.1.2.3"));
        assert!(!svc_masked.contains("pw"));

        // crawlrs 侧对齐:Other/ServiceUnavailable 对外为固定遮蔽文案
        let crawlrs_internal =
            CrawlRsError::Other("connect 10.0.0.1:5432 failed password=sk-secret".to_string());
        let crawlrs_msg = crawlrs_internal.user_message();
        assert!(!crawlrs_msg.contains("10.0.0.1"));
        assert!(!crawlrs_msg.contains("sk-secret"));

        let crawlrs_svc = CrawlRsError::ServiceUnavailable(svc_detail.to_string());
        let crawlrs_svc_msg = crawlrs_svc.user_message();
        assert!(!crawlrs_svc_msg.contains("10.1.2.3"));
        assert!(!crawlrs_svc_msg.contains("user:pw"));
    }

    /// i18n 三级回退链:locale 缺→default(en-US)缺→返回 key 本身。
    #[cfg(any(feature = "platform", feature = "web-axum"))]
    #[test]
    fn test_user_message_locale_fallback_chain() {
        use crate::i18n::{I18nBundle, Locale};
        let bundle = I18nBundle::load("en-US", &["en-US", "zh-CN"]).unwrap();
        let en: Locale = "en-US".parse().unwrap();
        let zh: Locale = "zh-CN".parse().unwrap();

        // 第一级:locale(zh-CN)命中
        let localized = CrawlRsError::Timeout("t".into()).user_message_locale(&zh, &bundle);
        assert!(!localized.is_empty());

        // 第二级:locale 缺→回落 default(en-US)
        let missing_in_zh = bundle.translate(&zh, "error-nonexistent-key");
        assert_eq!(missing_in_zh, "error-nonexistent-key");

        // 第三级:缺失 key 返回 key 本身(默认 locale 亦无该 key)
        assert_eq!(
            bundle.translate(&en, "error-nonexistent-key"),
            "error-nonexistent-key"
        );

        // 参数插值不丢失:Validation 的 message 经 String 传入
        let msg = CrawlRsError::Validation("email format invalid".to_string());
        let rendered = msg.user_message_locale(&en, &bundle);
        assert!(
            rendered.contains("email format invalid"),
            "arg interpolation lost: {rendered}"
        );
    }
}