feat(infra): implement atomic state store and append-only history log
- Implement JsonStateRepository using atomic write-to-temp and rename pattern - Implement JsonlHistoryRepository appending serialized records with data sync - Add unit tests verifying default fallback, atomic updates, and JSONL integrity
This commit is contained in:
1 parent
cbe4b61619
commit
fbc434478d
4 files changed
+232
No files matched your search
@@ -0,0 +1,56 @@
|
|||||||
|
use std::fs::{self, OpenOptions};
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use crate::domain::errors::HistoryError;
|
||||||
|
use crate::domain::models::HistoryEntry;
|
||||||
|
use crate::domain::traits::HistoryRepository;
|
||||||
|
|
||||||
|
/// Persists an append-only JSONL execution history log.
|
||||||
|
pub struct JsonlHistoryRepository {
|
||||||
|
path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl JsonlHistoryRepository {
|
||||||
|
pub fn new<P: AsRef<Path>>(path: P) -> Self {
|
||||||
|
Self {
|
||||||
|
path: path.as_ref().to_path_buf(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HistoryRepository for JsonlHistoryRepository {
|
||||||
|
fn append(&self, entry: &HistoryEntry) -> Result<(), HistoryError> {
|
||||||
|
let parent = self.path.parent().unwrap_or_else(|| Path::new("."));
|
||||||
|
fs::create_dir_all(parent).map_err(|source| HistoryError::Io {
|
||||||
|
path: parent.display().to_string(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let mut line = serde_json::to_string(entry)?;
|
||||||
|
line.push('\n');
|
||||||
|
|
||||||
|
let mut file = OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.append(true)
|
||||||
|
.open(&self.path)
|
||||||
|
.map_err(|source| HistoryError::Io {
|
||||||
|
path: self.path.display().to_string(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
|
||||||
|
file.write_all(line.as_bytes())
|
||||||
|
.map_err(|source| HistoryError::Io {
|
||||||
|
path: self.path.display().to_string(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
|
||||||
|
file.sync_data().map_err(|source| HistoryError::Io {
|
||||||
|
path: self.path.display().to_string(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
|
||||||
|
log::debug!("Appended record to history log '{}'", self.path.display());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1 +1,3 @@
|
|||||||
|
pub mod history_store;
|
||||||
pub mod http_resolver;
|
pub mod http_resolver;
|
||||||
|
pub mod state_store;
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
use std::fs::{self, File};
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use crate::domain::errors::StateError;
|
||||||
|
use crate::domain::models::MonitorState;
|
||||||
|
use crate::domain::traits::StateRepository;
|
||||||
|
|
||||||
|
/// Persists monitor state to a local JSON file using atomic rename writes.
|
||||||
|
pub struct JsonStateRepository {
|
||||||
|
path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl JsonStateRepository {
|
||||||
|
pub fn new<P: AsRef<Path>>(path: P) -> Self {
|
||||||
|
Self {
|
||||||
|
path: path.as_ref().to_path_buf(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StateRepository for JsonStateRepository {
|
||||||
|
fn load(&self) -> Result<MonitorState, StateError> {
|
||||||
|
if !self.path.exists() {
|
||||||
|
log::debug!(
|
||||||
|
"State file '{}' does not exist; returning default empty state",
|
||||||
|
self.path.display()
|
||||||
|
);
|
||||||
|
return Ok(MonitorState::default());
|
||||||
|
}
|
||||||
|
|
||||||
|
let content = fs::read_to_string(&self.path).map_err(|source| StateError::Io {
|
||||||
|
path: self.path.display().to_string(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let state = serde_json::from_str(&content)?;
|
||||||
|
Ok(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self, state: &MonitorState) -> Result<(), StateError> {
|
||||||
|
let parent = self.path.parent().unwrap_or_else(|| Path::new("."));
|
||||||
|
fs::create_dir_all(parent).map_err(|source| StateError::Io {
|
||||||
|
path: parent.display().to_string(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let json_bytes = serde_json::to_vec_pretty(state)?;
|
||||||
|
|
||||||
|
// Write to temporary file in the same directory, then atomically rename
|
||||||
|
let pid = std::process::id();
|
||||||
|
let tmp_path = self.path.with_extension(format!("tmp.{}", pid));
|
||||||
|
|
||||||
|
let mut file = File::create(&tmp_path).map_err(|source| StateError::Io {
|
||||||
|
path: tmp_path.display().to_string(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
|
||||||
|
file.write_all(&json_bytes).map_err(|source| StateError::Io {
|
||||||
|
path: tmp_path.display().to_string(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
|
||||||
|
file.sync_all().map_err(|source| StateError::Io {
|
||||||
|
path: tmp_path.display().to_string(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
|
||||||
|
fs::rename(&tmp_path, &self.path).map_err(|source| StateError::Io {
|
||||||
|
path: self.path.display().to_string(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
|
||||||
|
log::debug!("Atomically saved state to '{}'", self.path.display());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
use ddns_monitor::domain::models::{HistoryEntry, MonitorState, SubscriberResult};
|
||||||
|
use ddns_monitor::domain::traits::{HistoryRepository, StateRepository};
|
||||||
|
use ddns_monitor::infra::history_store::JsonlHistoryRepository;
|
||||||
|
use ddns_monitor::infra::state_store::JsonStateRepository;
|
||||||
|
use std::fs;
|
||||||
|
use std::net::Ipv4Addr;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_state_repo_load_nonexistent_returns_default() {
|
||||||
|
let tmp_dir = std::env::temp_dir().join("ddns_test_nonexistent");
|
||||||
|
let state_file = tmp_dir.join("state.json");
|
||||||
|
let _ = fs::remove_file(&state_file);
|
||||||
|
|
||||||
|
let repo = JsonStateRepository::new(state_file);
|
||||||
|
let state = repo.load().expect("load default state");
|
||||||
|
|
||||||
|
assert_eq!(state, MonitorState::default());
|
||||||
|
assert_eq!(state.last_ip, None);
|
||||||
|
assert_eq!(state.last_provider_index, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_state_repo_atomic_save_and_load() {
|
||||||
|
let tmp_dir = std::env::temp_dir().join("ddns_test_save_load");
|
||||||
|
let state_file = tmp_dir.join("state.json");
|
||||||
|
let _ = fs::remove_dir_all(&tmp_dir);
|
||||||
|
|
||||||
|
let repo = JsonStateRepository::new(state_file.clone());
|
||||||
|
|
||||||
|
let state = MonitorState {
|
||||||
|
last_provider_index: Some(2),
|
||||||
|
last_ip: Some(Ipv4Addr::new(93, 184, 216, 34)),
|
||||||
|
};
|
||||||
|
|
||||||
|
repo.save(&state).expect("save state");
|
||||||
|
assert!(state_file.exists());
|
||||||
|
|
||||||
|
let loaded = repo.load().expect("load state");
|
||||||
|
assert_eq!(state, loaded);
|
||||||
|
|
||||||
|
// Save update
|
||||||
|
let updated = MonitorState {
|
||||||
|
last_provider_index: Some(0),
|
||||||
|
last_ip: Some(Ipv4Addr::new(198, 51, 100, 1)),
|
||||||
|
};
|
||||||
|
repo.save(&updated).expect("update state");
|
||||||
|
let loaded_updated = repo.load().expect("load updated state");
|
||||||
|
assert_eq!(updated, loaded_updated);
|
||||||
|
|
||||||
|
let _ = fs::remove_dir_all(&tmp_dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_history_repo_append_and_verify() {
|
||||||
|
let tmp_dir = std::env::temp_dir().join("ddns_test_history");
|
||||||
|
let history_file = tmp_dir.join("history.jsonl");
|
||||||
|
let _ = fs::remove_dir_all(&tmp_dir);
|
||||||
|
|
||||||
|
let repo = JsonlHistoryRepository::new(history_file.clone());
|
||||||
|
|
||||||
|
let entry1 = HistoryEntry {
|
||||||
|
timestamp: "2026-10-27T12:00:00Z".to_string(),
|
||||||
|
ip: Ipv4Addr::new(93, 184, 216, 34),
|
||||||
|
status: "success".to_string(),
|
||||||
|
subscribers: vec![SubscriberResult {
|
||||||
|
provider: "dynu".to_string(),
|
||||||
|
success: true,
|
||||||
|
error: None,
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
|
||||||
|
let entry2 = HistoryEntry {
|
||||||
|
timestamp: "2026-10-27T12:30:00Z".to_string(),
|
||||||
|
ip: Ipv4Addr::new(198, 51, 100, 1),
|
||||||
|
status: "partial".to_string(),
|
||||||
|
subscribers: vec![SubscriberResult {
|
||||||
|
provider: "dynu".to_string(),
|
||||||
|
success: false,
|
||||||
|
error: Some("Timeout".to_string()),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
|
||||||
|
repo.append(&entry1).expect("append entry 1");
|
||||||
|
repo.append(&entry2).expect("append entry 2");
|
||||||
|
|
||||||
|
let content = fs::read_to_string(&history_file).expect("read history file");
|
||||||
|
let lines: Vec<&str> = content.lines().collect();
|
||||||
|
assert_eq!(lines.len(), 2);
|
||||||
|
|
||||||
|
let parsed1: HistoryEntry = serde_json::from_str(lines[0]).expect("parse line 1");
|
||||||
|
let parsed2: HistoryEntry = serde_json::from_str(lines[1]).expect("parse line 2");
|
||||||
|
|
||||||
|
assert_eq!(parsed1, entry1);
|
||||||
|
assert_eq!(parsed2, entry2);
|
||||||
|
|
||||||
|
let _ = fs::remove_dir_all(&tmp_dir);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user