Skip to main content

oxirs_chat/
persistence_types.rs

1//! Session persistence types, configuration, and data models.
2//!
3//! Sibling module of [`crate::persistence`]. Contains the value-object
4//! definitions used by the storage backend: configuration, persisted
5//! session payloads, conversation state, entity tracking, recovery
6//! descriptors, and persistence statistics.
7
8use serde::{Deserialize, Serialize};
9use std::{
10    collections::HashMap,
11    path::PathBuf,
12    time::{Duration, SystemTime},
13};
14
15use crate::{analytics::ConversationAnalytics, ChatConfig, Message, SessionMetrics};
16
17/// In-memory chat session used by the persistence layer. This is a
18/// reduced view of the full `ChatSession`, suitable for serialising
19/// to disk and re-hydrating later.
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct PersistentChatSession {
22    pub session_id: String,
23    pub config: ChatConfig,
24    pub messages: Vec<Message>,
25    pub created_at: SystemTime,
26    pub last_accessed: SystemTime,
27    pub metrics: SessionMetrics,
28    pub user_preferences: HashMap<String, serde_json::Value>,
29}
30
31/// Configuration for session persistence.
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct PersistenceConfig {
34    pub enabled: bool,
35    pub storage_path: PathBuf,
36    pub backup_path: PathBuf,
37    pub auto_save_interval: Duration,
38    pub session_ttl: Duration,
39    pub max_sessions: usize,
40    pub compression_enabled: bool,
41    pub encryption_enabled: bool,
42    /// Base64-encoded encryption key. Required when
43    /// [`Self::encryption_enabled`] is `true`.
44    pub encryption_key: Option<String>,
45    pub backup_retention_days: usize,
46    pub checkpoint_interval: Duration,
47}
48
49impl Default for PersistenceConfig {
50    fn default() -> Self {
51        Self {
52            enabled: true,
53            storage_path: PathBuf::from("data/sessions"),
54            backup_path: PathBuf::from("data/backups"),
55            auto_save_interval: Duration::from_secs(60), // Save every minute
56            session_ttl: Duration::from_secs(86400 * 7), // 7 days
57            max_sessions: 10000,
58            compression_enabled: true,
59            encryption_enabled: false, // Can be enabled by providing encryption_key
60            encryption_key: None,      // Should be set via environment variable or config
61            backup_retention_days: 30,
62            checkpoint_interval: Duration::from_secs(300), // Checkpoint every 5 minutes
63        }
64    }
65}
66
67/// Serializable session data for persistence.
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct PersistedSession {
70    pub session_id: String,
71    pub config: ChatConfig,
72    pub messages: Vec<Message>,
73    pub created_at: SystemTime,
74    pub last_accessed: SystemTime,
75    pub metrics: SessionMetrics,
76    pub analytics: Option<ConversationAnalytics>,
77    pub user_preferences: HashMap<String, serde_json::Value>,
78    pub conversation_state: ConversationState,
79    pub checksum: String,
80}
81
82/// Wrapper for persisted session with dirty flag tracking.
83#[derive(Debug, Clone)]
84pub struct SessionWithDirtyFlag {
85    pub session: PersistedSession,
86    pub dirty: bool,
87    pub last_saved: Option<SystemTime>,
88}
89
90/// Conversation state for advanced context management.
91#[derive(Debug, Clone, Serialize, Deserialize, Default)]
92pub struct ConversationState {
93    pub current_topic: Option<String>,
94    /// Message IDs in current context.
95    pub context_window: Vec<String>,
96    pub entity_history: Vec<EntityReference>,
97    pub query_history: Vec<QueryContext>,
98    pub user_intent_history: Vec<String>,
99    pub conversation_flow: ConversationFlow,
100}
101
102/// Entity reference for tracking.
103#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct EntityReference {
105    pub entity_uri: String,
106    pub entity_label: String,
107    pub first_mentioned: SystemTime,
108    pub mention_count: usize,
109    pub last_context: String,
110}
111
112/// Query context for tracking.
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct QueryContext {
115    pub sparql_query: String,
116    pub natural_language: String,
117    pub intent: String,
118    pub success: bool,
119    pub timestamp: SystemTime,
120    pub execution_time_ms: u64,
121}
122
123/// Conversation flow tracking.
124#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct ConversationFlow {
126    pub current_phase: ConversationPhase,
127    pub topic_transitions: Vec<TopicTransition>,
128    pub interaction_patterns: Vec<InteractionPattern>,
129    pub complexity_level: f32,
130}
131
132impl Default for ConversationFlow {
133    fn default() -> Self {
134        Self {
135            current_phase: ConversationPhase::Introduction,
136            topic_transitions: Vec::new(),
137            interaction_patterns: Vec::new(),
138            complexity_level: 1.0,
139        }
140    }
141}
142
143/// Conversation phases.
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub enum ConversationPhase {
146    Introduction,
147    Exploration,
148    DeepDive,
149    Analysis,
150    Conclusion,
151    Abandoned,
152}
153
154/// Topic transitions.
155#[derive(Debug, Clone, Serialize, Deserialize)]
156pub struct TopicTransition {
157    pub from_topic: Option<String>,
158    pub to_topic: String,
159    pub transition_type: TransitionType,
160    pub timestamp: SystemTime,
161    pub confidence: f32,
162}
163
164/// Transition types.
165#[derive(Debug, Clone, Serialize, Deserialize)]
166pub enum TransitionType {
167    /// Logical progression.
168    Natural,
169    /// User changed topic.
170    UserInitiated,
171    /// Seeking clarification.
172    Clarification,
173    /// Side topic.
174    Digression,
175    /// Back to previous topic.
176    Return,
177}
178
179/// Interaction patterns.
180#[derive(Debug, Clone, Serialize, Deserialize)]
181pub struct InteractionPattern {
182    pub pattern_type: InteractionType,
183    pub frequency: usize,
184    pub last_occurrence: SystemTime,
185    pub effectiveness: f32,
186}
187
188/// Interaction types.
189#[derive(Debug, Clone, Serialize, Deserialize)]
190pub enum InteractionType {
191    QuestionAnswer,
192    ExploratorySearch,
193    ComparativeAnalysis,
194    DeepInvestigation,
195    QuickLookup,
196    IterativeRefinement,
197}
198
199/// Session recovery information.
200#[derive(Debug, Clone, Serialize, Deserialize)]
201pub struct RecoveryInfo {
202    pub session_id: String,
203    pub last_checkpoint: SystemTime,
204    pub backup_available: bool,
205    pub corruption_detected: bool,
206    pub recovery_strategies: Vec<RecoveryStrategy>,
207}
208
209/// Recovery strategies.
210#[derive(Debug, Clone, Serialize, Deserialize)]
211pub enum RecoveryStrategy {
212    LoadFromCheckpoint,
213    LoadFromBackup,
214    PartialRecovery,
215    CreateNew,
216}
217
218/// Persistence statistics.
219#[derive(Debug, Default, Clone, Serialize, Deserialize)]
220pub struct PersistenceStats {
221    pub total_sessions_saved: usize,
222    pub total_sessions_loaded: usize,
223    pub save_failures: usize,
224    pub load_failures: usize,
225    pub recovery_operations: usize,
226    pub corrupted_sessions: usize,
227    pub total_backup_size: u64,
228    pub average_save_time_ms: f64,
229    pub average_load_time_ms: f64,
230}
231
232/// Session information for listing.
233#[derive(Debug, Clone, Serialize, Deserialize)]
234pub struct SessionInfo {
235    pub session_id: String,
236    pub created_at: SystemTime,
237    pub modified_at: SystemTime,
238    pub size_bytes: u64,
239    pub has_backup: bool,
240}