use std::collections::HashMap;
use std::env;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::core::CalcError;
const FRANKFURTER_URL: &str = "https://api.frankfurter.dev/v1/latest?base=EUR";
const DEFAULT_TTL_SECONDS: u64 = 24 * 3600;
const HTTP_TIMEOUT: Duration = Duration::from_secs(5);
const CACHE_DIR_NAME: &str = "calnexus";
const CACHE_FILE_NAME: &str = "fx_rates.json";
#[derive(Clone, Debug)]
pub struct RateTable {
pub base: String,
pub date: String,
pub rates: HashMap<String, f64>,
}
pub(crate) trait RateProvider: Send + Sync {
fn rates(&self) -> Result<RateTable, CalcError>;
}
#[derive(serde::Deserialize)]
struct FrankfurterResponse {
base: String,
date: String,
rates: HashMap<String, f64>,
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
struct CachedRateTable {
base: String,
date: String,
rates: HashMap<String, f64>,
fetched_at: u64,
}
impl From<CachedRateTable> for RateTable {
fn from(c: CachedRateTable) -> Self {
RateTable {
base: c.base,
date: c.date,
rates: c.rates,
}
}
}
pub struct FrankfurterProvider {
cache_path: Option<PathBuf>,
in_memory: Mutex<Option<RateTable>>,
}
impl FrankfurterProvider {
pub fn new() -> Self {
Self {
cache_path: default_cache_path(),
in_memory: Mutex::new(None),
}
}
#[cfg(test)]
fn with_cache_path(path: PathBuf) -> Self {
Self {
cache_path: Some(path),
in_memory: Mutex::new(None),
}
}
}
impl Default for FrankfurterProvider {
fn default() -> Self {
Self::new()
}
}
impl RateProvider for FrankfurterProvider {
fn rates(&self) -> Result<RateTable, CalcError> {
{
let mem = self.in_memory.lock().unwrap();
if let Some(table) = mem.as_ref() {
return Ok(table.clone());
}
}
let cached = self.cache_path.as_ref().and_then(|p| read_cache_file(p));
if let Some(ref c) = cached {
if !is_expired(c.fetched_at) {
let table: RateTable = c.clone().into();
*self.in_memory.lock().unwrap() = Some(table.clone());
return Ok(table);
}
}
match fetch_from_network() {
Ok(table) => {
if let Some(path) = &self.cache_path {
let now = current_unix_timestamp();
let _ = write_cache_file(path, &table, now);
}
*self.in_memory.lock().unwrap() = Some(table.clone());
Ok(table)
}
Err(_net_err) => {
apply_stale_policy(cached.as_ref(), read_allow_stale())
}
}
}
}
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)
}
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 ttl_seconds() -> u64 {
parse_ttl_hours(env::var("CALNEXUS_FX_TTL_HOURS").ok().as_deref())
}
fn is_expired(fetched_at: u64) -> bool {
let now = current_unix_timestamp();
is_expired_at(fetched_at, now, ttl_seconds())
}
fn is_expired_at(fetched_at: u64, now: u64, ttl_secs: u64) -> bool {
now.saturating_sub(fetched_at) > ttl_secs
}
fn read_allow_stale() -> bool {
env::var("CALNEXUS_FX_ALLOW_STALE")
.map(|v| v == "1")
.unwrap_or(false)
}
fn apply_stale_policy(
cached: Option<&CachedRateTable>,
allow_stale: bool,
) -> Result<RateTable, CalcError> {
match cached {
Some(c) if allow_stale => Ok(c.clone().into()),
Some(c) => Err(CalcError::domain(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 => Err(CalcError::domain(
"FX network unreachable, no local cache available".to_string(),
)
.with_i18n("msg.fx.network_unreachable", vec![])),
}
}
fn read_cache_file(path: &Path) -> Option<CachedRateTable> {
let content = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&content).ok()
}
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(),
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);
}
std::fs::write(path, json)
}
fn fetch_from_network() -> Result<RateTable, CalcError> {
let response = ureq::get(FRANKFURTER_URL)
.config()
.timeout_global(Some(HTTP_TIMEOUT))
.build()
.call()
.map_err(|e| {
CalcError::domain(format!("FX network request failed: {}", e))
.with_i18n("msg.fx.network_unreachable", vec![])
})?;
let body = response.into_body().read_to_string().map_err(|e| {
CalcError::domain(format!("FX response read failed: {}", e))
.with_i18n("msg.fx.network_unreachable", vec![])
})?;
let parsed: FrankfurterResponse = serde_json::from_str(&body).map_err(|e| {
CalcError::domain(format!("FX response parse failed: {}", e))
.with_i18n("msg.fx.network_unreachable", vec![])
})?;
Ok(RateTable {
base: parsed.base,
date: parsed.date,
rates: parsed.rates,
})
}
#[cfg(test)]
mod tests {
use super::*;
struct MockRateProvider {
rates: HashMap<String, f64>,
date: String,
base: 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(),
})
}
}
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(),
}
}
#[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_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(),
};
let fetched_at = current_unix_timestamp();
write_cache_file(&path, &table, fetched_at).unwrap();
let cached = read_cache_file(&path).expect("cache file should be readable");
assert_eq!(cached.base, "EUR");
assert_eq!(cached.date, "2026-07-25");
assert_eq!(cached.rates.len(), 4);
assert_eq!(cached.fetched_at, fetched_at);
}
#[test]
fn test_read_cache_file_nonexistent() {
let path = Path::new("/nonexistent/path/fx_rates.json");
assert!(read_cache_file(path).is_none());
}
#[test]
fn test_read_cache_file_invalid_json() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "not valid json").unwrap();
assert!(read_cache_file(tmp.path()).is_none());
}
#[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(),
};
write_cache_file(&nested_path, &table, 0).unwrap();
assert!(nested_path.exists());
let cached = read_cache_file(&nested_path).expect("should be readable");
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(),
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);
}
#[test]
fn test_stale_policy_no_cache_no_allow_stale() {
let result = apply_stale_policy(None, false);
let err = result.expect_err("expected error");
assert_eq!(err.kind, crate::core::ErrorKind::Domain);
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);
let err = result.expect_err("expected error");
assert_eq!(err.kind, crate::core::ErrorKind::Domain);
}
#[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,
};
let result = apply_stale_policy(Some(&cached), false);
let err = result.expect_err("expected error");
assert_eq!(err.kind, crate::core::ErrorKind::Domain);
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,
};
let result = apply_stale_policy(Some(&cached), true);
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_default_cache_path_returns_some_on_normal_platform() {
let _ = default_cache_path();
}
#[test]
fn test_frankfurter_provider_with_cache_path_uses_provided_path() {
let tmp = tempfile::NamedTempFile::new().unwrap();
let provider = FrankfurterProvider::with_cache_path(tmp.path().to_path_buf());
let table = RateTable {
base: "EUR".to_string(),
date: "2026-07-25".to_string(),
rates: mock_rates(),
};
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_frankfurter_provider_in_memory_cache_hit() {
let tmp = tempfile::NamedTempFile::new().unwrap();
let provider = FrankfurterProvider::with_cache_path(tmp.path().to_path_buf());
let table = RateTable {
base: "EUR".to_string(),
date: "2026-07-25".to_string(),
rates: mock_rates(),
};
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_frankfurter_provider_default_impl() {
let _provider = FrankfurterProvider::default();
}
#[test]
fn test_read_allow_stale_default_false() {
let _ = read_allow_stale();
}
}