Skip to main content

rostra_client_db/
extension.rs

1use std::marker::PhantomData;
2
3use bincode::{Decode, Encode};
4
5use crate::{DbResult, ReadTransaction, ReservedExtensionTableSnafu, WriteTransactionCtx};
6
7/// Built-in table-name prefixes unavailable to extension tables.
8pub const EXTENSION_RESERVED_TABLE_PREFIXES: &[&str] = &[
9    "_total_migration_",
10    "content_",
11    "db_",
12    "events_",
13    "ids_",
14    "reception_order_",
15    "shoutbox_",
16    "social_",
17];
18
19/// A typed definition for a caller-owned extension table.
20///
21/// Extension tables are a trusted in-process persistence facility. Their
22/// owners are responsible for schema compatibility, data invariants, and stable
23/// names. Core event replay and convergence do not rebuild or validate their
24/// contents, although total database migrations preserve extension tables
25/// byte-for-byte.
26///
27/// The durable schema consists of the table name and the exact bincode key and
28/// value encodings. The API cannot detect two components opening the same name
29/// with different Rust key or value types.
30///
31/// The exact name `events` and names beginning with any
32/// [`EXTENSION_RESERVED_TABLE_PREFIXES`] entry are rejected. New tables should
33/// use a globally unique, component-qualified name. Unqualified names are
34/// supported only to retain existing extension data.
35pub struct ExtensionTableDefinition<'a, K, V> {
36    /// Caller-owned redb table name.
37    name: &'a str,
38    /// Typed key and value marker.
39    marker: PhantomData<(K, V)>,
40}
41
42impl<'a, K, V> ExtensionTableDefinition<'a, K, V> {
43    /// Defines a caller-owned extension table.
44    pub const fn new(name: &'a str) -> Self {
45        Self {
46            name,
47            marker: PhantomData,
48        }
49    }
50
51    /// Returns the persistent redb table name.
52    pub const fn name(&self) -> &'a str {
53        self.name
54    }
55}
56
57/// Read-only access to trusted, caller-owned extension tables.
58pub struct ExtensionReadTransaction<'a> {
59    /// Underlying client-database read transaction.
60    tx: &'a ReadTransaction,
61}
62
63impl<'a> ExtensionReadTransaction<'a> {
64    pub(crate) fn new(tx: &'a ReadTransaction) -> Self {
65        Self { tx }
66    }
67
68    /// Opens a caller-owned extension table after checking its reserved name.
69    ///
70    /// Corrupt encoded values return an error from
71    /// [`redb_bincode::AccessGuard::value_try`]; the infallible `value` method
72    /// panics. Range iteration likewise panics before yielding a corrupt key.
73    ///
74    /// # Errors
75    ///
76    /// Returns [`crate::DbError::ReservedExtensionTable`] for a reserved name
77    /// and propagates table-open errors.
78    pub fn open_table<K, V>(
79        &self,
80        definition: &ExtensionTableDefinition<'_, K, V>,
81    ) -> DbResult<redb_bincode::ReadOnlyTable<K, V>>
82    where
83        K: Encode + Decode<()>,
84        V: Encode + Decode<()>,
85    {
86        ensure_extension_table(definition.name)?;
87        Ok(self
88            .tx
89            .open_table(&redb_bincode::TableDefinition::new(definition.name))?)
90    }
91}
92
93/// Mutable access to trusted, caller-owned extension tables.
94///
95/// This transaction deliberately exposes only typed extension-table access. It
96/// cannot open built-in graph, lifecycle, or projection tables and cannot
97/// register internal post-commit actions.
98pub struct ExtensionWriteTransaction<'a> {
99    /// Underlying serialized client-database write transaction.
100    tx: &'a WriteTransactionCtx,
101}
102
103impl<'a> ExtensionWriteTransaction<'a> {
104    pub(crate) fn new(tx: &'a WriteTransactionCtx) -> Self {
105        Self { tx }
106    }
107
108    /// Opens a caller-owned extension table after checking its reserved name.
109    ///
110    /// # Errors
111    ///
112    /// Returns [`crate::DbError::ReservedExtensionTable`] for a reserved name
113    /// and propagates table-open errors.
114    pub fn open_table<K, V>(
115        &self,
116        definition: &ExtensionTableDefinition<'_, K, V>,
117    ) -> DbResult<redb_bincode::Table<'_, K, V>>
118    where
119        K: Encode + Decode<()>,
120        V: Encode + Decode<()>,
121    {
122        ensure_extension_table(definition.name)?;
123        Ok(self
124            .tx
125            .open_table(&redb_bincode::TableDefinition::new(definition.name))?)
126    }
127}
128
129fn ensure_extension_table(name: &str) -> DbResult<()> {
130    if is_reserved_extension_table(name) {
131        return ReservedExtensionTableSnafu {
132            name: name.to_owned(),
133        }
134        .fail();
135    }
136    Ok(())
137}
138
139pub(crate) fn is_reserved_extension_table(name: &str) -> bool {
140    name == "events"
141        || EXTENSION_RESERVED_TABLE_PREFIXES
142            .iter()
143            .any(|prefix| name.starts_with(prefix))
144}
145
146/// Defines a typed caller-owned extension table.
147///
148/// Use a stable, globally unique, component-qualified name because the name is
149/// persisted in redb. Existing unqualified names may be retained for data
150/// compatibility. See [`ExtensionTableDefinition`] for ownership, replay, and
151/// reserved-name obligations.
152///
153/// ```
154/// rostra_client_db::define_extension_table!(
155///     cache_entries, "example.org/cache_entries": u64 => String
156/// );
157///
158/// assert_eq!(cache_entries::TABLE.name(), "example.org/cache_entries");
159/// ```
160#[macro_export]
161macro_rules! define_extension_table {
162    ($(#[$outer:meta])*
163        $name:ident, $persistent_name:literal : $k:ty => $v:ty) => {
164        #[allow(unused)]
165        $(#[$outer])*
166        pub mod $name {
167            use super::*;
168            pub type Key = $k;
169            pub type Value = $v;
170            pub type Definition<'a> =
171                $crate::ExtensionTableDefinition<'a, Key, Value>;
172            pub const TABLE: Definition<'static> =
173                $crate::ExtensionTableDefinition::new($persistent_name);
174        }
175    };
176}