Skip to main content

gglib_core/ports/
chat_history.rs

1//! Chat history repository port definition.
2//!
3//! This port defines the interface for persisting and retrieving chat
4//! conversations and messages.
5
6use async_trait::async_trait;
7use thiserror::Error;
8
9use crate::domain::chat::{Conversation, ConversationUpdate, Message, NewConversation, NewMessage};
10
11/// Errors that can occur in chat history operations.
12#[derive(Debug, Error)]
13pub enum ChatHistoryError {
14    #[error("Conversation not found: {0}")]
15    ConversationNotFound(i64),
16
17    #[error("Message not found: {0}")]
18    MessageNotFound(i64),
19
20    #[error("Invalid message role: {0}")]
21    InvalidRole(String),
22
23    #[error("Database error: {0}")]
24    Database(String),
25}
26
27/// Port for chat history persistence operations.
28///
29/// This trait defines the interface for storing and retrieving chat
30/// conversations and messages. Implementations handle the actual storage
31/// mechanism (`SQLite`, etc.).
32#[async_trait]
33pub trait ChatHistoryRepository: Send + Sync {
34    /// Create a new conversation.
35    async fn create_conversation(&self, conv: NewConversation) -> Result<i64, ChatHistoryError>;
36
37    /// List all conversations, ordered by most recently updated.
38    async fn list_conversations(&self) -> Result<Vec<Conversation>, ChatHistoryError>;
39
40    /// Get a specific conversation by ID.
41    async fn get_conversation(&self, id: i64) -> Result<Option<Conversation>, ChatHistoryError>;
42
43    /// Update conversation metadata.
44    async fn update_conversation(
45        &self,
46        id: i64,
47        update: ConversationUpdate,
48    ) -> Result<(), ChatHistoryError>;
49
50    /// Delete a conversation and all its messages.
51    async fn delete_conversation(&self, id: i64) -> Result<(), ChatHistoryError>;
52
53    /// Get conversation count.
54    async fn get_conversation_count(&self) -> Result<i64, ChatHistoryError>;
55
56    /// Get all messages for a conversation, ordered chronologically.
57    async fn get_messages(&self, conversation_id: i64) -> Result<Vec<Message>, ChatHistoryError>;
58
59    /// Save a new message and update conversation timestamp.
60    async fn save_message(&self, msg: NewMessage) -> Result<i64, ChatHistoryError>;
61
62    /// Update a message's content and optionally its metadata.
63    async fn update_message(
64        &self,
65        id: i64,
66        content: String,
67        metadata: Option<serde_json::Value>,
68    ) -> Result<(), ChatHistoryError>;
69
70    /// Delete a message and all subsequent messages in the same conversation.
71    /// Returns the number of messages deleted.
72    async fn delete_message_and_subsequent(&self, id: i64) -> Result<i64, ChatHistoryError>;
73
74    /// Get message count for a conversation.
75    async fn get_message_count(&self, conversation_id: i64) -> Result<i64, ChatHistoryError>;
76}