xx 2.5.3

A collection of useful Rust macros and small functions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Cache management utilities
//!
//! This module provides a cache manager with file-based caching, supporting
//! version-based invalidation, file dependency tracking, and time-based expiration.
//!
//! ## Features
//!
//! - **Version keys**: Invalidate cache when version changes
//! - **File dependencies**: Invalidate when watched files change
//! - **Time-based expiration**: Invalidate after a duration
//! - **Serialization**: JSON-based storage with serde
//!
//! ## Examples
//!
//! ```rust,no_run
//! use xx::cache::CacheManager;
//! use std::time::Duration;
//!
//! // Create a cache manager
//! let cache = CacheManager::builder()
//!     .cache_dir("/tmp/my-cache")
//!     .version("1.0.0")
//!     .fresh_duration(Duration::from_secs(3600))
//!     .build()
//!     .unwrap();
//!
//! // Use the cache
//! let key = "my-data";
//! if let Some(data) = cache.get::<Vec<String>>(key) {
//!     println!("Cached: {:?}", data);
//! } else {
//!     let data = vec!["computed".to_string(), "data".to_string()];
//!     cache.set(key, &data).unwrap();
//! }
//! ```

use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

use crate::{XXResult, file, hash::hash_to_str};

/// A cached entry with metadata
#[derive(Debug, Serialize, Deserialize)]
struct CacheEntry<T> {
    /// The cached data
    data: T,
    /// When this entry was created
    created_at: u64,
    /// Version key used when creating this entry
    version: String,
    /// Hash of watched files at creation time
    files_hash: Option<String>,
}

/// Builder for CacheManager
#[derive(Default)]
pub struct CacheManagerBuilder {
    cache_dir: Option<PathBuf>,
    version: String,
    fresh_duration: Option<Duration>,
    fresh_files: Vec<PathBuf>,
}

impl CacheManagerBuilder {
    /// Set the cache directory
    pub fn cache_dir<P: AsRef<Path>>(mut self, dir: P) -> Self {
        self.cache_dir = Some(dir.as_ref().to_path_buf());
        self
    }

    /// Set the version key for cache invalidation
    ///
    /// When the version changes, all cached data is considered stale.
    pub fn version<S: Into<String>>(mut self, version: S) -> Self {
        self.version = version.into();
        self
    }

    /// Set the freshness duration
    ///
    /// Cached data older than this duration is considered stale.
    pub fn fresh_duration(mut self, duration: Duration) -> Self {
        self.fresh_duration = Some(duration);
        self
    }

    /// Add a file to watch for changes
    ///
    /// When any watched file changes, cached data is considered stale.
    pub fn fresh_file<P: AsRef<Path>>(mut self, path: P) -> Self {
        self.fresh_files.push(path.as_ref().to_path_buf());
        self
    }

    /// Add multiple files to watch for changes
    pub fn fresh_files<I, P>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: AsRef<Path>,
    {
        for path in paths {
            self.fresh_files.push(path.as_ref().to_path_buf());
        }
        self
    }

    /// Build the CacheManager
    pub fn build(self) -> XXResult<CacheManager> {
        let cache_dir = self
            .cache_dir
            .ok_or_else(|| crate::error!("cache_dir is required"))?;

        file::mkdirp(&cache_dir)?;

        Ok(CacheManager {
            cache_dir,
            version: self.version,
            fresh_duration: self.fresh_duration,
            fresh_files: self.fresh_files,
        })
    }
}

/// A cache manager for file-based caching
pub struct CacheManager {
    cache_dir: PathBuf,
    version: String,
    fresh_duration: Option<Duration>,
    fresh_files: Vec<PathBuf>,
}

impl CacheManager {
    /// Create a new CacheManagerBuilder
    pub fn builder() -> CacheManagerBuilder {
        CacheManagerBuilder::default()
    }

    /// Get a value from the cache
    ///
    /// Returns None if:
    /// - The key doesn't exist
    /// - The cached data is stale (version mismatch, expired, files changed)
    /// - The data can't be deserialized
    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
        let path = self.cache_path(key);

