Skip to main content

uqa_storage/
read_only_snapshot.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Read-only adapters retain storage-owned snapshots and forward every read capability.
8
9use std::sync::Arc;
10use uqa_core::memory::{Budgeted, MemoryReservation};
11
12use crate::StorageBackendError;
13
14mod documents;
15mod inverted;
16mod vectors;
17
18/// Adapt an already captured snapshot to an owned read-only handle without copying its contents. The caller must supply the snapshot selected for its visibility boundary; this adapter does not capture or advance that boundary.
19pub struct ReadOnlySnapshot<T: ?Sized>(
20    Arc<T>,
21    Option<Arc<MemoryReservation>>,
22    Option<crate::read_control::StorageReadControl>,
23);
24
25impl<T> ReadOnlySnapshot<T> {
26    /// Share a captured value without separating its allocations from their original allowance.
27    pub fn from_budgeted(snapshot: Budgeted<T>) -> crate::StorageBackendResult<Self> {
28        let mut pending = snapshot.into_parts();
29        let shared = pending.1.budget().reserve(size_of::<T>())?;
30        pending.1.absorb(shared);
31        Self::with_retention(Arc::new(pending.0), pending.1)
32    }
33}
34
35impl<T: ?Sized> ReadOnlySnapshot<T> {
36    #[must_use]
37    pub fn new(snapshot: Arc<T>) -> Self {
38        Self(snapshot, None, None)
39    }
40
41    pub(crate) fn with_retention(
42        snapshot: Arc<T>,
43        memory: MemoryReservation,
44    ) -> crate::StorageBackendResult<Self> {
45        // Keep the snapshot ahead of its lease on failure, including the shared lease allocation.
46        let mut pending = (snapshot, memory);
47        let shared = pending.1.budget().reserve(size_of::<MemoryReservation>())?;
48        pending.1.absorb(shared);
49        Ok(Self::with_shared_retention(pending.0, Arc::new(pending.1)))
50    }
51
52    /// The owning value can retain the same lease so direct owner snapshots cannot separate shared data from its allowance.
53    pub(crate) fn with_shared_retention(snapshot: Arc<T>, memory: Arc<MemoryReservation>) -> Self {
54        Self(snapshot, Some(memory), None)
55    }
56}
57
58impl<T: ?Sized> Clone for ReadOnlySnapshot<T> {
59    fn clone(&self) -> Self {
60        Self(
61            Arc::clone(&self.0),
62            self.1.as_ref().map(Arc::clone),
63            self.2.clone(),
64        )
65    }
66}
67
68impl<T: ?Sized> std::ops::Deref for ReadOnlySnapshot<T> {
69    type Target = T;
70
71    fn deref(&self) -> &T {
72        &self.0
73    }
74}
75
76fn read_only_error() -> StorageBackendError {
77    StorageBackendError::Other("cannot write a retained storage snapshot".into())
78}
79
80#[cfg(test)]
81mod tests;