Files
zesdex/crates/zesdex-cms/src/infrastructure/persistence/conversation_repo.rs
T

46 lines
1.6 KiB
Rust
Raw Normal View History

//! JSON filebacked `ConversationRepository`.
//!
//! Path: `<session_dir>/conversation.json`
//!
//! Uses write-then-rename with fsync for crash safety.
use std::path::Path;
use anyhow::{Context, Result};
use zesdex_utils::write_json_atomic;
use crate::domain::conversation::Conversation;
use crate::domain::repository::ConversationRepository;
/// Persists `Conversation` as pretty-printed JSON at `<session_dir>/conversation.json`.
#[derive(Debug, Clone, Default)]
pub struct JsonConversationRepository;
impl JsonConversationRepository {
/// Create a new repository instance.
pub fn new() -> Self {
Self
}
}
impl ConversationRepository for JsonConversationRepository {
fn load(&self, session_dir: &Path) -> Result<Conversation> {
let path = session_dir.join("conversation.json");
let data = std::fs::read_to_string(&path)
.with_context(|| format!("failed to read conversation at '{}'", path.display()))?;
let conv: Conversation = serde_json::from_str(&data)
.with_context(|| format!("failed to parse conversation at '{}'", path.display()))?;
Ok(conv)
}
fn save(&self, session_dir: &Path, conversation: &Conversation) -> Result<()> {
std::fs::create_dir_all(session_dir)
.with_context(|| format!("failed to create session dir '{}'", session_dir.display()))?;
let path = session_dir.join("conversation.json");
write_json_atomic(&path, conversation, None)
.with_context(|| "failed to save conversation")?;
tracing::debug!("conversation saved to '{}'", path.display());
Ok(())
}
}