Skip to main content

uqa_storage_sqlite/connection/
serializable.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Retain an independently scoped SSI connection with the main database's encryption policy.
8
9use std::time::Duration;
10
11use uqa_storage::{
12    mvcc::{
13        DatabaseId, SerializablePredicate, SerializableReadContext, SerializableSession,
14        SerializableSnapshotCapture, SerializableSnapshotOptions, VersionError, VersionResult,
15    },
16    read_control::StorageReadControl,
17    PersistentStorageIdentity, StorageBackendResult,
18};
19
20use super::ManagedConnection;
21use crate::SQLiteConnectionLease;
22
23impl SerializableSession for ManagedConnection {
24    fn establish_serializable_snapshot(&self) -> StorageBackendResult<SerializableReadContext> {
25        self.with_serializable_session(|session| session.establish_serializable_snapshot())
26    }
27
28    fn establish_serializable_snapshot_with(
29        &self,
30        options: SerializableSnapshotOptions,
31        capture: &mut SerializableSnapshotCapture<'_>,
32    ) -> StorageBackendResult<SerializableReadContext> {
33        self.with_serializable_session(|session| {
34            session.establish_serializable_snapshot_with(options, capture)
35        })
36    }
37
38    fn serializable_read_context(&self) -> StorageBackendResult<Option<SerializableReadContext>> {
39        self.with_serializable_session(|session| session.serializable_read_context())
40    }
41
42    fn observe_serializable_write(
43        &self,
44        predicate: SerializablePredicate<'_>,
45    ) -> StorageBackendResult<()> {
46        self.with_serializable_session(|session| session.observe_serializable_write(predicate))
47    }
48}
49
50impl ManagedConnection {
51    pub(crate) fn with_local_receipt_admission<T>(
52        &self,
53        state: Option<&std::sync::Arc<uqa_storage::mvcc::LocalSerializableState>>,
54        control: &StorageReadControl,
55        operation: impl FnOnce(&dyn uqa_storage::mvcc::SerializableLeases) -> VersionResult<T>,
56    ) -> VersionResult<T> {
57        state
58            .unwrap_or(&self.pool.receipt_state)
59            .with_admission(&self.pool, control, operation)
60    }
61
62    fn with_serializable_session<T>(
63        &self,
64        operation: impl FnOnce(&dyn SerializableSession) -> StorageBackendResult<T>,
65    ) -> StorageBackendResult<T> {
66        self.surface_cleanup_failure()?;
67        let _gate = self.session.gate.read();
68        let logical = self
69            .session
70            .logical
71            .get()
72            .ok_or(crate::SQLiteError::LogicalSessionRequired)?;
73        operation(logical.store.as_ref())
74    }
75
76    pub(crate) fn serializable_local_leases(
77        &self,
78        control: &StorageReadControl,
79    ) -> std::sync::Arc<uqa_storage::mvcc::LocalSerializableLeases> {
80        let mut retained = self.pool.serializable_leases.lock();
81        std::sync::Arc::clone(retained.get_or_insert_with(|| {
82            std::sync::Arc::new(uqa_storage::mvcc::LocalSerializableLeases::new(
83                control.memory(),
84            ))
85        }))
86    }
87
88    pub(crate) fn serializable_connection(
89        &self,
90        database: DatabaseId,
91        control: &StorageReadControl,
92    ) -> VersionResult<Self> {
93        let mut retained = loop {
94            control.check()?;
95            if let Some(retained) = self
96                .pool
97                .serializable_connection
98                .try_lock_for(Duration::from_millis(2))
99            {
100                break retained;
101            }
102        };
103        if let Some((identity, connection)) = &*retained {
104            if *identity != database {
105                return Err(VersionError::WrongDatabase);
106            }
107            return Ok(connection.clone());
108        }
109        let connection = self
110            .open_serializable_connection()
111            .map_err(|error| VersionError::Storage(error.into()))?;
112        *retained = Some((database, connection.clone()));
113        Ok(connection)
114    }
115
116    /// Open the physical SSI database without attaching an incarnation-specific cache entry to the main pool.
117    pub(crate) fn open_serializable_connection(&self) -> crate::Result<Self> {
118        if let Some(path) = self.database_path() {
119            let PersistentStorageIdentity::File(path) =
120                PersistentStorageIdentity::for_database_path(path)?
121            else {
122                unreachable!("database file identity")
123            };
124            let mut auxiliary = path.into_os_string();
125            auxiliary.push(".uqa-serializable");
126            Self::from_spec_owned(
127                super::ConnectionSpec::Auxiliary {
128                    path: std::path::PathBuf::from(auxiliary),
129                    key: self.auxiliary_encryption_key(),
130                },
131                super::default_pool_connections(),
132                self.database_owner(),
133            )
134        } else {
135            // The parent pool retains this one physical in-memory database even between record handles.
136            Self::open_in_memory()
137        }
138    }
139
140    pub(crate) fn lease_connection_with_control(
141        &self,
142        control: &StorageReadControl,
143    ) -> crate::Result<SQLiteConnectionLease> {
144        self.pool
145            .checkout_with_cancellation(Some(control.cancellation()))
146            .map(SQLiteConnectionLease)
147    }
148}