Skip to main content

uqa_storage_sqlite/mvcc/
serializable.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Atomic, encrypted transport for the common SSI graph across independent `SQLite` processes.
8
9mod liveness;
10mod restore;
11mod schema;
12#[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
13pub(in crate::mvcc) use liveness::lease_file;
14#[cfg(test)]
15mod tests;
16
17use rusqlite::Connection;
18use uqa_storage::{
19    mvcc::{SerializableGraph, VersionResult, VersionedPersistence},
20    read_control::StorageReadControl,
21};
22
23use super::{admission, Error, PhysicalResult, SQLiteRecordStore};
24use crate::SQLiteConnectionLease;
25
26/// An exclusive, short-lived SSI admission over the database's auxiliary store. Every file-backed opener uses `SQLite`'s process-shared writer admission; in-memory sessions share their parent's retained auxiliary pool. Dropping this guard discards unpersisted changes and releases admission.
27///
28/// The caller owns participant liveness, receipt reconciliation and snapshot/publication ordering. Persist admission before exposing a participant, and persist prepared receipt bindings before publishing records, then reacquire admission while publishing and resolving them. A failed persistence call does not establish a physical record outcome. This transport does not enable SERIALIZABLE SQL by itself.
29pub struct SQLiteSerializableAdmission {
30    connection: SQLiteConnectionLease,
31    graph: SerializableGraph,
32    previous_timeout: std::time::Duration,
33}
34
35impl SQLiteRecordStore {
36    /// Acquire the shared SSI state without retaining a main-database physical transaction. The supplied allowance bounds the decoded graph and its predicate keys; serialization streams directly to a transactional BLOB.
37    pub fn serializable_admission(
38        &self,
39        control: &StorageReadControl,
40    ) -> VersionResult<SQLiteSerializableAdmission> {
41        control.check()?;
42        let auxiliary = self
43            .connection
44            .serializable_connection(self.identity, control)?;
45        let held = SQLiteSerializableAdmission::load(&auxiliary, control, |_| Ok(self.identity))?;
46        held.graph
47            .validate_persisted_publications(control, |transaction| {
48                self.commit_status(transaction, control)
49            })?;
50        Ok(held)
51    }
52}
53
54impl SQLiteSerializableAdmission {
55    fn load(
56        auxiliary: &crate::ManagedConnection,
57        control: &StorageReadControl,
58        identity: impl FnOnce(&Connection) -> PhysicalResult<uqa_storage::mvcc::DatabaseId>,
59    ) -> VersionResult<Self> {
60        let connection = auxiliary
61            .lease_connection_with_control(control)
62            .map_err(|error| Error::from(error).into_version())?;
63        let timeout = admission::BusyTimeout::new(&connection).map_err(super::sqlite_error)?;
64        begin(&connection, control).map_err(Error::into_version)?;
65        let identity = identity(&connection).map_err(Error::into_version)?;
66        let graph = schema::load(&connection, identity, control).map_err(Error::into_version)?;
67        drop(timeout);
68        let milliseconds: u32 = connection
69            .pragma_query_value(None, "busy_timeout", |row| row.get(0))
70            .map_err(super::sqlite_error)?;
71        connection
72            .busy_timeout(std::time::Duration::ZERO)
73            .map_err(super::sqlite_error)?;
74        Ok(Self {
75            connection,
76            graph,
77            previous_timeout: std::time::Duration::from_millis(u64::from(milliseconds)),
78        })
79    }
80}
81
82impl SQLiteSerializableAdmission {
83    pub fn graph(&self) -> &SerializableGraph {
84        &self.graph
85    }
86
87    pub fn graph_mut(&mut self) -> &mut SerializableGraph {
88        &mut self.graph
89    }
90
91    /// Atomically retain changed checkpoint records and release admission. An unchanged checkpoint needs no record writes. Cancellation or a failed BLOB write rolls back the auxiliary transaction. A failed COMMIT may be uncertain; callers must reconcile physical receipts before classifying a publication or admitting another data snapshot.
92    pub fn persist(self, control: &StorageReadControl) -> VersionResult<()> {
93        self.persist_in(control).map_err(Error::into_version)
94    }
95
96    fn persist_in(&self, control: &StorageReadControl) -> PhysicalResult<()> {
97        if !self.graph.checkpoint_records_changed() {
98            return retry(&self.connection, "COMMIT", false, control);
99        }
100        schema::persist(&self.connection, &self.graph, control)?;
101        retry(&self.connection, "COMMIT", false, control)
102    }
103}
104
105impl Drop for SQLiteSerializableAdmission {
106    fn drop(&mut self) {
107        // The owned lease performs rollback before returning the connection to its pool.
108        let _ = self.connection.busy_timeout(self.previous_timeout);
109    }
110}
111
112fn begin(connection: &Connection, control: &StorageReadControl) -> PhysicalResult<()> {
113    retry(connection, "BEGIN IMMEDIATE", true, control)
114}
115
116fn retry(
117    connection: &Connection,
118    sql: &str,
119    autocommit: bool,
120    control: &StorageReadControl,
121) -> PhysicalResult<()> {
122    admission::retry(connection, autocommit, control, || {
123        connection.execute_batch(sql).map_err(Into::into)
124    })
125}