rcman 0.1.9

Framework-agnostic settings management with schema, backup/restore, secrets and derive macro support
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
use crate::CacheStrategy;
use crate::error::{Error, Result};
use crate::storage::StorageBackend;
use crate::sub_settings::store::SubSettingsStore;
use crate::utils::sync::RwLockExt;
use log::debug;
use serde_json::Value;
use std::collections::HashMap;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};

type SubSettingsMigrator = Arc<dyn Fn(Value) -> Value + Send + Sync>;

enum CacheType {
    Full(HashMap<String, Value>),
    Lru(lru::LruCache<String, Value>),
}

struct MultiFileStoreState {
    cache: Option<CacheType>,
    loaded_from_dir: bool,
}

pub struct MultiFileStore<S: StorageBackend> {
    name: String,
    base_dir: PathBuf,
    extension: String,
    storage: S,
    migrator: Option<SubSettingsMigrator>,
    cache_strategy: CacheStrategy,
    state: RwLock<MultiFileStoreState>,
}

impl<S: StorageBackend> MultiFileStore<S> {
    pub fn new(
        name: String,
        base_dir: PathBuf,
        extension: String,
        storage: S,
        migrator: Option<SubSettingsMigrator>,
        cache_strategy: CacheStrategy,
    ) -> Self {
        Self {
            name,
            base_dir,
            extension,
            storage,
            migrator,
            cache_strategy,
            state: RwLock::new(MultiFileStoreState {
                cache: None,
                loaded_from_dir: false,
            }),
        }
    }

    fn file_path(&self, key: &str) -> PathBuf {
        self.base_dir.join(format!("{}.{}", key, self.extension))
    }

    fn ensure_cache_populated(&self) -> Result<()> {
        if matches!(self.cache_strategy, CacheStrategy::None) {
            return Ok(());
        }

        // Fast path
        if self.state.read_recovered()?.cache.is_some() {
            return Ok(());
        }

        let mut state = self.state.write_recovered()?;
        if state.cache.is_some() {
            return Ok(());
        }

        state.cache = Some(match self.cache_strategy {
            CacheStrategy::Full => CacheType::Full(HashMap::new()),
            CacheStrategy::Lru(size) => {
                let cap = NonZeroUsize::new(size).unwrap_or(NonZeroUsize::new(100).unwrap());
                CacheType::Lru(lru::LruCache::new(cap))
            }
            CacheStrategy::None => unreachable!(),
        });
        Ok(())
    }

    fn load_directory_into_cache_keys(&self) -> Result<()> {
        if matches!(self.cache_strategy, CacheStrategy::None) {
            return Ok(());
        }

        if self.state.read_recovered()?.loaded_from_dir {
            return Ok(());
        }

        let mut state = self.state.write_recovered()?;
        if state.loaded_from_dir {
            return Ok(());
        }

        // Make sure cache exists
        if state.cache.is_none() {
            state.cache = Some(match self.cache_strategy {
                CacheStrategy::Full => CacheType::Full(HashMap::new()),
                CacheStrategy::Lru(size) => {
                    let cap = NonZeroUsize::new(size).unwrap_or(NonZeroUsize::new(100).unwrap());
                    CacheType::Lru(lru::LruCache::new(cap))
                }
                CacheStrategy::None => {
                    unreachable!("Cache should not be initialized if strategy is None")
                }
            });
        }

        if !self.base_dir.exists() {
            state.loaded_from_dir = true;
            return Ok(());
        }

        let ext = format!(".{}", self.extension);
        match &mut state.cache {
            Some(CacheType::Full(cache)) => {
                for entry in
                    std::fs::read_dir(&self.base_dir).map_err(|e| Error::DirectoryRead {
                        path: self.base_dir.clone(),
                        source: e,
                    })?
                {
                    let entry = entry.map_err(|e| Error::DirectoryRead {
                        path: self.base_dir.clone(),
                        source: e,
                    })?;

                    let name = entry.file_name().to_string_lossy().to_string();
                    if name.ends_with(&ext) {
                        let key = name.trim_end_matches(&ext).to_string();
                        cache.entry(key).or_insert(Value::Null);
                    }
                }
            }
            Some(CacheType::Lru(cache)) => {
                for entry in
                    std::fs::read_dir(&self.base_dir).map_err(|e| Error::DirectoryRead {
                        path: self.base_dir.clone(),
                        source: e,
                    })?
                {
                    let entry = entry.map_err(|e| Error::DirectoryRead {
                        path: self.base_dir.clone(),
                        source: e,
                    })?;

                    let name = entry.file_name().to_string_lossy().to_string();
                    if name.ends_with(&ext) {
                        let key = name.trim_end_matches(&ext).to_string();
                        // For LRU, we don't want to pollute with all keys if we have thousands,
                        // but list() needs them. For now, we follow the same pattern
                        // but these will be evicted if many are added.
                        if !cache.contains(&key) {
                            cache.put(key, Value::Null);
                        }
                    }
                }
            }
            _ => {}
        }

        state.loaded_from_dir = true;
        Ok(())
    }
}

