2026-07-16 12:32:17 +07:00
|
|
|
//! Conversation use-case implementations.
|
|
|
|
|
//!
|
|
|
|
|
//! `ConversationServiceImpl` is generic over `R: ConversationRepository`,
|
|
|
|
|
//! delegating all persistence to that adapter.
|
|
|
|
|
|
|
|
|
|
use anyhow::{Context, Result};
|
|
|
|
|
|
|
|
|
|
use crate::domain::conversation::{ChatMessage, Conversation};
|
|
|
|
|
use crate::domain::repository::ConversationRepository;
|
|
|
|
|
use crate::domain::service::ConversationService;
|
|
|
|
|
|
|
|
|
|
/// Generic conversation service backed by an injected repository.
|
|
|
|
|
pub struct ConversationServiceImpl<R> {
|
|
|
|
|
pub repo: R,
|
|
|
|
|
pub sessions_dir: std::path::PathBuf,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<R: ConversationRepository> ConversationServiceImpl<R> {
|
|
|
|
|
/// Create a new service with the given repository and sessions directory.
|
|
|
|
|
pub fn new(repo: R, sessions_dir: impl Into<std::path::PathBuf>) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
repo,
|
|
|
|
|
sessions_dir: sessions_dir.into(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Compute the session directory for a given session id.
|
|
|
|
|
fn session_dir(&self, session_id: &str) -> std::path::PathBuf {
|
|
|
|
|
self.sessions_dir.join(session_id)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<R: ConversationRepository> ConversationService for ConversationServiceImpl<R> {
|
|
|
|
|
fn load_conversation(&self, session_id: &str) -> Result<Conversation> {
|
|
|
|
|
let dir = self.session_dir(session_id);
|
|
|
|
|
self.repo
|
|
|
|
|
.load(&dir)
|
|
|
|
|
.with_context(|| format!("failed to load conversation for session '{session_id}'"))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn save_conversation(&self, conv: &Conversation) -> Result<()> {
|
|
|
|
|
let dir = self.session_dir(&conv.session_id);
|
2026-07-17 06:44:31 +07:00
|
|
|
self.repo.save(&dir, conv).with_context(|| {
|
|
|
|
|
format!(
|
|
|
|
|
"failed to save conversation for session '{}'",
|
|
|
|
|
conv.session_id
|
|
|
|
|
)
|
|
|
|
|
})
|
2026-07-16 12:32:17 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn add_message(&self, conv: &mut Conversation, msg: ChatMessage) -> Result<()> {
|
|
|
|
|
conv.push(msg);
|
|
|
|
|
let dir = self.session_dir(&conv.session_id);
|
2026-07-17 06:44:31 +07:00
|
|
|
self.repo.save(&dir, conv).with_context(|| {
|
|
|
|
|
format!(
|
|
|
|
|
"failed to persist conversation after adding message for session '{}'",
|
|
|
|
|
conv.session_id
|
|
|
|
|
)
|
|
|
|
|
})
|
2026-07-16 12:32:17 +07:00
|
|
|
}
|
|
|
|
|
}
|