Skip to main content

oxirs_chat/
session_store.rs

1//! Chat session persistence and retrieval.
2//!
3//! Provides an in-memory store for managing chat sessions with
4//! capacity-bounded eviction of the oldest session.
5
6use std::collections::HashMap;
7
8/// The role of a message participant.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum MessageRole {
11    /// A message from the user.
12    User,
13    /// A message from the assistant.
14    Assistant,
15    /// A system-level instruction message.
16    System,
17}
18
19/// A single chat message.
20#[derive(Debug, Clone, PartialEq)]
21pub struct ChatMessage {
22    /// Role of the sender.
23    pub role: MessageRole,
24    /// Text content of the message.
25    pub content: String,
26    /// Wall-clock timestamp in milliseconds since Unix epoch.
27    pub timestamp_ms: u64,
28}
29
30/// A chat session containing ordered messages.
31#[derive(Debug, Clone)]
32pub struct ChatSession {
33    /// Unique session identifier.
34    pub session_id: String,
35    /// Ordered list of messages in this session.
36    pub messages: Vec<ChatMessage>,
37    /// Timestamp (ms) when the session was created.
38    pub created_ms: u64,
39    /// Timestamp (ms) when the session was last updated.
40    pub last_updated_ms: u64,
41    /// Arbitrary key-value metadata for this session.
42    pub metadata: HashMap<String, String>,
43}
44
45impl ChatSession {
46    /// Create a new empty session.
47    pub fn new(session_id: &str, now_ms: u64) -> Self {
48        Self {
49            session_id: session_id.to_string(),
50            messages: Vec::new(),
51            created_ms: now_ms,
52            last_updated_ms: now_ms,
53            metadata: HashMap::new(),
54        }
55    }
56
57    /// Append a message to this session, updating `last_updated_ms`.
58    pub fn add_message(&mut self, role: MessageRole, content: &str, now_ms: u64) {
59        self.messages.push(ChatMessage {
60            role,
61            content: content.to_string(),
62            timestamp_ms: now_ms,
63        });
64        self.last_updated_ms = now_ms;
65    }
66
67    /// Return the total number of messages in this session.
68    pub fn message_count(&self) -> usize {
69        self.messages.len()
70    }
71
72    /// Return the most recent message, or `None` if the session is empty.
73    pub fn last_message(&self) -> Option<&ChatMessage> {
74        self.messages.last()
75    }
76
77    /// Return all messages with the given role.
78    pub fn messages_by_role(&self, role: &MessageRole) -> Vec<&ChatMessage> {
79        self.messages.iter().filter(|m| &m.role == role).collect()
80    }
81}
82
83/// In-memory store for chat sessions with capacity-bounded eviction.
84///
85/// When the store is at capacity and a new session is created, the session
86/// with the smallest `created_ms` (oldest) is evicted.
87pub struct SessionStore {
88    sessions: HashMap<String, ChatSession>,
89    max_sessions: usize,
90}
91
92impl SessionStore {
93    /// Create a new store with the given maximum number of sessions.
94    ///
95    /// `max_sessions` must be at least 1; passing 0 is treated as 1.
96    pub fn new(max_sessions: usize) -> Self {
97        let cap = max_sessions.max(1);
98        Self {
99            sessions: HashMap::new(),
100            max_sessions: cap,
101        }
102    }
103
104    /// Create a new session and insert it into the store.
105    ///
106    /// If the store is at capacity, the oldest session is evicted first.
107    /// Returns a reference to the newly created session.
108    pub fn create(&mut self, session_id: &str, now_ms: u64) -> &ChatSession {
109        if self.sessions.len() >= self.max_sessions {
110            if let Some(oldest_id) = self.oldest_session_id().map(str::to_string) {
111                self.sessions.remove(&oldest_id);
112            }
113        }
114        let session = ChatSession::new(session_id, now_ms);
115        self.sessions.insert(session_id.to_string(), session);
116        // Safety: we just inserted the key.
117        self.sessions
118            .get(session_id)
119            .expect("session just inserted")
120    }
121
122    /// Return an immutable reference to a session by ID.
123    pub fn get(&self, session_id: &str) -> Option<&ChatSession> {
124        self.sessions.get(session_id)
125    }
126
127    /// Return a mutable reference to a session by ID.
128    pub fn get_mut(&mut self, session_id: &str) -> Option<&mut ChatSession> {
129        self.sessions.get_mut(session_id)
130    }
131
132    /// Remove a session from the store. Returns `true` if it existed.
133    pub fn delete(&mut self, session_id: &str) -> bool {
134        self.sessions.remove(session_id).is_some()
135    }
136
137    /// Return all session IDs currently in the store.
138    pub fn list_ids(&self) -> Vec<&str> {
139        self.sessions.keys().map(String::as_str).collect()
140    }
141
142    /// Return the number of sessions currently in the store.
143    pub fn count(&self) -> usize {
144        self.sessions.len()
145    }
146
147    /// Return the ID of the oldest session (smallest `created_ms`), or `None` if empty.
148    pub fn oldest_session_id(&self) -> Option<&str> {
149        self.sessions
150            .iter()
151            .min_by_key(|(_, s)| s.created_ms)
152            .map(|(id, _)| id.as_str())
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    fn store(max: usize) -> SessionStore {
161        SessionStore::new(max)
162    }
163
164    // --- ChatSession ---
165
166    #[test]
167    fn test_session_new_empty() {
168        let s = ChatSession::new("s1", 1000);
169        assert_eq!(s.session_id, "s1");
170        assert!(s.messages.is_empty());
171        assert_eq!(s.created_ms, 1000);
172        assert_eq!(s.last_updated_ms, 1000);
173    }
174
175    #[test]
176    fn test_session_add_message_increments_count() {
177        let mut s = ChatSession::new("s1", 1000);
178        s.add_message(MessageRole::User, "Hello", 1001);
179        assert_eq!(s.message_count(), 1);
180    }
181
182    #[test]
183    fn test_session_add_message_updates_last_updated() {
184        let mut s = ChatSession::new("s1", 1000);
185        s.add_message(MessageRole::User, "Hello", 2000);
186        assert_eq!(s.last_updated_ms, 2000);
187    }
188
189    #[test]
190    fn test_session_message_content_preserved() {
191        let mut s = ChatSession::new("s1", 1000);
192        s.add_message(MessageRole::Assistant, "How can I help?", 1001);
193        assert_eq!(s.messages[0].content, "How can I help?");
194    }
195
196    #[test]
197    fn test_session_message_role_preserved() {
198        let mut s = ChatSession::new("s1", 1000);
199        s.add_message(MessageRole::System, "Init", 1001);
200        assert_eq!(s.messages[0].role, MessageRole::System);
201    }
202
203    #[test]
204    fn test_session_message_count_multiple() {
205        let mut s = ChatSession::new("s1", 1000);
206        s.add_message(MessageRole::User, "a", 1001);
207        s.add_message(MessageRole::Assistant, "b", 1002);
208        s.add_message(MessageRole::User, "c", 1003);
209        assert_eq!(s.message_count(), 3);
210    }
211
212    #[test]
213    fn test_session_last_message_none_when_empty() {
214        let s = ChatSession::new("s1", 1000);
215        assert!(s.last_message().is_none());
216    }
217
218    #[test]
219    fn test_session_last_message_returns_last() {
220        let mut s = ChatSession::new("s1", 1000);
221        s.add_message(MessageRole::User, "first", 1001);
222        s.add_message(MessageRole::Assistant, "second", 1002);
223        let last = s.last_message().expect("should have last");
224        assert_eq!(last.content, "second");
225    }
226
227    #[test]
228    fn test_session_messages_by_role_user() {
229        let mut s = ChatSession::new("s1", 1000);
230        s.add_message(MessageRole::User, "u1", 1001);
231        s.add_message(MessageRole::Assistant, "a1", 1002);
232        s.add_message(MessageRole::User, "u2", 1003);
233        let user_msgs = s.messages_by_role(&MessageRole::User);
234        assert_eq!(user_msgs.len(), 2);
235    }
236
237    #[test]
238    fn test_session_messages_by_role_none_match() {
239        let mut s = ChatSession::new("s1", 1000);
240        s.add_message(MessageRole::User, "u1", 1001);
241        let sys_msgs = s.messages_by_role(&MessageRole::System);
242        assert!(sys_msgs.is_empty());
243    }
244
245    #[test]
246    fn test_session_metadata_insert() {
247        let mut s = ChatSession::new("s1", 1000);
248        s.metadata.insert("key".to_string(), "value".to_string());
249        assert_eq!(s.metadata.get("key").map(String::as_str), Some("value"));
250    }
251
252    // --- SessionStore ---
253
254    #[test]
255    fn test_store_create_and_get() {
256        let mut st = store(10);
257        st.create("s1", 1000);
258        assert!(st.get("s1").is_some());
259    }
260
261    #[test]
262    fn test_store_get_nonexistent() {
263        let st = store(10);
264        assert!(st.get("missing").is_none());
265    }
266
267    #[test]
268    fn test_store_count_after_create() {
269        let mut st = store(10);
270        st.create("s1", 1000);
271        st.create("s2", 1001);
272        assert_eq!(st.count(), 2);
273    }
274
275    #[test]
276    fn test_store_delete_existing() {
277        let mut st = store(10);
278        st.create("s1", 1000);
279        assert!(st.delete("s1"));
280        assert!(st.get("s1").is_none());
281    }
282
283    #[test]
284    fn test_store_delete_nonexistent() {
285        let mut st = store(10);
286        assert!(!st.delete("missing"));
287    }
288
289    #[test]
290    fn test_store_count_after_delete() {
291        let mut st = store(10);
292        st.create("s1", 1000);
293        st.create("s2", 1001);
294        st.delete("s1");
295        assert_eq!(st.count(), 1);
296    }
297
298    #[test]
299    fn test_store_list_ids_contains_all() {
300        let mut st = store(10);
301        st.create("a", 1000);
302        st.create("b", 1001);
303        let ids = st.list_ids();
304        assert_eq!(ids.len(), 2);
305        assert!(ids.contains(&"a"));
306        assert!(ids.contains(&"b"));
307    }
308
309    #[test]
310    fn test_store_list_ids_empty() {
311        let st = store(10);
312        assert!(st.list_ids().is_empty());
313    }
314
315    #[test]
316    fn test_store_get_mut_allows_modification() {
317        let mut st = store(10);
318        st.create("s1", 1000);
319        {
320            let session = st.get_mut("s1").expect("exists");
321            session.add_message(MessageRole::User, "hello", 1001);
322        }
323        let session = st.get("s1").expect("exists");
324        assert_eq!(session.message_count(), 1);
325    }
326
327    #[test]
328    fn test_store_get_mut_nonexistent() {
329        let mut st = store(10);
330        assert!(st.get_mut("missing").is_none());
331    }
332
333    #[test]
334    fn test_store_oldest_session_id_none_when_empty() {
335        let st = store(10);
336        assert!(st.oldest_session_id().is_none());
337    }
338
339    #[test]
340    fn test_store_oldest_session_id_single() {
341        let mut st = store(10);
342        st.create("s1", 1000);
343        assert_eq!(st.oldest_session_id(), Some("s1"));
344    }
345
346    #[test]
347    fn test_store_oldest_session_id_multiple() {
348        let mut st = store(10);
349        st.create("newer", 2000);
350        st.create("oldest", 500);
351        st.create("middle", 1000);
352        assert_eq!(st.oldest_session_id(), Some("oldest"));
353    }
354
355    #[test]
356    fn test_store_max_sessions_eviction() {
357        let mut st = store(2);
358        st.create("first", 100);
359        st.create("second", 200);
360        // At capacity; inserting "third" should evict "first" (oldest)
361        st.create("third", 300);
362        assert_eq!(st.count(), 2);
363        assert!(st.get("first").is_none(), "oldest should be evicted");
364        assert!(st.get("second").is_some());
365        assert!(st.get("third").is_some());
366    }
367
368    #[test]
369    fn test_store_max_sessions_one() {
370        let mut st = store(1);
371        st.create("a", 100);
372        st.create("b", 200);
373        assert_eq!(st.count(), 1);
374        assert!(st.get("b").is_some());
375    }
376
377    #[test]
378    fn test_store_max_sessions_zero_treated_as_one() {
379        let mut st = store(0);
380        st.create("a", 100);
381        st.create("b", 200);
382        assert_eq!(st.count(), 1);
383    }
384
385    #[test]
386    fn test_store_created_session_has_correct_id() {
387        let mut st = store(10);
388        let s = st.create("my_session", 5000);
389        assert_eq!(s.session_id, "my_session");
390    }
391
392    #[test]
393    fn test_store_created_session_timestamp() {
394        let mut st = store(10);
395        let s = st.create("s1", 9999);
396        assert_eq!(s.created_ms, 9999);
397    }
398
399    #[test]
400    fn test_message_role_eq() {
401        assert_eq!(MessageRole::User, MessageRole::User);
402        assert_ne!(MessageRole::User, MessageRole::Assistant);
403    }
404
405    #[test]
406    fn test_message_role_clone() {
407        let role = MessageRole::System;
408        let cloned = role.clone();
409        assert_eq!(role, cloned);
410    }
411
412    #[test]
413    fn test_chat_message_clone() {
414        let msg = ChatMessage {
415            role: MessageRole::User,
416            content: "test".to_string(),
417            timestamp_ms: 12345,
418        };
419        let cloned = msg.clone();
420        assert_eq!(cloned.content, "test");
421        assert_eq!(cloned.timestamp_ms, 12345);
422    }
423
424    #[test]
425    fn test_session_add_multiple_roles() {
426        let mut s = ChatSession::new("multi", 0);
427        s.add_message(MessageRole::System, "system init", 1);
428        s.add_message(MessageRole::User, "user msg", 2);
429        s.add_message(MessageRole::Assistant, "assistant reply", 3);
430        assert_eq!(s.messages_by_role(&MessageRole::System).len(), 1);
431        assert_eq!(s.messages_by_role(&MessageRole::User).len(), 1);
432        assert_eq!(s.messages_by_role(&MessageRole::Assistant).len(), 1);
433    }
434}