calnexus 0.2.0

A command-line math expression evaluator with 11 core and 3 optional (time/unit/fx) computation domains plus a numerical-linalg feature, symbolic calculus, REPL, batch processing, HTTP and MCP servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! 汇率数据提供者:RateProvider trait + 纯抓取实现 + 缓存/熔断装饰器。
//! 三级缓存(L1 内存 → L2 文件 → 网络)由 `CachedRateProvider` 统一承担,失败按 stale 策略显性返回。

use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
#[cfg(test)]
use std::sync::Arc;
#[cfg(test)]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crate::core::CalcError;
use crate::math::fx::{RateTable, date_from_unix_days};
use limiteron::sync::{CircuitCallError, SyncCircuitBreaker};
use oxcache::sync::ByteWeightCache;

/// Frankfurter API 固定端点(编译期常量,无 SSRF 面)。
const FRANKFURTER_URL: &str = "https://api.frankfurter.dev/v1/latest?base=EUR";

/// ExchangeRate-API 开放端点(免 key;EUR base 与 frankfurter 对齐,三角换算语义一致)。
const EXCHANGE_RATE_API_URL: &str = "https://open.er-api.com/v6/latest/EUR";

/// 默认 TTL:24 小时(秒)。
const DEFAULT_TTL_SECONDS: u64 = 24 * 3600;

/// HTTP 请求超时:5 秒。
const HTTP_TIMEOUT: Duration = Duration::from_secs(5);

/// 熔断默认阈值:连续 3 次网络失败后打开(小于 limiteron 默认 5:每次失败已付 5s 超时)。
const DEFAULT_BREAKER_THRESHOLD: u32 = 3;

/// 熔断默认冷却:30 秒。
const DEFAULT_BREAKER_COOLDOWN: Duration = Duration::from_secs(30);

/// 响应体读取上限:1 MB(防源站异常导致内存膨胀)。
const MAX_RESPONSE_BODY_BYTES: u64 = 1024 * 1024;

/// 缓存目录名。
const CACHE_DIR_NAME: &str = "calnexus";

/// 缓存文件名。
const CACHE_FILE_NAME: &str = "fx_rates.json";

/// L1(oxcache ByteWeightCache)单 key:汇率表唯一主键。
const FX_RATES_KEY: &str = "fx:rates";

/// L1 字节预算:1 MiB(单 key 缓存,预算不构成实际约束)。
const FX_RATES_BUDGET_BYTES: u64 = 1024 * 1024;

/// L1 单条准入阈值:256 KiB(超过即跳过写入,防异常大表撑爆预算)。
const FX_RATES_MAX_ENTRY_BYTES: u64 = 256 * 1024;

/// 汇率数据源 trait(可注入 mock 测试)。
pub trait RateProvider: Send + Sync {
    /// 获取最新汇率表。
    fn rates(&self) -> Result<RateTable, CalcError>;

    /// 数据源名称(failover 错误聚合与来源可观测)。
    fn name(&self) -> &'static str {
        "unknown"
    }

    /// 组合 provider(如 failover 链)可覆盖:按调用顺序返回全部源名称。
    fn source_names(&self) -> Vec<&'static str> {
        vec![self.name()]
    }
}

/// Frankfurter API 响应体(仅提取所需字段,忽略 amount 等额外字段)。
#[derive(serde::Deserialize)]
struct FrankfurterResponse {
    base: String,
    date: String,
    rates: HashMap<String, f64>,
}

/// ExchangeRate-API 响应体(仅提取所需字段,忽略 time_last_update_utc 等额外字段)。
#[derive(serde::Deserialize)]
struct ExchangeRateApiResponse {
    result: String,
    base_code: String,
    time_last_update_unix: u64,
    rates: HashMap<String, f64>,
}

/// 缓存文件格式(v2):RateTable(含 source)+ 抓取时间戳。
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
struct CachedRateTable {
    base: String,
    date: String,
    rates: HashMap<String, f64>,
    source: String,
    fetched_at: u64,
}

impl From<CachedRateTable> for RateTable {
    fn from(c: CachedRateTable) -> Self {
        RateTable {
            base: c.base,
            date: c.date,
            rates: c.rates,
            source: c.source,
        }
    }
}

/// CachedRateProvider:缓存与容错装饰器(L1 内存 + L2 文件 + 熔断 + stale 策略)。
///
/// 包装任意 `RateProvider`(单源或 failover 链):缓存与熔断对整条链只生效一次。
pub struct CachedRateProvider {
    /// 缓存文件路径(None 时降级为仅内存缓存)。
    cache_path: Option<PathBuf>,
    /// L1 内存缓存(单 key `"fx:rates"`,get_or_compute 单飞,失败不落缓存)。
    cache: ByteWeightCache<&'static str, RateTable, fn(&RateTable) -> u64>,
    /// 网络熔断器:连续失败达阈值后 Open 快速失败(调用点在单飞闭包内)。
    breaker: SyncCircuitBreaker,
    /// 实际抓取实现(单源或 failover 链)。
    inner: Box<dyn RateProvider>,
}

/// fx 表估重(weigher):按条目数线性估算(每条目约 96 B + 固定头部),
/// 使 `with_max_entry_bytes` 准入阈值对真实表规模有意义(166 币种 ≈ 16 KB)。
fn rate_table_weight(table: &RateTable) -> u64 {
    table.rates.len() as u64 * 96 + 256
}

/// 手动 Debug:`ByteWeightCache` 未实现 Debug,仅输出路径与条目数。
impl fmt::Debug for CachedRateProvider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CachedRateProvider")
            .field("cache_path", &self.cache_path)
            .field("cache_entries", &self.cache.entry_count())
            .field("breaker", &self.breaker)
            .field("inner", &self.inner.name())
            .finish()
    }
}

impl CachedRateProvider {
    fn build_cache() -> ByteWeightCache<&'static str, RateTable, fn(&RateTable) -> u64> {
        ByteWeightCache::new(
            FX_RATES_BUDGET_BYTES,
            rate_table_weight as fn(&RateTable) -> u64,
        )
        .with_max_entry_bytes(FX_RATES_MAX_ENTRY_BYTES)
    }

    /// 创建默认实例:缓存路径为 `dirs::cache_dir()/calnexus/fx_rates.json`。
    pub fn new(inner: Box<dyn RateProvider>) -> Self {
        Self::with_config(inner, &FxProviderConfig::from_env())
    }

    /// 按显式配置装配(熔断参数取自 cfg,缓存路径取平台默认)。
    pub fn with_config(inner: Box<dyn RateProvider>, cfg: &FxProviderConfig) -> Self {
        Self {
            cache_path: default_cache_path(),
            cache: Self::build_cache(),
            breaker: SyncCircuitBreaker::new(cfg.breaker_threshold(), cfg.breaker_cooldown()),
            inner,
        }
    }

    /// 测试专用构造函数:指定缓存文件路径。
    #[cfg(test)]
    fn with_cache_path(inner: Box<dyn RateProvider>, path: PathBuf) -> Self {
        Self {
            cache_path: Some(path),
            cache: Self::build_cache(),
            breaker: SyncCircuitBreaker::new(DEFAULT_BREAKER_THRESHOLD, DEFAULT_BREAKER_COOLDOWN),
            inner,
        }
    }

    /// 测试专用构造函数:注入内层 provider 与熔断参数(不出网的确定性测试)。
    #[cfg(test)]
    fn with_inner(inner: Box<dyn RateProvider>, threshold: u32, cooldown: Duration) -> Self {
        Self {
            cache_path: None,
            cache: Self::build_cache(),
            breaker: SyncCircuitBreaker::new(threshold, cooldown),
            inner,
        }
    }

    /// 测试专用构造函数:缓存文件路径 + 注入内层 provider(覆盖「L2 过期文件」场景)。
    #[cfg(test)]
    fn with_cache_path_and_inner(
        path: PathBuf,
        inner: Box<dyn RateProvider>,
        threshold: u32,
        cooldown: Duration,
    ) -> Self {
        Self {
            cache_path: Some(path),
            cache: Self::build_cache(),
            breaker: SyncCircuitBreaker::new(threshold, cooldown),
            inner,
        }
    }

    /// 测试专用:内层 provider 的源名称序列(工厂装配断言)。
    #[cfg(test)]
    fn inner_names(&self) -> Vec<&'static str> {
        self.inner.source_names()
    }
}

