diff options
| author | Max Audron <me@audron.dev> | 2026-01-30 18:19:42 +0100 |
|---|---|---|
| committer | Max Audron <me@audron.dev> | 2026-01-30 18:19:42 +0100 |
| commit | 84e778c6f693027c4f9215eeeda203e36cc19f9a (patch) | |
| tree | 0598fc34cac17c60d6530e0af7f86c8aa48276a6 /src/storage.rs | |
init
Diffstat (limited to 'src/storage.rs')
| -rw-r--r-- | src/storage.rs | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/src/storage.rs b/src/storage.rs new file mode 100644 index 0000000..1055839 --- /dev/null +++ b/src/storage.rs @@ -0,0 +1,60 @@ +use crate::models::Storage; +use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock}; + +pub type SharedStorage = Arc<RwLock<Storage>>; + +pub fn load_storage(path: &Path) -> Result<Storage, Box<dyn std::error::Error>> { + if path.exists() { + let content = fs::read_to_string(path)?; + let storage = serde_json::from_str(&content)?; + Ok(storage) + } else { + Ok(Storage::default()) + } +} + +pub fn watch_storage( + storage_path: PathBuf, + shared_storage: SharedStorage, +) -> Result<(), Box<dyn std::error::Error>> { + let (tx, rx) = std::sync::mpsc::channel::<Result<Event, notify::Error>>(); + + let mut watcher = RecommendedWatcher::new(tx, Config::default())?; + watcher.watch(&storage_path, RecursiveMode::NonRecursive)?; + + tracing::info!("Watching storage file: {:?}", storage_path); + + std::thread::spawn(move || { + let _watcher = watcher; // Keep watcher alive + + for res in rx { + match res { + Ok(event) => { + if event.kind.is_modify() || event.kind.is_create() { + tracing::info!("Storage file changed, reloading..."); + + match load_storage(&storage_path) { + Ok(new_storage) => { + if let Ok(mut storage) = shared_storage.write() { + *storage = new_storage; + tracing::info!("Storage reloaded successfully"); + } else { + tracing::error!("Failed to acquire write lock on storage"); + } + } + Err(e) => { + tracing::error!("Failed to reload storage: {}", e); + } + } + } + } + Err(e) => tracing::error!("Watch error: {:?}", e), + } + } + }); + + Ok(()) +} |
