Skip to main content

uqa_storage_redb/
lib.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Pure-Rust redb implementation of UQA's ordered Key/Value storage contract.
8//!
9//! [`RedbStorage`] owns one database and implements
10//! [`uqa_storage::PersistentStorageProvider`]. Every opened engine session gets
11//! an independent [`RedbKeyValueStore`] transaction state while sharing the
12//! same MVCC database.
13
14mod error;
15mod mvcc;
16
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19
20use redb::Database;
21use uqa_storage::{
22    CatalogFacade, KeyValueCatalog, KeyValueStorageBackend, KeyValueStore,
23    PersistentStorageBackend, PersistentStorageIdentity, PersistentStorageProvider,
24    PersistentStorageSession, StorageBackendError, StorageBackendResult,
25};
26
27pub use mvcc::RedbRecordStore;
28pub use uqa_storage::mvcc::{VersionedKeyValueStore as RedbKeyValueStore, VersionedSessionOptions};
29
30use error::redb_error;
31use uqa_storage::read_control::{CancellationToken, StorageReadControl};
32
33/// Shared redb database owner and engine-session factory.
34#[derive(Clone)]
35pub struct RedbStorage {
36    records: Arc<RedbRecordStore>,
37    identity: PathBuf,
38    options: VersionedSessionOptions,
39}
40
41impl RedbStorage {
42    /// Open an existing redb database or create a new one at `path`.
43    pub fn open(path: impl AsRef<Path>) -> StorageBackendResult<Self> {
44        Self::open_with_options(path, VersionedSessionOptions::default())
45    }
46
47    /// Open with an explicit per-session retention limit. Private changes beyond half of it move into temporary files encrypted with a key that exists only in memory; no plaintext reaches disk.
48    pub fn open_with_options(
49        path: impl AsRef<Path>,
50        options: VersionedSessionOptions,
51    ) -> StorageBackendResult<Self> {
52        let path = path.as_ref();
53        let database = Arc::new(Database::create(path).map_err(redb_error)?);
54        let records = RedbRecordStore::new(database)
55            .map_err(uqa_storage::mvcc::VersionError::into_storage_error)?;
56        Self::from_records(path, records, options)
57    }
58
59    /// Open a closed, consistent backup as a new database history. Every prior provider, session, snapshot and serializable participant for `path` must be closed; redb's exclusive file ownership enforces this before any restore mutation.
60    ///
61    /// Retain `request` outside the database before calling. Retry that same request after an error because the durable transition may have completed. A retry after completion preserves new receipts and writes. A separate restoration requires a new request. Ordinary reopen uses `open` or `open_with_options` and preserves the existing incarnation and outcomes.
62    pub fn open_restored(
63        path: impl AsRef<Path>,
64        request: uqa_storage::mvcc::DatabaseRestore,
65        options: VersionedSessionOptions,
66        control: &StorageReadControl,
67    ) -> StorageBackendResult<Self> {
68        control.check()?;
69        let path = path.as_ref();
70        let database = Database::open(path).map_err(redb_error)?;
71        let records = mvcc::restore::open(database, request, control)
72            .map_err(uqa_storage::mvcc::VersionError::into_storage_error)?;
73        Self::from_records(path, records, options)
74    }
75
76    fn from_records(
77        path: &Path,
78        records: RedbRecordStore,
79        options: VersionedSessionOptions,
80    ) -> StorageBackendResult<Self> {
81        records
82            .migrate_key_value()
83            .map_err(uqa_storage::mvcc::VersionError::into_storage_error)?;
84        let identity = std::fs::canonicalize(path).map_err(|error| {
85            StorageBackendError::Other(format!(
86                "canonicalize redb database `{}`: {error}",
87                path.display()
88            ))
89        })?;
90        Ok(Self {
91            records: Arc::new(records),
92            identity,
93            options,
94        })
95    }
96
97    /// Create an independent logical session without acquiring a physical writer.
98    pub fn store(&self) -> RedbKeyValueStore {
99        self.store_with_cancellation(&CancellationToken::new())
100    }
101
102    fn store_with_cancellation(&self, cancellation: &CancellationToken) -> RedbKeyValueStore {
103        RedbKeyValueStore::new_with_cancellation(
104            self.records.clone(),
105            Some(PersistentStorageIdentity::File(self.identity.clone())),
106            self.options,
107            cancellation.clone(),
108        )
109    }
110
111    /// Share the record persistence used by this owner's Key/Value and catalog sessions.
112    pub fn record_store(&self) -> uqa_storage::mvcc::VersionResult<RedbRecordStore> {
113        Ok((*self.records).clone())
114    }
115}
116
117impl PersistentStorageProvider for RedbStorage {
118    fn open_session(&self) -> StorageBackendResult<PersistentStorageSession> {
119        self.open_session_with_cancellation(&CancellationToken::new())
120    }
121
122    fn open_session_with_cancellation(
123        &self,
124        cancellation: &CancellationToken,
125    ) -> StorageBackendResult<PersistentStorageSession> {
126        cancellation.check()?;
127        let store: Arc<dyn KeyValueStore> = Arc::new(self.store_with_cancellation(cancellation));
128        let catalog: Arc<dyn CatalogFacade> = Arc::new(KeyValueCatalog::new(Arc::clone(&store)));
129        let backend: Arc<dyn PersistentStorageBackend> =
130            Arc::new(KeyValueStorageBackend::new(store));
131        Ok(PersistentStorageSession::new(catalog, backend))
132    }
133
134    fn storage_identity(&self) -> StorageBackendResult<Option<PersistentStorageIdentity>> {
135        Ok(Some(PersistentStorageIdentity::File(self.identity.clone())))
136    }
137}