Skip to main content

edge_core/
cache.rs

1//! Local file cache for the last-received `EdgeConfig`. When `weave-server`
2//! is unreachable on startup, the agent loads this file so local operation
3//! can continue with the previous mapping set.
4
5use std::path::{Path, PathBuf};
6
7use weave_contracts::EdgeConfig;
8
9/// Resolve the cache path for an edge: `${XDG_STATE_HOME:-~/.local/state}/edge-agent/config-cache-${edge_id}.json`.
10pub fn default_cache_path(edge_id: &str) -> PathBuf {
11    let base = std::env::var_os("XDG_STATE_HOME")
12        .map(PathBuf::from)
13        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("state")))
14        .unwrap_or_else(|| PathBuf::from("."));
15    base.join("edge-agent")
16        .join(format!("config-cache-{}.json", edge_id))
17}
18
19pub async fn load(path: &Path) -> anyhow::Result<Option<EdgeConfig>> {
20    match tokio::fs::read_to_string(path).await {
21        Ok(s) => Ok(Some(serde_json::from_str(&s)?)),
22        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
23        Err(e) => Err(e.into()),
24    }
25}
26
27pub async fn save(path: &Path, config: &EdgeConfig) -> anyhow::Result<()> {
28    if let Some(parent) = path.parent() {
29        tokio::fs::create_dir_all(parent).await?;
30    }
31    let json = serde_json::to_string_pretty(config)?;
32    tokio::fs::write(path, json).await?;
33    Ok(())
34}