impl<S: StorageBackend> SubSettingsStore for MultiFileStore<S> {
    fn get(&self, key: &str) -> Result<Value> {
        self.ensure_cache_populated()?;

        // Check cache first
        {
            // For Full strategy, we can use a read lock
            if matches!(self.cache_strategy, CacheStrategy::Full) {
                let state = self.state.read_recovered()?;
                if let Some(CacheType::Full(cache)) = &state.cache
                    && let Some(val) = cache.get(key)
                    && !val.is_null()
                {
                    return Ok(val.clone());
                }
            } else if matches!(self.cache_strategy, CacheStrategy::Lru(_)) {
                // For LRU, we MUST use a write lock to update use order
                let mut state = self.state.write_recovered()?;
                if let Some(CacheType::Lru(cache)) = &mut state.cache
                    && let Some(val) = cache.get(key)
                    && !val.is_null()
                {
                    return Ok(val.clone());
                }
            }
        }

        // Read from disk
        let path = self.file_path(key);
        if !path.exists() {
            if let Ok(mut state) = self.state.write_recovered()
                && let Some(cache) = &mut state.cache
            {
                match cache {
                    CacheType::Full(c) => {
                        c.remove(key);
                    }
                    CacheType::Lru(c) => {
                        c.pop(key);
                    }
                }
            }
            return Err(Error::SubSettingsEntryNotFound(format!(
                "{}/{}",
                self.name, key
            )));
        }

        let mut value: Value = self.storage.read(&path)?;

        // Migration logic
        if let Some(migrator) = &self.migrator {
            let original = value.clone();
            value = migrator(value);
            if value != original {
                debug!("Migrated sub-settings entry: {key}");
                self.storage.write(&path, &value)?;
            }
        }

        // Update cache
        if !matches!(self.cache_strategy, CacheStrategy::None) {
            let mut state = self.state.write_recovered()?;
            match &mut state.cache {
                Some(CacheType::Full(cache)) => {
                    cache.insert(key.to_string(), value.clone());
                }
                Some(CacheType::Lru(cache)) => {
                    cache.put(key.to_string(), value.clone());
                }
                _ => {}
            }
        }

        Ok(value)
    }

