1#![doc(
7 html_logo_url = "https://raw.githubusercontent.com/ChaoticQubit/troupekit/main/assets/brand/logo-mark.svg",
8 html_favicon_url = "https://raw.githubusercontent.com/ChaoticQubit/troupekit/main/assets/brand/favicon.svg"
9)]
10
11mod queue;
12mod schema;
13mod stores;
14mod vectors;
15
16use rusqlite::config::DbConfig;
17use rusqlite::{Connection, OpenFlags};
18use std::collections::HashMap;
19use std::path::{Path, PathBuf};
20use std::sync::{Arc, Mutex};
21use std::time::{Duration, Instant};
22use troupekit_core::clock::{Clock, SystemClock};
23use troupekit_core::error::CoreError;
24#[cfg(any(feature = "sqlcipher", feature = "sqlcipher-system"))]
25use troupekit_core::secret::Secret;
26pub use troupekit_index::{HnswParams, IndexKind, Quantization};
27pub use vectors::{OpenReport, SqliteVectors, VectorSettings};
28
29pub const SCHEMA_VERSION: u32 = schema::STEPS.len() as u32;
33
34const _: () = assert!(SCHEMA_VERSION > 0);
35
36const BYTES_LIMIT_SQLITE: u64 = 1_000_000_000;
37const STATE_BYTES_MAX_DEFAULT: u64 = 64 * 1024 * 1024;
38const BLOB_BYTES_MAX_DEFAULT: u64 = 64 * 1024 * 1024;
39const HISTORY_STEPS_MAX_DEFAULT: u64 = 100_000;
40const HISTORY_BYTES_MAX_DEFAULT: u64 = 1024 * 1024 * 1024;
41const BUSY_TIMEOUT_MS_DEFAULT: u32 = 5_000;
42const OPEN_RETRY_PAUSE: Duration = Duration::from_millis(20);
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
49#[non_exhaustive]
50pub enum Durability {
51 #[default]
52 Full,
53 Normal,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub(crate) struct Limits {
58 pub(crate) state_bytes_max: u64,
59 pub(crate) blob_bytes_max: u64,
60 pub(crate) history_steps_max: u64,
61 pub(crate) history_bytes_max: u64,
62}
63
64#[derive(Clone)]
69pub struct SqliteStoreBuilder {
70 path: PathBuf,
71 durability: Durability,
72 clock: Arc<dyn Clock>,
73 limits: Limits,
74 busy_timeout_ms: u32,
75 secure_delete: bool,
76 #[cfg(any(feature = "sqlcipher", feature = "sqlcipher-system"))]
77 key: Option<Secret>,
78}
79
80impl std::fmt::Debug for SqliteStoreBuilder {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 f.debug_struct("SqliteStoreBuilder")
83 .field("path", &self.path)
84 .field("durability", &self.durability)
85 .field("limits", &self.limits)
86 .field("busy_timeout_ms", &self.busy_timeout_ms)
87 .field("secure_delete", &self.secure_delete)
88 .finish_non_exhaustive()
89 }
90}
91
92impl SqliteStoreBuilder {
93 pub fn durability(mut self, durability: Durability) -> Self {
96 self.durability = durability;
97 self
98 }
99
100 pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
104 self.clock = clock;
105 self
106 }
107
108 pub fn max_state_bytes(mut self, bytes: u64) -> Self {
111 self.limits.state_bytes_max = bytes;
112 self
113 }
114
115 pub fn max_blob_bytes(mut self, bytes: u64) -> Self {
118 self.limits.blob_bytes_max = bytes;
119 self
120 }
121
122 pub fn max_history_steps(mut self, steps: u64) -> Self {
125 self.limits.history_steps_max = steps;
126 self
127 }
128
129 pub fn max_history_bytes(mut self, bytes: u64) -> Self {
133 self.limits.history_bytes_max = bytes;
134 self
135 }
136
137 pub fn busy_timeout_ms(mut self, ms: u32) -> Self {
141 self.busy_timeout_ms = ms;
142 self
143 }
144
145 pub fn secure_delete(mut self, on: bool) -> Self {
154 self.secure_delete = on;
155 self
156 }
157
158 #[cfg(any(feature = "sqlcipher", feature = "sqlcipher-system"))]
162 pub fn key(mut self, key: Secret) -> Self {
163 self.key = Some(key);
164 self
165 }
166
167 pub async fn open(self) -> Result<SqliteStore, CoreError> {
171 validate(&self.limits, self.busy_timeout_ms)?;
172 let settings = self.clone();
173 let conn = tokio::task::spawn_blocking(move || open_retrying(&settings))
174 .await
175 .unwrap_or_else(join_failed)?;
176 Ok(SqliteStore {
177 inner: Arc::new(Inner {
178 conn: Mutex::new(conn),
179 clock: self.clock,
180 limits: self.limits,
181 path: self.path,
182 secure_delete: self.secure_delete,
183 vectors: Mutex::new(HashMap::new()),
184 }),
185 })
186 }
187}
188
189fn validate(limits: &Limits, busy_timeout_ms: u32) -> Result<(), CoreError> {
190 if i32::try_from(busy_timeout_ms).is_err() {
191 return Err(CoreError::Store(format!(
192 "busy_timeout_ms must be 0 to {}, got {busy_timeout_ms}",
193 i32::MAX
194 )));
195 }
196 for (name, value) in [
197 ("max_state_bytes", limits.state_bytes_max),
198 ("max_blob_bytes", limits.blob_bytes_max),
199 ] {
200 if value == 0 || value > BYTES_LIMIT_SQLITE {
201 return Err(CoreError::Store(format!(
202 "{name} must be 1 to {BYTES_LIMIT_SQLITE}, got {value}"
203 )));
204 }
205 }
206 if limits.history_steps_max == 0 {
207 return Err(CoreError::Store(
208 "max_history_steps must be at least 1".into(),
209 ));
210 }
211 if limits.history_bytes_max == 0 {
212 return Err(CoreError::Store(
213 "max_history_bytes must be at least 1".into(),
214 ));
215 }
216 Ok(())
217}
218
219fn create_private(path: &Path) -> Result<(), CoreError> {
224 if path.exists() {
225 return Ok(());
226 }
227 let mut options = std::fs::OpenOptions::new();
228 options.write(true).create_new(true);
229 #[cfg(unix)]
230 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
231 options.open(path).map(drop).or_else(|e| match e.kind() {
232 std::io::ErrorKind::AlreadyExists => Ok(()),
233 _ => Err(CoreError::Store(format!("cannot create store: {e}"))),
234 })
235}
236
237fn open_retrying(settings: &SqliteStoreBuilder) -> Result<Connection, CoreError> {
242 let deadline = Instant::now() + Duration::from_millis(u64::from(settings.busy_timeout_ms));
243 let mut attempts: u32 = 0;
244 loop {
245 attempts += 1;
246 match open_connection(settings) {
247 Err(e) if is_busy(&e) && Instant::now() < deadline => {
248 assert!(attempts < 1_000_000, "the deadline bounds the retries");
249 std::thread::sleep(OPEN_RETRY_PAUSE);
250 }
251 other => return other,
252 }
253 }
254}
255
256fn is_busy(e: &CoreError) -> bool {
259 matches!(e, CoreError::Store(m) if m.ends_with("database is locked") || m.ends_with("database is busy"))
260}
261
262fn open_connection(settings: &SqliteStoreBuilder) -> Result<Connection, CoreError> {
263 create_private(&settings.path)?;
264 let flags = OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX;
265 let mut conn = Connection::open_with_flags(&settings.path, flags)
266 .map_err(|e| CoreError::Store(format!("cannot open store: {e}")))?;
267 conn.busy_timeout(Duration::from_millis(u64::from(settings.busy_timeout_ms)))
268 .map_err(db)?;
269 #[cfg(any(feature = "sqlcipher", feature = "sqlcipher-system"))]
270 if let Some(key) = &settings.key {
271 conn.pragma_update(None, "key", key.expose())
272 .map_err(|_| wrong_key())?;
273 }
274 conn.query_row("SELECT COUNT(*) FROM sqlite_schema", [], |row| {
275 row.get::<_, i64>(0)
276 })
277 .map_err(|e| match e.sqlite_error_code() {
278 Some(rusqlite::ErrorCode::NotADatabase) => wrong_key(),
279 _ => db(e),
280 })?;
281 {
282 let preflight = conn.transaction().map_err(db)?;
283 schema::check_header(schema::read_header(&preflight)?, SCHEMA_VERSION)?;
284 preflight.commit().map_err(db)?;
285 }
286 let mode: String = conn
287 .pragma_update_and_check(None, "journal_mode", "WAL", |row| row.get(0))
288 .map_err(db)?;
289 if !mode.eq_ignore_ascii_case("wal") {
290 return Err(CoreError::Store(format!(
291 "store cannot use WAL, got {mode}"
292 )));
293 }
294 let (synchronous, fullfsync) = match settings.durability {
295 Durability::Full => ("FULL", true),
296 Durability::Normal => ("NORMAL", false),
297 };
298 let checkpoint_fullfsync = true;
299 conn.pragma_update(None, "synchronous", synchronous)
300 .map_err(db)?;
301 conn.pragma_update(None, "fullfsync", fullfsync)
302 .map_err(db)?;
303 conn.pragma_update(None, "checkpoint_fullfsync", checkpoint_fullfsync)
304 .map_err(db)?;
305 conn.pragma_update(None, "trusted_schema", "OFF")
306 .map_err(db)?;
307 conn.pragma_update(None, "secure_delete", settings.secure_delete)
308 .map_err(db)?;
309 conn.set_db_config(DbConfig::SQLITE_DBCONFIG_DEFENSIVE, true)
310 .map_err(db)?;
311 let version = schema::migrate(&mut conn, schema::STEPS)?;
312 assert_eq!(version, SCHEMA_VERSION);
313 assert_eq!(schema::read_header(&conn)?.user_version, SCHEMA_VERSION);
314 Ok(conn)
315}
316
317fn wrong_key() -> CoreError {
318 CoreError::Store("cannot open store: wrong key or not a database".into())
319}
320
321pub(crate) fn db(e: rusqlite::Error) -> CoreError {
325 CoreError::Store(format!("sqlite: {e}"))
326}
327
328fn join_failed<T>(e: tokio::task::JoinError) -> Result<T, CoreError> {
329 if e.is_panic() {
330 std::panic::resume_unwind(e.into_panic());
331 }
332 Err(CoreError::Store(format!("store task did not finish: {e}")))
333}
334
335struct Inner {
336 conn: Mutex<Connection>,
337 clock: Arc<dyn Clock>,
338 limits: Limits,
339 path: PathBuf,
340 secure_delete: bool,
341 vectors: Mutex<HashMap<String, Arc<vectors::IndexState>>>,
342}
343
344#[derive(Clone)]
349pub struct SqliteStore {
350 inner: Arc<Inner>,
351}
352
353impl std::fmt::Debug for SqliteStore {
354 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
355 f.debug_struct("SqliteStore")
356 .field("path", &self.inner.path)
357 .field("limits", &self.inner.limits)
358 .finish_non_exhaustive()
359 }
360}
361
362impl SqliteStore {
363 pub fn builder(path: impl AsRef<Path>) -> SqliteStoreBuilder {
367 SqliteStoreBuilder {
368 path: path.as_ref().to_path_buf(),
369 durability: Durability::Full,
370 clock: Arc::new(SystemClock),
371 limits: Limits {
372 state_bytes_max: STATE_BYTES_MAX_DEFAULT,
373 blob_bytes_max: BLOB_BYTES_MAX_DEFAULT,
374 history_steps_max: HISTORY_STEPS_MAX_DEFAULT,
375 history_bytes_max: HISTORY_BYTES_MAX_DEFAULT,
376 },
377 busy_timeout_ms: BUSY_TIMEOUT_MS_DEFAULT,
378 secure_delete: true,
379 #[cfg(any(feature = "sqlcipher", feature = "sqlcipher-system"))]
380 key: None,
381 }
382 }
383
384 pub async fn open(path: impl AsRef<Path>) -> Result<SqliteStore, CoreError> {
388 Self::builder(path).open().await
389 }
390
391 pub(crate) fn limits(&self) -> Limits {
392 self.inner.limits
393 }
394
395 pub(crate) async fn call<T, F>(&self, f: F) -> Result<T, CoreError>
400 where
401 T: Send + 'static,
402 F: FnOnce(&mut Connection) -> Result<T, CoreError> + Send + 'static,
403 {
404 let inner = Arc::clone(&self.inner);
405 let scope = troupekit_trace::current();
406 tokio::task::spawn_blocking(move || match scope {
407 Some(scope) => scope.enter(|| run_locked(&inner, f)),
408 None => run_locked(&inner, f),
409 })
410 .await
411 .unwrap_or_else(|e| join_failed(e))
412 }
413}
414
415fn run_locked<T, F>(inner: &Inner, f: F) -> Result<T, CoreError>
419where
420 F: FnOnce(&mut Connection) -> Result<T, CoreError>,
421{
422 let mut conn = match inner.conn.lock() {
423 Ok(conn) => conn,
424 Err(poisoned) => {
425 let conn = poisoned.into_inner();
426 if !conn.is_autocommit() {
427 conn.execute_batch("ROLLBACK").map_err(db)?;
428 }
429 inner.conn.clear_poison();
430 conn
431 }
432 };
433 assert!(
434 conn.is_autocommit(),
435 "a store call starts outside a transaction"
436 );
437 let out = f(&mut conn);
438 assert!(conn.is_autocommit(), "a store call left a transaction open");
439 out
440}
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445 use rusqlite::TransactionBehavior;
446
447 async fn temp_store(
448 builder: impl FnOnce(SqliteStoreBuilder) -> SqliteStoreBuilder,
449 ) -> (tempfile::TempDir, SqliteStore) {
450 let dir = tempfile::tempdir().unwrap();
451 let store = builder(SqliteStore::builder(dir.path().join("t.db")))
452 .open()
453 .await
454 .unwrap();
455 (dir, store)
456 }
457
458 async fn pragma(store: &SqliteStore, name: &'static str) -> i64 {
459 store
460 .call(move |conn| {
461 conn.pragma_query_value(None, name, |row| row.get(0))
462 .map_err(db)
463 })
464 .await
465 .unwrap()
466 }
467
468 #[tokio::test]
469 async fn defaults_are_the_safe_values() {
470 let builder = SqliteStore::builder("unused.db");
471 assert_eq!(builder.durability, Durability::Full);
472 assert_eq!(builder.limits.state_bytes_max, 64 * 1024 * 1024);
473 assert_eq!(builder.limits.blob_bytes_max, 64 * 1024 * 1024);
474 assert_eq!(builder.limits.history_steps_max, 100_000);
475 assert_eq!(builder.limits.history_bytes_max, 1024 * 1024 * 1024);
476 assert_eq!(builder.busy_timeout_ms, 5_000);
477 assert!(builder.secure_delete);
478 let before = SystemClock.now_ms();
479 assert!(builder.clock.now_ms() >= before);
480 let (_dir, store) = temp_store(|b| b).await;
481 assert_eq!(pragma(&store, "synchronous").await, 2);
482 assert_eq!(pragma(&store, "fullfsync").await, 1);
483 assert_eq!(pragma(&store, "checkpoint_fullfsync").await, 1);
484 assert_eq!(pragma(&store, "busy_timeout").await, 5_000);
485 assert_eq!(pragma(&store, "trusted_schema").await, 0);
486 assert_eq!(pragma(&store, "secure_delete").await, 1);
487 }
488
489 #[tokio::test]
490 async fn secure_delete_off_reaches_the_connection() {
491 let (_dir, store) = temp_store(|b| b.secure_delete(false)).await;
492 assert_eq!(pragma(&store, "secure_delete").await, 0);
493 }
494
495 #[tokio::test]
496 async fn durability_normal_sets_synchronous_normal() {
497 let (_dir, store) = temp_store(|b| b.durability(Durability::Normal)).await;
498 assert_eq!(pragma(&store, "synchronous").await, 1);
499 assert_eq!(pragma(&store, "fullfsync").await, 0);
500 assert_eq!(pragma(&store, "checkpoint_fullfsync").await, 1);
501 }
502
503 #[tokio::test]
504 async fn busy_timeout_setting_reaches_the_connection() {
505 let (_dir, store) = temp_store(|b| b.busy_timeout_ms(1234)).await;
506 assert_eq!(pragma(&store, "busy_timeout").await, 1234);
507 }
508
509 #[tokio::test]
510 async fn zero_cap_is_refused() {
511 let dir = tempfile::tempdir().unwrap();
512 let path = dir.path().join("t.db");
513 for builder in [
514 SqliteStore::builder(&path).max_state_bytes(0),
515 SqliteStore::builder(&path).max_blob_bytes(0),
516 SqliteStore::builder(&path).max_history_steps(0),
517 SqliteStore::builder(&path).max_history_bytes(0),
518 ] {
519 let err = builder.open().await.unwrap_err();
520 assert!(matches!(err, CoreError::Store(_)), "{err:?}");
521 }
522 assert!(!path.exists());
523 }
524
525 #[tokio::test]
526 async fn busy_timeout_above_i32_is_refused_not_a_panic() {
527 let dir = tempfile::tempdir().unwrap();
528 let path = dir.path().join("t.db");
529 let err = SqliteStore::builder(&path)
530 .busy_timeout_ms(u32::MAX)
531 .open()
532 .await
533 .unwrap_err();
534 assert!(
535 matches!(&err, CoreError::Store(m) if m.contains("busy_timeout_ms")),
536 "{err:?}"
537 );
538 assert!(!path.exists());
539 let max = u32::try_from(i32::MAX).unwrap();
540 let (_dir, store) = temp_store(|b| b.busy_timeout_ms(max)).await;
541 assert_eq!(pragma(&store, "busy_timeout").await, i64::from(i32::MAX));
542 }
543
544 #[tokio::test]
545 async fn cap_above_sqlite_limit_is_refused() {
546 let dir = tempfile::tempdir().unwrap();
547 let path = dir.path().join("t.db");
548 for builder in [
549 SqliteStore::builder(&path).max_state_bytes(1_000_000_001),
550 SqliteStore::builder(&path).max_blob_bytes(1_000_000_001),
551 ] {
552 let err = builder.open().await.unwrap_err();
553 assert!(
554 matches!(&err, CoreError::Store(m) if m.contains("1000000000")),
555 "{err:?}"
556 );
557 }
558 assert!(SqliteStore::builder(&path)
559 .max_blob_bytes(1_000_000_000)
560 .open()
561 .await
562 .is_ok());
563 }
564
565 #[tokio::test]
566 async fn panic_in_a_store_call_reaches_the_caller() {
567 let (_dir, store) = temp_store(|b| b).await;
568 let task = tokio::spawn(async move {
569 store
570 .call(|_conn| -> Result<(), CoreError> { panic!("boom in call") })
571 .await
572 });
573 let err = task.await.unwrap_err();
574 assert!(err.is_panic());
575 let payload = err.into_panic();
576 assert_eq!(payload.downcast_ref::<&str>(), Some(&"boom in call"));
577 }
578
579 #[tokio::test]
580 async fn panic_inside_a_transaction_rolls_it_back() {
581 let (_dir, store) = temp_store(|b| b).await;
582 let clone = store.clone();
583 let task = tokio::spawn(async move {
584 clone
585 .call(|conn| -> Result<(), CoreError> {
586 let tx = conn
587 .transaction_with_behavior(TransactionBehavior::Immediate)
588 .unwrap();
589 tx.execute(
590 "INSERT INTO blob_entry (path, bytes) VALUES ('p', x'01')",
591 [],
592 )
593 .unwrap();
594 panic!("boom in transaction")
595 })
596 .await
597 });
598 assert!(task.await.unwrap_err().is_panic());
599 let rows: i64 = store
600 .call(|conn| {
601 conn.query_row("SELECT COUNT(*) FROM blob_entry", [], |r| r.get(0))
602 .map_err(db)
603 })
604 .await
605 .unwrap();
606 assert_eq!(rows, 0);
607 }
608
609 #[tokio::test]
610 async fn store_stays_usable_after_a_panicked_call() {
611 let (_dir, store) = temp_store(|b| b).await;
612 let clone = store.clone();
613 let task = tokio::spawn(async move {
614 clone
615 .call(|_conn| -> Result<(), CoreError> { panic!("boom") })
616 .await
617 });
618 assert!(task.await.unwrap_err().is_panic());
619 assert!(store.inner.conn.is_poisoned());
620 let written = store
621 .call(|conn| {
622 conn.execute(
623 "INSERT INTO blob_entry (path, bytes) VALUES ('q', x'02')",
624 [],
625 )
626 .map_err(db)
627 })
628 .await
629 .unwrap();
630 assert_eq!(written, 1);
631 assert_eq!(
632 pragma(&store, "user_version").await,
633 i64::from(SCHEMA_VERSION)
634 );
635 }
636}