Skip to main content

nativeview_store/table/
mod.rs

1//! `NvTable` trait (implemented by `#[derive(NvTable)]`), typed property handles, and the
2//! process-global table slot registry.
3
4mod field;
5#[cfg(test)]
6mod packing_tests;
7#[cfg(test)]
8mod value_tests;
9#[cfg(test)]
10mod wire_tests;
11
12use std::sync::atomic::{AtomicU8, Ordering};
13use std::sync::{Arc, RwLock};
14
15use nativeview_abi::table::{table_flags, Storage, TableDesc, TableKey, Word, MAX_TABLE_SLOTS};
16
17use crate::row::{RowRef, RowWriter};
18
19pub use field::{Prop, Res, ResProp, ScalarField, Str, StrProp, TableField};
20
21/// Maximum number of compiled static table slots (`0..MAX_STATIC_TABLE_SLOTS`).
22/// Wire-declared dynamic tables occupy the disjoint upper range
23/// `MAX_STATIC_TABLE_SLOTS..MAX_TABLE_SLOTS` so static and dynamic slots can never collide.
24pub const MAX_STATIC_TABLE_SLOTS: usize = 96;
25
26/// Process-local table slot (bit index into `NodeRow::tables`).
27#[repr(transparent)]
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
29pub struct TableSlot(pub u8);
30
31impl TableSlot {
32    /// Sentinel slot meaning plain container with no realizing table (`NV_PRIMARY_SLOT_NONE`).
33    pub const NONE: Self = Self(nativeview_abi::NV_PRIMARY_SLOT_NONE);
34
35    #[inline(always)]
36    pub const fn is_none(self) -> bool {
37        self.0 == nativeview_abi::NV_PRIMARY_SLOT_NONE
38    }
39
40    #[inline(always)]
41    pub const fn bit(self) -> u128 {
42        if self.0 >= MAX_TABLE_SLOTS as u8 {
43            0
44        } else {
45            1u128 << self.0
46        }
47    }
48}
49
50/// A word table. Implemented by `#[derive(NvTable)]`; the struct itself is the schema.
51///
52/// # Safety
53///
54/// Implementors must guarantee that:
55/// - [`Self::DESC`] satisfies [`validate_desc_invariants`] (`str_words`, `resource_words`,
56///   `defaults`, and `word_effects` are mutually consistent and string/resource defaults are zero).
57/// - [`Self::from_row_ref`] and [`Self::from_row_writer`] only read/write word indices matching
58///   the declared field kinds in [`Self::DESC`].
59/// - [`Self::slot`] returns the static slot (`< MAX_STATIC_TABLE_SLOTS`) registered for
60///   [`Self::DESC`] via [`register_static`].
61pub unsafe trait NvTable: 'static {
62    const DESC: TableDesc;
63    /// Zero-copy typed row reader tied to the borrowing `NodeStore`'s lifetime.
64    type Ref<'a>: Copy;
65    /// Fluent typed row writer.
66    type Mut<'a>;
67
68    /// Sealed row-reader constructor used by `NodeStore`/`NodeRef`.
69    #[doc(hidden)]
70    fn from_row_ref<'a>(row: RowRef<'a>) -> Self::Ref<'a>;
71
72    /// Sealed row-writer constructor used by `Transaction`/`NodeMut`.
73    #[doc(hidden)]
74    fn from_row_writer<'a>(writer: RowWriter<'a>) -> Self::Mut<'a>;
75
76    /// Process-local slot, registered on first use.
77    fn slot() -> TableSlot;
78}
79
80/// Owned value snapshot of one table row: the `<Table>Value` type `#[derive(NvTable)]` emits for
81/// every table (`Str` → `String`, `Res<R>` → `Option<R>`, inherited fields → `Option<_>`).
82///
83/// Lets value-keyed writers (`nativeview_view::table_value`) stay generic over tables.
84pub trait TableValue: Default {
85    /// The table this value writes.
86    type Table: NvTable;
87
88    /// Writes every field onto `node`'s [`Self::Table`] row inside `tx`.
89    fn write(&self, tx: &mut crate::Transaction<'_>, node: crate::NodeId);
90}
91
92/// Marker and typed listener-mask handle for tables declared with `#[nv_table(events = E)]`.
93///
94/// # Safety
95///
96/// Implementors must guarantee that:
97/// - `(Self::DESC.flags & table_flags::HAS_EVENTS) != 0`,
98/// - `Self::DESC.events_word == 0` and `(Self::DESC.str_words | Self::DESC.resource_words) & 1 == 0`,
99/// - `Self::DESC.defaults[0] == 0`, and
100/// - [`Self::LISTENERS`] addresses word `0` with full 32-bit mask `u32::MAX`.
101pub unsafe trait HasEvents: NvTable + Sized {
102    type Event: nativeview_abi::EventEnum;
103    const LISTENERS: Prop<Self, nativeview_abi::EventSet<Self::Event>>;
104}
105
106/// Owned descriptor for a runtime/wire-declared dynamic table scoped to a single
107/// [`crate::wire::WireDecoder`] / [`crate::NodeStore`] (never leaked into global `REGISTRY`).
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub(crate) struct OwnedTableDesc {
110    pub(crate) key: TableKey,
111    pub(crate) name: Box<str>,
112    pub(crate) schema_hash: u64,
113    pub(crate) storage: Storage,
114    pub(crate) flags: u16,
115    pub(crate) realization_priority: u8,
116    pub(crate) defaults: Box<[Word]>,
117    pub(crate) word_effects: Box<[u8]>,
118    pub(crate) str_words: u32,
119    pub(crate) resource_words: u32,
120}
121
122/// Borrowed descriptor schema fields compared for full wire/registry equality.
123pub(crate) struct TableDescSpec<'a> {
124    pub(crate) schema_hash: u64,
125    pub(crate) storage: Storage,
126    pub(crate) flags: u16,
127    pub(crate) realization_priority: u8,
128    pub(crate) defaults: &'a [Word],
129    pub(crate) word_effects: &'a [u8],
130    pub(crate) str_words: u32,
131    pub(crate) resource_words: u32,
132    /// Resource kind bindings for static descriptors (`None` on wire `DeclareTables`, which
133    /// validates `resource_kinds` via `schema_hash`).
134    pub(crate) resource_kinds: Option<&'a [(u8, nativeview_abi::Key64)]>,
135}
136
137impl OwnedTableDesc {
138    #[inline(always)]
139    pub(crate) fn effects(&self) -> u8 {
140        self.word_effects.iter().fold(0, |a, &e| a | e)
141    }
142
143    pub(crate) fn matches_spec(&self, spec: &TableDescSpec<'_>) -> bool {
144        self.schema_hash == spec.schema_hash
145            && self.storage == spec.storage
146            && (self.flags & !table_flags::HOST_SLOT) == (spec.flags & !table_flags::HOST_SLOT)
147            && self.realization_priority == spec.realization_priority
148            && self.defaults.as_ref() == spec.defaults
149            && self.word_effects.as_ref() == spec.word_effects
150            && self.str_words == spec.str_words
151            && self.resource_words == spec.resource_words
152    }
153}
154
155/// Descriptor backing one [`crate::column::Column`]: compiled static `&'static TableDesc` or
156/// session-scoped `Arc<OwnedTableDesc>` from wire `DeclareTables` (freed on store/decoder drop).
157#[derive(Debug, Clone)]
158pub(crate) enum TableMeta {
159    Static(&'static TableDesc),
160    Dynamic(Arc<OwnedTableDesc>),
161}
162
163impl TableMeta {
164    #[inline(always)]
165    pub(crate) fn key(&self) -> TableKey {
166        match self {
167            Self::Static(d) => d.key,
168            Self::Dynamic(d) => d.key,
169        }
170    }
171
172    #[inline(always)]
173    pub(crate) fn name(&self) -> &str {
174        match self {
175            Self::Static(d) => d.name,
176            Self::Dynamic(d) => &d.name,
177        }
178    }
179
180    #[inline(always)]
181    pub(crate) fn schema_hash(&self) -> u64 {
182        match self {
183            Self::Static(d) => d.schema_hash,
184            Self::Dynamic(d) => d.schema_hash,
185        }
186    }
187
188    #[inline(always)]
189    pub(crate) fn storage(&self) -> Storage {
190        match self {
191            Self::Static(d) => d.storage,
192            Self::Dynamic(d) => d.storage,
193        }
194    }
195
196    #[inline(always)]
197    pub(crate) fn flags(&self) -> u16 {
198        match self {
199            Self::Static(d) => d.flags,
200            Self::Dynamic(d) => d.flags,
201        }
202    }
203
204    #[inline(always)]
205    pub(crate) fn realization_priority(&self) -> u8 {
206        match self {
207            Self::Static(d) => d.realization_priority,
208            Self::Dynamic(d) => d.realization_priority,
209        }
210    }
211
212    #[inline(always)]
213    pub(crate) fn words(&self) -> usize {
214        self.defaults().len()
215    }
216
217    #[inline(always)]
218    pub(crate) fn defaults(&self) -> &[Word] {
219        match self {
220            Self::Static(d) => d.defaults,
221            Self::Dynamic(d) => &d.defaults,
222        }
223    }
224
225    #[inline(always)]
226    pub(crate) fn word_effects(&self) -> &[u8] {
227        match self {
228            Self::Static(d) => d.word_effects,
229            Self::Dynamic(d) => &d.word_effects,
230        }
231    }
232
233    #[inline(always)]
234    pub(crate) fn str_words(&self) -> u32 {
235        match self {
236            Self::Static(d) => d.str_words,
237            Self::Dynamic(d) => d.str_words,
238        }
239    }
240
241    #[inline(always)]
242    pub(crate) fn resource_words(&self) -> u32 {
243        match self {
244            Self::Static(d) => d.resource_words,
245            Self::Dynamic(d) => d.resource_words,
246        }
247    }
248
249    #[inline(always)]
250    pub(crate) fn resource_kind(&self, word: usize) -> Option<nativeview_abi::Key64> {
251        match self {
252            Self::Static(d) => d.resource_kind(word),
253            Self::Dynamic(_) => None,
254        }
255    }
256
257    #[inline(always)]
258    pub(crate) fn effects(&self) -> u8 {
259        match self {
260            Self::Static(d) => d.effects(),
261            Self::Dynamic(d) => d.effects(),
262        }
263    }
264
265    #[inline(always)]
266    pub(crate) fn inherited(&self) -> bool {
267        match self {
268            Self::Static(d) => d.inherited,
269            Self::Dynamic(d) => (d.flags & table_flags::INHERITED) != 0,
270        }
271    }
272
273    #[inline(always)]
274    pub(crate) fn events_word(&self) -> u8 {
275        match self {
276            Self::Static(d) => d.events_word,
277            Self::Dynamic(d) => {
278                if (d.flags & table_flags::HAS_EVENTS) != 0 {
279                    0
280                } else {
281                    nativeview_abi::table::NO_VAL_WORD
282                }
283            }
284        }
285    }
286
287    #[inline(always)]
288    pub(crate) fn as_static(&self) -> Option<&'static TableDesc> {
289        match self {
290            Self::Static(d) => Some(*d),
291            Self::Dynamic(_) => None,
292        }
293    }
294}
295
296// ---------------------------------------------------------------------------------------------
297// Process-global slot registry
298// ---------------------------------------------------------------------------------------------
299
300static REGISTRY: RwLock<Vec<&'static TableDesc>> = RwLock::new(Vec::new());
301
302/// Error registering a table.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub enum RegistryError {
305    /// All `MAX_STATIC_TABLE_SLOTS` slots are taken.
306    Full,
307    /// A table with this key is registered with a different schema.
308    SchemaMismatch { name: &'static str, key: TableKey },
309}
310
311fn resource_kinds_match(a: &[(u8, nativeview_abi::Key64)], b: &[(u8, nativeview_abi::Key64)]) -> bool {
312    if a.len() != b.len() {
313        return false;
314    }
315    if a == b {
316        return true;
317    }
318    a.iter().all(|entry| {
319        a.iter().filter(|x| *x == entry).count() == b.iter().filter(|x| *x == entry).count()
320    })
321}
322
323pub(crate) fn static_desc_matches(existing: &TableDesc, spec: &TableDescSpec<'_>) -> bool {
324    let resource_kinds_ok = spec
325        .resource_kinds
326        .is_none_or(|rk| resource_kinds_match(existing.resource_kinds, rk));
327    existing.schema_hash == spec.schema_hash
328        && existing.storage == spec.storage
329        && (existing.flags & !table_flags::HOST_SLOT) == (spec.flags & !table_flags::HOST_SLOT)
330        && existing.realization_priority == spec.realization_priority
331        && existing.defaults == spec.defaults
332        && existing.word_effects == spec.word_effects
333        && existing.str_words == spec.str_words
334        && existing.resource_words == spec.resource_words
335        && resource_kinds_ok
336}
337
338fn register_locked(desc: &'static TableDesc) -> Result<TableSlot, RegistryError> {
339    let has_events = (desc.flags & table_flags::HAS_EVENTS) != 0;
340    let events_word_ok = if has_events {
341        desc.events_word == 0
342    } else {
343        desc.events_word == nativeview_abi::table::NO_VAL_WORD
344    };
345    if desc.inherited != ((desc.flags & table_flags::INHERITED) != 0)
346        || !events_word_ok
347        || !validate_desc_invariants(
348            desc.words(),
349            desc.flags,
350            desc.str_words,
351            desc.resource_words,
352            desc.defaults,
353            desc.word_effects,
354        )
355    {
356        return Err(RegistryError::SchemaMismatch {
357            name: desc.name,
358            key: desc.key,
359        });
360    }
361    let mut reg = REGISTRY.write().unwrap_or_else(|e| e.into_inner());
362    if let Some(i) = reg.iter().position(|d| d.key == desc.key) {
363        let spec = TableDescSpec {
364            schema_hash: desc.schema_hash,
365            storage: desc.storage,
366            flags: desc.flags,
367            realization_priority: desc.realization_priority,
368            defaults: desc.defaults,
369            word_effects: desc.word_effects,
370            str_words: desc.str_words,
371            resource_words: desc.resource_words,
372            resource_kinds: Some(desc.resource_kinds),
373        };
374        if !static_desc_matches(reg[i], &spec) {
375            return Err(RegistryError::SchemaMismatch {
376                name: desc.name,
377                key: desc.key,
378            });
379        }
380        return Ok(TableSlot(i as u8));
381    }
382    if reg.len() >= MAX_STATIC_TABLE_SLOTS {
383        return Err(RegistryError::Full);
384    }
385    reg.push(desc);
386    Ok(TableSlot((reg.len() - 1) as u8))
387}
388
389/// Slot of a compiled table; caches it in the table's `static` slot cell. Used by the derive.
390#[doc(hidden)]
391#[cold]
392pub fn register_static(desc: &'static TableDesc, cell: &AtomicU8) -> TableSlot {
393    let slot = register_locked(desc)
394        .expect("NvTable static registration must succeed (unique key and <= 96 tables)");
395    cell.store(slot.0, Ordering::Release);
396    slot
397}
398
399/// Validates a descriptor's word/string/resource/default invariants before registration.
400pub(crate) fn validate_desc_invariants(
401    words: usize,
402    flags: u16,
403    str_words: u32,
404    resource_words: u32,
405    defaults: &[Word],
406    word_effects: &[u8],
407) -> bool {
408    if words == 0 || words > nativeview_abi::table::MAX_TABLE_WORDS {
409        return false;
410    }
411    if defaults.len() != words || word_effects.len() != words {
412        return false;
413    }
414    if (flags & table_flags::INHERITED) != 0 && (flags & table_flags::HAS_EVENTS) != 0 {
415        return false;
416    }
417    if (flags & table_flags::INHERITED) != 0
418        && (words < 2
419            || defaults[0] != 0
420            || word_effects[0] != 0
421            || ((str_words | resource_words) & 1) != 0)
422    {
423        return false;
424    }
425    if (flags & table_flags::HAS_EVENTS) != 0
426        && (defaults[0] != 0 || ((str_words | resource_words) & 1) != 0)
427    {
428        return false;
429    }
430    let valid_mask = if words == 32 { u32::MAX } else { (1u32 << words) - 1 };
431    if (str_words & !valid_mask) != 0 || (resource_words & !valid_mask) != 0 {
432        return false;
433    }
434    // No string bit at the last word (strings occupy two consecutive words `w` and `w + 1`).
435    if (str_words & (1u32 << (words - 1))) != 0 {
436        return false;
437    }
438    // No overlapping consecutive string words.
439    if (str_words & (str_words << 1)) != 0 {
440        return false;
441    }
442    // No overlap between string word pairs and resource words.
443    if ((str_words | (str_words << 1)) & resource_words) != 0 {
444        return false;
445    }
446    // String and resource defaults must be zero so uninitialized rows never point into slabs/resources.
447    let mut sm = str_words;
448    while sm != 0 {
449        let w = sm.trailing_zeros() as usize;
450        sm &= sm - 1;
451        if defaults[w] != 0 || defaults[w + 1] != 0 {
452            return false;
453        }
454    }
455    let mut rm = resource_words;
456    while rm != 0 {
457        let w = rm.trailing_zeros() as usize;
458        rm &= rm - 1;
459        if defaults[w] != 0 {
460            return false;
461        }
462    }
463    true
464}
465
466/// Looks up a compiled/static table by key without mutating `REGISTRY`.
467pub(crate) fn lookup_static(key: TableKey) -> Option<(TableSlot, &'static TableDesc)> {
468    let reg = REGISTRY.read().unwrap_or_else(|e| e.into_inner());
469    reg.iter()
470        .position(|d| d.key == key)
471        .map(|i| (TableSlot(i as u8), reg[i]))
472}
473
474/// Descriptor of a static slot, if registered.
475pub(crate) fn try_desc(slot: TableSlot) -> Option<&'static TableDesc> {
476    REGISTRY
477        .read()
478        .unwrap_or_else(|e| e.into_inner())
479        .get(slot.0 as usize)
480        .copied()
481}
482
483/// Slot registered for `key`, if any.
484pub fn slot_of(key: TableKey) -> Option<TableSlot> {
485    let reg = REGISTRY.read().unwrap_or_else(|e| e.into_inner());
486    reg.iter()
487        .position(|d| d.key == key)
488        .map(|i| TableSlot(i as u8))
489}
490
491/// Descriptor of a registered slot.
492pub fn desc(slot: TableSlot) -> &'static TableDesc {
493    REGISTRY.read().unwrap_or_else(|e| e.into_inner())[slot.0 as usize]
494}
495
496/// Deterministic 64-bit XXH64 digest over an arbitrary iterator of `(TableKey, schema_hash)` pairs
497/// (sorted and deduplicated so iteration order, duplicates, and lazy registration state never
498/// affect the hash).
499pub(crate) fn hash_table_schema_pairs(pairs: impl IntoIterator<Item = (u64, u64)>) -> u64 {
500    let mut pairs: Vec<(u64, u64)> = pairs.into_iter().collect();
501    pairs.sort_unstable();
502    pairs.dedup();
503    let mut hasher = nativeview_abi::Xxh64Hasher::new(0x4E56_4554_424C_5331); // "NV_TBLS1"
504    for (key, hash) in pairs {
505        hasher.update(&key.to_le_bytes());
506        hasher.update(&hash.to_le_bytes());
507    }
508    hasher.digest()
509}
510
511/// Deterministic 64-bit XXH64 digest over an explicit slice of static table descriptors
512/// (sorted and deduplicated by `TableKey` so slice order, duplicate descriptors, and process-global
513/// lazy registration state never affect the hash).
514pub fn tables_schema_hash(descs: &[&'static TableDesc]) -> u64 {
515    hash_table_schema_pairs(descs.iter().map(|d| (d.key.0, d.schema_hash)))
516}