    fn set(&self, key: &str, value: Value) -> Result<()> {
        // If value is null, treat as removal (TOML doesn't support nulls, and it's cleaner)
        if value.is_null() {
            return self.remove(key);
        }

        let path = self.file_path(key);

        // Ensure directory exists
        if !self.base_dir.exists() {
            crate::utils::security::ensure_secure_dir(&self.base_dir)?;
        }

        self.storage.write(&path, &value)?;

        // Update cache
        if !matches!(self.cache_strategy, CacheStrategy::None) {
            let mut state = self.state.write_recovered()?;
            // Initialize cache if needed
            if state.cache.is_none() {
                state.cache = Some(match self.cache_strategy {
                    CacheStrategy::Full => CacheType::Full(HashMap::new()),
                    CacheStrategy::Lru(size) => {
                        let cap =
                            NonZeroUsize::new(size).unwrap_or(NonZeroUsize::new(100).unwrap());
                        CacheType::Lru(lru::LruCache::new(cap))
                    }
                    CacheStrategy::None => {
                        unreachable!("Cache should not be initialized if strategy is None")
                    }
                });
            }
            match &mut state.cache {
                Some(CacheType::Full(cache)) => {
                    cache.insert(key.to_string(), value);
                }
                Some(CacheType::Lru(cache)) => {
                    cache.put(key.to_string(), value);
                }
                _ => {}
            }
        }

        Ok(())
    }

    fn remove(&self, key: &str) -> Result<()> {
        let path = self.file_path(key);

        if path.exists() {
            std::fs::remove_file(&path).map_err(|e| Error::FileDelete { path, source: e })?;
        }

        // Remove from cache
        let mut state = self.state.write_recovered()?;
        match &mut state.cache {
            Some(CacheType::Full(cache)) => {
                cache.remove(key);
            }
            Some(CacheType::Lru(cache)) => {
                cache.pop(key);
            }
            _ => {}
        }

        Ok(())
    }

    fn list(&self) -> Result<Vec<String>> {
        if matches!(self.cache_strategy, CacheStrategy::None) {
            if !self.base_dir.exists() {
                return Ok(Vec::new());
            }

            let mut entries = Vec::new();
            let ext = format!(".{}", self.extension);

            for entry in std::fs::read_dir(&self.base_dir).map_err(|e| Error::DirectoryRead {
                path: self.base_dir.clone(),
                source: e,
            })? {
                let entry = entry.map_err(|e| Error::DirectoryRead {
                    path: self.base_dir.clone(),
                    source: e,
                })?;
                let name = entry.file_name().to_string_lossy().to_string();
                if name.ends_with(&ext) {
                    entries.push(name.trim_end_matches(&ext).to_string());
                }
            }

            entries.sort();
            return Ok(entries);
        }

        // Populate the cache with existing directory entries as lazy placeholders
        self.load_directory_into_cache_keys()?;

        let state = self.state.read_recovered()?;
        match &state.cache {
            Some(CacheType::Full(cache)) => {
                let mut keys: Vec<String> = cache.keys().cloned().collect();
                keys.sort();
                Ok(keys)
            }
            Some(CacheType::Lru(cache)) => {
                let mut keys: Vec<String> = cache.iter().map(|(k, _)| k.clone()).collect();
                keys.sort();
                Ok(keys)
            }
            _ => Ok(Vec::new()),
        }
    }

    fn get_all(&self) -> Result<HashMap<String, Value>> {
        let keys = self.list()?;
        let mut result = HashMap::with_capacity(keys.len());

        for key in keys {
            if let Ok(value) = self.get(key.as_str()) {
                result.insert(key, value);
            }
        }

        Ok(result)
    }

    fn invalidate_cache(&self) {
        if let Ok(mut state) = self.state.write_recovered() {
            state.cache = None;
            state.loaded_from_dir = false;
        }
    }

    fn get_base_path(&self) -> PathBuf {
        self.base_dir.clone()
    }

