yang-base 0.6.0

个人使用构建后端服务器
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
//! 错误处理模块
//!
//! 定义系统中所有模块使用的统一错误类型。
//!
//! # 主要组件
//!
//! - `BaseError`:统一错误枚举类型
//!
//! # 示例
//!
//! ```rust,ignore
//! use yang_base::error::BaseError;
//!
//! fn do_something() -> Result<(), BaseError> {
//!     // 插件未找到错误
//!     Err(BaseError::PluginNotFound("my_plugin".to_string()))
//! }
//! ```

use thiserror::Error;

/// 以 [`BaseError`] 为默认错误类型的统一 `Result` 别名。
///
/// 允许下游以 `yang_base::Result<T>` 书写返回类型,省去重复的 `, BaseError`。
/// 保留类型参数 `E = BaseError`,少数需要其它错误类型的签名仍可显式覆盖。
pub type Result<T, E = BaseError> = std::result::Result<T, E>;

/// 系统统一错误类型
///
/// 包含所有模块的错误变体,使用中文错误消息
///
/// 标注 `#[non_exhaustive]`:未来新增变体不构成跨 crate 破坏性变更(下游 match 需
/// 带 `_` 臂)。同 crate 内的穷举 match(`code()`/`code_str()`/`category()`)不受
/// 影响,新增变体时 `test_code_str_matches_code` 测试会捕获漏编。
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum BaseError {
    // ==================== 插件管理错误 ====================
    /// 插件已注册
    #[error("插件已注册: {0}")]
    PluginAlreadyRegistered(String),

    /// 插件未找到
    #[error("插件未找到: {0}")]
    PluginNotFound(String),

    /// 插件注册失败
    #[error("插件注册失败 [{0}]: {1}")]
    PluginRegisterFailed(String, String),

    /// 插件初始化失败
    #[error("插件初始化失败 [{0}]: {1}")]
    PluginInitFailed(String, String),

    /// 插件依赖缺失
    #[error("插件依赖缺失 [{0}]: 缺少依赖 {1}")]
    PluginDependencyMissing(String, String),

    /// 插件循环依赖
    #[error("插件循环依赖: {0}")]
    PluginCircularDependency(String),

    /// 插件配置无效
    #[error("插件配置无效 [{0}]: {1}")]
    PluginConfigInvalid(String, String),

    /// 插件关闭失败
    #[error("插件关闭失败 [{0}]: {1}")]
    PluginShutdownFailed(String, String),

    /// 插件生命周期回调失败,保留插件名、阶段与底层错误链。
    #[error("插件生命周期失败 [{plugin}] ({stage}): {source}")]
    PluginLifecycleFailed {
        /// 插件名称。
        plugin: String,
        /// 失败阶段。
        stage: crate::plugin::PluginLifecycleStage,
        /// 插件回调或初始化操作返回的底层错误。
        #[source]
        source: crate::plugin::PluginError,
    },

    // ==================== 数据库错误 ====================
    /// 数据库连接失败,持有底层 DbError 以保留错误链
    #[error("数据库连接失败 [DbError]: {0}")]
    DatabaseConnectionFailed(#[source] yang_db::DbError),

    /// 数据库连接失败(DbError 专用变体,用于 `From<DbError>` 映射)
    ///
    /// 与 `DatabaseConnectionFailed` 语义相同但独立编码 200011,
    /// 便于下游区分"直接构造的连接错误"和"来自 DbError 包装的连接错误"。
    #[error("数据库连接失败 [DbError]: {0}")]
    DatabaseConnectionDbError(#[source] yang_db::DbError),

    /// 数据库已初始化
    #[error("数据库已初始化")]
    DatabaseAlreadyInitialized,

    /// 数据库查询失败,持有底层 DbError 以保留错误链
    #[error("数据库查询失败: {0}")]
    DatabaseQueryFailed(#[source] yang_db::DbError),

    /// 数据库执行失败,持有底层 DbError 以保留错误链
    #[error("数据库执行失败: {0}")]
    DatabaseExecuteFailed(#[source] yang_db::DbError),

    /// 数据库初始化失败
    #[error("数据库初始化失败: {0}")]
    DatabaseInitFailed(String),

    /// 数据库未初始化
    #[error("数据库未初始化")]
    DatabaseNotInitialized,

    /// 数据库事务失败,持有底层 DbError 以保留错误链
    #[error("数据库事务失败: {0}")]
    DatabaseTransactionFailed(#[source] yang_db::DbError),

    /// 当前后端/构建不支持请求的能力(如方言专属语法)。
    ///
    /// 与 [`BaseError::ConfigError`] 区分:这是「运行时能力矩阵」的显式拒绝,
    /// 调用方应降级或换用受支持的入口,而不是修复配置。
    #[error("当前后端不支持该能力: {0}")]
    UnsupportedCapability(String),

    /// 表与事务不属于同一逻辑数据源。
    #[error("事务与表数据源不一致 [{table}]: 期望 {expected},实际 {actual}")]
    DatasourceMismatch {
        /// 表名。
        table: String,
        /// 表所属数据源。
        expected: String,
        /// 事务所属数据源(未标注时为 `unscoped`)。
        actual: String,
    },

    /// UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作
    ///
    /// 与 yang-db 的 `MissingWhereClause` 安全网对齐:无 WHERE 的更新/删除
    /// 始终被拒绝,以防止误操作整表。
    #[error("UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作: {0}")]
    MissingWhereClause(String),

    // ==================== Redis 错误 ====================
    /// Redis 连接失败,持有底层 DbError 以保留错误链。
    #[error("Redis 连接失败: {0}")]
    RedisConnectionFailed(#[source] yang_db::DbError),

    /// Redis 已初始化
    #[error("Redis 已初始化")]
    RedisAlreadyInitialized,

    /// Redis 未初始化
    #[error("Redis 未初始化")]
    RedisNotInitialized,

    /// Redis 操作失败,持有底层 DbError 以保留错误链。
    #[error("Redis 操作失败: {0}")]
    RedisOperationFailed(#[source] yang_db::DbError),

    /// Redis 操作失败,持有底层 DbError 以保留错误链
    #[error("Redis 操作失败: {0}")]
    RedisOperationDbError(#[source] yang_db::DbError),

    // ==================== HTTP 客户端错误 ====================
    /// HTTP 客户端创建失败,持有底层 reqwest::Error 以保留错误链
    #[cfg(feature = "http")]
    #[error("HTTP 客户端创建失败: {0}")]
    HttpClientCreateFailed(#[source] reqwest::Error),

    /// HTTP 客户端创建失败(无 http feature 时使用字符串)
    #[cfg(not(feature = "http"))]
    #[error("HTTP 客户端创建失败: {0}")]
    HttpClientCreateFailed(String),

    /// HTTP 请求失败,持有底层 reqwest::Error 以保留错误链
    #[cfg(feature = "http")]
    #[error("HTTP 请求失败: {0}")]
    HttpRequestFailed(#[source] reqwest::Error),

    /// HTTP 请求失败(无 http feature 时使用字符串)
    #[cfg(not(feature = "http"))]
    #[error("HTTP 请求失败: {0}")]
    HttpRequestFailed(String),

    /// HTTP 响应解析失败
    #[error("HTTP 响应解析失败: {0}")]
    HttpResponseParseFailed(String),

    /// HTTP 响应体超过配置上限(防异常/恶意上游耗尽内存)
    #[error("HTTP 响应体超过上限: 上限 {limit} 字节, 实际 {actual:?} 字节")]
    HttpResponseTooLarge {
        /// 配置的响应体上限(字节)。
        limit: usize,
        /// 上游声明(Content-Length)的实际大小;流式累计触发时为 None。
        actual: Option<u64>,
    },

    /// HTTP 超时
    #[error("HTTP 请求超时")]
    HttpTimeout,

    /// HTTP 客户端已初始化
    #[error("HTTP 客户端已初始化")]
    HttpClientAlreadyInitialized,

    /// HTTP 客户端未初始化
    #[error("HTTP 客户端未初始化")]
    HttpClientNotInitialized,

    /// HTTP 熔断器打开:目标 host 近期连续失败,请求被快速拒绝
    #[error("HTTP 熔断器已打开,目标主机暂不可用: {0}")]
    HttpCircuitBreakerOpen(String),

    /// 上游依赖暂时不可用(**与具体传输无关**)。
    ///
    /// 存在的理由:[`BaseError::HttpRequestFailed`] 在 `http` feature 开启时持有
    /// `reqwest::Error`、关闭时持有 `String`,也就是说**它的可构造性取决于 feature**。
    /// 非 HTTP 传输(SMTP、消息队列等)需要同一语义的可重试错误,却又不能依赖该
    /// feature —— 否则「上游暂时不可用」会随构建配置在「可重试」与「不可重试」之间
    /// 漂移(历史上邮件投递就因此从 503 退化成 500)。
    ///
    /// 分类是 [`ErrorCategory::Transient`],在 HTTP 边界映射为 **503**,
    /// 语义上等同于 `HttpRequestFailed`,但不携带传输层错误链。
    #[error("上游服务暂不可用: {0}")]
    UpstreamUnavailable(String),

    // ==================== Token 管理错误 ====================
    /// Token 密钥无效
    #[error("Token 密钥无效: {0}")]
    TokenKeyInvalid(String),

    /// Token 生成失败,持有底层 jsonwebtoken::errors::Error 以保留错误链
    #[cfg(feature = "token")]
    #[error("Token 生成失败: {0}")]
    TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),

    /// Token 生成失败(无 token feature 时使用字符串)
    #[cfg(not(feature = "token"))]
    #[error("Token 生成失败: {0}")]
    TokenGenerateFailed(String),

    /// Token 验证失败,持有底层 jsonwebtoken::errors::Error 以保留错误链
    #[cfg(feature = "token")]
    #[error("Token 验证失败: {0}")]
    TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),

    /// Token 验证失败(无 token feature 时使用字符串)
    #[cfg(not(feature = "token"))]
    #[error("Token 验证失败: {0}")]
    TokenVerifyFailed(String),

    /// Token 解析失败,持有底层 jsonwebtoken::errors::Error 以保留错误链
    #[cfg(feature = "token")]
    #[error("Token 解析失败: {0}")]
    TokenParseFailed(#[source] jsonwebtoken::errors::Error),

    /// Token 解析失败(无 token feature 时使用字符串)
    #[cfg(not(feature = "token"))]
    #[error("Token 解析失败: {0}")]
    TokenParseFailed(String),

    /// Token 已过期
    #[error("Token 已过期")]
    TokenExpired,

    /// Token 已被撤销(命中黑名单)
    #[error("Token 已被撤销")]
    TokenRevoked,

    /// Token 撤销状态损坏或返回结构不符合协议。
    #[error("Token 撤销状态无效: {0}")]
    TokenRevocationStateInvalid(String),

    /// Access Token 中的授权版本已落后于当前事实版本。
    #[error("授权状态已变更,请刷新登录")]
    AuthorizationStale,

    /// Access Token 中的授权版本缺失、非法或领先于事实版本。
    #[error("授权版本无效")]
    AuthorizationVersionInvalid,

    /// 授权版本缓存与事实存储均无法完成请求时校验。
    #[error("授权状态暂时无法校验")]
    AuthorizationCheckUnavailable,

    /// Token 类型无效
    #[error("Token 类型无效: {0}")]
    TokenTypeInvalid(String),

    // ==================== 序列化错误 ====================
    /// JSON 序列化失败
    #[error("JSON 序列化失败: {0}")]
    JsonSerializeFailed(String),

    /// JSON 反序列化失败
    #[error("JSON 反序列化失败: {0}")]
    JsonDeserializeFailed(String),

    // ==================== 字段验证错误 ====================
    /// 字段类型无效
    #[error("字段类型无效 [{0}]: {1}")]
    InvalidFieldType(String, String),

    /// 枚举值无效
    #[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
    InvalidEnumValue(String, String),

    /// 字符串长度超出限制
    #[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
    StringTooLong(String, usize, usize),

    /// JSON 格式无效
    #[error("JSON 格式无效 [{0}]: {1}")]
    InvalidJsonFormat(String, String),

    /// 验证失败
    #[error("验证失败 [{0}]: {1}")]
    ValidationFailed(String, String),

    /// 字段必填
    #[error("字段必填: {0}")]
    FieldRequired(String),

    /// 字段未找到
    #[error("字段未找到 [表: {0}]: {1}")]
    FieldNotFound(String, String),

    /// 字段权限被拒绝
    #[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
    FieldPermissionDenied(String, String, String),

    // ==================== Action 系统错误 ====================
    /// Action 未找到
    #[error("Action 未找到: {0}")]
    ActionNotFound(String),

    /// 权限被拒绝
    #[error("权限被拒绝: {0}")]
    PermissionDenied(String),

    /// 未授权
    #[error("未授权: {0}")]
    Unauthorized(String),

    /// 参数缺失
    #[error("参数缺失: {0}")]
    ParamMissing(String),

    /// 参数无效
    #[error("参数无效 [{0}]: {1}")]
    ParamInvalid(String, String),

    /// 请求超过速率限制。
    #[error("请求过于频繁,请在 {retry_after_seconds} 秒后重试")]
    RateLimitExceeded {
        /// 建议客户端等待的秒数。
        retry_after_seconds: u64,
    },

    /// 第一因子已通过,需要第二因子(TOTP 动态码或恢复码)才能完成认证。
    ///
    /// 仅在密码校验通过后返回:客户端据此进入第二因子输入阶段
    /// (两段式登录:账号密码 → 动态码),与 `InvalidPassword` 语义区分。
    #[error("需要输入双重验证码")]
    SecondFactorRequired,

    /// 记录未找到
    #[error("记录未找到: {0}")]
    RecordNotFound(String),

    /// 用户未找到
    #[error("用户未找到: {0}")]
    UserNotFound(String),

    /// 密码无效
    #[error("密码无效")]
    InvalidPassword,

    /// 表定义未设置
    #[error("表定义未设置")]
    TableDefinitionNotSet,

    /// 敏感 Action 尚未完成短期重认证。
    #[cfg(feature = "token")]
    #[error("敏感操作需要重新认证")]
    StepUpRequired(crate::action::StepUpChallenge),

    // ==================== 通用错误 ====================
    /// 配置错误
    #[error("配置错误: {0}")]
    ConfigError(String),

    /// IO 错误
    #[error("IO 错误: {0}")]
    IoError(String),

    /// 未知错误
    #[error("未知错误: {0}")]
    Unknown(String),
}

// ==================== From trait 实现 ====================

/// 从数据库约束错误的报文里提取**唯一键冲突**的键名。
///
/// 返回 `None` 表示「这不是唯一键冲突」。
///
/// # 为什么不看错误码
///
/// MySQL 的外键、非空、CHECK 与唯一键**共用同一个 SQLSTATE(23000)**,
/// PostgreSQL 的唯一约束是 23505 而 SQLSTATE 在 `yang-db` 里已被抹平成
/// `DbError::ConstraintError`。所以在这一层只能看报文。
///
/// 覆盖两种形态:
/// - MySQL:`Duplicate entry 'x' for key 'source_key'`(键名可能被库名/表名限定)
/// - PostgreSQL:`duplicate key value violates unique constraint "xxx"`
fn duplicate_key_field(message: &str) -> Option<String> {
    if message.contains("Duplicate entry") {
        if let Some((_, rest)) = message.split_once("for key '") {
            // MySQL 8 会写成 `库.表.键`,取最后一段才是键名本身
            let raw = rest.split('\'').next().unwrap_or_default();
            let last = raw.rsplit('.').next().unwrap_or(raw);
            if !last.is_empty() {
                return Some(last.to_string());
            }
        }
    }
    if message.contains("duplicate key value violates unique constraint") {
        if let Some((_, rest)) = message.split_once("unique constraint \"") {
            let name = rest.split('"').next().unwrap_or_default();
            if !name.is_empty() {
                return Some(name.to_string());
            }
        }
    }
    None
}

/// 从 yang_db::DbError 转换为 BaseError
///
/// 按 DbError 变体分类映射到对应的 BaseError 变体:
/// - 查询类 → DatabaseQueryFailed
/// - 执行类 → DatabaseExecuteFailed(**唯一键冲突例外**,见下)
/// - 事务类 → DatabaseTransactionFailed
/// - 连接类 → DatabaseConnectionFailed(包装 DbError 保留错误链)
/// - Redis 连接类 → RedisConnectionFailed
/// - Redis 其他操作类 → RedisOperationFailed
///
/// 唯一键冲突映射为 [`BaseError::ParamInvalid`]:它是**可归因的输入问题**
/// (自动派生的 `source_key`、系统生成的 token 都可能撞唯一索引),
/// 落成 `DatabaseExecuteFailed` 会让控制台只能显示「数据库执行失败」,
/// 运维看不出撞的是哪个键。
#[allow(unreachable_patterns)]
impl From<yang_db::DbError> for BaseError {
    fn from(err: yang_db::DbError) -> Self {
        use yang_db::DbError as D;
        match &err {
            // 查询类:查询错误、表不存在、类型转换、反序列化、不支持的操作符、未知错误
            D::QueryError(_)
            | D::TableNotFound(_)
            | D::TypeConversionError(_)
            | D::DeserializationError(_)
            | D::UnsupportedOperator(_)
            | D::Unknown(_) => BaseError::DatabaseQueryFailed(err),

            // 结构化 SQLSTATE:唯一键冲突归因为参数错误;连接类保留错误链;
            // 其余约束/语法/数据错误统一落到执行失败,避免把数据完整性问题
            // 误报成用户输入错误。
            D::DatabaseError(info) => match info.kind() {
                yang_db::SqlErrorKind::UniqueViolation => {
                    let field = info
                        .constraint()
                        .and_then(|constraint| constraint.rsplit('.').next())
                        .map(str::to_string)
                        .or_else(|| duplicate_key_field(info.message()))
                        .unwrap_or_else(|| "unknown".to_string());
                    BaseError::ParamInvalid(field, "该值已存在".to_string())
                }
                yang_db::SqlErrorKind::UndefinedTable => BaseError::DatabaseQueryFailed(err),
                yang_db::SqlErrorKind::ConnectionFailure
                | yang_db::SqlErrorKind::TooManyConnections => {
                    BaseError::DatabaseConnectionDbError(err)
                }
                _ => BaseError::DatabaseExecuteFailed(err),
            },

            // 连接池关闭不可重试,保留错误链供运维定位。
            D::PoolClosed => BaseError::DatabaseConnectionDbError(err),

            // 唯一键冲突:**先于**通用执行类分支判定,让它变成可归因的参数错误。
            // 报文不匹配时原样落回 DatabaseExecuteFailed——外键/非空/CHECK 都走这一支。
            D::ConstraintError(message) => match duplicate_key_field(message) {
                Some(field) => BaseError::ParamInvalid(field, "该值已存在".to_string()),
                None => BaseError::DatabaseExecuteFailed(err),
            },

            // 其余执行类:SQL 语法错误、缺少 WHERE 条件、缺少 GROUP BY、序列化错误、参数非法
            D::SqlSyntaxError(_)
            | D::MissingWhereClause
            | D::MissingGroupByClause
            | D::InvalidArgument(_)
            | D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),

            // 事务类:事务错误
            D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),

            // 连接类:连接错误(保留底层 DbError 错误链)→ DatabaseConnectionDbError (200011)
            D::ConnectionError(_) => BaseError::DatabaseConnectionDbError(err),

            // Redis 连接类:保留底层 DbError 错误链
            D::RedisConnectionError(_) => BaseError::RedisConnectionFailed(err),

            // Redis 操作类:保留底层 DbError 错误链
            D::RedisCommandError(_)
            | D::RedisPoolError(_)
            | D::RedisPoolClosed
            | D::RedisError(_)
            | D::RedisTypeConversionError(_)
            | D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err),

            // 未来新增变体(DbError 标注 #[non_exhaustive])统一按查询失败处理
            _ => BaseError::DatabaseQueryFailed(err),
        }
    }
}

/// 从 std::io::Error 转换为 BaseError
impl From<std::io::Error> for BaseError {
    fn from(err: std::io::Error) -> Self {
        BaseError::IoError(err.to_string())
    }
}

/// 从 serde_json::Error 转换为 BaseError
impl From<serde_json::Error> for BaseError {
    fn from(err: serde_json::Error) -> Self {
        if err.is_syntax() || err.is_data() || err.is_eof() {
            BaseError::JsonDeserializeFailed(err.to_string())
        } else {
            BaseError::JsonSerializeFailed(err.to_string())
        }
    }
}

/// 从 reqwest::Error 转换为 BaseError
#[cfg(feature = "http")]
impl From<reqwest::Error> for BaseError {
    fn from(err: reqwest::Error) -> Self {
        if err.is_timeout() {
            BaseError::HttpTimeout
        } else {
            // is_connect() 属于「发送请求」阶段的连接失败(DNS/TCP/TLS),
            // 客户端此时早已创建成功,故与其它发送错误统一归为 HttpRequestFailed。
            // 真正的客户端创建失败由 http/client.rs 显式 map_err(HttpClientCreateFailed) 处理。
            BaseError::HttpRequestFailed(err)
        }
    }
}

/// 从 jsonwebtoken::errors::Error 转换为 BaseError
///
/// 按 ErrorKind 分类映射:
/// - ExpiredSignature → TokenExpired
/// - InvalidToken / InvalidSignature → TokenVerifyFailed
/// - 其他 → TokenParseFailed
#[cfg(feature = "token")]
impl From<jsonwebtoken::errors::Error> for BaseError {
    fn from(err: jsonwebtoken::errors::Error) -> Self {
        use jsonwebtoken::errors::ErrorKind;
        match err.kind() {
            ErrorKind::ExpiredSignature => BaseError::TokenExpired,
            ErrorKind::InvalidToken
            | ErrorKind::InvalidSignature
            | ErrorKind::InvalidIssuer
            | ErrorKind::InvalidAudience
            | ErrorKind::InvalidSubject
            | ErrorKind::InvalidAlgorithm
            | ErrorKind::MissingAlgorithm
            | ErrorKind::ImmatureSignature
            | ErrorKind::MissingRequiredClaim(_)
            | ErrorKind::InvalidEcdsaKey
            | ErrorKind::InvalidRsaKey(_)
            | ErrorKind::InvalidKeyFormat
            | ErrorKind::RsaFailedSigning
            | ErrorKind::InvalidAlgorithmName => BaseError::TokenVerifyFailed(err),
            // 真正解析/IO 错误 → TokenParseFailed
            ErrorKind::Base64(_) | ErrorKind::Json(_) | ErrorKind::Utf8(_) => {
                BaseError::TokenParseFailed(err)
            }
            // 防非穷尽: 未显式列出的验证类错误 → TokenVerifyFailed
            _ => BaseError::TokenVerifyFailed(err),
        }
    }
}

/// 引擎级错误分类(与具体 HTTP/传输层无关)。
///
/// 用于下游统一适配(弹性重试、错误上报分桶、HTTP status 映射的中间层)。
/// HTTP status 映射属调用方传输层边界,不在引擎层硬编码。
///
/// `is_client_error()` = `Client` + `Auth` + `NotFound`;`is_server_error()` = `Server` +
/// `Transient` + `Conflict`。详见 [`BaseError::category`] 文档。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorCategory {
    /// 调用方过错(参数错误、字段验证、序列化、插件依赖/配置/循环)
    Client,
    /// 认证/授权失败(登录过期、Token 撤销、密码错误、权限不足)
    Auth,
    /// 资源不存在(记录/用户/Action/表未找到)
    NotFound,
    /// 资源冲突(插件注册冲突)
    Conflict,
    /// 瞬时故障(连接失败/超时/连接池/HTTP 超时/熔断打开),可重试
    ///
    /// 在 `is_server_error` 中视为服务端错误(可重试的服务端故障,
    /// 如连接超时 = HTTP 503 语义),但 `is_client_error` 中**不**视为客户端错误。
    Transient,
    /// 服务端/基础设施错误(内部失败、配置错误、未知错误)
    Server,
}

/// 服务尚未就绪:传输层 `/health/ready` 与管理面就绪探针共用的错误码。
///
/// 取值沿用 `900001`(通用错误区间)以保持既有线格式不变;两处引用同一常量,
/// 禁止再各自硬编码字面量。见 `test_not_ready_code_is_stable`。
pub const NOT_READY_CODE: i32 = 900001;

impl BaseError {
    /// 获取错误码
    ///
    /// 返回与错误类型对应的数字错误码,用于 API 响应
    ///
    /// # 错误码规范
    ///
    /// - 1xxxxx: 插件管理错误
    /// - 2xxxxx: 数据库错误
    ///   - 21xxxx: Redis 错误(隶属数据库 2xxxxx 大类)
    /// - 3xxxxx: HTTP 客户端错误
    /// - 4xxxxx: Token 管理错误
    /// - 5xxxxx: 序列化错误
    /// - 6xxxxx: 字段验证错误
    /// - 7xxxxx: Action 系统错误
    /// - 9xxxxx: 通用错误
    ///
    /// # 返回
    ///
    /// - 错误码(非零整数)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::error::BaseError;
    ///
    /// let error = BaseError::FieldRequired("username".to_string());
    /// assert_eq!(error.code(), 600006);
    /// ```
    pub fn code(&self) -> i32 {
        match self {
            // ==================== 插件管理错误 (1xxxxx) ====================
            BaseError::PluginAlreadyRegistered(_) => 100001,
            BaseError::PluginNotFound(_) => 100002,
            BaseError::PluginRegisterFailed(_, _) => 100003,
            BaseError::PluginInitFailed(_, _) => 100004,
            BaseError::PluginDependencyMissing(_, _) => 100005,
            BaseError::PluginCircularDependency(_) => 100006,
            BaseError::PluginConfigInvalid(_, _) => 100007,
            BaseError::PluginShutdownFailed(_, _) => 100008,
            BaseError::PluginLifecycleFailed { stage, .. } => match stage {
                crate::plugin::PluginLifecycleStage::Register => 100003,
                crate::plugin::PluginLifecycleStage::Initialize => 100004,
                crate::plugin::PluginLifecycleStage::Shutdown => 100008,
            },

            // ==================== 数据库错误 (2xxxxx) ====================
            BaseError::DatabaseConnectionFailed(_) => 200001,
            BaseError::DatabaseConnectionDbError(_) => 200011,
            BaseError::DatabaseAlreadyInitialized => 200002,
            BaseError::DatabaseQueryFailed(_) => 200003,
            BaseError::DatabaseExecuteFailed(_) => 200004,
            BaseError::DatabaseInitFailed(_) => 200005,
            BaseError::DatabaseNotInitialized => 200008,
            BaseError::DatabaseTransactionFailed(_) => 200009,
            BaseError::MissingWhereClause(_) => 200010,
            BaseError::UnsupportedCapability(_) => 200012,
            BaseError::DatasourceMismatch { .. } => 200013,

            // ==================== Redis 错误 (21xxxx) ====================
            BaseError::RedisConnectionFailed(_) => 210001,
            BaseError::RedisAlreadyInitialized => 210002,
            BaseError::RedisNotInitialized => 210003,
            BaseError::RedisOperationFailed(_) => 210004,
            BaseError::RedisOperationDbError(_) => 210011,

            // ==================== HTTP 客户端错误 (3xxxxx) ====================
            BaseError::HttpClientCreateFailed(_) => 300001,
            BaseError::HttpRequestFailed(_) => 300002,
            BaseError::HttpResponseParseFailed(_) => 300003,
            BaseError::HttpTimeout => 300004,
            BaseError::HttpClientAlreadyInitialized => 300005,
            BaseError::HttpClientNotInitialized => 300006,
            BaseError::HttpCircuitBreakerOpen(_) => 300007,
            BaseError::HttpResponseTooLarge { .. } => 300008,
            // 与传输无关的上游依赖错误:与 300002 同为 Transient,但可在任何
            // feature 组合下构造(见变体文档)。
            BaseError::UpstreamUnavailable(_) => 300009,

            // ==================== Token 管理错误 (4xxxxx) ====================
            BaseError::TokenKeyInvalid(_) => 400001,
            BaseError::TokenGenerateFailed(_) => 400002,
            BaseError::TokenVerifyFailed(_) => 400003,
            BaseError::TokenParseFailed(_) => 400004,
            BaseError::TokenExpired => 400005,
            BaseError::TokenTypeInvalid(_) => 400006,
            BaseError::TokenRevoked => 400007,
            BaseError::TokenRevocationStateInvalid(_) => 400008,
            BaseError::AuthorizationStale => 400009,
            BaseError::AuthorizationVersionInvalid => 400010,
            BaseError::AuthorizationCheckUnavailable => 400011,

            // ==================== 序列化错误 (5xxxxx) ====================
            BaseError::JsonSerializeFailed(_) => 500001,
            BaseError::JsonDeserializeFailed(_) => 500002,

            // ==================== 字段验证错误 (6xxxxx) ====================
            BaseError::InvalidFieldType(_, _) => 600001,
            BaseError::InvalidEnumValue(_, _) => 600002,
            BaseError::StringTooLong(_, _, _) => 600003,
            BaseError::InvalidJsonFormat(_, _) => 600004,
            BaseError::ValidationFailed(_, _) => 600005,
            BaseError::FieldRequired(_) => 600006,
            BaseError::FieldNotFound(_, _) => 600007,
            BaseError::FieldPermissionDenied(_, _, _) => 600008,

            // ==================== Action 系统错误 (7xxxxx) ====================
            BaseError::ActionNotFound(_) => 700001,
            BaseError::PermissionDenied(_) => 700002,
            BaseError::Unauthorized(_) => 700003,
            BaseError::ParamMissing(_) => 700004,
            BaseError::ParamInvalid(_, _) => 700005,
            BaseError::RecordNotFound(_) => 700006,
            BaseError::UserNotFound(_) => 700007,
            BaseError::InvalidPassword => 700008,
            BaseError::TableDefinitionNotSet => 700009,
            #[cfg(feature = "token")]
            BaseError::StepUpRequired(_) => 700010,
            BaseError::RateLimitExceeded { .. } => 700011,
            BaseError::SecondFactorRequired => 700012,

            // ==================== 通用错误 (9xxxxx) ====================
            BaseError::ConfigError(_) => 900001,
            BaseError::IoError(_) => 900002,
            BaseError::Unknown(_) => 999999,
        }
    }

    /// 返回错误码的 `&'static str` 形式,供 metrics label 使用(零分配、低基数)。
    ///
    /// 与 [`BaseError::code`] 一一对应:`code_str()` 是 `code()` 的字符串字面量版本,
    /// 专用于 `metrics` 的 label(label 必须是 `&'static str`,**严禁** `code().to_string()`
    /// 造成每次派发堆分配 + 高基数)。新增变体时两者需同步维护,并由
    /// `test_code_str_matches_code` 守护一致性。
    pub fn code_str(&self) -> &'static str {
        match self {
            // 插件管理错误 (1xxxxx)
            BaseError::PluginAlreadyRegistered(_) => "100001",
            BaseError::PluginNotFound(_) => "100002",
            BaseError::PluginRegisterFailed(_, _) => "100003",
            BaseError::PluginInitFailed(_, _) => "100004",
            BaseError::PluginDependencyMissing(_, _) => "100005",
            BaseError::PluginCircularDependency(_) => "100006",
            BaseError::PluginConfigInvalid(_, _) => "100007",
            BaseError::PluginShutdownFailed(_, _) => "100008",
            BaseError::PluginLifecycleFailed { stage, .. } => match stage {
                crate::plugin::PluginLifecycleStage::Register => "100003",
                crate::plugin::PluginLifecycleStage::Initialize => "100004",
                crate::plugin::PluginLifecycleStage::Shutdown => "100008",
            },
            // 数据库错误 (2xxxxx)
            BaseError::DatabaseConnectionFailed(_) => "200001",
            BaseError::DatabaseConnectionDbError(_) => "200011",
            BaseError::DatabaseAlreadyInitialized => "200002",
            BaseError::DatabaseQueryFailed(_) => "200003",
            BaseError::DatabaseExecuteFailed(_) => "200004",
            BaseError::DatabaseInitFailed(_) => "200005",
            BaseError::DatabaseNotInitialized => "200008",
            BaseError::DatabaseTransactionFailed(_) => "200009",
            BaseError::MissingWhereClause(_) => "200010",
            BaseError::UnsupportedCapability(_) => "200012",
            BaseError::DatasourceMismatch { .. } => "200013",
            // Redis 错误 (21xxxx)
            BaseError::RedisConnectionFailed(_) => "210001",
            BaseError::RedisAlreadyInitialized => "210002",
            BaseError::RedisNotInitialized => "210003",
            BaseError::RedisOperationFailed(_) => "210004",
            BaseError::RedisOperationDbError(_) => "210011",
            // HTTP 客户端错误 (3xxxxx)
            BaseError::HttpClientCreateFailed(_) => "300001",
            BaseError::HttpRequestFailed(_) => "300002",
            BaseError::HttpResponseParseFailed(_) => "300003",
            BaseError::HttpTimeout => "300004",
            BaseError::HttpClientAlreadyInitialized => "300005",
            BaseError::HttpClientNotInitialized => "300006",
            BaseError::HttpCircuitBreakerOpen(_) => "300007",
            BaseError::HttpResponseTooLarge { .. } => "300008",
            BaseError::UpstreamUnavailable(_) => "300009",
            // Token 管理错误 (4xxxxx)
            BaseError::TokenKeyInvalid(_) => "400001",
            BaseError::TokenGenerateFailed(_) => "400002",
            BaseError::TokenVerifyFailed(_) => "400003",
            BaseError::TokenParseFailed(_) => "400004",
            BaseError::TokenExpired => "400005",
            BaseError::TokenTypeInvalid(_) => "400006",
            BaseError::TokenRevoked => "400007",
            BaseError::TokenRevocationStateInvalid(_) => "400008",
            BaseError::AuthorizationStale => "400009",
            BaseError::AuthorizationVersionInvalid => "400010",
            BaseError::AuthorizationCheckUnavailable => "400011",
            // 序列化错误 (5xxxxx)
            BaseError::JsonSerializeFailed(_) => "500001",
            BaseError::JsonDeserializeFailed(_) => "500002",
            // 字段验证错误 (6xxxxx)
            BaseError::InvalidFieldType(_, _) => "600001",
            BaseError::InvalidEnumValue(_, _) => "600002",
            BaseError::StringTooLong(_, _, _) => "600003",
            BaseError::InvalidJsonFormat(_, _) => "600004",
            BaseError::ValidationFailed(_, _) => "600005",
            BaseError::FieldRequired(_) => "600006",
            BaseError::FieldNotFound(_, _) => "600007",
            BaseError::FieldPermissionDenied(_, _, _) => "600008",
            // Action 系统错误 (7xxxxx)
            BaseError::ActionNotFound(_) => "700001",
            BaseError::PermissionDenied(_) => "700002",
            BaseError::Unauthorized(_) => "700003",
            BaseError::ParamMissing(_) => "700004",
            BaseError::ParamInvalid(_, _) => "700005",
            BaseError::RecordNotFound(_) => "700006",
            BaseError::UserNotFound(_) => "700007",
            BaseError::InvalidPassword => "700008",
            BaseError::TableDefinitionNotSet => "700009",
            #[cfg(feature = "token")]
            BaseError::StepUpRequired(_) => "700010",
            BaseError::RateLimitExceeded { .. } => "700011",
            BaseError::SecondFactorRequired => "700012",
            // 通用错误 (9xxxxx)
            BaseError::ConfigError(_) => "900001",
            BaseError::IoError(_) => "900002",
            BaseError::Unknown(_) => "999999",
        }
    }

    /// 引擎级错误分类(弹性重试与任意下游适配的共同基座)。
    ///
    /// 返回 [`ErrorCategory`],是 `is_retryable` / `is_client_error` /
    /// `is_server_error` 的单一事实源。分类语义为**引擎自有**,与具体 HTTP status
    /// 映射无关——HTTP 映射属调用方传输层边界。
    ///
    /// `Transient` 在 `is_server_error` 中视为服务端错误(但可重试),
    /// 在 `is_client_error` 中**不**视为客户端错误。`Auth` 和 `NotFound` 在
    /// `is_client_error` 中视为客户端错误(认证/授权失败和资源不存在均归调用方过错)。
    pub fn category(&self) -> ErrorCategory {
        use ErrorCategory as C;
        match self {
            // 插件管理错误:除注册冲突外均为服务端/配置问题
            BaseError::PluginAlreadyRegistered(_) => C::Conflict,
            BaseError::PluginCircularDependency(_) => C::Client,
            BaseError::PluginDependencyMissing(_, _) => C::Client,
            BaseError::PluginConfigInvalid(_, _) => C::Client,
            BaseError::PluginNotFound(_)
            | BaseError::PluginRegisterFailed(_, _)
            | BaseError::PluginInitFailed(_, _)
            | BaseError::PluginShutdownFailed(_, _)
            | BaseError::PluginLifecycleFailed { .. } => C::Server,
            // 数据库错误:连接失败/超时/连接池为瞬时(可重试),
            // 已包装的 DbError 同理(底层连接/超时语义已由 From<DbError> 正确分桶)
            BaseError::DatabaseConnectionFailed(_) | BaseError::DatabaseConnectionDbError(_) => {
                C::Transient
            }
            BaseError::MissingWhereClause(_) => C::Client,
            BaseError::UnsupportedCapability(_) => C::Server,
            BaseError::DatabaseAlreadyInitialized
            | BaseError::DatabaseNotInitialized
            | BaseError::DatabaseInitFailed(_)
            | BaseError::DatasourceMismatch { .. } => C::Server,
            // 事务失败可能是死锁(可重试)或约束违反(不可重试),保守归为 Server 避免无限重试
            BaseError::DatabaseQueryFailed(_)
            | BaseError::DatabaseExecuteFailed(_)
            | BaseError::DatabaseTransactionFailed(_) => C::Server,
            // Redis 错误:连接失败/超时/连接池为瞬时
            BaseError::RedisConnectionFailed(_) => C::Transient,
            BaseError::RedisAlreadyInitialized | BaseError::RedisNotInitialized => C::Server,
            BaseError::RedisOperationFailed(source) | BaseError::RedisOperationDbError(source) => {
                match source.category() {
                    yang_db::DbErrorCategory::Transient => C::Transient,
                    yang_db::DbErrorCategory::Conflict => C::Conflict,
                    yang_db::DbErrorCategory::Client => C::Client,
                    yang_db::DbErrorCategory::NotFound => C::NotFound,
                    yang_db::DbErrorCategory::Server => C::Server,
                    _ => C::Server,
                }
            }
            // HTTP 客户端错误
            BaseError::HttpClientCreateFailed(_)
            | BaseError::HttpClientNotInitialized
            | BaseError::HttpClientAlreadyInitialized => C::Client,
            // 解析失败是客户端编程错误(期望的响应类型不匹配),不是瞬时网络问题
            BaseError::HttpResponseParseFailed(_) => C::Client,
            BaseError::HttpRequestFailed(_) | BaseError::HttpTimeout => C::Transient,
            // 上游依赖不可用是瞬时故障:重试有意义(客户端应据 503 重试)。
            BaseError::UpstreamUnavailable(_) => C::Transient,
            // 熔断器打开意味着下游服务不健康,立即重试无济于事
            BaseError::HttpCircuitBreakerOpen(_) => C::Server,
            // 对端违约/谎报大小导致超出上限:非瞬时网络问题,与熔断器同类归为服务端
            BaseError::HttpResponseTooLarge { .. } => C::Server,
            // Token 错误
            BaseError::TokenKeyInvalid(_)
            | BaseError::TokenGenerateFailed(_)
            | BaseError::TokenTypeInvalid(_)
            | BaseError::TokenParseFailed(_) => C::Client,
            BaseError::TokenExpired | BaseError::TokenRevoked | BaseError::TokenVerifyFailed(_) => {
                C::Auth
            }
            BaseError::TokenRevocationStateInvalid(_) => C::Server,
            BaseError::AuthorizationStale | BaseError::AuthorizationVersionInvalid => C::Auth,
            BaseError::AuthorizationCheckUnavailable => C::Transient,
            // 序列化错误
            BaseError::JsonSerializeFailed(_) | BaseError::JsonDeserializeFailed(_) => C::Client,
            // 字段验证错误
            BaseError::InvalidFieldType(_, _)
            | BaseError::InvalidEnumValue(_, _)
            | BaseError::StringTooLong(_, _, _)
            | BaseError::InvalidJsonFormat(_, _)
            | BaseError::ValidationFailed(_, _)
            | BaseError::FieldRequired(_)
            | BaseError::FieldPermissionDenied(_, _, _) => C::Client,
            BaseError::FieldNotFound(_, _) => C::NotFound,
            // Action 系统错误
            BaseError::Unauthorized(_)
            | BaseError::PermissionDenied(_)
            | BaseError::SecondFactorRequired => C::Auth,
            BaseError::ParamMissing(_)
            | BaseError::ParamInvalid(_, _)
            | BaseError::RateLimitExceeded { .. } => C::Client,
            BaseError::RecordNotFound(_) | BaseError::UserNotFound(_) => C::NotFound,
            BaseError::InvalidPassword => C::Auth,
            BaseError::ActionNotFound(_) | BaseError::TableDefinitionNotSet => C::NotFound,
            #[cfg(feature = "token")]
            BaseError::StepUpRequired(_) => C::Client,
            // 通用错误
            BaseError::ConfigError(_) | BaseError::IoError(_) | BaseError::Unknown(_) => C::Server,
        }
    }

    /// 取被包裹的底层数据库错误(不含 Redis 之外的其它传输错误)。
    fn db_error(&self) -> Option<&yang_db::DbError> {
        match self {
            BaseError::DatabaseConnectionFailed(err)
            | BaseError::DatabaseConnectionDbError(err)
            | BaseError::DatabaseQueryFailed(err)
            | BaseError::DatabaseExecuteFailed(err)
            | BaseError::DatabaseTransactionFailed(err)
            | BaseError::RedisConnectionFailed(err)
            | BaseError::RedisOperationFailed(err)
            | BaseError::RedisOperationDbError(err) => Some(err),
            _ => None,
        }
    }

    /// 暴露包裹的 SQLSTATE 结构化信息(含约束/表/列/诊断)。
    ///
    /// 外键、NOT NULL、CHECK 等约束错误在映射时保留原始 `DatabaseError`,
    /// 调用方可据此分流,而无需解析本地化报文。
    pub fn sql_error_info(&self) -> Option<&yang_db::SqlErrorInfo> {
        match self.db_error()? {
            yang_db::DbError::DatabaseError(info) => Some(info.as_ref()),
            _ => None,
        }
    }

    /// 原始 SQLSTATE 五字符码;无结构化数据库错误时返回 `None`。
    pub fn sqlstate(&self) -> Option<&str> {
        self.sql_error_info().map(yang_db::SqlErrorInfo::code)
    }

    /// 触发错误的约束名(如外键/唯一索引/CHECK 名称)。
    pub fn constraint(&self) -> Option<&str> {
        self.sql_error_info()
            .and_then(yang_db::SqlErrorInfo::constraint)
    }

    /// 是否为可重试的瞬时错误。
    ///
    /// 包裹的 [`yang_db::DbError`] 以其自身 `is_retryable()` 为准:PostgreSQL
    /// `40001`/`40P01`、`08xxx`、`53xxx` 可重试;`55P03`/`57014`/`25P02` 不可。
    /// 非数据库错误沿用 [`BaseError::category`] 的 `Transient` 语义。
    pub fn is_retryable(&self) -> bool {
        self.db_error().map_or_else(
            || self.category() == ErrorCategory::Transient,
            |err| err.is_retryable(),
        )
    }

    /// 是否处于 PostgreSQL 的「事务已中止」状态(SQLSTATE `25P02`)。
    ///
    /// 此时任何语句都会继续失败,必须先 `ROLLBACK`。
    pub fn is_transaction_aborted(&self) -> bool {
        self.sql_error_info()
            .is_some_and(|info| info.kind() == yang_db::SqlErrorKind::InFailedTransaction)
    }

    /// 是否为超时/取消类错误:`57014`(语句取消)或 `55P03`(锁不可用),
    /// 以及既有 HTTP 超时。
    pub fn is_timeout(&self) -> bool {
        matches!(self, BaseError::HttpTimeout)
            || self.sql_error_info().is_some_and(|info| {
                matches!(
                    info.kind(),
                    yang_db::SqlErrorKind::QueryCanceled | yang_db::SqlErrorKind::LockNotAvailable
                )
            })
    }

    /// 是否为客户端过错(`Client`、`Auth` 或 `NotFound` 类)。
    ///
    /// 用于下游统一适配——客户端过错不可重试,调用方应修正请求而非重试。
    /// 注意 `Transient` **不**在此列:虽然瞬时错误也可归「服务端」,但它不是
    /// 调用方过错,且可重试——`is_server_error` 已覆盖该语义。
    pub fn is_client_error(&self) -> bool {
        matches!(
            self.category(),
            ErrorCategory::Client | ErrorCategory::Auth | ErrorCategory::NotFound
        )
    }

    /// 是否为服务端/基础设施错误(`Server`、`Transient` 或 `Conflict`)。
    ///
    /// 用于下游统一适配。`Transient` 在此视为服务端(可重试的服务端错误,
    /// 如连接超时 = HTTP 503 语义);`Conflict` 也计入(资源冲突 = HTTP 409,
    /// 但常由并发写引起而非纯调用方过错)。
    pub fn is_server_error(&self) -> bool {
        matches!(
            self.category(),
            ErrorCategory::Server | ErrorCategory::Transient | ErrorCategory::Conflict
        )
    }
}

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

    #[test]
    fn test_not_ready_code_is_stable() {
        assert_eq!(NOT_READY_CODE, 900001);
    }

    #[test]
    fn test_error_codes_plugin() {
        assert_eq!(
            BaseError::PluginAlreadyRegistered("test".to_string()).code(),
            100001
        );
        assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
        assert_eq!(
            BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
            100003
        );
        assert_eq!(
            BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
            100004
        );
        assert_eq!(
            BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
            100005
        );
        assert_eq!(
            BaseError::PluginCircularDependency("test".to_string()).code(),
            100006
        );
        assert_eq!(
            BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
            100007
        );
        assert_eq!(
            BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
            100008
        );
    }

    #[test]
    fn test_error_codes_database() {
        assert_eq!(
            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError(
                "reason".to_string()
            ))
            .code(),
            200001
        );
        assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
        assert_eq!(
            BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("reason".to_string()))
                .code(),
            200003
        );
        assert_eq!(
            BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("reason".to_string()))
                .code(),
            200004
        );
        assert_eq!(
            BaseError::DatabaseInitFailed("reason".to_string()).code(),
            200005
        );
        assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
        assert_eq!(
            BaseError::DatabaseTransactionFailed(yang_db::DbError::TransactionError(
                "reason".to_string()
            ))
            .code(),
            200009
        );
    }

    #[cfg(feature = "http")]
    #[test]
    fn test_error_codes_http() {
        // 注意:reqwest::Error 无法直接构造,通过 code() 方法间接测试
        assert_eq!(
            BaseError::HttpResponseParseFailed("reason".to_string()).code(),
            300003
        );
        assert_eq!(BaseError::HttpTimeout.code(), 300004);
        assert_eq!(BaseError::HttpClientAlreadyInitialized.code(), 300005);
        assert_eq!(BaseError::HttpClientNotInitialized.code(), 300006);
    }

    #[cfg(feature = "token")]
    #[test]
    fn test_error_codes_token() {
        assert_eq!(
            BaseError::TokenKeyInvalid("reason".to_string()).code(),
            400001
        );
        assert_eq!(
            BaseError::TokenGenerateFailed(jsonwebtoken::errors::Error::from(
                jsonwebtoken::errors::ErrorKind::InvalidToken
            ))
            .code(),
            400002
        );
        assert_eq!(
            BaseError::TokenVerifyFailed(jsonwebtoken::errors::Error::from(
                jsonwebtoken::errors::ErrorKind::InvalidToken
            ))
            .code(),
            400003
        );
        assert_eq!(
            BaseError::TokenParseFailed(jsonwebtoken::errors::Error::from(
                jsonwebtoken::errors::ErrorKind::InvalidToken
            ))
            .code(),
            400004
        );
        assert_eq!(BaseError::TokenExpired.code(), 400005);
        assert_eq!(
            BaseError::TokenTypeInvalid("reason".to_string()).code(),
            400006
        );
    }

    #[test]
    fn test_error_codes_serialization() {
        assert_eq!(
            BaseError::JsonSerializeFailed("reason".to_string()).code(),
            500001
        );
        assert_eq!(
            BaseError::JsonDeserializeFailed("reason".to_string()).code(),
            500002
        );
    }

    #[test]
    fn test_error_codes_field_validation() {
        assert_eq!(
            BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
            600001
        );
        assert_eq!(
            BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
            600002
        );
        assert_eq!(
            BaseError::StringTooLong("field".to_string(), 100, 50).code(),
            600003
        );
        assert_eq!(
            BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
            600004
        );
        assert_eq!(
            BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
            600005
        );
        assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
        assert_eq!(
            BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
            600007
        );
        assert_eq!(
            BaseError::FieldPermissionDenied(
                "table".to_string(),
                "field".to_string(),
                "reason".to_string()
            )
            .code(),
            600008
        );
    }

    #[test]
    fn test_error_codes_action_system() {
        assert_eq!(
            BaseError::ActionNotFound("test_action".to_string()).code(),
            700001
        );
        assert_eq!(
            BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
            700002
        );
        assert_eq!(
            BaseError::Unauthorized("Token 无效".to_string()).code(),
            700003
        );
        assert_eq!(
            BaseError::ParamMissing("user_id".to_string()).code(),
            700004
        );
        assert_eq!(
            BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
            700005
        );
        assert_eq!(
            BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
            700006
        );
        assert_eq!(
            BaseError::UserNotFound("user_123".to_string()).code(),
            700007
        );
        assert_eq!(BaseError::InvalidPassword.code(), 700008);
        assert_eq!(BaseError::TableDefinitionNotSet.code(), 700009);
        assert_eq!(
            BaseError::RateLimitExceeded {
                retry_after_seconds: 30
            }
            .code(),
            700011
        );
        assert_eq!(BaseError::SecondFactorRequired.code(), 700012);
        assert_eq!(BaseError::SecondFactorRequired.code_str(), "700012");
    }

    #[test]
    fn test_error_codes_general() {
        assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
        assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
        assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
    }

    #[test]
    fn test_all_error_codes_are_nonzero() {
        // 确保所有错误码都是非零的
        let errors: Vec<BaseError> = vec![
            BaseError::PluginNotFound("test".to_string()),
            BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("test".to_string())),
            BaseError::HttpTimeout,
            BaseError::TokenExpired,
            BaseError::JsonSerializeFailed("test".to_string()),
            BaseError::FieldRequired("test".to_string()),
            BaseError::ActionNotFound("test".to_string()),
            BaseError::PermissionDenied("test".to_string()),
            BaseError::Unauthorized("test".to_string()),
            BaseError::ParamMissing("test".to_string()),
            BaseError::RecordNotFound("test".to_string()),
            BaseError::UserNotFound("test".to_string()),
            BaseError::InvalidPassword,
            BaseError::TableDefinitionNotSet,
            BaseError::RateLimitExceeded {
                retry_after_seconds: 30,
            },
            BaseError::Unknown("test".to_string()),
        ];

        for error in errors {
            assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
        }
    }

    /// 测试数据库错误链 source() 可遍历
    #[test]
    fn test_database_error_source_chain() {
        use std::error::Error;

        let db_err = yang_db::DbError::QueryError("底层查询错误".to_string());
        let base_err = BaseError::DatabaseQueryFailed(db_err);

        // BaseError.source() 应返回 Some,指向 DbError
        let source = base_err.source();
        assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
    }

    /// 测试 From<DbError> 转换保留错误链
    #[test]
    fn test_from_db_error_preserves_source() {
        use std::error::Error;

        let db_err = yang_db::DbError::QueryError("查询失败".to_string());
        let base_err: BaseError = db_err.into();

        // 验证转换后仍可通过 source() 访问底层错误
        assert!(base_err.source().is_some());
        assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
    }

    #[test]
    fn test_redis_connection_and_operation_errors_preserve_db_source() {
        use std::error::Error;

        let connection = BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError(
            "connection refused".into(),
        ));
        let operation = BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError(
            "WRONGTYPE".into(),
        ));

        assert_eq!(connection.code(), 210001);
        assert_eq!(operation.code(), 210004);
        assert!(connection.source().is_some());
        assert!(operation.source().is_some());
    }

    #[test]
    fn test_plugin_lifecycle_error_preserves_stage_and_source() {
        use std::error::Error;

        let error = BaseError::PluginLifecycleFailed {
            plugin: "audit".into(),
            stage: crate::plugin::PluginLifecycleStage::Shutdown,
            source: Box::new(std::io::Error::other("flush failed")),
        };

        assert_eq!(error.code(), 100008);
        assert_eq!(error.code_str(), "100008");
        assert!(error.to_string().contains("audit"));
        assert!(error.to_string().contains("shutdown"));
        assert!(error.source().is_some());
    }

    /// code_str() 必须与 code() 一致(metrics label 与数值码同源,防漂移)
    #[test]
    fn test_code_str_matches_code() {
        // 覆盖各域代表变体;新增变体时若两处不同步,此处会失败
        let samples: Vec<BaseError> = vec![
            BaseError::PluginNotFound("p".into()),
            BaseError::PluginLifecycleFailed {
                plugin: "p".into(),
                stage: crate::plugin::PluginLifecycleStage::Initialize,
                source: Box::new(std::io::Error::other("init")),
            },
            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into())),
            BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into())),
            BaseError::DatabaseNotInitialized,
            BaseError::RedisNotInitialized,
            BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError("c".into())),
            BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError("o".into())),
            BaseError::RedisOperationDbError(yang_db::DbError::RedisConnectionError("c".into())),
            BaseError::HttpTimeout,
            BaseError::TokenExpired,
            BaseError::TokenRevoked,
            BaseError::TokenRevocationStateInvalid("invalid".into()),
            BaseError::AuthorizationStale,
            BaseError::AuthorizationVersionInvalid,
            BaseError::AuthorizationCheckUnavailable,
            BaseError::JsonSerializeFailed("s".into()),
            BaseError::FieldNotFound("t".into(), "f".into()),
            BaseError::ParamInvalid("k".into(), "r".into()),
            BaseError::TableDefinitionNotSet,
            BaseError::RateLimitExceeded {
                retry_after_seconds: 30,
            },
            BaseError::SecondFactorRequired,
            BaseError::ConfigError("c".into()),
            BaseError::Unknown("u".into()),
        ];
        for err in samples {
            let code = err.code();
            let code_str = err.code_str();
            assert_eq!(
                code_str.parse::<i32>().unwrap(),
                code,
                "code_str {:?} 与 code {} 不一致(变体 {:?})",
                code_str,
                code,
                err
            );
        }
    }

    /// ErrorCategory 全变体覆盖:每个分类至少有一个代表性变体
    #[test]
    fn test_error_category_coverage() {
        // Client
        assert_eq!(
            BaseError::ParamInvalid("k".into(), "r".into()).category(),
            ErrorCategory::Client
        );
        assert_eq!(
            BaseError::ValidationFailed("f".into(), "r".into()).category(),
            ErrorCategory::Client
        );
        // Auth
        assert_eq!(
            BaseError::Unauthorized("u".into()).category(),
            ErrorCategory::Auth
        );
        assert_eq!(BaseError::TokenExpired.category(), ErrorCategory::Auth);
        assert_eq!(BaseError::InvalidPassword.category(), ErrorCategory::Auth);
        assert_eq!(
            BaseError::SecondFactorRequired.category(),
            ErrorCategory::Auth
        );
        // NotFound
        assert_eq!(
            BaseError::RecordNotFound("r".into()).category(),
            ErrorCategory::NotFound
        );
        assert_eq!(
            BaseError::FieldNotFound("t".into(), "f".into()).category(),
            ErrorCategory::NotFound
        );
        // Conflict
        assert_eq!(
            BaseError::PluginAlreadyRegistered("p".into()).category(),
            ErrorCategory::Conflict
        );
        // Transient
        assert_eq!(
            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
                .category(),
            ErrorCategory::Transient
        );
        assert_eq!(
            BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into()))
                .category(),
            ErrorCategory::Transient
        );
        assert_eq!(BaseError::HttpTimeout.category(), ErrorCategory::Transient);
        // Server
        assert_eq!(
            BaseError::Unknown("u".into()).category(),
            ErrorCategory::Server
        );
        assert_eq!(
            BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("q".into())).category(),
            ErrorCategory::Server
        );
    }

    /// is_retryable = (category == Transient)
    #[test]
    fn test_is_retryable() {
        assert!(
            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
                .is_retryable()
        );
        assert!(BaseError::HttpTimeout.is_retryable());
        assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_retryable());
        assert!(!BaseError::Unauthorized("u".into()).is_retryable());
        assert!(!BaseError::Unknown("u".into()).is_retryable());
    }

    /// is_client_error = (Client | Auth | NotFound)
    #[test]
    fn test_is_client_error() {
        assert!(BaseError::ParamInvalid("k".into(), "r".into()).is_client_error());
        assert!(BaseError::Unauthorized("u".into()).is_client_error());
        assert!(BaseError::TokenExpired.is_client_error());
        assert!(BaseError::RecordNotFound("r".into()).is_client_error());
        assert!(BaseError::ActionNotFound("a".into()).is_client_error());
        assert!(
            !BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
                .is_client_error()
        );
        assert!(!BaseError::Unknown("u".into()).is_client_error());
    }

    /// is_server_error = (Server | Transient | Conflict)
    #[test]
    fn test_is_server_error() {
        assert!(BaseError::Unknown("u".into()).is_server_error());
        assert!(
            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
                .is_server_error()
        );
        assert!(BaseError::PluginAlreadyRegistered("p".into()).is_server_error());
        assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_server_error());
        assert!(!BaseError::Unauthorized("u".into()).is_server_error());
    }

    /// MySQL 唯一键冲突必须变成可归因的参数错误,而不是裸 DB 错误。
    #[test]
    fn mysql_duplicate_entry_maps_to_param_invalid_naming_the_key() {
        // 「Duplicate entry 'x' for key 'source_key'」是 MySQL 1062 的报文形态。
        // 系统自动派生 source_key、系统生成 token 都会撞唯一索引;裸 DB 错误会让
        // 控制台只能显示「数据库执行失败」,运维无从知道撞的是哪个键。
        let error = BaseError::from(yang_db::DbError::ConstraintError(
            "Duplicate entry 'payment_currency' for key 'source_key'".to_string(),
        ));
        match error {
            BaseError::ParamInvalid(field, message) => {
                assert_eq!(field, "source_key", "要点名冲突的键");
                assert!(!message.is_empty());
            }
            other => panic!("唯一键冲突应映射为 ParamInvalid,实际: {other:?}"),
        }
    }

    /// 复合/限定形态:MySQL 8 可能把库名或表名带进 key。
    #[test]
    fn qualified_mysql_key_name_keeps_only_the_last_segment() {
        assert_eq!(
            duplicate_key_field(
                "Duplicate entry 'x' for key 'yang_system.feishu_datasource.source_key'"
            ),
            Some("source_key".to_string())
        );
    }

    /// PostgreSQL 的唯一约束冲突(23505)同样要归因到可读的名字。
    #[test]
    fn postgres_unique_violation_maps_to_param_invalid() {
        let error = BaseError::from(yang_db::DbError::ConstraintError(
            "duplicate key value violates unique constraint \"feishu_option_option_id_key\""
                .to_string(),
        ));
        match error {
            BaseError::ParamInvalid(field, _) => assert_eq!(field, "feishu_option_option_id_key"),
            other => panic!("PG 唯一约束冲突应映射为 ParamInvalid,实际: {other:?}"),
        }
    }

    /// 回归守卫:约束错误里**只有**唯一键冲突该变成 ParamInvalid。
    ///
    /// 外键、非空、CHECK 与唯一键在 MySQL 上共用同一个 SQLSTATE(23000),
    /// 把它们也吞成「参数非法」会让真正的数据完整性问题显示成用户的输入错误。
    #[test]
    fn other_constraint_errors_keep_their_own_mapping() {
        for message in [
            "Cannot add or update a child row: a foreign key constraint fails",
            "Column 'title' cannot be null",
            "Check constraint 'positive_amount' is violated",
        ] {
            let error = BaseError::from(yang_db::DbError::ConstraintError(message.to_string()));
            assert!(
                !matches!(error, BaseError::ParamInvalid(_, _)),
                "{message:?} 不该被当成参数非法,实际: {error:?}"
            );
        }
    }

    /// 报文提取本身是纯函数,单独钉住它的边界。
    #[test]
    fn duplicate_key_field_returns_none_for_unrecognised_messages() {
        assert_eq!(duplicate_key_field(""), None);
        assert_eq!(
            duplicate_key_field("Duplicate entry 'x'"),
            None,
            "缺 for key 段就该放弃提取,而不是编一个名字出来"
        );
        assert_eq!(duplicate_key_field("some other db error"), None);
    }

    fn sql_error(code: &str, constraint: Option<&str>) -> BaseError {
        let mut info = yang_db::SqlErrorInfo::new(code, format!("sqlstate {code}"));
        if let Some(constraint) = constraint {
            info = info.with_constraint(Some(constraint.to_string()));
        }
        BaseError::DatabaseExecuteFailed(yang_db::DbError::DatabaseError(Box::new(info)))
    }

    /// P0-13/P1-17:SQLSTATE 语义(可重试 / 取消超时 / 事务中止)必须从包裹的
    /// `yang_db::DbError` 透出,而不是被「数据库执行失败」压平。
    #[test]
    fn sqlstate_semantics_are_exposed_from_wrapped_db_error() {
        // 40001 序列化失败、40P01 死锁:可重试。
        for code in ["40001", "40P01"] {
            let error = sql_error(code, None);
            assert!(error.is_retryable(), "{code} 应可重试");
            assert!(!error.is_timeout(), "{code} 不是超时");
            assert!(!error.is_transaction_aborted(), "{code} 不是事务中止");
        }

        // 08xxx 连接失败、53xxx 资源不足:可重试。
        assert!(sql_error("08006", None).is_retryable());
        assert!(sql_error("53300", None).is_retryable());

        // 55P03 锁不可用、57014 语句取消:不可重试,但属于超时/取消。
        for code in ["55P03", "57014"] {
            let error = sql_error(code, None);
            assert!(!error.is_retryable(), "{code} 不应自动重试");
            assert!(error.is_timeout(), "{code} 应识别为超时/取消");
        }

        // 25P02 事务已中止:不可重试,且必须显式识别以触发 ROLLBACK。
        let aborted = sql_error("25P02", None);
        assert!(aborted.is_transaction_aborted());
        assert!(!aborted.is_retryable());
        assert!(!aborted.is_timeout());
        assert!(!sql_error("40001", None).is_transaction_aborted());
    }

    /// 外键/NOT NULL/CHECK 违反保留 SQLSTATE 与约束名,供 409/422 分流。
    #[test]
    fn constraint_errors_keep_sqlstate_and_constraint_context() {
        let foreign_key = sql_error("23503", Some("orders_user_id_fkey"));
        assert_eq!(foreign_key.sqlstate(), Some("23503"));
        assert_eq!(foreign_key.constraint(), Some("orders_user_id_fkey"));
        assert!(!foreign_key.is_retryable());
        assert!(foreign_key.is_server_error());

        let not_null = sql_error("23502", Some("users_email_not_null"));
        assert_eq!(not_null.sqlstate(), Some("23502"));
        assert_eq!(not_null.constraint(), Some("users_email_not_null"));

        let check = sql_error("23514", Some("positive_amount"));
        assert_eq!(check.constraint(), Some("positive_amount"));

        // 非结构化错误没有 SQLSTATE 上下文。
        let plain = BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("boom".into()));
        assert_eq!(plain.sqlstate(), None);
        assert_eq!(plain.constraint(), None);
    }
}