impl RateProvider for CachedRateProvider {
    fn rates(&self) -> Result<RateTable, CalcError> {
        // L1 命中直接返回;未命中时 get_or_compute 单飞执行 compute
        // (L2 读 → TTL 判定 → 熔断拉取 → 写回),失败不写缓存,下次调用重试。
        self.cache.get_or_compute(FX_RATES_KEY, || {
            // L2: 文件缓存(TTL 内有效;损坏自愈为 miss)
            let cache_read = self
                .cache_path
                .as_ref()
                .map(|p| read_cache_file(p))
                .unwrap_or(CacheRead::Missing);
            let cached = match &cache_read {
                CacheRead::Loaded(c) => {
                    if !is_expired_at(c.fetched_at, current_unix_timestamp(), ttl_seconds()) {
                        let table: RateTable = c.clone().into();
                        return Ok(table);
                    }
                    Some(c.clone())
                }
                _ => None,
            };

            // 网络抓取经熔断器包装:连续失败达阈值后 Open 快速失败。
            match self.breaker.call(|| self.inner.rates()) {
                Ok(table) => {
                    // 写回文件缓存(best-effort,失败静默降级)
                    if let Some(path) = &self.cache_path {
                        let now = current_unix_timestamp();
                        let _ = write_cache_file(path, &table, now);
                    }
                    Ok(table)
                }
                Err(breaker_err) => {
                    // 熔断拒绝与网络失败同等进入 stale 策略;缓存损坏分类为 cache_unreadable。
                    let net_err = match breaker_err {
                        CircuitCallError::Inner(err) => err,
                        CircuitCallError::Open => CalcError::dependency_unavailable(
                            "FX rate source circuit is open after repeated failures",
                        )
                        .with_i18n("msg.fx.circuit_open", vec![]),
                    };
                    let cache_corrupted = matches!(cache_read, CacheRead::Corrupted);
                    apply_stale_policy(cached.as_ref(), read_allow_stale(), cache_corrupted)
                        .map_err(|e| e.with_source(net_err.message))
                }
            }
        })
    }

    fn name(&self) -> &'static str {
        self.inner.name()
    }

    fn source_names(&self) -> Vec<&'static str> {
        self.inner.source_names()
    }
}

/// FrankfurterProvider:ECB 口径纯抓取实现(无状态、无缓存)。
#[derive(Debug, Default, Clone, Copy)]
pub struct FrankfurterProvider;

impl RateProvider for FrankfurterProvider {
    fn rates(&self) -> Result<RateTable, CalcError> {
        fetch_from_network()
    }

    fn name(&self) -> &'static str {
        "frankfurter"
    }
}

/// ExchangeRateApiProvider:聚合源纯抓取实现(免 key,覆盖 160+ 币种)。
#[derive(Debug, Default, Clone, Copy)]
pub struct ExchangeRateApiProvider;

impl RateProvider for ExchangeRateApiProvider {
    fn rates(&self) -> Result<RateTable, CalcError> {
        let body = fetch_body(EXCHANGE_RATE_API_URL)?;
        parse_erapi_response(&body)
    }

    fn name(&self) -> &'static str {
        "erapi"
    }
}

/// 上游受控字段入错误消息前的清洗:仅保留可打印 ASCII;超 32 字符截断并以 `...` 标记(防日志注入)。
fn sanitize_upstream_field(raw: &str) -> String {
    let filtered: String = raw
        .chars()
        .filter(|c| c.is_ascii_graphic() || *c == ' ')
        .collect();
    if filtered.chars().count() > 32 {
        format!("{}...", filtered.chars().take(32).collect::<String>())
    } else {
        filtered
    }
}

/// er-api 响应归一:`base_code`→base、`time_last_update_unix`→date、rates 直取。
fn parse_erapi_response(body: &str) -> Result<RateTable, CalcError> {
    let parsed: ExchangeRateApiResponse = serde_json::from_str(body).map_err(|e| {
        // 三分类之二:响应 JSON 解析失败(含缺 base_code/rates)→ invalid_response
        CalcError::dependency_unavailable("FX response parse failed")
            .with_source(e.to_string())
            .with_i18n("msg.fx.invalid_response", vec![])
    })?;
    if parsed.result != "success" {
        return Err(CalcError::dependency_unavailable(format!(
            "FX provider returned non-success result: {}",
            sanitize_upstream_field(&parsed.result)
        ))
        .with_i18n("msg.fx.invalid_response", vec![]));
    }
    if parsed.rates.is_empty() {
        return Err(
            CalcError::dependency_unavailable("FX provider returned an empty rate table")
                .with_i18n("msg.fx.invalid_response", vec![]),
        );
    }
    Ok(RateTable {
        base: parsed.base_code,
        date: date_from_unix_days(parsed.time_last_update_unix),
        rates: parsed.rates,
        source: "erapi".to_string(),
    })
}

/// failover 链:按固定顺序依次尝试,任一成功即返回;全部失败聚合各源原因。
pub struct ChainRateProvider {
    providers: Vec<Box<dyn RateProvider>>,
}

impl ChainRateProvider {
    /// 固定顺序装配(顺序即代码,不随运行时状态变化)。
    pub fn new(providers: Vec<Box<dyn RateProvider>>) -> Self {
        Self { providers }
    }
}

impl RateProvider for ChainRateProvider {
    fn rates(&self) -> Result<RateTable, CalcError> {
        let mut failures = Vec::with_capacity(self.providers.len());
        for provider in &self.providers {
            match provider.rates() {
                Ok(table) => return Ok(table),
                Err(e) => failures.push(format!("{}: {}", provider.name(), e.message)),
            }
        }
        let details = failures.join("; ");
        Err(
            CalcError::dependency_unavailable(format!("all FX providers failed: {}", details))
                .with_i18n(
                    "msg.fx.all_providers_failed",
                    vec![("details".to_string(), details)],
                ),
        )
    }

    fn name(&self) -> &'static str {
        "auto"
    }

    fn source_names(&self) -> Vec<&'static str> {
        self.providers
            .iter()
            .flat_map(|p| p.source_names())
            .collect()
    }
}

/// 唯一装配入口:按 `provider_name()` 选择内层 provider,外层统一包缓存/熔断装饰器。
///
/// - 未设/frankfurter:仅 frankfurter(默认路径,行为与变更前一致)
/// - erapi:仅 er-api
/// - auto:固定顺序 `[frankfurter, erapi]` failover 链
pub fn build_provider(cfg: &FxProviderConfig) -> CachedRateProvider {
    let inner: Box<dyn RateProvider> = match cfg.provider_name() {
        "erapi" => Box::new(ExchangeRateApiProvider),
        "auto" => Box::new(ChainRateProvider::new(vec![
            Box::new(FrankfurterProvider),
            Box::new(ExchangeRateApiProvider),
        ])),
        _ => Box::new(FrankfurterProvider),
    };
    CachedRateProvider::with_config(inner, cfg)
}

/// 默认缓存文件路径;平台无缓存目录时返回 None,降级为仅内存缓存。
fn default_cache_path() -> Option<PathBuf> {
    dirs::cache_dir().map(|d| d.join(CACHE_DIR_NAME).join(CACHE_FILE_NAME))
}

/// 当前 Unix 时间戳(秒)。系统时钟异常时返回 0。
fn current_unix_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// fx 环境配置:字段为原始字符串,非法或缺省由访问器回退默认;构建失败整体回退默认。
#[derive(confers::Config, serde::Deserialize, Debug, Clone)]
#[config(env_prefix = "CALNEXUS_FX_")]
pub struct FxProviderConfig {
    /// `CALNEXUS_FX_TTL_HOURS`(小时,支持小数;非法回退 24h)。
    #[serde(default, deserialize_with = "de_env_string")]
    pub ttl_hours: Option<String>,
    /// `CALNEXUS_FX_BREAKER_THRESHOLD`(连续失败次数;非法或 <1 回退默认)。
    #[serde(default, deserialize_with = "de_env_string")]
    pub breaker_threshold: Option<String>,
    /// `CALNEXUS_FX_BREAKER_COOLDOWN_SECS`(秒;0=关闭快速失败,非法回退默认)。
    #[serde(default, deserialize_with = "de_env_string")]
    pub breaker_cooldown_secs: Option<String>,
    /// `CALNEXUS_FX_ALLOW_STALE`(仅 "1" 为 true)。
    #[serde(default, deserialize_with = "de_env_string")]
    pub allow_stale: Option<String>,
    /// `CALNEXUS_FX_PROVIDER`(frankfurter/erapi/auto;非法或空回退 frankfurter)。
    #[serde(default, deserialize_with = "de_env_string")]
    pub provider: Option<String>,
}

/// 把 confers 推断的标量 env 值转回字符串:否则 "48" 被推断为整数、反序列化失败会被 `unwrap_or_default` 静默吞成默认值(env 失效)。
fn de_env_string<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct EnvStringVisitor;

    impl<'de> serde::de::Visitor<'de> for EnvStringVisitor {
        type Value = Option<String>;

        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            formatter.write_str("a scalar env value (string, number, or bool)")
        }

        fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
            Ok(Some(v.to_string()))
        }

        fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Self::Value, E> {
            Ok(Some(v.to_string()))
        }

        fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Self::Value, E> {
            Ok(Some(v.to_string()))
        }

        fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<Self::Value, E> {
            Ok(Some(v.to_string()))
        }

        fn visit_bool<E: serde::de::Error>(self, v: bool) -> Result<Self::Value, E> {
            Ok(Some(v.to_string()))
        }

        fn visit_none<E: serde::de::Error>(self) -> Result<Self::Value, E> {
            Ok(None)
        }

        fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
            Ok(None)
        }

        fn visit_some<D2>(self, deserializer: D2) -> Result<Self::Value, D2::Error>
        where
            D2: serde::Deserializer<'de>,
        {
            deserializer.deserialize_any(self)
        }
    }

    deserializer.deserialize_any(EnvStringVisitor)
}

