Skip to main content

esh_cache/
file.rs

1//! Opt-in file cache. Disabled by default in the façade (zero plaintext persistence NFR).
2//!
3//! Values are stored as JSON. Prefer encrypting the cache directory at rest (OS / KMS)
4//! when enabling this backend.
5
6use async_trait::async_trait;
7use chrono::{DateTime, Utc};
8use esh_core::{Cache, CacheKey, ConfigValue, Error, Result};
9use serde::{Deserialize, Serialize};
10use std::path::{Path, PathBuf};
11use std::time::Duration;
12use tracing::warn;
13
14#[derive(Serialize, Deserialize)]
15struct DiskEntry {
16    value: ConfigValue,
17    expires_at: DateTime<Utc>,
18}
19
20/// Filesystem cache backend.
21pub struct FileCache {
22    root: PathBuf,
23}
24
25impl FileCache {
26    /// Create cache root directory if needed.
27    pub fn new(root: impl AsRef<Path>) -> Result<Self> {
28        let root = root.as_ref().to_path_buf();
29        std::fs::create_dir_all(&root)?;
30        warn!(
31            path = %root.display(),
32            "file cache enabled — ensure directory is encrypted at rest; secrets may persist on disk"
33        );
34        Ok(Self { root })
35    }
36
37    fn path_for(&self, key: &CacheKey) -> PathBuf {
38        let name = match &key.namespace {
39            Some(ns) => format!("{ns}__{}", key.key),
40            None => key.key.clone(),
41        };
42        // Sanitize path segments.
43        let safe: String = name
44            .chars()
45            .map(|c| {
46                if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
47                    c
48                } else {
49                    '_'
50                }
51            })
52            .collect();
53        self.root.join(format!("{safe}.json"))
54    }
55}
56
57#[async_trait]
58impl Cache for FileCache {
59    async fn get(&self, key: &CacheKey) -> Result<Option<ConfigValue>> {
60        let path = self.path_for(key);
61        if !path.exists() {
62            return Ok(None);
63        }
64        let raw = tokio::fs::read_to_string(&path)
65            .await
66            .map_err(|e| Error::Cache(e.to_string()))?;
67        let entry: DiskEntry =
68            serde_json::from_str(&raw).map_err(|e| Error::Cache(e.to_string()))?;
69        if entry.expires_at > Utc::now() {
70            Ok(Some(entry.value))
71        } else {
72            let _ = tokio::fs::remove_file(&path).await;
73            Ok(None)
74        }
75    }
76
77    async fn put(&self, key: &CacheKey, value: ConfigValue, ttl: Duration) -> Result<()> {
78        let expires_at = Utc::now()
79            + chrono::Duration::from_std(ttl).unwrap_or_else(|_| chrono::Duration::seconds(0));
80        let entry = DiskEntry { value, expires_at };
81        let raw = serde_json::to_string(&entry).map_err(|e| Error::Cache(e.to_string()))?;
82        let path = self.path_for(key);
83        tokio::fs::write(&path, raw)
84            .await
85            .map_err(|e| Error::Cache(e.to_string()))?;
86        Ok(())
87    }
88
89    async fn invalidate(&self, key: &CacheKey) -> Result<()> {
90        let path = self.path_for(key);
91        if path.exists() {
92            tokio::fs::remove_file(path)
93                .await
94                .map_err(|e| Error::Cache(e.to_string()))?;
95        }
96        Ok(())
97    }
98
99    async fn clear(&self) -> Result<()> {
100        let mut rd = tokio::fs::read_dir(&self.root)
101            .await
102            .map_err(|e| Error::Cache(e.to_string()))?;
103        while let Some(ent) = rd
104            .next_entry()
105            .await
106            .map_err(|e| Error::Cache(e.to_string()))?
107        {
108            let path = ent.path();
109            if path.extension().and_then(|e| e.to_str()) == Some("json") {
110                let _ = tokio::fs::remove_file(path).await;
111            }
112        }
113        Ok(())
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120    use esh_test_support::{run_cache_conformance, CacheConformanceCfg, TempSecrets};
121    use std::time::Duration;
122
123    #[tokio::test]
124    async fn file_cache_conformance() {
125        let tmp = TempSecrets::create();
126        let cache = FileCache::new(tmp.path().join("cache")).unwrap();
127        run_cache_conformance(
128            &cache,
129            &CacheConformanceCfg {
130                supports_clear: true,
131                short_ttl: Duration::from_millis(40),
132                test_expiry: true,
133            },
134        )
135        .await;
136    }
137
138    #[test]
139    fn file_cache_is_opt_in_construction() {
140        // Construction succeeds only when caller explicitly creates FileCache.
141        let tmp = TempSecrets::create();
142        assert!(FileCache::new(tmp.path().join("c")).is_ok());
143    }
144}