Skip to main content

ai_usagebar/
cache.rs

1//! Per-vendor on-disk cache with atomic writes, TTL checks, and inter-process
2//! locking.
3//!
4//! Mirrors claudebar's cache layout but per-vendor:
5//!   `~/.cache/ai-usagebar/<vendor>/usage.json`         payload
6//!   `~/.cache/ai-usagebar/<vendor>/.stale`             marker (cache is stale)
7//!   `~/.cache/ai-usagebar/<vendor>/.last_error`        HTTP code\nmessage
8//!   `~/.cache/ai-usagebar/<vendor>/.fetch.lock`        flock target
9//!
10//! Multi-monitor safety: callers should `acquire_lock()` before the refresh+
11//! fetch window, mirroring claudebar:402-407's `exec 9>"$_lockfile" / flock`.
12
13use std::fs::{self, File, OpenOptions};
14use std::io::{Read, Write};
15use std::path::{Path, PathBuf};
16use std::time::{Duration, SystemTime};
17
18use fs2::FileExt;
19
20use crate::error::{AppError, Result};
21
22/// Default TTL — claudebar's `CACHE_TTL=60`.
23pub const DEFAULT_TTL: Duration = Duration::from_secs(60);
24
25/// Maximum staleness before we refuse to serve cached data even on failure.
26/// Mirrors claudebar's `WEEKLY_WINDOW` (7 days).
27pub const MAX_STALE: Duration = Duration::from_secs(7 * 24 * 3600);
28
29/// Per-vendor cache directory and helper API.
30///
31/// Construct with [`Cache::for_vendor`]; the directory is created lazily.
32#[derive(Debug, Clone)]
33pub struct Cache {
34    dir: PathBuf,
35}
36
37impl Cache {
38    /// Build a cache rooted at `~/.cache/ai-usagebar/<vendor>` (or under
39    /// `$XDG_CACHE_HOME` when set).
40    pub fn for_vendor(vendor: &str) -> Result<Self> {
41        let base = xdg_cache_dir()?.join("ai-usagebar").join(vendor);
42        Ok(Self { dir: base })
43    }
44
45    /// Cache rooted at an arbitrary directory — for tests.
46    pub fn at(path: PathBuf) -> Self {
47        Self { dir: path }
48    }
49
50    /// Ensure the directory exists. Safe to call repeatedly.
51    pub fn ensure_dir(&self) -> Result<()> {
52        fs::create_dir_all(&self.dir).map_err(|e| AppError::io_at(&self.dir, e))
53    }
54
55    pub fn dir(&self) -> &Path {
56        &self.dir
57    }
58
59    pub fn payload_path(&self) -> PathBuf {
60        self.dir.join("usage.json")
61    }
62    pub fn stale_path(&self) -> PathBuf {
63        self.dir.join(".stale")
64    }
65    pub fn last_error_path(&self) -> PathBuf {
66        self.dir.join(".last_error")
67    }
68    pub fn lock_path(&self) -> PathBuf {
69        self.dir.join(".fetch.lock")
70    }
71
72    /// Age of the payload (`None` if it doesn't exist). Used by the widget to
73    /// decide whether the 60s cache window applies.
74    pub fn payload_age(&self) -> Option<Duration> {
75        let meta = fs::metadata(self.payload_path()).ok()?;
76        let mtime = meta.modified().ok()?;
77        SystemTime::now().duration_since(mtime).ok()
78    }
79
80    /// Returns the cached payload only if it is younger than `ttl`. Used as
81    /// the fast path in `_fetch_usage` (claudebar:343-349).
82    pub fn fresh_payload(&self, ttl: Duration) -> Result<Option<Vec<u8>>> {
83        let Some(age) = self.payload_age() else {
84            return Ok(None);
85        };
86        if age < ttl {
87            self.read_payload().map(Some)
88        } else {
89            Ok(None)
90        }
91    }
92
93    /// Read the payload regardless of age. `Err` if the file exists but is
94    /// unreadable; `Ok(None)` if it just doesn't exist.
95    pub fn maybe_payload(&self) -> Result<Option<Vec<u8>>> {
96        if !self.payload_path().exists() {
97            return Ok(None);
98        }
99        self.read_payload().map(Some)
100    }
101
102    fn read_payload(&self) -> Result<Vec<u8>> {
103        let p = self.payload_path();
104        let mut f = File::open(&p).map_err(|e| AppError::io_at(&p, e))?;
105        let mut buf = Vec::new();
106        f.read_to_end(&mut buf)
107            .map_err(|e| AppError::io_at(&p, e))?;
108        Ok(buf)
109    }
110
111    /// Atomically write a new payload. Uses `tempfile + persist` (POSIX
112    /// rename), matching claudebar's `mktemp + mv` invariant.
113    pub fn write_payload(&self, bytes: &[u8]) -> Result<()> {
114        self.ensure_dir()?;
115        let mut tmp = tempfile::Builder::new()
116            .prefix(".usage.")
117            .tempfile_in(&self.dir)
118            .map_err(|e| AppError::io_at(&self.dir, e))?;
119        tmp.write_all(bytes)
120            .map_err(|e| AppError::io_at(tmp.path(), e))?;
121        tmp.as_file_mut()
122            .sync_all()
123            .map_err(|e| AppError::io_at(tmp.path(), e))?;
124        tmp.persist(self.payload_path())
125            .map_err(|e| AppError::io_at(self.payload_path(), e.error))?;
126        // A successful write clears any stale marker.
127        let _ = fs::remove_file(self.stale_path());
128        let _ = fs::remove_file(self.last_error_path());
129        Ok(())
130    }
131
132    /// Mark the cache as stale. Idempotent.
133    pub fn mark_stale(&self) {
134        let _ = self.ensure_dir();
135        let _ = File::create(self.stale_path());
136    }
137
138    pub fn is_stale(&self) -> bool {
139        self.stale_path().exists()
140    }
141
142    /// Write the `.last_error` marker — first line `code`, second line `msg`.
143    /// Best-effort, never errors (matches claudebar:478-486 which silently
144    /// continues if the cache dir isn't writable).
145    pub fn write_last_error(&self, code: u16, msg: &str) {
146        let _ = self.ensure_dir();
147        let path = self.last_error_path();
148        let body = format!("{code}\n{msg}");
149        let _ = atomic_write(&path, body.as_bytes());
150    }
151
152    /// Best-effort removal of the `.last_error` marker.
153    pub fn clear_last_error(&self) {
154        let _ = fs::remove_file(self.last_error_path());
155    }
156
157    pub fn read_last_error(&self) -> Option<(u16, String)> {
158        let raw = fs::read_to_string(self.last_error_path()).ok()?;
159        let mut lines = raw.lines();
160        let code = lines.next()?.parse::<u16>().ok()?;
161        let msg = lines.next().unwrap_or_default().to_string();
162        Some((code, msg))
163    }
164}
165
166/// Acquire an exclusive flock on `path`, blocking up to `timeout`.
167/// Returned guard releases the lock on drop.
168///
169/// The flock file is created if missing, but its content is unused — only
170/// the lock matters.
171pub fn acquire_lock(path: &Path, timeout: Duration) -> Result<LockGuard> {
172    if let Some(parent) = path.parent() {
173        fs::create_dir_all(parent).map_err(|e| AppError::io_at(parent, e))?;
174    }
175    let f = OpenOptions::new()
176        .create(true)
177        .read(true)
178        .write(true)
179        .truncate(false)
180        .open(path)
181        .map_err(|e| AppError::io_at(path, e))?;
182
183    let deadline = std::time::Instant::now() + timeout;
184    loop {
185        match f.try_lock_exclusive() {
186            Ok(()) => return Ok(LockGuard { file: f }),
187            Err(_) => {
188                if std::time::Instant::now() >= deadline {
189                    return Err(AppError::Other(format!(
190                        "cache lock timeout after {:?}",
191                        timeout
192                    )));
193                }
194                std::thread::sleep(Duration::from_millis(50));
195            }
196        }
197    }
198}
199
200/// Releases the flock on drop. Holding this across an `.await` is fine as
201/// long as you don't move it across tasks (we always use it in `tokio::main`
202/// on a single thread).
203pub struct LockGuard {
204    file: File,
205}
206
207impl Drop for LockGuard {
208    fn drop(&mut self) {
209        let _ = FileExt::unlock(&self.file);
210    }
211}
212
213/// Atomic write helper used by `write_last_error`. Public for vendors that
214/// need to write small sidecar files (credentials, etc.).
215pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
216    let dir = path.parent().ok_or_else(|| {
217        AppError::Other(format!(
218            "atomic_write: path has no parent: {}",
219            path.display()
220        ))
221    })?;
222    fs::create_dir_all(dir).map_err(|e| AppError::io_at(dir, e))?;
223    let mut tmp = tempfile::Builder::new()
224        .prefix(".tmp.")
225        .tempfile_in(dir)
226        .map_err(|e| AppError::io_at(dir, e))?;
227    tmp.write_all(bytes)
228        .map_err(|e| AppError::io_at(tmp.path(), e))?;
229    tmp.as_file_mut()
230        .sync_all()
231        .map_err(|e| AppError::io_at(tmp.path(), e))?;
232    tmp.persist(path)
233        .map_err(|e| AppError::io_at(path, e.error))?;
234    Ok(())
235}
236
237fn xdg_cache_dir() -> Result<PathBuf> {
238    directories::BaseDirs::new()
239        .map(|b| b.cache_dir().to_path_buf())
240        .ok_or_else(|| AppError::Other("could not resolve XDG cache dir (no HOME?)".into()))
241}
242
243/// The user's home directory, resolved cross-platform via `directories`
244/// (`$HOME` on Unix/macOS, `%USERPROFILE%` / the Known Folder on Windows).
245///
246/// The OAuth-credential vendors (`anthropic`, `openai`) read their CLI-managed
247/// files from fixed dotfiles under `$HOME`; they share this resolver the same
248/// way they already share [`atomic_write`], so home resolution lives in one
249/// place rather than being reimplemented per vendor.
250pub fn home_dir() -> Result<PathBuf> {
251    directories::BaseDirs::new()
252        .map(|b| b.home_dir().to_path_buf())
253        .ok_or_else(|| AppError::Other("could not resolve home directory (no HOME?)".into()))
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use tempfile::TempDir;
260
261    fn fixture() -> (TempDir, Cache) {
262        let td = TempDir::new().unwrap();
263        let cache = Cache::at(td.path().join("anthropic"));
264        cache.ensure_dir().unwrap();
265        (td, cache)
266    }
267
268    #[test]
269    fn ensure_dir_is_idempotent() {
270        let (_td, cache) = fixture();
271        cache.ensure_dir().unwrap();
272        cache.ensure_dir().unwrap();
273        assert!(cache.dir().is_dir());
274    }
275
276    #[test]
277    fn write_then_read_round_trip() {
278        let (_td, cache) = fixture();
279        cache.write_payload(b"hello world").unwrap();
280        let got = cache.maybe_payload().unwrap();
281        assert_eq!(got.as_deref(), Some(&b"hello world"[..]));
282    }
283
284    #[test]
285    fn maybe_payload_returns_none_when_missing() {
286        let (_td, cache) = fixture();
287        assert!(cache.maybe_payload().unwrap().is_none());
288    }
289
290    #[test]
291    fn fresh_payload_respects_ttl() {
292        let (_td, cache) = fixture();
293        cache.write_payload(b"x").unwrap();
294        // Fresh = within a generous TTL.
295        assert!(
296            cache
297                .fresh_payload(Duration::from_secs(10))
298                .unwrap()
299                .is_some()
300        );
301        // Force "stale" by passing a zero TTL — payload is older than 0s.
302        assert!(
303            cache
304                .fresh_payload(Duration::from_secs(0))
305                .unwrap()
306                .is_none()
307        );
308    }
309
310    #[test]
311    fn write_clears_stale_marker_and_last_error() {
312        let (_td, cache) = fixture();
313        cache.mark_stale();
314        cache.write_last_error(429, "rate limited");
315        assert!(cache.is_stale());
316        assert!(cache.read_last_error().is_some());
317
318        cache.write_payload(b"fresh").unwrap();
319        assert!(!cache.is_stale());
320        assert!(cache.read_last_error().is_none());
321    }
322
323    #[test]
324    fn last_error_round_trip() {
325        let (_td, cache) = fixture();
326        cache.write_last_error(503, "service unavailable");
327        let (code, msg) = cache.read_last_error().unwrap();
328        assert_eq!(code, 503);
329        assert_eq!(msg, "service unavailable");
330    }
331
332    #[test]
333    fn last_error_with_empty_message_round_trips() {
334        let (_td, cache) = fixture();
335        cache.write_last_error(429, "");
336        let (code, msg) = cache.read_last_error().unwrap();
337        assert_eq!(code, 429);
338        assert_eq!(msg, "");
339    }
340
341    #[test]
342    fn lock_serializes_concurrent_acquirers() {
343        // First lock succeeds; while held, a second non-blocking attempt
344        // should time out quickly.
345        let (_td, cache) = fixture();
346        let lock_path = cache.lock_path();
347        let _guard = acquire_lock(&lock_path, Duration::from_millis(500)).unwrap();
348
349        let res = acquire_lock(&lock_path, Duration::from_millis(100));
350        assert!(matches!(res, Err(AppError::Other(_))));
351    }
352
353    #[test]
354    fn atomic_write_creates_parent_dirs() {
355        let td = TempDir::new().unwrap();
356        let nested = td.path().join("a/b/c/file.txt");
357        atomic_write(&nested, b"abc").unwrap();
358        assert_eq!(fs::read(&nested).unwrap(), b"abc");
359    }
360}