impl FxProviderConfig {
    /// 从环境变量单点加载(env_prefix `CALNEXUS_FX_`,`__` 作嵌套分隔符)。
    pub fn from_env() -> Self {
        confers::config::<Self>()
            .env_separator("__")
            .env_prefix("CALNEXUS_FX_")
            .build()
            .unwrap_or_default()
    }

    /// TTL(秒):薄胶水,hours→seconds 换算与非法回退。
    pub fn ttl_seconds(&self) -> u64 {
        parse_ttl_hours(self.ttl_hours.as_deref())
    }

    /// 熔断阈值。
    pub fn breaker_threshold(&self) -> u32 {
        parse_breaker_threshold(self.breaker_threshold.as_deref())
    }

    /// 熔断冷却(Duration)。
    pub fn breaker_cooldown(&self) -> Duration {
        parse_breaker_cooldown(self.breaker_cooldown_secs.as_deref())
    }

    /// stale 回退开关(仅 "1" 为 true)。
    pub fn allow_stale(&self) -> bool {
        parse_allow_stale(self.allow_stale.as_deref())
    }

    /// 选源名称:erapi/auto 原样通过,其余(未设/空/frankfurter/非法)回退 frankfurter。
    pub fn provider_name(&self) -> &str {
        match self.provider.as_deref() {
            Some("erapi") => "erapi",
            Some("auto") => "auto",
            _ => "frankfurter",
        }
    }
}

/// 进程级薄胶水:从环境加载 fx 配置取 TTL(rates() 热路径每次调用)。
fn ttl_seconds() -> u64 {
    FxProviderConfig::from_env().ttl_seconds()
}

/// 进程级薄胶水:从环境加载 fx 配置取 stale 开关。
fn read_allow_stale() -> bool {
    FxProviderConfig::from_env().allow_stale()
}

/// 解析 TTL 小时字符串为秒数,解析失败回退默认 24h。
fn parse_ttl_hours(hours_str: Option<&str>) -> u64 {
    hours_str
        .and_then(|s| s.parse::<f64>().ok())
        .map(|h| (h * 3600.0) as u64)
        .unwrap_or(DEFAULT_TTL_SECONDS)
}

/// 解析熔断阈值,非法或 <1 时回退默认值。
fn parse_breaker_threshold(raw: Option<&str>) -> u32 {
    raw.and_then(|s| s.parse::<u32>().ok())
        .filter(|&t| t >= 1)
        .unwrap_or(DEFAULT_BREAKER_THRESHOLD)
}

/// 解析熔断冷却秒数,非法回退默认;0 表示关闭快速失败。
fn parse_breaker_cooldown(raw: Option<&str>) -> Duration {
    raw.and_then(|s| s.parse::<u64>().ok())
        .map(Duration::from_secs)
        .unwrap_or(DEFAULT_BREAKER_COOLDOWN)
}

/// 解析 ALLOW_STALE:仅 `"1"` 为 true,其余为 false。
fn parse_allow_stale(raw: Option<&str>) -> bool {
    matches!(raw, Some("1"))
}

/// 基于显式参数判断是否过期(不依赖系统时钟/环境变量)。
fn is_expired_at(fetched_at: u64, now: u64, ttl_secs: u64) -> bool {
    now.saturating_sub(fetched_at) > ttl_secs
}

/// Stale 策略:网络失败时按 allow_stale 决定返回过期缓存或 domain 错误。
fn apply_stale_policy(
    cached: Option<&CachedRateTable>,
    allow_stale: bool,
    cache_corrupted: bool,
) -> Result<RateTable, CalcError> {
    match cached {
        Some(c) if allow_stale => Ok(c.clone().into()),
        Some(c) => Err(CalcError::dependency_unavailable(format!(
            "FX network unreachable, local snapshot: {}, set CALNEXUS_FX_ALLOW_STALE=1 to allow stale cache",
            c.date
        ))
        .with_i18n("msg.fx.network_unreachable", vec![])),
        None => {
            if cache_corrupted {
                // 三分类之二:缓存文件损坏
                Err(CalcError::dependency_unavailable(
                    "FX rate cache file is corrupted and network fetch failed".to_string(),
                )
                .with_i18n("msg.fx.cache_unreadable", vec![]))
            } else {
                // 三分类之一:网络不可达且无本地缓存
                Err(CalcError::dependency_unavailable(
                    "FX network unreachable, no local cache available".to_string(),
                )
                .with_i18n("msg.fx.network_unreachable", vec![]))
            }
        }
    }
}

/// 缓存文件读取结果(区分缺失与损坏,支撑三分类错误)。
#[derive(Debug)]
enum CacheRead {
    /// 文件不存在(正常首次运行)。
    Missing,
    /// 文件存在但读取/解析失败(损坏,可自愈重拉)。
    Corrupted,
    /// 成功读取。
    Loaded(CachedRateTable),
}

/// 读取缓存文件并反序列化。文件不存在返回 Missing,损坏返回 Corrupted(自愈为 miss)。
/// v1 文件缺 `source` 字段 → 反序列化失败 → Corrupted(一次性重拉升级为 v2)。
fn read_cache_file(path: &Path) -> CacheRead {
    match std::fs::read_to_string(path) {
        Err(_) => CacheRead::Missing,
        Ok(content) => match serde_json::from_str(&content) {
            Ok(table) => CacheRead::Loaded(table),
            Err(_) => CacheRead::Corrupted,
        },
    }
}

/// 写入缓存文件(序列化 + 创建父目录)。失败时返回 io::Error(调用方决定是否忽略)。
fn write_cache_file(path: &Path, table: &RateTable, fetched_at: u64) -> std::io::Result<()> {
    let cached = CachedRateTable {
        base: table.base.clone(),
        date: table.date.clone(),
        rates: table.rates.clone(),
        source: table.source.clone(),
        fetched_at,
    };
    let json = serde_json::to_string(&cached).map_err(std::io::Error::other)?;

    // 创建父目录(best-effort,目录已存在不报错)
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    // 原子写:temp 文件 + rename 替换,杜绝并发读到 torn write。
    let file_name = path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| "fx_rates.json".to_string());
    let tmp_path = path.with_file_name(format!(".{}.tmp.{}", file_name, std::process::id()));
    {
        use std::io::Write;
        let mut f = std::fs::File::create(&tmp_path)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ = f.set_permissions(std::fs::Permissions::from_mode(0o600));
        }
        f.write_all(json.as_bytes())?;
        f.sync_all().ok();
    }
    match std::fs::rename(&tmp_path, path) {
        Ok(()) => Ok(()),
        Err(e) => {
            let _ = std::fs::remove_file(&tmp_path);
            Err(e)
        }
    }
}

/// 抓取固定端点响应体(超时 5s、仅 https、1MB 响应上限)。
fn fetch_body(url: &str) -> Result<String, CalcError> {
    let response = ureq::get(url)
        .config()
        .timeout_global(Some(HTTP_TIMEOUT))
        .https_only(true) // 拒绝降级到明文/重定向到 http
        .build()
        .call()
        .map_err(|e| {
            CalcError::dependency_unavailable("FX network request failed")
                .with_source(e.to_string())
                .with_i18n("msg.fx.network_unreachable", vec![])
        })?;

    // 响应体读取上限 1MB:源站被劫持/异常时防止内存膨胀
    response
        .into_body()
        .with_config()
        .limit(MAX_RESPONSE_BODY_BYTES)
        .read_to_string()
        .map_err(|e| {
            // 三分类之二:响应读取失败 → invalid_response
            CalcError::dependency_unavailable("FX response read failed")
                .with_source(e.to_string())
                .with_i18n("msg.fx.invalid_response", vec![])
        })
}

