aither_attachments/
lib.rs1use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5use std::time::{Duration, SystemTime};
6
7use async_fs::File;
8use futures_lite::io::AsyncReadExt;
9use serde::{Deserialize, Serialize};
10use sha2::{Digest, Sha256};
11
12const CACHE_FILE_NAME: &str = "file_cache.json";
13
14#[must_use]
16pub fn default_cache_dir() -> PathBuf {
17 std::env::var_os("AITHER_CACHE_DIR").map_or_else(
18 || std::env::temp_dir().join("aither").join("cache"),
19 PathBuf::from,
20 )
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct CacheEntry {
26 pub content_hash: String,
28 pub provider: String,
30 pub reference: String,
32 #[serde(with = "system_time_option")]
34 pub expires_at: Option<SystemTime>,
35}
36
37impl CacheEntry {
38 #[must_use]
40 pub const fn new(
41 content_hash: String,
42 provider: String,
43 reference: String,
44 expires_at: Option<SystemTime>,
45 ) -> Self {
46 Self {
47 content_hash,
48 provider,
49 reference,
50 expires_at,
51 }
52 }
53
54 #[must_use]
56 pub fn is_valid(&self, current_hash: &str) -> bool {
57 if self.content_hash != current_hash {
58 return false;
59 }
60 self.expires_at
61 .is_none_or(|expires| SystemTime::now() < expires)
62 }
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct FileCache {
71 #[serde(skip)]
73 cache_dir: PathBuf,
74 entries: HashMap<String, CacheEntry>,
76}
77
78impl FileCache {
79 pub async fn open(cache_dir: PathBuf) -> std::io::Result<Self> {
87 let cache_file = cache_dir.join(CACHE_FILE_NAME);
88 if async_fs::metadata(&cache_file).await.is_ok() {
89 let contents = async_fs::read_to_string(&cache_file).await?;
90 let cache: Self = serde_json::from_str(&contents)
91 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
92 return Ok(Self {
93 cache_dir,
94 entries: cache.entries,
95 });
96 }
97 Ok(Self {
98 cache_dir,
99 entries: HashMap::new(),
100 })
101 }
102
103 pub async fn save(&self) -> std::io::Result<()> {
109 async_fs::create_dir_all(&self.cache_dir).await?;
110 let cache_file = self.cache_dir.join(CACHE_FILE_NAME);
111 let contents = serde_json::to_string_pretty(self)
112 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
113 async_fs::write(cache_file, contents).await?;
114 Ok(())
115 }
116
117 fn cache_key(file_path: &Path, provider: &str) -> String {
119 format!("{}::{}", file_path.display(), provider)
120 }
121
122 pub async fn get(
133 &self,
134 file_path: &Path,
135 provider: &str,
136 ) -> std::io::Result<Option<CacheEntry>> {
137 let key = Self::cache_key(file_path, provider);
138 let Some(entry) = self.entries.get(&key) else {
139 return Ok(None);
140 };
141
142 let current_hash = hash_file(file_path).await?;
143 if entry.is_valid(¤t_hash) {
144 Ok(Some(entry.clone()))
145 } else {
146 Ok(None)
147 }
148 }
149
150 pub async fn insert(
158 &mut self,
159 file_path: &Path,
160 provider: &str,
161 reference: String,
162 expires_at: Option<SystemTime>,
163 ) -> std::io::Result<()> {
164 let content_hash = hash_file(file_path).await?;
165 let key = Self::cache_key(file_path, provider);
166 let entry = CacheEntry::new(content_hash, provider.to_string(), reference, expires_at);
167 self.entries.insert(key, entry);
168 Ok(())
169 }
170
171 pub fn remove(&mut self, file_path: &Path, provider: &str) -> Option<CacheEntry> {
173 let key = Self::cache_key(file_path, provider);
174 self.entries.remove(&key)
175 }
176
177 pub fn prune_expired(&mut self) -> bool {
181 let now = SystemTime::now();
182 let before = self.entries.len();
183 self.entries
184 .retain(|_, entry| entry.expires_at.is_none_or(|expires| now < expires));
185 before != self.entries.len()
186 }
187
188 #[must_use]
190 pub fn expires_in(duration: Duration) -> Option<SystemTime> {
191 SystemTime::now().checked_add(duration)
192 }
193}
194
195async fn hash_file(path: &Path) -> std::io::Result<String> {
196 let mut file = File::open(path).await?;
197 let mut hasher = Sha256::new();
198 let mut buffer = [0u8; 8192];
199 loop {
200 let bytes_read = file.read(&mut buffer).await?;
201 if bytes_read == 0 {
202 break;
203 }
204 hasher.update(&buffer[..bytes_read]);
205 }
206 let result = hasher.finalize();
207 Ok(const_hex::encode(result))
208}
209
210mod system_time_option {
212 use serde::{Deserialize, Deserializer, Serialize, Serializer};
213 use std::time::{Duration, SystemTime, UNIX_EPOCH};
214
215 #[allow(clippy::ref_option)]
216 pub fn serialize<S>(time: &Option<SystemTime>, serializer: S) -> Result<S::Ok, S::Error>
217 where
218 S: Serializer,
219 {
220 match time {
221 Some(t) => {
222 let duration = t.duration_since(UNIX_EPOCH).unwrap_or_default();
223 Some(duration.as_secs()).serialize(serializer)
224 }
225 None => None::<u64>.serialize(serializer),
226 }
227 }
228
229 pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<SystemTime>, D::Error>
230 where
231 D: Deserializer<'de>,
232 {
233 let secs: Option<u64> = Option::deserialize(deserializer)?;
234 Ok(secs.map(|s| UNIX_EPOCH + Duration::from_secs(s)))
235 }
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241
242 #[tokio::test]
243 async fn test_file_cache_insert_get() {
244 let dir = tempfile::tempdir().expect("create temp dir");
245 let cache_dir = dir.path().join("cache");
246 let file_path = dir.path().join("file.txt");
247 async_fs::write(&file_path, b"hello")
248 .await
249 .expect("write file");
250
251 let mut cache = FileCache::open(cache_dir).await.expect("open cache");
252 cache
253 .insert(&file_path, "openai", "file-1".to_string(), None)
254 .await
255 .expect("insert");
256 cache.save().await.expect("save");
257
258 let cache = FileCache::open(dir.path().join("cache"))
259 .await
260 .expect("reload");
261 let entry = cache
262 .get(&file_path, "openai")
263 .await
264 .expect("get")
265 .expect("entry");
266 assert_eq!(entry.reference, "file-1");
267 }
268}