1use std::{
8 collections::HashMap,
9 fs,
10 path::Path,
11 str::FromStr,
12 sync::{Arc, Mutex, MutexGuard},
13};
14
15use agent_runtime::Message;
16use chrono::{DateTime, Utc};
17use rusqlite::{Connection, OptionalExtension, params};
18
19use crate::{Conversation, ConversationId, ConversationStoreError, FamilyId};
20
21#[derive(Clone)]
22pub struct SqliteConversationStore {
23 connection: Arc<Mutex<Connection>>,
24}
25
26impl SqliteConversationStore {
27 pub fn open(path: impl AsRef<Path>) -> Result<Self, ConversationStoreError> {
29 let connection = Connection::open(path).map_err(sqlite_error)?;
30 connection
31 .busy_timeout(std::time::Duration::from_secs(5))
32 .map_err(sqlite_error)?;
33 connection
34 .execute_batch("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL;")
35 .map_err(sqlite_error)?;
36 connection
37 .execute_batch(include_str!("../migrations/0006_conversations.sql"))
38 .map_err(sqlite_error)?;
39 Ok(Self {
40 connection: Arc::new(Mutex::new(connection)),
41 })
42 }
43
44 pub fn create(
45 &self,
46 owner: impl Into<String>,
47 agent: impl Into<String>,
48 ) -> Result<Conversation, ConversationStoreError> {
49 let owner = owner.into();
50 let agent = agent.into();
51 if owner.trim().is_empty() {
52 return Err(ConversationStoreError::EmptyOwner);
53 }
54 if agent.trim().is_empty() {
55 return Err(ConversationStoreError::EmptyAgent);
56 }
57
58 let now = Utc::now();
59 let conversation = Conversation {
60 id: ConversationId::new(),
61 owner: owner.clone(),
62 agent,
63 title: "New conversation".to_owned(),
64 archived: false,
65 selected_family_id: None,
66 created_at: now,
67 updated_at: now,
68 messages: Vec::new(),
69 };
70 let mut connection = self.lock();
71 let tx = connection.transaction().map_err(sqlite_error)?;
72 tx.execute(
73 "INSERT INTO conversations(id, owner, agent, title, archived, selected_family_id, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, 0, NULL, ?5, ?5)",
74 params![
75 conversation.id.to_string(),
76 owner,
77 conversation.agent,
78 conversation.title,
79 now.to_rfc3339()
80 ],
81 )
82 .map_err(sqlite_error)?;
83 tx.execute(
84 "INSERT INTO active_conversations(owner, conversation_id) VALUES (?1, ?2) ON CONFLICT(owner) DO UPDATE SET conversation_id = excluded.conversation_id",
85 params![conversation.owner, conversation.id.to_string()],
86 )
87 .map_err(sqlite_error)?;
88 tx.commit().map_err(sqlite_error)?;
89 Ok(conversation)
90 }
91
92 pub fn active(&self, owner: &str) -> Result<Option<Conversation>, ConversationStoreError> {
93 let connection = self.lock();
94 let id: Option<String> = connection
95 .query_row(
96 "SELECT conversation_id FROM active_conversations WHERE owner = ?1",
97 [owner],
98 |row| row.get(0),
99 )
100 .optional()
101 .map_err(sqlite_error)?;
102 id.map(|id| {
103 self.load(
104 &connection,
105 ConversationId::from_str(&id)
106 .map_err(|error| ConversationStoreError::Sqlite(error.to_string()))?,
107 )
108 })
109 .transpose()
110 }
111
112 pub fn list(&self, owner: &str) -> Result<Vec<Conversation>, ConversationStoreError> {
114 self.list_with_archive_state(owner, false)
115 }
116
117 pub fn list_archived(&self, owner: &str) -> Result<Vec<Conversation>, ConversationStoreError> {
119 self.list_with_archive_state(owner, true)
120 }
121
122 fn list_with_archive_state(
123 &self,
124 owner: &str,
125 archived: bool,
126 ) -> Result<Vec<Conversation>, ConversationStoreError> {
127 let connection = self.lock();
128 let mut statement = connection
129 .prepare(
130 "SELECT id FROM conversations WHERE owner = ?1 AND archived = ?2 ORDER BY updated_at DESC, id DESC",
131 )
132 .map_err(sqlite_error)?;
133 let ids = statement
134 .query_map(params![owner, archived], |row| row.get::<_, String>(0))
135 .map_err(sqlite_error)?;
136 let mut result = Vec::new();
137 for id in ids {
138 let id = ConversationId::from_str(&id.map_err(sqlite_error)?)
139 .map_err(|error| ConversationStoreError::Sqlite(error.to_string()))?;
140 result.push(self.load(&connection, id)?);
141 }
142 Ok(result)
143 }
144
145 pub fn set_active(
146 &self,
147 owner: &str,
148 id: ConversationId,
149 ) -> Result<(), ConversationStoreError> {
150 let mut connection = self.lock();
151 let tx = connection.transaction().map_err(sqlite_error)?;
152 let actual_owner: Option<String> = tx
153 .query_row(
154 "SELECT owner FROM conversations WHERE id = ?1",
155 [id.to_string()],
156 |row| row.get(0),
157 )
158 .optional()
159 .map_err(sqlite_error)?;
160 match actual_owner {
161 None => return Err(ConversationStoreError::NotFound(id)),
162 Some(actual) if actual != owner => {
163 return Err(ConversationStoreError::OwnerMismatch {
164 conversation_id: id,
165 owner: owner.to_owned(),
166 });
167 }
168 _ => {}
169 }
170 tx.execute(
171 "INSERT INTO active_conversations(owner, conversation_id) VALUES (?1, ?2) ON CONFLICT(owner) DO UPDATE SET conversation_id = excluded.conversation_id",
172 params![owner, id.to_string()],
173 )
174 .map_err(sqlite_error)?;
175 tx.commit().map_err(sqlite_error)
176 }
177
178 pub fn get(&self, id: ConversationId) -> Result<Conversation, ConversationStoreError> {
179 self.load(&self.lock(), id)
180 }
181
182 pub fn rename(
183 &self,
184 owner: &str,
185 id: ConversationId,
186 title: impl Into<String>,
187 ) -> Result<Conversation, ConversationStoreError> {
188 let title = title.into();
189 let title = title.trim();
190 if title.is_empty() {
191 return Err(ConversationStoreError::EmptyTitle);
192 }
193 self.update_owned(owner, id, |connection| {
194 connection
195 .execute(
196 "UPDATE conversations SET title = ?1, updated_at = ?2 WHERE id = ?3",
197 params![title, Utc::now().to_rfc3339(), id.to_string()],
198 )
199 .map_err(sqlite_error)?;
200 Ok(())
201 })?;
202 self.get(id)
203 }
204
205 pub fn set_selected_family(
206 &self,
207 owner: &str,
208 id: ConversationId,
209 family_id: Option<FamilyId>,
210 ) -> Result<Conversation, ConversationStoreError> {
211 self.update_owned(owner, id, |connection| {
212 connection
213 .execute(
214 "UPDATE conversations SET selected_family_id = ?1, updated_at = ?2 WHERE id = ?3",
215 params![
216 family_id.map(|id| id.to_string()),
217 Utc::now().to_rfc3339(),
218 id.to_string()
219 ],
220 )
221 .map_err(sqlite_error)?;
222 Ok(())
223 })?;
224 self.get(id)
225 }
226
227 pub fn set_archived(
232 &self,
233 owner: &str,
234 id: ConversationId,
235 archived: bool,
236 ) -> Result<Conversation, ConversationStoreError> {
237 let mut connection = self.lock();
238 let tx = connection.transaction().map_err(sqlite_error)?;
239 let actual_owner: Option<String> = tx
240 .query_row(
241 "SELECT owner FROM conversations WHERE id = ?1",
242 [id.to_string()],
243 |row| row.get(0),
244 )
245 .optional()
246 .map_err(sqlite_error)?;
247 match actual_owner {
248 None => return Err(ConversationStoreError::NotFound(id)),
249 Some(actual) if actual != owner => {
250 return Err(ConversationStoreError::OwnerMismatch {
251 conversation_id: id,
252 owner: owner.to_owned(),
253 });
254 }
255 _ => {}
256 }
257
258 tx.execute(
259 "UPDATE conversations SET archived = ?1, updated_at = ?2 WHERE id = ?3",
260 params![archived, Utc::now().to_rfc3339(), id.to_string()],
261 )
262 .map_err(sqlite_error)?;
263 if archived {
264 tx.execute(
265 "DELETE FROM active_conversations WHERE owner = ?1 AND conversation_id = ?2",
266 params![owner, id.to_string()],
267 )
268 .map_err(sqlite_error)?;
269 }
270 tx.commit().map_err(sqlite_error)?;
271 self.get(id)
272 }
273
274 pub fn delete(&self, owner: &str, id: ConversationId) -> Result<(), ConversationStoreError> {
275 let mut connection = self.lock();
276 let tx = connection.transaction().map_err(sqlite_error)?;
277 let actual_owner: Option<String> = tx
278 .query_row(
279 "SELECT owner FROM conversations WHERE id = ?1",
280 [id.to_string()],
281 |row| row.get(0),
282 )
283 .optional()
284 .map_err(sqlite_error)?;
285 match actual_owner {
286 None => return Err(ConversationStoreError::NotFound(id)),
287 Some(actual) if actual != owner => {
288 return Err(ConversationStoreError::OwnerMismatch {
289 conversation_id: id,
290 owner: owner.to_owned(),
291 });
292 }
293 _ => {}
294 }
295 tx.execute(
296 "DELETE FROM active_conversations WHERE owner = ?1 AND conversation_id = ?2",
297 params![owner, id.to_string()],
298 )
299 .map_err(sqlite_error)?;
300 tx.execute("DELETE FROM conversations WHERE id = ?1", [id.to_string()])
301 .map_err(sqlite_error)?;
302 tx.commit().map_err(sqlite_error)
303 }
304
305 pub fn save_messages(
308 &self,
309 id: ConversationId,
310 messages: Vec<Message>,
311 ) -> Result<Conversation, ConversationStoreError> {
312 let mut connection = self.lock();
313 let tx = connection.transaction().map_err(sqlite_error)?;
314 let exists: bool = tx
315 .query_row(
316 "SELECT EXISTS(SELECT 1 FROM conversations WHERE id = ?1)",
317 [id.to_string()],
318 |row| row.get(0),
319 )
320 .map_err(sqlite_error)?;
321 if !exists {
322 return Err(ConversationStoreError::NotFound(id));
323 }
324 tx.execute(
325 "DELETE FROM conversation_messages WHERE conversation_id = ?1",
326 [id.to_string()],
327 )
328 .map_err(sqlite_error)?;
329 for (sequence, message) in messages.iter().enumerate() {
330 let json = serde_json::to_string(message)?;
331 tx.execute(
332 "INSERT INTO conversation_messages(conversation_id, sequence, message_json) VALUES (?1, ?2, ?3)",
333 params![id.to_string(), sequence as i64, json],
334 )
335 .map_err(sqlite_error)?;
336 }
337 tx.execute(
338 "UPDATE conversations SET updated_at = ?1 WHERE id = ?2",
339 params![Utc::now().to_rfc3339(), id.to_string()],
340 )
341 .map_err(sqlite_error)?;
342 tx.commit().map_err(sqlite_error)?;
343 self.get(id)
344 }
345
346 pub fn import_legacy(
351 &self,
352 legacy_root: impl AsRef<Path>,
353 ) -> Result<LegacyImportReport, ConversationStoreError> {
354 let legacy_root = legacy_root.as_ref();
355 let conversations_dir = legacy_root.join("conversations");
356 let mut report = LegacyImportReport::default();
357
358 if conversations_dir.exists() {
359 let mut paths = fs::read_dir(&conversations_dir)?
360 .map(|entry| entry.map(|entry| entry.path()))
361 .collect::<Result<Vec<_>, _>>()?
362 .into_iter()
363 .filter(|path| {
364 path.is_file()
365 && path.extension().and_then(|value| value.to_str()) == Some("json")
366 })
367 .collect::<Vec<_>>();
368 paths.sort();
369
370 for path in paths {
371 let parsed = fs::read(&path)
372 .map_err(ConversationStoreError::Io)
373 .and_then(|bytes| {
374 serde_json::from_slice::<Conversation>(&bytes)
375 .map_err(ConversationStoreError::Serialization)
376 });
377 let conversation = match parsed {
378 Ok(conversation) => conversation,
379 Err(error) => {
380 report
381 .invalid_documents
382 .push(format!("{}: {error}", path.display()));
383 continue;
384 }
385 };
386 match self.import_conversation(&conversation) {
387 Ok(true) => report.imported += 1,
388 Ok(false) => report.already_present += 1,
389 Err(error) => report
390 .invalid_documents
391 .push(format!("{}: {error}", path.display())),
392 }
393 }
394 }
395
396 let active_path = legacy_root.join("active-conversations.json");
397 if active_path.exists() {
398 let bytes = fs::read(&active_path)?;
399 let active: HashMap<String, ConversationId> = serde_json::from_slice(&bytes)?;
400 let connection = self.lock();
401 for (owner, id) in active {
402 let actual_owner: Option<String> = connection
403 .query_row(
404 "SELECT owner FROM conversations WHERE id = ?1",
405 [id.to_string()],
406 |row| row.get(0),
407 )
408 .optional()
409 .map_err(sqlite_error)?;
410 match actual_owner {
411 Some(actual) if actual == owner => {
412 let inserted = connection
413 .execute(
414 "INSERT OR IGNORE INTO active_conversations(owner, conversation_id) VALUES (?1, ?2)",
415 params![owner, id.to_string()],
416 )
417 .map_err(sqlite_error)?;
418 report.active_mappings_imported += inserted;
419 }
420 Some(_) => report
421 .invalid_active_entries
422 .push(format!("owner mapping does not match conversation {id}")),
423 None => report
424 .invalid_active_entries
425 .push(format!("active conversation {id} does not exist")),
426 }
427 }
428 }
429 Ok(report)
430 }
431
432 fn import_conversation(
433 &self,
434 conversation: &Conversation,
435 ) -> Result<bool, ConversationStoreError> {
436 let mut connection = self.lock();
437 let tx = connection.transaction().map_err(sqlite_error)?;
438 let exists: bool = tx
439 .query_row(
440 "SELECT EXISTS(SELECT 1 FROM conversations WHERE id = ?1)",
441 [conversation.id.to_string()],
442 |row| row.get(0),
443 )
444 .map_err(sqlite_error)?;
445 if exists {
446 tx.rollback().map_err(sqlite_error)?;
447 return Ok(false);
448 }
449 tx.execute(
450 "INSERT INTO conversations(id, owner, agent, title, archived, selected_family_id, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
451 params![
452 conversation.id.to_string(),
453 conversation.owner,
454 conversation.agent,
455 conversation.title,
456 conversation.archived,
457 conversation.selected_family_id.map(|id| id.to_string()),
458 conversation.created_at.to_rfc3339(),
459 conversation.updated_at.to_rfc3339()
460 ],
461 )
462 .map_err(sqlite_error)?;
463 for (sequence, message) in conversation.messages.iter().enumerate() {
464 tx.execute(
465 "INSERT INTO conversation_messages(conversation_id, sequence, message_json) VALUES (?1, ?2, ?3)",
466 params![
467 conversation.id.to_string(),
468 sequence as i64,
469 serde_json::to_string(message)?
470 ],
471 )
472 .map_err(sqlite_error)?;
473 }
474 tx.commit().map_err(sqlite_error)?;
475 Ok(true)
476 }
477
478 fn update_owned<F>(
479 &self,
480 owner: &str,
481 id: ConversationId,
482 update: F,
483 ) -> Result<(), ConversationStoreError>
484 where
485 F: FnOnce(&Connection) -> Result<(), ConversationStoreError>,
486 {
487 let connection = self.lock();
488 let actual_owner: Option<String> = connection
489 .query_row(
490 "SELECT owner FROM conversations WHERE id = ?1",
491 [id.to_string()],
492 |row| row.get(0),
493 )
494 .optional()
495 .map_err(sqlite_error)?;
496 match actual_owner {
497 None => Err(ConversationStoreError::NotFound(id)),
498 Some(actual) if actual != owner => Err(ConversationStoreError::OwnerMismatch {
499 conversation_id: id,
500 owner: owner.to_owned(),
501 }),
502 _ => update(&connection),
503 }
504 }
505
506 fn load(
507 &self,
508 connection: &Connection,
509 id: ConversationId,
510 ) -> Result<Conversation, ConversationStoreError> {
511 let row = connection
512 .query_row(
513 "SELECT owner, agent, title, archived, selected_family_id, created_at, updated_at FROM conversations WHERE id = ?1",
514 [id.to_string()],
515 |row| {
516 Ok((
517 row.get::<_, String>(0)?,
518 row.get::<_, String>(1)?,
519 row.get::<_, String>(2)?,
520 row.get::<_, bool>(3)?,
521 row.get::<_, Option<String>>(4)?,
522 row.get::<_, String>(5)?,
523 row.get::<_, String>(6)?,
524 ))
525 },
526 )
527 .optional()
528 .map_err(sqlite_error)?;
529 let Some((owner, agent, title, archived, family, created, updated)) = row else {
530 return Err(ConversationStoreError::NotFound(id));
531 };
532 let mut statement = connection
533 .prepare(
534 "SELECT message_json FROM conversation_messages WHERE conversation_id = ?1 ORDER BY sequence ASC",
535 )
536 .map_err(sqlite_error)?;
537 let rows = statement
538 .query_map([id.to_string()], |row| row.get::<_, String>(0))
539 .map_err(sqlite_error)?;
540 let mut messages = Vec::new();
541 for row in rows {
542 messages.push(serde_json::from_str(&row.map_err(sqlite_error)?)?);
543 }
544 Ok(Conversation {
545 id,
546 owner,
547 agent,
548 title,
549 archived,
550 selected_family_id: family
551 .map(|value| {
552 FamilyId::from_str(&value)
553 .map_err(|error| ConversationStoreError::Sqlite(error.to_string()))
554 })
555 .transpose()?,
556 created_at: parse_time(&created)?,
557 updated_at: parse_time(&updated)?,
558 messages,
559 })
560 }
561
562 fn lock(&self) -> MutexGuard<'_, Connection> {
563 self.connection
564 .lock()
565 .unwrap_or_else(|poisoned| poisoned.into_inner())
566 }
567}
568
569fn sqlite_error(error: rusqlite::Error) -> ConversationStoreError {
570 ConversationStoreError::Sqlite(error.to_string())
571}
572
573fn parse_time(value: &str) -> Result<DateTime<Utc>, ConversationStoreError> {
574 DateTime::parse_from_rfc3339(value)
575 .map(|value| value.with_timezone(&Utc))
576 .map_err(|error| ConversationStoreError::Sqlite(error.to_string()))
577}
578
579#[derive(Debug, Default)]
582pub struct LegacyImportReport {
583 pub imported: usize,
584 pub already_present: usize,
585 pub active_mappings_imported: usize,
586 pub invalid_documents: Vec<String>,
587 pub invalid_active_entries: Vec<String>,
588}
589
590#[cfg(test)]
591mod tests;