Skip to main content

alopex_core/kv/
mod.rs

1//! Traits for the Key-Value storage layer.
2
3use crate::error::Result;
4use crate::txn::TxnManager;
5use crate::types::{Key, TxnId, TxnMode, Value};
6
7/// Runtime statistics exposed by SQL system functions.
8#[derive(Debug, Clone, PartialEq)]
9pub enum RuntimeStats {
10    /// Statistics for the in-memory store.
11    Memory(crate::kv::memory::MemoryStats),
12    /// Statistics for the LSM store.
13    Lsm(crate::lsm::metrics::LsmMetricsSnapshot),
14}
15
16#[cfg(feature = "test-hooks")]
17pub mod hooks;
18
19/// MemoryKV / LsmKV を 1 つの型として扱うためのラッパー。
20pub mod any;
21/// Async adapter for sync KV stores (requires `tokio` feature).
22#[cfg(feature = "tokio")]
23pub mod async_adapter;
24/// Async KV traits (requires `async` feature).
25#[cfg(feature = "async")]
26pub mod async_kv;
27/// Atomic local range-change journal capability.
28pub mod change_journal;
29pub mod memory;
30/// Owned session contracts for long-lived local consumers.
31pub mod owned;
32/// Read-point capability for fenced distributed reads.
33pub mod read_at;
34/// Storage mode selection helpers (disk vs memory).
35pub mod storage;
36
37/// S3-backed storage (requires `s3` feature).
38#[cfg(feature = "s3")]
39pub mod s3;
40
41pub use any::AnyKV;
42#[cfg(feature = "tokio")]
43pub use async_adapter::{AsyncKVStoreAdapter, AsyncKVTransactionAdapter};
44#[cfg(feature = "async")]
45pub use async_kv::{AsyncKVStore, AsyncKVTransaction};
46pub use change_journal::{
47    decode_range_change, journal_key, stage_range_change, RangeChangeJournalCapability,
48    RangeChangePayload, RangeChangeRecord,
49};
50pub use owned::{
51    OwnedKVScan, OwnedKVStore, OwnedKVTransaction, OwnedKVTransactionAdapter, OwnedReadLease,
52    OwnedReadOptions, OwnedReadSession, OwnedReadSessionApi, OwnedSessionFactory,
53    OwnedTransactionLease, OwnedTransactionSession, OwnedTransactionSessionApi,
54};
55pub use read_at::{ReadAtCapability, ReadAtError, ReadAtPoint, ReadAtResult};
56
57#[cfg(feature = "s3")]
58pub use s3::{S3Config, S3KV};
59
60/// A transaction for interacting with the key-value store.
61///
62/// Transactions provide snapshot isolation.
63pub trait KVTransaction<'a> {
64    /// Returns the transaction's unique ID.
65    fn id(&self) -> TxnId;
66
67    /// Returns the transaction's mode (ReadOnly or ReadWrite).
68    fn mode(&self) -> TxnMode;
69
70    /// Retrieves the value for a given key.
71    fn get(&mut self, key: &Key) -> Result<Option<Value>>;
72
73    /// Sets a value for a given key.
74    /// This operation is buffered and will be applied on commit.
75    ///
76    /// # Errors
77    ///
78    /// Returns an error if the transaction is read-only.
79    fn put(&mut self, key: Key, value: Value) -> Result<()>;
80
81    /// Deletes a key-value pair.
82    /// This operation is buffered and will be applied on commit.
83    ///
84    /// # Errors
85    ///
86    /// Returns an error if the transaction is read-only.
87    fn delete(&mut self, key: Key) -> Result<()>;
88
89    /// Scans all key-value pairs whose keys start with the given prefix.
90    ///
91    /// Implementations must respect snapshot isolation: results should reflect
92    /// the transaction's start version plus its in-flight writes.
93    fn scan_prefix(&mut self, prefix: &[u8])
94        -> Result<Box<dyn Iterator<Item = (Key, Value)> + '_>>;
95
96    /// Scans key-value pairs in the half-open range [start, end).
97    ///
98    /// Implementations must respect snapshot isolation: results should reflect
99    /// the transaction's start version plus its in-flight writes.
100    fn scan_range(
101        &mut self,
102        start: &[u8],
103        end: &[u8],
104    ) -> Result<Box<dyn Iterator<Item = (Key, Value)> + '_>>;
105
106    /// Commits the transaction, applying all buffered writes.
107    ///
108    /// This method consumes the transaction. On success, all writes become
109    /// visible to subsequent transactions. On failure, no changes are applied.
110    fn commit_self(self) -> Result<()>;
111
112    /// Rolls back the transaction, discarding all buffered writes.
113    ///
114    /// This method consumes the transaction. All pending writes are discarded.
115    fn rollback_self(self) -> Result<()>;
116}
117
118/// The main trait for a key-value storage engine.
119///
120/// This trait provides the primary entry point for interacting with the database.
121pub trait KVStore: Send + Sync {
122    /// The transaction type for this store.
123    type Transaction<'a>: KVTransaction<'a>
124    where
125        Self: 'a;
126
127    /// The transaction manager for this store.
128    type Manager<'a>: TxnManager<'a, Self::Transaction<'a>>
129    where
130        Self: 'a;
131
132    /// Returns the transaction manager for this store.
133    fn txn_manager(&self) -> Self::Manager<'_>;
134
135    /// A convenience method to begin a new transaction.
136    fn begin(&self, mode: TxnMode) -> Result<Self::Transaction<'_>>;
137
138    /// Reports whether this backend can open a retained snapshot at a
139    /// caller-provided cluster data epoch.
140    ///
141    /// A normal `begin(ReadOnly)` snapshot is intentionally not evidence for a
142    /// distributed read point: it has only node-local transaction semantics.
143    /// Backends must return [`ReadAtCapability::Unavailable`] unless they can
144    /// retain and prove the requested epoch, schema, and index cut.
145    fn read_at_capability(&self) -> ReadAtCapability {
146        ReadAtCapability::unavailable("backend does not prove retained cluster read points")
147    }
148
149    /// Opens a read-only snapshot at a previously fenced cluster read point.
150    ///
151    /// The safe default never substitutes a local transaction for `point`.
152    /// A backend that advertises [`ReadAtCapability::Available`] must override
153    /// this method and validate retention before returning a transaction.
154    fn begin_read_at(&self, point: &ReadAtPoint) -> ReadAtResult<Self::Transaction<'_>> {
155        Err(self
156            .read_at_capability()
157            .unavailable_error(point, "backend did not implement begin_read_at"))
158    }
159
160    /// Returns a point-in-time runtime statistics snapshot, when supported.
161    fn runtime_stats(&self) -> Option<RuntimeStats> {
162        None
163    }
164
165    /// Sets the memory limit in bytes, when supported.
166    fn set_memory_limit_bytes(&self, _limit: Option<usize>) -> Result<()> {
167        Ok(())
168    }
169
170    /// Sets the cache capacity in bytes, when supported.
171    fn set_cache_capacity_bytes(&self, _capacity: usize) -> Result<()> {
172        Ok(())
173    }
174
175    /// Clears the cache and returns the number of bytes removed.
176    fn clear_cache(&self) -> Result<usize> {
177        Ok(0)
178    }
179}