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;
const FRANKFURTER_URL: &str = "https://api.frankfurter.dev/v1/latest?base=EUR";
const EXCHANGE_RATE_API_URL: &str = "https://open.er-api.com/v6/latest/EUR";
const DEFAULT_TTL_SECONDS: u64 = 24 * 3600;
const HTTP_TIMEOUT: Duration = Duration::from_secs(5);
const DEFAULT_BREAKER_THRESHOLD: u32 = 3;
const DEFAULT_BREAKER_COOLDOWN: Duration = Duration::from_secs(30);
const MAX_RESPONSE_BODY_BYTES: u64 = 1024 * 1024;
const CACHE_DIR_NAME: &str = "calnexus";
const CACHE_FILE_NAME: &str = "fx_rates.json";
const FX_RATES_KEY: &str = "fx:rates";
const FX_RATES_BUDGET_BYTES: u64 = 1024 * 1024;
const FX_RATES_MAX_ENTRY_BYTES: u64 = 256 * 1024;
pub trait RateProvider: Send + Sync {
fn rates(&self) -> Result<RateTable, CalcError>;
fn name(&self) -> &'static str {
"unknown"
}
fn source_names(&self) -> Vec<&'static str> {
vec![self.name()]
}
}
#[derive(serde::Deserialize)]
struct FrankfurterResponse {
base: String,
date: String,
rates: HashMap<String, f64>,
}
#[derive(serde::Deserialize)]
struct ExchangeRateApiResponse {
result: String,
base_code: String,
time_last_update_unix: u64,
rates: HashMap<String, f64>,
}
#[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,
}
}
}
pub struct CachedRateProvider {
cache_path: Option<PathBuf>,
cache: ByteWeightCache<&'static str, RateTable, fn(&RateTable) -> u64>,
breaker: SyncCircuitBreaker,
inner: Box<dyn RateProvider>,
}
fn rate_table_weight(table: &RateTable) -> u64 {
table.rates.len() as u64 * 96 + 256
}
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)
}
pub fn new(inner: Box<dyn RateProvider>) -> Self {
Self::with_config(inner, &FxProviderConfig::from_env())
}
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,
}
}
#[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,
}
}
#[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,
}
}
#[cfg(test)]
fn inner_names(&self) -> Vec<&'static str> {
self.inner.source_names()
}
}
impl RateProvider for CachedRateProvider {
fn rates(&self) -> Result<RateTable, CalcError> {
self.cache.get_or_compute(FX_RATES_KEY, || {
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,
};
match self.breaker.call(|| self.inner.rates()) {
Ok(table) => {
if let Some(path) = &self.cache_path {
let now = current_unix_timestamp();
let _ = write_cache_file(path, &table, now);
}
Ok(table)
}
Err(breaker_err) => {
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()
}
}
#[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"
}
}
#[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"
}
}
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
}
}
fn parse_erapi_response(body: &str) -> Result<RateTable, CalcError> {
let parsed: ExchangeRateApiResponse = serde_json::from_str(body).map_err(|e| {
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(),
})
}
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()
}
}
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)
}
fn default_cache_path() -> Option<PathBuf> {
dirs::cache_dir().map(|d| d.join(CACHE_DIR_NAME).join(CACHE_FILE_NAME))
}
fn current_unix_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
#[derive(confers::Config, serde::Deserialize, Debug, Clone)]
#[config(env_prefix = "CALNEXUS_FX_")]
pub struct FxProviderConfig {
#[serde(default, deserialize_with = "de_env_string")]
pub ttl_hours: Option<String>,
#[serde(default, deserialize_with = "de_env_string")]
pub breaker_threshold: Option<String>,
#[serde(default, deserialize_with = "de_env_string")]
pub breaker_cooldown_secs: Option<String>,
#[serde(default, deserialize_with = "de_env_string")]
pub allow_stale: Option<String>,
#[serde(default, deserialize_with = "de_env_string")]
pub provider: Option<String>,
}
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 {
pub fn from_env() -> Self {
confers::config::<Self>()
.env_separator("__")
.env_prefix("CALNEXUS_FX_")
.build()
.unwrap_or_default()
}
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())
}
pub fn breaker_cooldown(&self) -> Duration {
parse_breaker_cooldown(self.breaker_cooldown_secs.as_deref())
}
pub fn allow_stale(&self) -> bool {
parse_allow_stale(self.allow_stale.as_deref())
}
pub fn provider_name(&self) -> &str {
match self.provider.as_deref() {
Some("erapi") => "erapi",
Some("auto") => "auto",
_ => "frankfurter",
}
}
}
fn ttl_seconds() -> u64 {
FxProviderConfig::from_env().ttl_seconds()
}
fn read_allow_stale() -> bool {
FxProviderConfig::from_env().allow_stale()
}
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)
}
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)
}
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)
}
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
}
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),
}
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,
},
}
}
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)?;
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
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)
}
}
}
fn fetch_body(url: &str) -> Result<String, CalcError> {
let response = ureq::get(url)
.config()
.timeout_global(Some(HTTP_TIMEOUT))
.https_only(true) .build()
.call()
.map_err(|e| {
CalcError::dependency_unavailable("FX network request failed")
.with_source(e.to_string())
.with_i18n("msg.fx.network_unreachable", vec![])
})?;
response
.into_body()
.with_config()
.limit(MAX_RESPONSE_BODY_BYTES)
.read_to_string()
.map_err(|e| {
CalcError::dependency_unavailable("FX response read failed")
.with_source(e.to_string())
.with_i18n("msg.fx.invalid_response", vec![])
})
}
fn fetch_from_network() -> Result<RateTable, CalcError> {
let body = fetch_body(FRANKFURTER_URL)?;
let parsed: FrankfurterResponse = serde_json::from_str(&body).map_err(|e| {
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::*;
static FX_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
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(),
})
}
}
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(),
}
}
#[test]
fn test_triangle_conversion_usd_to_cny() {
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() {
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() {
let provider = mock_provider();
let table = provider.rates().unwrap();
let result = table.rates.get("XYZ");
assert!(result.is_none());
assert_eq!(table.rates.len(), 4);
}
#[test]
fn test_parse_ttl_hours_default() {
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() {
assert_eq!(parse_ttl_hours(Some("48")), 48 * 3600);
assert_eq!(parse_ttl_hours(Some("0.5")), 1800);
}
#[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);
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));
assert_eq!(parse_breaker_cooldown(Some("0")), Duration::ZERO);
}
#[test]
fn test_is_expired_25h_old_default_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() {
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() {
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() {
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() {
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() {
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() {
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");
}
#[test]
fn test_stale_policy_no_cache_no_allow_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() {
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() {
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() {
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() {
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(|| 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();
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() {
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);
}
}
#[test]
fn test_breaker_opens_after_consecutive_fetch_failures() {
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);
}
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() {
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()); 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);
assert!(provider.rates().is_ok());
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 3);
}
#[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 态迟到成功不应关闭熔断"
);
}
#[test]
fn test_default_cache_path_returns_some_on_normal_platform() {
let _ = default_cache_path();
}
#[test]
fn test_cached_provider_with_cache_path_uses_provided_path() {
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();
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() {
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();
let r1 = provider.rates().unwrap();
assert_eq!(r1.date, "2026-07-25");
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() {
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() {
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")));
}
#[test]
fn test_fx_config_env_mapping_contract() {
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",
];
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");
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") };
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");
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() {
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); assert_eq!(cfg.breaker_cooldown(), Duration::ZERO); assert!(cfg.allow_stale());
assert_eq!(cfg.provider_name(), "erapi");
}
#[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:?}");
}
}
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() {
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() {
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() {
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());
}
#[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() {
assert_eq!(sanitize_upstream_field("err\nor\x1b[31m"), "error[31m");
let long = "x".repeat(50);
let sanitized = sanitize_upstream_field(&long);
assert_eq!(sanitized.chars().count(), 35); assert!(sanitized.ends_with("..."));
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"]);
}
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);
}
#[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"
);
}
#[test]
fn test_fx_config_deserialize_from_typed_values() {
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));
assert!(!cfg.allow_stale());
}
#[test]
fn test_fx_config_deserialize_float_ttl() {
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() {
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() {
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"));
}
}