        if !path.exists() {
            return None;
        }

        let content = file::read_to_string(&path).ok()?;
        let entry: CacheEntry<T> = serde_json::from_str(&content).ok()?;

        if !self.is_entry_fresh(
            key,
            entry.created_at,
            &entry.version,
            entry.files_hash.as_deref(),
        ) {
            return None;
        }

        trace!("Cache hit: {}", key);
        Some(entry.data)
    }

    /// Store a value in the cache
    pub fn set<T: Serialize>(&self, key: &str, data: &T) -> XXResult<()> {
        let path = self.cache_path(key);

        let entry = CacheEntry {
            data,
            created_at: SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            version: self.version.clone(),
            files_hash: self.compute_files_hash(),
        };

        let content = serde_json::to_string_pretty(&entry)
            .map_err(|e| crate::error!("Failed to serialize cache entry: {}", e))?;

        file::write(&path, content)?;
        trace!("Cache set: {}", key);
        Ok(())
    }

    /// Remove a value from the cache
    pub fn remove(&self, key: &str) -> XXResult<()> {
        let path = self.cache_path(key);
        file::remove_file(&path)
    }

    /// Clear all cached data
    pub fn clear(&self) -> XXResult<()> {
        file::remove_dir_all(&self.cache_dir)?;
        file::mkdirp(&self.cache_dir)
    }

    /// Get or compute a value
    ///
    /// Returns the cached value if fresh, otherwise computes and caches the new value.
    pub fn get_or_try<T, F, E>(&self, key: &str, f: F) -> Result<T, E>
    where
        T: Serialize + DeserializeOwned,
        F: FnOnce() -> Result<T, E>,
        E: From<crate::XXError>,
    {
        if let Some(value) = self.get::<T>(key) {
            return Ok(value);
        }

        let value = f()?;
        self.set(key, &value)?;
        Ok(value)
    }

    /// Check if a key exists and is fresh
    pub fn contains(&self, key: &str) -> bool {
        let path = self.cache_path(key);
        if !path.exists() {
            return false;
        }

        // Read and check metadata without deserializing the data
        if let Ok(content) = file::read_to_string(&path) {
            if let Ok(entry) = serde_json::from_str::<CacheEntry<serde_json::Value>>(&content) {
                return self.is_entry_fresh(
                    key,
                    entry.created_at,
                    &entry.version,
                    entry.files_hash.as_deref(),
                );
            }
        }

        false
    }

    /// Get the path to a cache file
    fn cache_path(&self, key: &str) -> PathBuf {
        let hash = hash_to_str(&key);
        self.cache_dir.join(format!("{}.json", hash))
    }

    /// Check if a cache entry is still fresh
    fn is_entry_fresh(
        &self,
        key: &str,
        created_at: u64,
        version: &str,
        files_hash: Option<&str>,
    ) -> bool {
        // Check version
        if version != self.version {
            trace!("Cache miss (version mismatch): {}", key);
            return false;
        }

        // Check freshness duration
        if let Some(duration) = self.fresh_duration {
            let now = SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();

            // Use saturating_sub to handle clock adjustments gracefully
            if now.saturating_sub(created_at) >= duration.as_secs() {
                trace!("Cache miss (expired): {}", key);
                return false;
            }
        }

        // Check watched files - compare current hash with stored hash
        // Invalidate if:
        // - stored_hash is Some but doesn't match current
        // - stored_hash is None but current_hash is Some (files were added to watch list)
        // - stored_hash is Some but current_hash is None (files were removed from watch list)
        let current_hash = self.compute_files_hash();
        if current_hash.as_deref() != files_hash {
            trace!("Cache miss (files changed): {}", key);
            return false;
        }

        true
    }

    /// Compute a hash of the watched files' modification times
    ///
    /// Returns a hash that includes information about all watched files.
    /// If a file doesn't exist or can't be accessed, we include a marker
    /// for that in the hash so that deletion or creation of files also
    /// invalidates the cache.
    fn compute_files_hash(&self) -> Option<String> {
        if self.fresh_files.is_empty() {
            return None;
        }

        // Include file existence/modification state for each watched file
        // Using Option<u64> so that missing files are represented as None
        // and affect the hash differently than existing files
        let mtimes: Vec<Option<u64>> = self
            .fresh_files
            .iter()
            .map(|path| file::modified_time(path).ok().map(|m| m.as_secs()))
            .collect();

        Some(hash_to_str(&mtimes))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cache_basic() {
        let tmpdir = tempfile::tempdir().unwrap();
        let cache = CacheManager::builder()
            .cache_dir(tmpdir.path())
            .version("1.0")
            .build()
            .unwrap();

        // Initially empty
        assert!(cache.get::<String>("key1").is_none());

        // Set and get
        cache.set("key1", &"value1".to_string()).unwrap();
        assert_eq!(cache.get::<String>("key1"), Some("value1".to_string()));

        // Remove
        cache.remove("key1").unwrap();
        assert!(cache.get::<String>("key1").is_none());
    }

    #[test]
    fn test_cache_version_invalidation() {
        let tmpdir = tempfile::tempdir().unwrap();

        // Create cache with version 1
        let cache_v1 = CacheManager::builder()
            .cache_dir(tmpdir.path())
            .version("1.0")
            .build()
            .unwrap();

        cache_v1.set("key", &"value".to_string()).unwrap();
        assert_eq!(cache_v1.get::<String>("key"), Some("value".to_string()));

        // Create cache with version 2
        let cache_v2 = CacheManager::builder()
            .cache_dir(tmpdir.path())
            .version("2.0")
            .build()
            .unwrap();

        // Should not find the old cached value
        assert!(cache_v2.get::<String>("key").is_none());
    }

    #[test]
    fn test_cache_duration_expiration() {
        let tmpdir = tempfile::tempdir().unwrap();
        let cache = CacheManager::builder()
            .cache_dir(tmpdir.path())
            .version("1.0")
            .fresh_duration(Duration::from_secs(0)) // Immediately expire
            .build()
            .unwrap();

        cache.set("key", &"value".to_string()).unwrap();
        // Should be expired immediately
        std::thread::sleep(Duration::from_millis(10));
        assert!(cache.get::<String>("key").is_none());
    }

    #[test]
    fn test_cache_contains() {
        let tmpdir = tempfile::tempdir().unwrap();
        let cache = CacheManager::builder()
            .cache_dir(tmpdir.path())
            .version("1.0")
            .build()
            .unwrap();

        assert!(!cache.contains("key"));
        cache.set("key", &"value".to_string()).unwrap();
        assert!(cache.contains("key"));
    }

    #[test]
    fn test_cache_clear() {
        let tmpdir = tempfile::tempdir().unwrap();
        let cache = CacheManager::builder()
            .cache_dir(tmpdir.path())
            .version("1.0")
            .build()
            .unwrap();

        cache.set("key1", &"value1".to_string()).unwrap();
        cache.set("key2", &"value2".to_string()).unwrap();

        cache.clear().unwrap();

        assert!(!cache.contains("key1"));
        assert!(!cache.contains("key2"));
    }

    #[test]
    fn test_cache_complex_types() {
        let tmpdir = tempfile::tempdir().unwrap();
        let cache = CacheManager::builder()
            .cache_dir(tmpdir.path())
            .version("1.0")
            .build()
            .unwrap();

        #[derive(Debug, Serialize, Deserialize, PartialEq)]
        struct TestData {
            name: String,
            values: Vec<i32>,
        }

        let data = TestData {
            name: "test".to_string(),
            values: vec![1, 2, 3],
        };

        cache.set("complex", &data).unwrap();
        let retrieved: Option<TestData> = cache.get("complex");
        assert_eq!(retrieved, Some(data));
    }
}