    fn get_single_file_path(&self) -> Option<PathBuf> {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::JsonStorage;
    use serde::Serialize;
    use serde::de::DeserializeOwned;
    use serde_json::json;
    use std::path::Path;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[derive(Clone)]
    struct CountingStorage {
        inner: JsonStorage,
        writes: Arc<AtomicUsize>,
        reads: Arc<AtomicUsize>,
    }

    impl CountingStorage {
        fn new(writes: Arc<AtomicUsize>, reads: Arc<AtomicUsize>) -> Self {
            Self {
                inner: JsonStorage::new(),
                writes,
                reads,
            }
        }
    }

    impl StorageBackend for CountingStorage {
        fn extension(&self) -> &str {
            self.inner.extension()
        }

        fn serialize<T: Serialize>(&self, data: &T) -> Result<String> {
            self.inner.serialize(data)
        }

        fn deserialize<T: DeserializeOwned>(&self, content: &str) -> Result<T> {
            self.inner.deserialize(content)
        }

        fn read<T: DeserializeOwned>(&self, path: &Path) -> Result<T> {
            self.reads.fetch_add(1, Ordering::SeqCst);
            self.inner.read(path)
        }

        fn write<T: Serialize>(&self, path: &Path, data: &T) -> Result<()> {
            self.writes.fetch_add(1, Ordering::SeqCst);
            self.inner.write(path, data)
        }
    }

    #[test]
    fn test_multifile_caching_eliminates_disk_io() {
        let dir = tempfile::tempdir().unwrap();
        let writes = Arc::new(AtomicUsize::new(0));
        let reads = Arc::new(AtomicUsize::new(0));
        let storage = CountingStorage::new(writes.clone(), reads.clone());

        let store = MultiFileStore::new(
            "remotes".to_string(),
            dir.path().to_path_buf(),
            "json".to_string(),
            storage,
            None,
            CacheStrategy::Full,
        );

        // Pre-create two entities
        store.set("remote1", json!({"type": "gdrive"})).unwrap();
        store.set("remote2", json!({"type": "s3"})).unwrap();
        assert_eq!(writes.load(Ordering::SeqCst), 2);
        assert_eq!(reads.load(Ordering::SeqCst), 0);

        // Clear cache completely (simulate a new instance)
        store.invalidate_cache();

        // List files (should read directory, but NOT read files = 0 file disk reads)
        let keys = store.list().unwrap();
        assert_eq!(keys.len(), 2);
        assert_eq!(reads.load(Ordering::SeqCst), 0);

        // Get the first entity (should read 1 file from disk)
        let _ = store.get("remote1").unwrap();
        assert_eq!(reads.load(Ordering::SeqCst), 1);

        // Get the first entity AGAIN (should serve from cache = 1 file disk read still)
        let _ = store.get("remote1").unwrap();
        assert_eq!(reads.load(Ordering::SeqCst), 1);

        // Get the second entity (should read 1 file from disk, total = 2)
        let _ = store.get("remote2").unwrap();
        assert_eq!(reads.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn test_multifile_lru_eviction() {
        let dir = tempfile::tempdir().unwrap();
        let writes = Arc::new(AtomicUsize::new(0));
        let reads = Arc::new(AtomicUsize::new(0));
        let storage = CountingStorage::new(writes.clone(), reads.clone());

        let store = MultiFileStore::new(
            "remotes".to_string(),
            dir.path().to_path_buf(),
            "json".to_string(),
            storage,
            None,
            CacheStrategy::Lru(2), // Capacity of 2
        );

        // Set 3 items
        store.set("a", json!(1)).unwrap();
        store.set("b", json!(2)).unwrap();
        store.set("c", json!(3)).unwrap(); // "a" should be evicted from cache

        assert_eq!(reads.load(Ordering::SeqCst), 0);

        // Get "c" (should be in cache)
        store.get("c").unwrap();
        assert_eq!(reads.load(Ordering::SeqCst), 0);

        // Get "b" (should be in cache)
        store.get("b").unwrap();
        assert_eq!(reads.load(Ordering::SeqCst), 0);

        // Get "a" (should NOT be in cache, requires disk read)
        store.get("a").unwrap();
        assert_eq!(reads.load(Ordering::SeqCst), 1);

        // Getting "a" again should now be cached (evicting "c" or "b" - specifically "c" as "b" was used last)
        store.get("a").unwrap();
        assert_eq!(reads.load(Ordering::SeqCst), 1);
    }
}