/// 从 Frankfurter API 抓取最新汇率(URL 编译期固定)。
fn fetch_from_network() -> Result<RateTable, CalcError> {
    let body = fetch_body(FRANKFURTER_URL)?;

    let parsed: FrankfurterResponse = serde_json::from_str(&body).map_err(|e| {
        // 三分类之二:响应 JSON 解析失败 → invalid_response
        CalcError::dependency_unavailable("FX response parse failed")
            .with_source(e.to_string())
            .with_i18n("msg.fx.invalid_response", vec![])
    })?;

    Ok(RateTable {
        base: parsed.base,
        date: parsed.date,
        rates: parsed.rates,
        source: "frankfurter".to_string(),
    })
}

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

    /// CALNEXUS_FX_* 进程级环境变量的跨测试互斥:CI 并行腿下,写者(env mapping contract
    /// 测试 set/remove 五个 fx env 键)与读者(rates() 内 read_allow_stale()/ttl_seconds()
    /// 的默认值依赖)线程重叠时,stale/TTL 语义被进程级 env 污染——实测
    /// test_fetch_lock_concurrent_consistency 因此在 CI 并行腿出现「恒失败 fetcher 却
    /// 拿到 Ok(stale 表)」的误判(本地 --test-threads=1 串行永不重叠,故仅 CI 复现)。
    /// 所有依赖 fx env 的测试必须整程持锁;锁只拦同模块测试线程,闭包子线程不取锁无死锁。
    static FX_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// 测试用 mock provider:返回预设的汇率表。
    struct MockRateProvider {
        rates: HashMap<String, f64>,
        date: String,
        base: String,
        source: String,
    }

    impl RateProvider for MockRateProvider {
        fn rates(&self) -> Result<RateTable, CalcError> {
            Ok(RateTable {
                base: self.base.clone(),
                date: self.date.clone(),
                rates: self.rates.clone(),
                source: self.source.clone(),
            })
        }
    }

    /// 测试用闭包 provider(替代原 TestFetcher 注入点,装配在装饰器的 inner 上)。
    struct MockFnProvider<F>(F);

    impl<F> RateProvider for MockFnProvider<F>
    where
        F: Fn() -> Result<RateTable, CalcError> + Send + Sync,
    {
        fn rates(&self) -> Result<RateTable, CalcError> {
            (self.0)()
        }
    }

    fn boxed_fn(
        f: impl Fn() -> Result<RateTable, CalcError> + Send + Sync + 'static,
    ) -> Box<dyn RateProvider> {
        Box::new(MockFnProvider(f))
    }

    fn mock_rates() -> HashMap<String, f64> {
        let mut rates = HashMap::new();
        rates.insert("USD".to_string(), 1.08);
        rates.insert("CNY".to_string(), 7.85);
        rates.insert("GBP".to_string(), 0.85);
        rates.insert("JPY".to_string(), 165.0);
        rates
    }

    fn mock_provider() -> MockRateProvider {
        MockRateProvider {
            rates: mock_rates(),
            date: "2026-07-25".to_string(),
            base: "EUR".to_string(),
            source: "frankfurter".to_string(),
        }
    }

    // ===== 三角换算(经 base EUR) =====

    #[test]
    fn test_triangle_conversion_usd_to_cny() {
        // fx(100, "USD", "CNY") = 100 / rate[USD] * rate[CNY] = 100 / 1.08 * 7.85
        let provider = mock_provider();
        let table = provider.rates().unwrap();
        let rate_usd = table.rates["USD"];
        let rate_cny = table.rates["CNY"];
        let result = 100.0 / rate_usd * rate_cny;
        let expected = 100.0 / 1.08 * 7.85;
        assert!((result - expected).abs() < 1e-9);
    }

    #[test]
    fn test_same_currency_identity() {
        // fx(1, "USD", "USD") = 1(同币种恒等)
        let provider = mock_provider();
        let table = provider.rates().unwrap();
        let rate_usd = table.rates["USD"];
        let result = 1.0 / rate_usd * rate_usd;
        assert!((result - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_unknown_currency_error_includes_count() {
        // 未知币种 → DomainError,消息含支持币种数量
        let provider = mock_provider();
        let table = provider.rates().unwrap();
        let result = table.rates.get("XYZ");
        assert!(result.is_none());
        // 验证支持币种数量(mock_rates 有 4 个币种)
        assert_eq!(table.rates.len(), 4);
    }

    // ===== TTL 判断 =====

    #[test]
    fn test_parse_ttl_hours_default() {
        // 无环境变量 → 默认 24h
        assert_eq!(parse_ttl_hours(None), 24 * 3600);
        assert_eq!(parse_ttl_hours(Some("")), 24 * 3600);
        assert_eq!(parse_ttl_hours(Some("invalid")), 24 * 3600);
    }

    #[test]
    fn test_parse_ttl_hours_override() {
        // CALNEXUS_FX_TTL_HOURS=48 → 48h
        assert_eq!(parse_ttl_hours(Some("48")), 48 * 3600);
        // 小数支持:0.5h = 1800s
        assert_eq!(parse_ttl_hours(Some("0.5")), 1800);
    }

    // ===== 熔断参数解析(CALNEXUS_FX_BREAKER_*) =====

    #[test]
    fn test_parse_breaker_threshold_default() {
        assert_eq!(parse_breaker_threshold(None), 3);
        assert_eq!(parse_breaker_threshold(Some("")), 3);
        assert_eq!(parse_breaker_threshold(Some("invalid")), 3);
        // <1 非法,回退默认
        assert_eq!(parse_breaker_threshold(Some("0")), 3);
    }

    #[test]
    fn test_parse_breaker_threshold_override() {
        assert_eq!(parse_breaker_threshold(Some("1")), 1);
        assert_eq!(parse_breaker_threshold(Some("5")), 5);
    }

    #[test]
    fn test_parse_breaker_cooldown_default() {
        assert_eq!(parse_breaker_cooldown(None), Duration::from_secs(30));
        assert_eq!(parse_breaker_cooldown(Some("")), Duration::from_secs(30));
        assert_eq!(parse_breaker_cooldown(Some("bad")), Duration::from_secs(30));
    }

    #[test]
    fn test_parse_breaker_cooldown_override() {
        assert_eq!(parse_breaker_cooldown(Some("60")), Duration::from_secs(60));
        // 0 = 关闭快速失败(冷却到期即刻放行探针)
        assert_eq!(parse_breaker_cooldown(Some("0")), Duration::ZERO);
    }

    #[test]
    fn test_is_expired_25h_old_default_ttl() {
        // 25h 前的时间戳 + 默认 24h TTL → 过期
        let now = 1_000_000_000u64;
        let fetched_at = now - 25 * 3600;
        let ttl = 24 * 3600;
        assert!(is_expired_at(fetched_at, now, ttl));
    }

    #[test]
    fn test_is_expired_25h_old_ttl_48() {
        // 25h 前的时间戳 + TTL=48h → 未过期
        let now = 1_000_000_000u64;
        let fetched_at = now - 25 * 3600;
        let ttl = 48 * 3600;
        assert!(!is_expired_at(fetched_at, now, ttl));
    }

    #[test]
    fn test_is_expired_10h_old_default_ttl() {
        // 10h 前的时间戳 + 默认 24h TTL → 未过期
        let now = 1_000_000_000u64;
        let fetched_at = now - 10 * 3600;
        let ttl = 24 * 3600;
        assert!(!is_expired_at(fetched_at, now, ttl));
    }

    #[test]
    fn test_is_expired_exactly_at_ttl() {
        // 恰好 TTL 时 → 未过期(> TTL 才算过期,<= TTL 未过期)
        let now = 1_000_000_000u64;
        let ttl = 24 * 3600;
        let fetched_at = now - ttl;
        assert!(!is_expired_at(fetched_at, now, ttl));
    }

    #[test]
    fn test_is_expired_future_timestamp() {
        // 未来时间戳 → 未过期(saturating_sub 返回 0)
        let now = 1_000_000_000u64;
        let fetched_at = now + 3600;
        let ttl = 24 * 3600;
        assert!(!is_expired_at(fetched_at, now, ttl));
    }

    // ===== 文件缓存读写 =====

    #[test]
    fn test_write_and_read_cache_file() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let path = tmp.path().to_path_buf();

        let table = RateTable {
            base: "EUR".to_string(),
            date: "2026-07-25".to_string(),
            rates: mock_rates(),
            source: "frankfurter".to_string(),
        };
        let fetched_at = current_unix_timestamp();
        write_cache_file(&path, &table, fetched_at).unwrap();

        let cached = match read_cache_file(&path) {
            CacheRead::Loaded(c) => c,
            other => panic!(
                "cache file should be Loaded, got non-Loaded variant ({:?})",
                matches!(other, CacheRead::Loaded(_))
            ),
        };
        assert_eq!(cached.base, "EUR");
        assert_eq!(cached.date, "2026-07-25");
        assert_eq!(cached.rates.len(), 4);
        assert_eq!(cached.source, "frankfurter");
        assert_eq!(cached.fetched_at, fetched_at);
    }

    #[test]
    fn test_read_cache_file_nonexistent() {
        let path = Path::new("/nonexistent/path/fx_rates.json");
        assert!(matches!(read_cache_file(path), CacheRead::Missing));
    }

    #[test]
    fn test_read_cache_file_invalid_json() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(tmp.path(), "not valid json").unwrap();
        assert!(matches!(read_cache_file(tmp.path()), CacheRead::Corrupted));
    }

    #[test]
    fn test_read_cache_file_v1_without_source_is_corrupted() {
        // v1 文件缺 source 字段 → 反序列化失败 → Corrupted(自愈重拉)
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let v1 = serde_json::json!({
            "base": "EUR",
            "date": "2026-07-25",
            "rates": {"USD": 1.08},
            "fetched_at": 0u64,
        });
        std::fs::write(tmp.path(), v1.to_string()).unwrap();
        assert!(matches!(read_cache_file(tmp.path()), CacheRead::Corrupted));
    }

    #[test]
    fn test_v1_cache_self_heals_with_source() {
        // v1 文件 → Corrupted → 重拉成功返回带 source 的表,并写回 v2
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let v1 = serde_json::json!({
            "base": "EUR",
            "date": "2026-07-25",
            "rates": {"USD": 1.08},
            "fetched_at": 0u64,
        });
        std::fs::write(tmp.path(), v1.to_string()).unwrap();

        let calls = Arc::new(AtomicUsize::new(0));
        let calls_inner = Arc::clone(&calls);
        let provider = CachedRateProvider::with_cache_path_and_inner(
            tmp.path().to_path_buf(),
            boxed_fn(move || {
                calls_inner.fetch_add(1, Ordering::SeqCst);
                Ok(RateTable {
                    base: "EUR".to_string(),
                    date: "2026-10-28".to_string(),
                    rates: mock_rates(),
                    source: "erapi".to_string(),
                })
            }),
            DEFAULT_BREAKER_THRESHOLD,
            DEFAULT_BREAKER_COOLDOWN,
        );

        let table = provider.rates().expect("v1 cache should self-heal");
        assert_eq!(table.source, "erapi");
        assert_eq!(calls.load(Ordering::SeqCst), 1, "应重拉一次");
        match read_cache_file(tmp.path()) {
            CacheRead::Loaded(c) => assert_eq!(c.source, "erapi", "重拉后应写回 v2"),
            other => panic!("expected v2 cache, got {other:?}"),
        }
    }

    #[test]
    fn test_write_cache_file_creates_parent_dirs() {
        let tmp_dir = tempfile::tempdir().unwrap();
        let nested_path = tmp_dir.path().join("a").join("b").join("fx_rates.json");

        let table = RateTable {
            base: "EUR".to_string(),
            date: "2026-07-25".to_string(),
            rates: mock_rates(),
            source: "frankfurter".to_string(),
        };
        write_cache_file(&nested_path, &table, 0).unwrap();

        assert!(nested_path.exists());
        let cached = match read_cache_file(&nested_path) {
            CacheRead::Loaded(c) => c,
            other => panic!("should be readable, got {:?}", other),
        };
        assert_eq!(cached.base, "EUR");
    }

    #[test]
    fn test_cached_rate_table_to_rate_table() {
        let cached = CachedRateTable {
            base: "EUR".to_string(),
            date: "2026-07-25".to_string(),
            rates: mock_rates(),
            source: "frankfurter".to_string(),
            fetched_at: 12345,
        };
        let table: RateTable = cached.into();
        assert_eq!(table.base, "EUR");
        assert_eq!(table.date, "2026-07-25");
        assert_eq!(table.rates.len(), 4);
        assert_eq!(table.source, "frankfurter");
    }

    // ===== Stale 策略 =====

    #[test]
    fn test_stale_policy_no_cache_no_allow_stale() {
        // 无缓存 + 不允许 stale → 错误
        let result = apply_stale_policy(None, false, false);
        let err = result.expect_err("expected error");
        assert_eq!(err.kind, crate::core::ErrorKind::DependencyUnavailable);
        assert_eq!(err.i18n_key, Some("msg.fx.network_unreachable"));
    }

    #[test]
    fn test_stale_policy_no_cache_with_allow_stale() {
        // 无缓存 + 允许 stale → 仍然错误(没有数据可用)
        let result = apply_stale_policy(None, true, false);
        let err = result.expect_err("expected error");
        assert_eq!(err.kind, crate::core::ErrorKind::DependencyUnavailable);
    }

    #[test]
    fn test_stale_policy_expired_cache_no_allow_stale() {
        // 过期缓存 + 不允许 stale → 错误(含快照日期 + ALLOW_STALE 提示)
        let cached = CachedRateTable {
            base: "EUR".to_string(),
            date: "2026-07-20".to_string(),
            rates: mock_rates(),
            fetched_at: 0,
            source: "frankfurter".to_string(),
        };
        let result = apply_stale_policy(Some(&cached), false, false);
        let err = result.expect_err("expected error");
        assert_eq!(err.kind, crate::core::ErrorKind::DependencyUnavailable);
        assert!(err.message.contains("2026-07-20"), "msg: {}", err.message);
        assert!(
            err.message.contains("CALNEXUS_FX_ALLOW_STALE"),
            "msg: {}",
            err.message
        );
        assert_eq!(err.i18n_key, Some("msg.fx.network_unreachable"));
    }

    #[test]
    fn test_stale_policy_expired_cache_with_allow_stale() {
        // 过期缓存 + 允许 stale → 返回缓存数据
        let cached = CachedRateTable {
            base: "EUR".to_string(),
            date: "2026-07-20".to_string(),
            rates: mock_rates(),
            fetched_at: 0,
            source: "frankfurter".to_string(),
        };
        let result = apply_stale_policy(Some(&cached), true, false);
        let table = result.expect("expected Ok with stale data");
        assert_eq!(table.base, "EUR");
        assert_eq!(table.date, "2026-07-20");
        assert_eq!(table.rates.len(), 4);
    }

    // ===== 拉取单飞并发一致性 =====

    #[test]
    fn test_fetch_lock_concurrent_consistency() {
        // 过期缓存 + 恒失败 fetcher 下 8 线程并发 rates():全部得到 DependencyUnavailable,无 panic。
        // 整程持 FX_ENV_LOCK:rates() 失败路径经 read_allow_stale() 读进程级 env,
        // 防并行写者开启 stale 策略导致误 Ok(CI 并行腿实录)。
        let _env = FX_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let table = RateTable {
            base: "EUR".to_string(),
            date: "2026-07-20".to_string(),
            rates: mock_rates(),
            source: "frankfurter".to_string(),
        };
        // 写入后将 fetched_at 置 0(必然过期)
        write_cache_file(tmp.path(), &table, 0).unwrap();

        let provider = std::sync::Arc::new(CachedRateProvider::with_cache_path_and_inner(
            tmp.path().to_path_buf(),
            boxed_fn(|| Err(CalcError::dependency_unavailable("synthetic fx outage"))),
            DEFAULT_BREAKER_THRESHOLD,
            DEFAULT_BREAKER_COOLDOWN,
        ));
        let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
        let mut handles = vec![];
        for _ in 0..8 {
            let p = std::sync::Arc::clone(&provider);
            let b = std::sync::Arc::clone(&barrier);
            handles.push(std::thread::spawn(move || {
                b.wait();
                p.rates()
            }));
        }
        let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        // fetch 失败与熔断 Open 映射到同一 DependencyUnavailable kind
        for r in &results {
            match r {
                Err(e) => assert_eq!(
                    e.kind,
                    crate::core::ErrorKind::DependencyUnavailable,
                    "got {e:?}"
                ),
                Ok(t) => panic!("注入 fetcher 恒失败,不应出现成功结果:{t:?}"),
            }
        }
    }

    #[test]
    fn test_fetch_lock_concurrent_success_consistency() {
        // 成功侧镜像:部分线程真实抓取并写回 L1/L2,并发下所有线程必须看到同一张表(同 base/date/rates)。
        // 整程持 FX_ENV_LOCK:rates() 的 TTL/allow_stale 读进程级 env,防并行写者污染。
        let _env = FX_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let table = RateTable {
            base: "EUR".to_string(),
            date: "2026-07-20".to_string(),
            rates: mock_rates(),
            source: "frankfurter".to_string(),
        };
        write_cache_file(tmp.path(), &table, 0).unwrap(); // 置为必然过期

        let provider = std::sync::Arc::new(CachedRateProvider::with_cache_path_and_inner(
            tmp.path().to_path_buf(),
            boxed_fn(move || Ok(table.clone())),
            DEFAULT_BREAKER_THRESHOLD,
            DEFAULT_BREAKER_COOLDOWN,
        ));
        let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
        let mut handles = vec![];
        for _ in 0..8 {
            let p = std::sync::Arc::clone(&provider);
            let b = std::sync::Arc::clone(&barrier);
            handles.push(std::thread::spawn(move || {
                b.wait();
                p.rates()
            }));
        }
        let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        let first = results[0]
            .as_ref()
            .expect("injected fetcher always succeeds");
        for r in &results[1..] {
            let t = r.as_ref().expect("all threads should succeed");
            assert_eq!(t.base, first.base);
            assert_eq!(t.date, first.date);
            assert_eq!(t.rates, first.rates);
        }
    }

    // ===== 网络熔断器集成(注入 fetcher,不出网) =====

    #[test]
    fn test_breaker_opens_after_consecutive_fetch_failures() {
        // 阈值 2:前两次失败真实执行注入闭包(计数增长),第三次被熔断拒绝(计数停增)
        // 整程持 FX_ENV_LOCK:rates() 失败路径读进程级 env(allow_stale),防并行写者污染。
        let _env = FX_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let calls = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let counter = calls.clone();
        let provider = CachedRateProvider::with_inner(
            boxed_fn(move || {
                counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                Err(CalcError::dependency_unavailable("synthetic fx outage"))
            }),
            2,
            Duration::from_secs(30),
        );
        for _ in 0..2 {
            let err = provider.rates().expect_err("fetcher always fails");
            assert_eq!(err.kind, crate::core::ErrorKind::DependencyUnavailable);
        }
        // 第 3 次:熔断已打开,闭包不再执行;stale 策略仍给出显性错误
        let err = provider.rates().expect_err("circuit should be open");
        assert_eq!(err.kind, crate::core::ErrorKind::DependencyUnavailable);
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 2);
    }

    #[test]
    fn test_breaker_recovers_via_half_open_probe_success() {
        // 阈值 2 + 冷却 0:两次失败后打开,下一调用立即探针;探针成功回闭合
        // 整程持 FX_ENV_LOCK:rates() 失败路径读进程级 env(allow_stale),防并行写者污染。
        let _env = FX_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let calls = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let counter = calls.clone();
        let provider = CachedRateProvider::with_inner(
            boxed_fn(move || {
                let n = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                if n < 2 {
                    Err(CalcError::dependency_unavailable("synthetic fx outage"))
                } else {
                    Ok(RateTable {
                        base: "EUR".to_string(),
                        date: "2026-09-15".to_string(),
                        rates: HashMap::new(),
                        source: "frankfurter".to_string(),
                    })
                }
            }),
            2,
            Duration::ZERO,
        );
        assert!(provider.rates().is_err());
        assert!(provider.rates().is_err()); // 达阈值,熔断打开
        // Open + 冷却 0 → 半开探针成功 → 回闭合
        let table = provider.rates().expect("half-open probe should succeed");
        assert_eq!(table.base, "EUR");
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 3);
        // 探针成功后 L1 已填充:下一次调用经 L1 命中放行,不再触发网络(计数不增)
        assert!(provider.rates().is_ok());
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 3);
    }

    /// Open 态迟到成功不回闭合(limiteron 0.3.0-rc.6 修复锚点:在途调用先放行,熔断随后被其他失败打开)。
    #[test]
    fn test_breaker_open_state_survives_late_success() {
        let breaker = SyncCircuitBreaker::new(1, Duration::from_secs(60));
        assert!(breaker.admit(), "闭合态应放行在途调用");
        breaker.record_failure();
        breaker.record_success();
        assert!(
            breaker.call(|| Ok::<(), CalcError>(())).is_err(),
            "Open 态迟到成功不应关闭熔断"
        );
    }

    // ===== FrankfurterProvider 基本行为(不出网) =====

    #[test]
    fn test_default_cache_path_returns_some_on_normal_platform() {
        // 正常环境下 dirs::cache_dir() 应返回 Some(CI 可能为 None),仅做非 panic 验证。
        let _ = default_cache_path();
    }

    #[test]
    fn test_cached_provider_with_cache_path_uses_provided_path() {
        // 验证 with_cache_path 构造函数不 panic 且路径被使用
        // 整程持 FX_ENV_LOCK:L2 TTL 判定读进程级 env(TTL_HOURS),防并行写者污染。
        let _env = FX_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let provider = CachedRateProvider::with_cache_path(
            Box::new(mock_provider()),
            tmp.path().to_path_buf(),
        );

        // 预写一份未过期的缓存文件
        let table = RateTable {
            base: "EUR".to_string(),
            date: "2026-07-25".to_string(),
            rates: mock_rates(),
            source: "frankfurter".to_string(),
        };
        let now = current_unix_timestamp();
        write_cache_file(tmp.path(), &table, now).unwrap();

        // 从文件缓存读取(L2 命中,不出网)
        let result = provider.rates().unwrap();
        assert_eq!(result.base, "EUR");
        assert_eq!(result.date, "2026-07-25");
        assert_eq!(result.rates.len(), 4);
    }

    #[test]
    fn test_cached_provider_in_memory_cache_hit() {
        // L1 命中:第二次调用直接从内存缓存返回(不出网)
        // 整程持 FX_ENV_LOCK:L2 TTL 判定读进程级 env(TTL_HOURS),防并行写者污染。
        let _env = FX_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let provider = CachedRateProvider::with_cache_path(
            Box::new(mock_provider()),
            tmp.path().to_path_buf(),
        );

        // 预写缓存文件
        let table = RateTable {
            base: "EUR".to_string(),
            date: "2026-07-25".to_string(),
            rates: mock_rates(),
            source: "frankfurter".to_string(),
        };
        let now = current_unix_timestamp();
        write_cache_file(tmp.path(), &table, now).unwrap();

        // 第一次调用:L2 文件缓存命中
        let r1 = provider.rates().unwrap();
        assert_eq!(r1.date, "2026-07-25");

        // 删除缓存文件,验证第二次调用仍成功(L1 内存命中)
        std::fs::remove_file(tmp.path()).unwrap();
        let r2 = provider.rates().unwrap();
        assert_eq!(r2.date, "2026-07-25");
    }

    #[test]
    fn test_cached_provider_default_wraps_frankfurter() {
        // 装饰器默认装配:inner 为 frankfurter(不出网构造)
        // 整程持 FX_ENV_LOCK:provider 选择读进程级 env(PROVIDER),防并行写者改变装配面。
        let _env = FX_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let provider = CachedRateProvider::new(Box::new(FrankfurterProvider));
        assert_eq!(provider.name(), "frankfurter");
        assert_eq!(provider.source_names(), vec!["frankfurter"]);
    }

    #[test]
    fn test_parse_allow_stale_contract() {
        // 仅 "1" 为 true;None/"0"/其它任意值均为 false(三态契约)
        assert!(!parse_allow_stale(None));
        assert!(!parse_allow_stale(Some("0")));
        assert!(!parse_allow_stale(Some("true")));
        assert!(!parse_allow_stale(Some("")));
        assert!(parse_allow_stale(Some("1")));
    }

    /// confers env 接线契约:未设取默认、设值生效、remove 回默认;env_prefix 接线的唯一直接保护,纯解析测试无法暴露该故障。
    #[test]
    fn test_fx_config_env_mapping_contract() {
        // 唯一 env 写者:与全部读者共用模块级 FX_ENV_LOCK(原测试内局部锁对并行读者无保护)。
        let _guard = FX_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());

        const KEYS: [&str; 5] = [
            "CALNEXUS_FX_TTL_HOURS",
            "CALNEXUS_FX_BREAKER_THRESHOLD",
            "CALNEXUS_FX_BREAKER_COOLDOWN_SECS",
            "CALNEXUS_FX_ALLOW_STALE",
            "CALNEXUS_FX_PROVIDER",
        ];

        // 未设任何 env:五字段访问器等于默认
        unsafe {
            for key in KEYS {
                std::env::remove_var(key);
            }
        }
        let cfg = FxProviderConfig::from_env();
        assert_eq!(cfg.ttl_seconds(), 24 * 3600);
        assert_eq!(cfg.breaker_threshold(), DEFAULT_BREAKER_THRESHOLD);
        assert_eq!(cfg.breaker_cooldown(), DEFAULT_BREAKER_COOLDOWN);
        assert!(!cfg.allow_stale());
        assert_eq!(cfg.provider_name(), "frankfurter");

        // 逐一设值:env_prefix 映射生效(整数与小数均覆盖)
        unsafe { std::env::set_var("CALNEXUS_FX_TTL_HOURS", "48") };
        assert_eq!(FxProviderConfig::from_env().ttl_seconds(), 48 * 3600);
        unsafe { std::env::set_var("CALNEXUS_FX_TTL_HOURS", "0.5") };
        assert_eq!(FxProviderConfig::from_env().ttl_seconds(), 1800);
        unsafe { std::env::remove_var("CALNEXUS_FX_TTL_HOURS") };

        unsafe { std::env::set_var("CALNEXUS_FX_BREAKER_THRESHOLD", "3") };
        assert_eq!(FxProviderConfig::from_env().breaker_threshold(), 3);
        unsafe { std::env::remove_var("CALNEXUS_FX_BREAKER_THRESHOLD") };

        unsafe { std::env::set_var("CALNEXUS_FX_BREAKER_COOLDOWN_SECS", "0") };
        assert_eq!(
            FxProviderConfig::from_env().breaker_cooldown(),
            Duration::ZERO
        );
        unsafe { std::env::remove_var("CALNEXUS_FX_BREAKER_COOLDOWN_SECS") };

        unsafe { std::env::set_var("CALNEXUS_FX_ALLOW_STALE", "1") };
        assert!(FxProviderConfig::from_env().allow_stale());
        unsafe { std::env::remove_var("CALNEXUS_FX_ALLOW_STALE") };

        // CALNEXUS_FX_PROVIDER:三值 + 非法回退 + remove 回默认
        unsafe { std::env::set_var("CALNEXUS_FX_PROVIDER", "auto") };
        assert_eq!(FxProviderConfig::from_env().provider_name(), "auto");
        unsafe { std::env::set_var("CALNEXUS_FX_PROVIDER", "erapi") };
        assert_eq!(FxProviderConfig::from_env().provider_name(), "erapi");
        unsafe { std::env::set_var("CALNEXUS_FX_PROVIDER", "foo") };
        assert_eq!(FxProviderConfig::from_env().provider_name(), "frankfurter");
        unsafe { std::env::set_var("CALNEXUS_FX_PROVIDER", "") };
        assert_eq!(FxProviderConfig::from_env().provider_name(), "frankfurter");
        unsafe { std::env::remove_var("CALNEXUS_FX_PROVIDER") };
        assert_eq!(FxProviderConfig::from_env().provider_name(), "frankfurter");

        // remove 后回默认(不留环境痕迹)
        let cfg = FxProviderConfig::from_env();
        assert_eq!(cfg.ttl_seconds(), 24 * 3600);
        assert!(!cfg.allow_stale());
        assert_eq!(cfg.provider_name(), "frankfurter");
    }

    #[test]
    fn test_fx_config_accessors_contract() {
        // FxProviderConfig 访问器=纯解析函数的薄胶水:非法/缺省回退默认
        let cfg = FxProviderConfig::default();
        assert_eq!(cfg.ttl_seconds(), 24 * 3600);
        assert_eq!(cfg.breaker_threshold(), DEFAULT_BREAKER_THRESHOLD);
        assert_eq!(cfg.breaker_cooldown(), DEFAULT_BREAKER_COOLDOWN);
        assert!(!cfg.allow_stale());
        assert_eq!(cfg.provider_name(), "frankfurter");
        let cfg = FxProviderConfig {
            ttl_hours: Some("0.5".to_string()),
            breaker_threshold: Some("0".to_string()),
            breaker_cooldown_secs: Some("0".to_string()),
            allow_stale: Some("1".to_string()),
            provider: Some("erapi".to_string()),
        };
        assert_eq!(cfg.ttl_seconds(), 1800);
        assert_eq!(cfg.breaker_threshold(), DEFAULT_BREAKER_THRESHOLD); // <1 回退
        assert_eq!(cfg.breaker_cooldown(), Duration::ZERO); // 0=关闭快失败
        assert!(cfg.allow_stale());
        assert_eq!(cfg.provider_name(), "erapi");
    }

    /// CALNEXUS_FX_PROVIDER 三值契约:未设/空/非法 → frankfurter;erapi/auto 原样通过。
    #[test]
    fn test_provider_name_contract() {
        let cases: [(Option<&str>, &str); 6] = [
            (None, "frankfurter"),
            (Some(""), "frankfurter"),
            (Some("frankfurter"), "frankfurter"),
            (Some("erapi"), "erapi"),
            (Some("auto"), "auto"),
            (Some("foo"), "frankfurter"),
        ];
        for (raw, expected) in cases {
            let cfg = FxProviderConfig {
                provider: raw.map(str::to_string),
                ..Default::default()
            };
            assert_eq!(cfg.provider_name(), expected, "raw={raw:?}");
        }
    }

    // ===== L1 单飞(oxcache ByteWeightCache::get_or_compute) =====

    fn sample_rate_table() -> RateTable {
        RateTable {
            base: "EUR".to_string(),
            date: "2026-10-09".to_string(),
            rates: mock_rates(),
            source: "frankfurter".to_string(),
        }
    }

    #[test]
    fn rates_concurrent_calls_fetch_exactly_once() {
        // 8 线程并发 rates():fetcher 恰执行一次,全部调用方拿到一致结果(单飞)。
        let calls = Arc::new(AtomicUsize::new(0));
        let calls_in_fetcher = Arc::clone(&calls);
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let provider = std::sync::Arc::new(CachedRateProvider::with_cache_path_and_inner(
            tmp.path().to_path_buf(),
            boxed_fn(move || {
                calls_in_fetcher.fetch_add(1, Ordering::SeqCst);
                std::thread::sleep(Duration::from_millis(50)); // 拉长在途窗口
                Ok(sample_rate_table())
            }),
            DEFAULT_BREAKER_THRESHOLD,
            DEFAULT_BREAKER_COOLDOWN,
        ));
        let mut handles = Vec::new();
        for _ in 0..8 {
            let p = Arc::clone(&provider);
            handles.push(std::thread::spawn(move || p.rates()));
        }
        let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        assert_eq!(
            calls.load(Ordering::SeqCst),
            1,
            "fetcher 应恰执行一次(单飞)"
        );
        for r in &results {
            let table = r.as_ref().expect("rates 应成功");
            assert_eq!(table.base, "EUR");
            assert_eq!(table.rates.len(), 4);
        }
    }

    #[test]
    fn rates_fetch_failure_not_cached_and_retried() {
        // compute 失败不写缓存:首次 Err,第二次(网络恢复)Ok。
        let attempts = Arc::new(AtomicUsize::new(0));
        let attempts_in_fetcher = Arc::clone(&attempts);
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let provider = CachedRateProvider::with_cache_path_and_inner(
            tmp.path().to_path_buf(),
            boxed_fn(move || {
                let n = attempts_in_fetcher.fetch_add(1, Ordering::SeqCst);
                if n == 0 {
                    Err(CalcError::dependency_unavailable("boom"))
                } else {
                    Ok(sample_rate_table())
                }
            }),
            DEFAULT_BREAKER_THRESHOLD,
            DEFAULT_BREAKER_COOLDOWN,
        );
        assert!(provider.rates().is_err(), "首次失败应显性返回 Err");
        let second = provider.rates().expect("第二次(恢复后)应成功");
        assert_eq!(second.base, "EUR");
        assert_eq!(
            attempts.load(Ordering::SeqCst),
            2,
            "失败未落缓存,重试应再抓取"
        );
    }

    #[test]
    fn rates_second_call_hits_l1_without_fetch() {
        // L1 命中:第二次 rates() 不再触发 fetcher(字节缓存生效)。
        let calls = Arc::new(AtomicUsize::new(0));
        let calls_in_fetcher = Arc::clone(&calls);
        let provider = CachedRateProvider::with_inner(
            boxed_fn(move || {
                calls_in_fetcher.fetch_add(1, Ordering::SeqCst);
                Ok(sample_rate_table())
            }),
            DEFAULT_BREAKER_THRESHOLD,
            DEFAULT_BREAKER_COOLDOWN,
        );
        let first = provider.rates().expect("first");
        let second = provider.rates().expect("second");
        assert_eq!(calls.load(Ordering::SeqCst), 1, "第二次应命中 L1 不再抓取");
        assert_eq!(first.rates.len(), second.rates.len());
    }

    // ===== ExchangeRateApiProvider 响应归一(注入 mock 响应体,不出网) =====

    #[test]
    fn test_erapi_parse_success_normalizes_fields() {
        let body = r#"{
            "result": "success",
            "base_code": "EUR",
            "time_last_update_unix": 1761234567,
            "rates": {"USD": 1.08, "CNY": 7.85}
        }"#;
        let table = parse_erapi_response(body).expect("valid er-api response");
        assert_eq!(table.base, "EUR");
        assert_eq!(table.date, "2025-10-23");
        assert_eq!(table.rates["USD"], 1.08);
        assert_eq!(table.rates.len(), 2);
        assert_eq!(table.source, "erapi");
    }

    #[test]
    fn test_erapi_parse_non_success_is_invalid_response() {
        let body = r#"{
            "result": "error",
            "base_code": "EUR",
            "time_last_update_unix": 1761234567,
            "rates": {}
        }"#;
        let err = parse_erapi_response(body).expect_err("result != success must fail");
        assert_eq!(err.kind, crate::core::ErrorKind::DependencyUnavailable);
        assert_eq!(err.i18n_key, Some("msg.fx.invalid_response"));
        // 上游受控字段经清洗入消息:换行/控制符被剥离
        assert!(
            !err.message.contains(['\n', '\r', '\x1b']),
            "error message must not carry control chars: {:?}",
            err.message
        );
    }

    #[test]
    fn test_sanitize_upstream_field_strips_controls_and_truncates() {
        // 控制字符与 ANSI 转义被剥离,可打印内容保留(未触上限不加载断标记)
        assert_eq!(sanitize_upstream_field("err\nor\x1b[31m"), "error[31m");
        // 超长截断到 32 字符并加 `...` 标记
        let long = "x".repeat(50);
        let sanitized = sanitize_upstream_field(&long);
        assert_eq!(sanitized.chars().count(), 35); // 32 + "..."
        assert!(sanitized.ends_with("..."));
        // 恰好 32 字符不截断
        assert_eq!(sanitize_upstream_field(&"x".repeat(32)), "x".repeat(32));
    }

    #[test]
    fn test_erapi_parse_missing_base_code_is_invalid_response() {
        let body = r#"{
            "result": "success",
            "time_last_update_unix": 1761234567,
            "rates": {"USD": 1.08}
        }"#;
        let err = parse_erapi_response(body).expect_err("missing base_code must fail");
        assert_eq!(err.kind, crate::core::ErrorKind::DependencyUnavailable);
        assert_eq!(err.i18n_key, Some("msg.fx.invalid_response"));
    }

    #[test]
    fn test_erapi_parse_missing_rates_is_invalid_response() {
        let body = r#"{
            "result": "success",
            "base_code": "EUR",
            "time_last_update_unix": 1761234567
        }"#;
        let err = parse_erapi_response(body).expect_err("missing rates must fail");
        assert_eq!(err.kind, crate::core::ErrorKind::DependencyUnavailable);
        assert_eq!(err.i18n_key, Some("msg.fx.invalid_response"));
    }

    #[test]
    fn test_erapi_parse_160_currencies() {
        let rates: serde_json::Map<String, serde_json::Value> = (0..160)
            .map(|i| (format!("C{:03}", i), serde_json::Value::from(1.0)))
            .collect();
        let body = serde_json::json!({
            "result": "success",
            "base_code": "EUR",
            "time_last_update_unix": 1761234567u64,
            "rates": rates,
        })
        .to_string();
        let table = parse_erapi_response(&body).expect("160-currency table should parse");
        assert_eq!(table.rates.len(), 160);
        assert_eq!(table.source, "erapi");
    }

    #[test]
    fn test_erapi_provider_identity() {
        let provider = ExchangeRateApiProvider;
        assert_eq!(provider.name(), "erapi");
        assert_eq!(provider.source_names(), vec!["erapi"]);
    }

    // ===== ChainRateProvider(failover 链,不出网) =====

    /// 带名字与调用计数的 mock provider。
    struct NamedMockProvider<F> {
        name: &'static str,
        calls: Arc<AtomicUsize>,
        f: F,
    }

    impl<F> RateProvider for NamedMockProvider<F>
    where
        F: Fn() -> Result<RateTable, CalcError> + Send + Sync,
    {
        fn rates(&self) -> Result<RateTable, CalcError> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            (self.f)()
        }

        fn name(&self) -> &'static str {
            self.name
        }
    }

    fn named(
        name: &'static str,
        calls: Arc<AtomicUsize>,
        f: impl Fn() -> Result<RateTable, CalcError> + Send + Sync + 'static,
    ) -> Box<dyn RateProvider> {
        Box::new(NamedMockProvider { name, calls, f })
    }

    fn table_with_source(source: &str) -> RateTable {
        RateTable {
            base: "EUR".to_string(),
            date: "2026-10-28".to_string(),
            rates: mock_rates(),
            source: source.to_string(),
        }
    }

    #[test]
    fn test_chain_first_success_short_circuits() {
        let first_calls = Arc::new(AtomicUsize::new(0));
        let second_calls = Arc::new(AtomicUsize::new(0));
        let chain = ChainRateProvider::new(vec![
            named("frankfurter", Arc::clone(&first_calls), || {
                Ok(table_with_source("frankfurter"))
            }),
            named("erapi", Arc::clone(&second_calls), || {
                Ok(table_with_source("erapi"))
            }),
        ]);

        let table = chain.rates().expect("first provider should succeed");
        assert_eq!(table.source, "frankfurter");
        assert_eq!(first_calls.load(Ordering::SeqCst), 1);
        assert_eq!(
            second_calls.load(Ordering::SeqCst),
            0,
            "首源成功后次源不得被调用"
        );
        assert_eq!(chain.source_names(), vec!["frankfurter", "erapi"]);
    }

    #[test]
    fn test_chain_falls_back_to_second() {
        let first_calls = Arc::new(AtomicUsize::new(0));
        let second_calls = Arc::new(AtomicUsize::new(0));
        let chain = ChainRateProvider::new(vec![
            named("frankfurter", Arc::clone(&first_calls), || {
                Err(CalcError::dependency_unavailable("net down"))
            }),
            named("erapi", Arc::clone(&second_calls), || {
                Ok(table_with_source("erapi"))
            }),
        ]);

        let table = chain.rates().expect("second provider should succeed");
        assert_eq!(table.source, "erapi");
        assert_eq!(first_calls.load(Ordering::SeqCst), 1);
        assert_eq!(second_calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_chain_all_fail_aggregates_error() {
        let chain = ChainRateProvider::new(vec![
            named("frankfurter", Arc::new(AtomicUsize::new(0)), || {
                Err(CalcError::dependency_unavailable("net down"))
            }),
            named("erapi", Arc::new(AtomicUsize::new(0)), || {
                Err(CalcError::dependency_unavailable("parse boom"))
            }),
        ]);

        let err = chain.rates().expect_err("both providers fail");
        assert!(err.message.contains("frankfurter"), "msg: {}", err.message);
        assert!(err.message.contains("erapi"), "msg: {}", err.message);
        assert!(err.message.contains("net down"), "msg: {}", err.message);
        assert!(err.message.contains("parse boom"), "msg: {}", err.message);
        assert_eq!(err.i18n_key, Some("msg.fx.all_providers_failed"));
        assert_eq!(err.kind, crate::core::ErrorKind::DependencyUnavailable);
    }

    // ===== build_provider 工厂装配(不出网) =====

    #[test]
    fn test_build_provider_default_is_frankfurter() {
        let provider = build_provider(&FxProviderConfig::default());
        assert_eq!(provider.inner_names(), vec!["frankfurter"]);
    }

    #[test]
    fn test_build_provider_erapi_is_single_source() {
        let cfg = FxProviderConfig {
            provider: Some("erapi".to_string()),
            ..Default::default()
        };
        assert_eq!(build_provider(&cfg).inner_names(), vec!["erapi"]);
    }

    #[test]
    fn test_build_provider_auto_chain_order() {
        let cfg = FxProviderConfig {
            provider: Some("auto".to_string()),
            ..Default::default()
        };
        assert_eq!(
            build_provider(&cfg).inner_names(),
            vec!["frankfurter", "erapi"],
            "auto 链序固定为 frankfurter → erapi"
        );
    }

    // ===== 覆盖率补测:配置 serde 非字符串源、元数据与解析边界 =====

    #[test]
    fn test_fx_config_deserialize_from_typed_values() {
        // 配置文件源(数值/布尔字面量)走 de_env_string 的 visit_u64/visit_f64/visit_bool 分支
        let cfg: FxProviderConfig = serde_json::from_str(
            r#"{"ttl_hours": 48, "breaker_threshold": 2, "breaker_cooldown_secs": 2, "allow_stale": true}"#,
        )
        .unwrap();
        assert_eq!(cfg.ttl_seconds(), 48 * 3600);
        assert_eq!(cfg.breaker_threshold(), 2);
        assert_eq!(cfg.breaker_cooldown(), Duration::from_secs(2));
        // 三态契约:bool true 归一为 "true",非 "1",仍为 false
        assert!(!cfg.allow_stale());
    }

    #[test]
    fn test_fx_config_deserialize_float_ttl() {
        // 小数 ttl 走 visit_f64(cooldown 解析器为 u64,浮点非法回退默认的语义另有钉)
        let cfg: FxProviderConfig = serde_json::from_str(r#"{"ttl_hours": 0.5}"#).unwrap();
        assert_eq!(cfg.ttl_seconds(), 1800);
    }

    #[test]
    fn test_fx_config_deserialize_null_and_missing() {
        // null → visit_unit → None → 默认;字段缺省同理
        let cfg: FxProviderConfig = serde_json::from_str(r#"{"ttl_hours": null}"#).unwrap();
        assert_eq!(cfg.ttl_seconds(), 24 * 3600);
        let cfg2: FxProviderConfig = serde_json::from_str("{}").unwrap();
        assert_eq!(cfg2.ttl_seconds(), 24 * 3600);
        assert!(!cfg2.allow_stale());
    }

    #[test]
    fn test_cached_rate_provider_debug_impl() {
        let cfg = FxProviderConfig::default();
        let text = format!("{:?}", build_provider(&cfg));
        assert!(text.contains("CachedRateProvider"), "debug: {text}");
    }

    #[test]
    fn test_chain_provider_metadata() {
        let chain = ChainRateProvider::new(vec![
            Box::new(FrankfurterProvider),
            Box::new(ExchangeRateApiProvider),
        ]);
        assert_eq!(chain.name(), "auto");
        assert_eq!(chain.source_names(), vec!["frankfurter", "erapi"]);
    }

    #[test]
    fn test_rate_provider_default_name() {
        // 未覆写 name() 的实现走 trait 默认(failover 聚合时的兜底标识)
        struct Anonymous;
        impl RateProvider for Anonymous {
            fn rates(&self) -> Result<RateTable, CalcError> {
                Ok(RateTable {
                    base: "EUR".to_string(),
                    date: "2026-01-01".to_string(),
                    rates: HashMap::new(),
                    source: "anonymous".to_string(),
                })
            }
        }
        assert_eq!(Anonymous.name(), "unknown");
    }

    #[test]
    fn test_erapi_parse_empty_rates_is_invalid_response() {
        let body = r#"{
            "result": "success",
            "base_code": "EUR",
            "time_last_update_unix": 1761234567,
            "rates": {}
        }"#;
        let err = parse_erapi_response(body).expect_err("空汇率表必须显性拒绝");
        assert_eq!(err.kind, crate::core::ErrorKind::DependencyUnavailable);
        assert_eq!(err.i18n_key, Some("msg.fx.invalid_response"));
    }
}