Skip to main content

nativeview_store/wire/
decode.rs

1//! `NV02` bytes → replica `NodeStore` mutations (inside a [`Transaction`]).
2
3use std::sync::Arc;
4
5use nativeview_abi::Key64;
6use nativeview_abi::table::{MAX_TABLE_SLOTS, Storage, table_flags};
7
8use crate::id::{NodeId, ResourceId};
9use crate::store::NodeStore;
10use crate::table::{self, OwnedTableDesc, TableSlot};
11use crate::tx::Transaction;
12
13use super::budget::{MAX_RESOURCE_SLOTS, SessionBudget};
14use super::{HEADER_WORDS, MAGIC, Op, VERSION, WireError, pad4_checked};
15
16/// Maximum length of a runtime-declared table name in `Op::DeclareTables`.
17const MAX_TABLE_NAME_BYTES: usize = 128;
18
19/// Receiver-side session state: wire slot → local slot, session-scoped dynamic table descriptors
20/// (never leaked into global `REGISTRY`), session slot-memory budget, and child scratch buffer.
21#[derive(Debug, Clone)]
22pub struct WireDecoder {
23    map: [u8; MAX_TABLE_SLOTS],
24    dynamic_descs: Vec<(TableSlot, Arc<OwnedTableDesc>)>,
25    next_dynamic_slot: TableSlot,
26    dynamic_exhausted: bool,
27    kids_scratch: Vec<NodeId>,
28    budget: SessionBudget,
29    res_children_scratch: Vec<ResourceId>,
30    /// Bounds the CPU of resource-graph cycle checks per frame (hostile deep child chains).
31    cycle_budget: usize,
32}
33
34impl Default for WireDecoder {
35    fn default() -> Self {
36        Self {
37            map: [u8::MAX; MAX_TABLE_SLOTS],
38            dynamic_descs: Vec::new(),
39            next_dynamic_slot: TableSlot((MAX_TABLE_SLOTS - 1) as u8),
40            dynamic_exhausted: false,
41            kids_scratch: Vec::new(),
42            budget: SessionBudget::default(),
43            res_children_scratch: Vec::new(),
44            cycle_budget: 0,
45        }
46    }
47}
48
49struct R<'a> {
50    b: &'a [u8],
51    at: usize,
52}
53
54impl<'a> R<'a> {
55    #[inline(always)]
56    fn remaining(&self) -> usize {
57        self.b.len().saturating_sub(self.at)
58    }
59
60    #[inline]
61    fn u32(&mut self) -> Result<u32, WireError> {
62        let end = self.at.checked_add(4).ok_or(WireError::Truncated)?;
63        let s = self.b.get(self.at..end).ok_or(WireError::Truncated)?;
64        self.at = end;
65        Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
66    }
67
68    fn bytes(&mut self, len: usize) -> Result<&'a [u8], WireError> {
69        let end = self.at.checked_add(len).ok_or(WireError::Truncated)?;
70        let next = pad4_checked(end).ok_or(WireError::Truncated)?;
71        if next > self.b.len() {
72            return Err(WireError::Truncated);
73        }
74        let s = &self.b[self.at..end];
75        self.at = next;
76        Ok(s)
77    }
78
79    fn node(&mut self) -> Result<NodeId, WireError> {
80        self.u32().map(NodeId::from_raw_or_null)
81    }
82}
83
84impl WireDecoder {
85    pub fn reset(&mut self) {
86        self.map = [u8::MAX; MAX_TABLE_SLOTS];
87        self.dynamic_descs.clear();
88        self.next_dynamic_slot = TableSlot((MAX_TABLE_SLOTS - 1) as u8);
89        self.dynamic_exhausted = false;
90        self.kids_scratch.clear();
91        self.res_children_scratch.clear();
92        self.budget.reset();
93    }
94
95    /// Maximum `NodeStore` slot hint a Frame-0 pre-reservation may claim for `wire_bytes` without
96    /// exceeding the session slot-memory ceiling before decoding starts.
97    #[inline]
98    pub fn max_frame0_node_hint(wire_bytes: usize) -> usize {
99        SessionBudget::max_frame0_node_hint(wire_bytes)
100    }
101
102    /// Returns every active `(wire_slot, local_slot)` table mapping declared in this decoder
103    /// session, including sparse tables with zero currently-attached rows.
104    pub fn declared_wire_tables(&self) -> impl Iterator<Item = (u8, TableSlot)> + '_ {
105        self.map
106            .iter()
107            .enumerate()
108            .filter_map(|(wire, &local)| (local != u8::MAX).then_some((wire as u8, TableSlot(local))))
109    }
110
111    fn slot_layout(store: &NodeStore, slot: TableSlot) -> Option<(usize, u32, u32)> {
112        if let Some(m) = store.table_meta(slot) {
113            return Some((m.words(), m.str_words(), m.resource_words()));
114        }
115        table::try_desc(slot).map(|d| (d.words(), d.str_words, d.resource_words))
116    }
117
118    /// Declared resource kind of `word` in `slot`, falling back to the static registry before the
119    /// replica lazily allocates the column on its first `Op::Patch`.
120    fn slot_resource_kind(store: &NodeStore, slot: TableSlot, word: usize) -> Option<Key64> {
121        match store.table_meta(slot) {
122            Some(m) => m.resource_kind(word),
123            None => table::try_desc(slot).and_then(|d| d.resource_kind(word)),
124        }
125    }
126
127    fn local(&self, wire: u8) -> Result<TableSlot, WireError> {
128        match self.map.get(wire as usize) {
129            Some(&s) if s != u8::MAX => Ok(TableSlot(s)),
130            _ => Err(WireError::UndeclaredTable(wire)),
131        }
132    }
133
134    /// Validates the `NV02` 24-byte header (alignment, magic, version, flags == 0, exact word
135    /// length) and returns `(frame, op_count)` without mutating any state.
136    pub fn validate_header(bytes: &[u8]) -> Result<(u64, u32), WireError> {
137        if !bytes.len().is_multiple_of(4) {
138            return Err(WireError::Misaligned);
139        }
140        let mut r = R { b: bytes, at: 0 };
141        let magic = r.u32()?;
142        if magic != MAGIC {
143            return Err(WireError::BadMagic(magic));
144        }
145        let ver_flags = r.u32()?;
146        let version = ver_flags as u16;
147        if version != VERSION {
148            return Err(WireError::UnsupportedVersion(version));
149        }
150        let flags = (ver_flags >> 16) as u16;
151        if flags != 0 {
152            return Err(WireError::UnsupportedFlags(flags));
153        }
154        let frame = r.u32()? as u64 | (r.u32()? as u64) << 32;
155        let ops = r.u32()?;
156        let words = r.u32()? as usize;
157        if words.checked_mul(4) != Some(bytes.len()) || r.at != HEADER_WORDS * 4 {
158            return Err(WireError::Truncated);
159        }
160        Ok((frame, ops))
161    }
162
163    /// Applies one `NV02` frame to the replica behind `tx`; returns the frame number.
164    pub fn apply(&mut self, tx: &mut Transaction<'_>, bytes: &[u8]) -> Result<u64, WireError> {
165        let (frame, ops) = Self::validate_header(bytes)?;
166        let fresh_store = tx.store().frame() == 0
167            && tx.store().capacity() <= 1
168            && tx.store().resources.slots() <= 1
169            && tx.store().table_slots().next().is_none();
170        if self.budget.begin_frame(frame, bytes.len(), fresh_store) {
171            // Account for any pre-reserved `NodeStore::nodes` capacity (e.g. caller invoked
172            // `reserve_for_frame0` before `apply`) so pre-sizing can never bypass `SessionBudget`.
173            let pre_reserved = tx
174                .store()
175                .nodes_cap()
176                .saturating_sub(2)
177                .checked_mul(size_of::<crate::store::NodeRow>())
178                .ok_or(WireError::Budget)?;
179            if pre_reserved > 0 {
180                self.budget.charge(pre_reserved)?;
181            }
182        }
183        self.cycle_budget = (bytes.len() / 4).max(1024).saturating_mul(8);
184        let mut r = R {
185            b: bytes,
186            at: HEADER_WORDS * 4,
187        };
188        for _ in 0..ops {
189            let head = r.u32()?;
190            let len = (r.u32()? as usize)
191                .checked_mul(4)
192                .ok_or(WireError::Truncated)?;
193            let end = r.at.checked_add(len).ok_or(WireError::Truncated)?;
194            let body = bytes.get(r.at..end).ok_or(WireError::Truncated)?;
195            r.at = end;
196            let op = Op::try_from_u8(head as u8).ok_or(WireError::UnknownOp(head as u8))?;
197            let inline_count = head >> 16;
198            let mut body_r = R { b: body, at: 0 };
199            let count = if inline_count != 0xFFFF {
200                inline_count
201            } else {
202                body_r.u32()?
203            };
204            self.op(tx, op, (head >> 8) as u8, count, &mut body_r, bytes.len())?;
205            if body_r.at != body.len() {
206                return Err(WireError::TrailingBytes);
207            }
208        }
209        if r.at != bytes.len() {
210            return Err(WireError::TrailingBytes);
211        }
212        Ok(frame)
213    }
214
215    fn op(
216        &mut self,
217        tx: &mut Transaction<'_>,
218        op: Op,
219        table: u8,
220        count: u32,
221        r: &mut R<'_>,
222        frame_bytes: usize,
223    ) -> Result<(), WireError> {
224        match op {
225            Op::DeclareTables => {
226                // Minimum entry size: 8 header words + >=1 default + >=1 effect word + name_len = 44 bytes.
227                if (count as usize) > r.remaining() / 44 {
228                    return Err(WireError::Truncated);
229                }
230                for _ in 0..count {
231                    self.declare(tx, r)?;
232                }
233            }
234            Op::CreateNodes => {
235                if (count as usize) > r.remaining() / 4 {
236                    return Err(WireError::Truncated);
237                }
238                let is_fresh_nodes = tx.store().capacity() <= 1;
239                let existing_creatable = tx.store().capacity().saturating_sub(1);
240                let min_new_slots = (count as usize).saturating_sub(existing_creatable);
241                if min_new_slots > 0 {
242                    let min_needed = tx
243                        .store()
244                        .capacity()
245                        .checked_add(min_new_slots)
246                        .ok_or(WireError::Budget)?;
247                    tx.store_mut()
248                        .reserve_nodes_budgeted(min_needed, &mut self.budget)?;
249                }
250                if is_fresh_nodes && count > 1 {
251                    tx.store_mut()
252                        .reserve_aux_for_frame0(count as usize, frame_bytes)?;
253                }
254                for _ in 0..count {
255                    let id = r.node()?;
256                    if !tx.store_mut().try_create_at(id, Some(&mut self.budget))? {
257                        return Err(WireError::NodeExists(id.raw()));
258                    }
259                }
260            }
261            Op::DefineResources => {
262                // Minimum entry size: id + kind_lo + kind_hi + flags + child_count + byte_len = 24 bytes.
263                if (count as usize) > r.remaining() / 24 {
264                    return Err(WireError::Truncated);
265                }
266                for _ in 0..count {
267                    let id = r.u32()?;
268                    let rid = ResourceId(id);
269                    if rid.index() == 0 {
270                        return Err(WireError::Resource { id, kind: 0 });
271                    }
272                    if rid.index() >= MAX_RESOURCE_SLOTS as usize {
273                        return Err(WireError::Budget);
274                    }
275                    let kind = Key64::from_halves(r.u32()?, r.u32()?);
276                    let flags = r.u32()?;
277                    if (flags & !1u32) != 0 {
278                        return Err(WireError::Resource { id, kind: kind.0 });
279                    }
280                    let ephemeral = (flags & 1) != 0;
281                    let child_count = r.u32()? as usize;
282                    if child_count > r.remaining() / 4 {
283                        return Err(WireError::Truncated);
284                    }
285                    self.res_children_scratch.clear();
286                    for _ in 0..child_count {
287                        self.res_children_scratch.push(ResourceId(r.u32()?));
288                    }
289                    let len = r.u32()? as usize;
290                    if !len.is_multiple_of(4) {
291                        return Err(WireError::Resource { id, kind: kind.0 });
292                    }
293                    let blob = r.bytes(len)?;
294                    if !tx.store_mut().resources.define_at_with_budget(
295                        rid,
296                        kind,
297                        ephemeral,
298                        &self.res_children_scratch,
299                        blob,
300                        &mut self.cycle_budget,
301                        Some(&mut self.budget),
302                    )? {
303                        return Err(WireError::Resource { id, kind: kind.0 });
304                    }
305                }
306            }
307            Op::Patch => {
308                if (count as usize) > r.remaining() / 8 {
309                    return Err(WireError::Truncated);
310                }
311                let slot = self.local(table)?;
312                if count == 0 {
313                    return Ok(());
314                }
315                let (words_usize, str_words, resource_words) =
316                    Self::slot_layout(tx.store(), slot).ok_or(WireError::UndeclaredTable(table))?;
317                let store_cap = tx.store().capacity();
318                tx.store_mut().reserve_column_bulk(
319                    slot,
320                    count as usize,
321                    store_cap,
322                    &mut self.budget,
323                )?;
324                let words = words_usize as u32;
325                for _ in 0..count {
326                    let id = self.live(tx, r.node()?)?;
327                    let mask = r.u32()?;
328                    if words < 32 && mask >> words != 0 {
329                        return Err(WireError::BadMask { mask, words });
330                    }
331                    if str_words & mask != 0 || (str_words << 1) & mask != 0 {
332                        return Err(WireError::BadMask { mask, words });
333                    }
334                    let mut vals = [0u32; 32];
335                    let mut bits = mask;
336                    while bits != 0 {
337                        let i = bits.trailing_zeros() as usize;
338                        bits &= bits - 1;
339                        vals[i] = r.u32()?;
340                        let res = ResourceId(vals[i]);
341                        if resource_words & (1 << i) != 0 && !res.is_none() {
342                            if let Some(expected) = Self::slot_resource_kind(tx.store(), slot, i) {
343                                if tx.store().resources.kind(res) != Some(expected) {
344                                    return Err(WireError::Resource { id: res.0, kind: expected.0 });
345                                }
346                            } else if !tx.store().resources.is_defined(res) {
347                                return Err(WireError::Resource { id: res.0, kind: 0 });
348                            }
349                        }
350                    }
351                    let mut w = tx.try_writer(id, slot, &mut self.budget)?;
352                    let mut bits = mask;
353                    while bits != 0 {
354                        let i = bits.trailing_zeros() as usize;
355                        bits &= bits - 1;
356                        if resource_words & (1 << i) != 0 {
357                            w.put_resource_id_wire(i, ResourceId(vals[i]));
358                        } else if i == 0 && w.desc.inherited() {
359                            w.put_explicit_word(vals[0]);
360                        } else {
361                            w.put(i, 0, u32::MAX, vals[i]);
362                        }
363                    }
364                }
365            }
366            Op::SetStrings => {
367                if (count as usize) > r.remaining() / 8 {
368                    return Err(WireError::Truncated);
369                }
370                let slot = self.local(table)?;
371                if count == 0 {
372                    return Ok(());
373                }
374                let (_, str_words, _) =
375                    Self::slot_layout(tx.store(), slot).ok_or(WireError::UndeclaredTable(table))?;
376                let store_cap = tx.store().capacity();
377                tx.store_mut().reserve_column_bulk(
378                    slot,
379                    count as usize,
380                    store_cap,
381                    &mut self.budget,
382                )?;
383                for _ in 0..count {
384                    let id = self.live(tx, r.node()?)?;
385                    let word_len = r.u32()?;
386                    let word = word_len & 0xFF;
387                    let len = (word_len >> 8) as usize;
388                    let text =
389                        core::str::from_utf8(r.bytes(len)?).map_err(|_| WireError::InvalidUtf8)?;
390                    if word >= 32 || str_words & (1 << word) == 0 {
391                        return Err(WireError::BadMask {
392                            mask: 1 << (word & 31),
393                            words: word,
394                        });
395                    }
396                    tx.try_writer(id, slot, &mut self.budget)?
397                        .put_str(word as usize, text);
398                }
399            }
400            Op::Detach => {
401                if (count as usize) > r.remaining() / 4 {
402                    return Err(WireError::Truncated);
403                }
404                let slot = self.local(table)?;
405                for _ in 0..count {
406                    let id = self.live(tx, r.node()?)?;
407                    tx.try_detach_slot(id, slot)?;
408                }
409            }
410            Op::SetChildren => {
411                if (count as usize) > r.remaining() / 8 {
412                    return Err(WireError::Truncated);
413                }
414                for _ in 0..count {
415                    let parent = self.live(tx, r.node()?)?;
416                    let n = r.u32()? as usize;
417                    if n > r.remaining() / 4 {
418                        return Err(WireError::Truncated);
419                    }
420                    self.kids_scratch.clear();
421                    if self.kids_scratch.capacity() < n {
422                        self.kids_scratch
423                            .try_reserve(n)
424                            .map_err(|_| WireError::Alloc)?;
425                    }
426                    for _ in 0..n {
427                        self.kids_scratch.push(self.live(tx, r.node()?)?);
428                    }
429                    if !tx.try_set_children(parent, &self.kids_scratch) {
430                        return Err(WireError::InvalidChildren);
431                    }
432                }
433            }
434            Op::RemoveNodes => {
435                if (count as usize) > r.remaining() / 4 {
436                    return Err(WireError::Truncated);
437                }
438                for _ in 0..count {
439                    // Descendants may already be gone through their removed ancestor.
440                    let id = r.node()?;
441                    tx.remove(id);
442                }
443            }
444            Op::ReleaseResources => {
445                if (count as usize) > r.remaining() / 4 {
446                    return Err(WireError::Truncated);
447                }
448                // Refcounts mirror row references, so releases already happened through the row
449                // writes / removals above; the list is consumed for framing only.
450                for _ in 0..count {
451                    r.u32()?;
452                }
453            }
454        }
455        Ok(())
456    }
457
458    fn live(&self, tx: &Transaction<'_>, id: NodeId) -> Result<NodeId, WireError> {
459        if tx.store().is_live(id) { Ok(id) } else { Err(WireError::DeadNode(id.raw())) }
460    }
461
462    fn declare(&mut self, tx: &mut Transaction<'_>, r: &mut R<'_>) -> Result<(), WireError> {
463        let key = Key64::from_halves(r.u32()?, r.u32()?);
464        let schema_hash = r.u32()? as u64 | (r.u32()? as u64) << 32;
465        let packed = r.u32()?;
466        let (wire_slot, storage_raw, flags_lo, words) = (
467            packed as u8,
468            (packed >> 8) as u8,
469            (packed >> 16) as u8,
470            (packed >> 24) as usize,
471        );
472        let str_words = r.u32()?;
473        let resource_words = r.u32()?;
474        let priority_and_flags_hi = r.u32()?;
475        if (priority_and_flags_hi >> 16) != 0 {
476            return Err(WireError::SchemaMismatch { key: key.0 });
477        }
478        let realization_priority = (priority_and_flags_hi & 0xFF) as u8;
479        let flags = (flags_lo as u16) | (((priority_and_flags_hi >> 8) as u16) << 8);
480        if words == 0 || words > 32 || wire_slot as usize >= MAX_TABLE_SLOTS {
481            return Err(WireError::BadMask {
482                mask: 0,
483                words: words as u32,
484            });
485        }
486        let storage = match storage_raw {
487            0 => Storage::Dense,
488            1 => Storage::Sparse,
489            _ => return Err(WireError::SchemaMismatch { key: key.0 }),
490        };
491        let mut defaults = Vec::with_capacity(words);
492        for _ in 0..words {
493            defaults.push(r.u32()?);
494        }
495        let effects = r.bytes(words)?.to_vec();
496        let name_len = r.u32()? as usize;
497        if name_len > MAX_TABLE_NAME_BYTES {
498            return Err(WireError::SchemaMismatch { key: key.0 });
499        }
500        let name = core::str::from_utf8(r.bytes(name_len)?).map_err(|_| WireError::InvalidUtf8)?;
501        if !table::validate_desc_invariants(
502            words,
503            flags,
504            str_words,
505            resource_words,
506            &defaults,
507            &effects,
508        ) {
509            return Err(WireError::SchemaMismatch { key: key.0 });
510        }
511
512        let spec = table::TableDescSpec {
513            schema_hash,
514            storage,
515            flags,
516            realization_priority,
517            defaults: &defaults,
518            word_effects: &effects,
519            str_words,
520            resource_words,
521            resource_kinds: None,
522        };
523
524        // 1. Check session-scoped dynamic descriptors FIRST so wire-slot mappings stay stable
525        //    within an active decoder session. Typed Rust module tables must be registered before
526        //    wire decoding begins so they resolve directly through step 2 below.
527        if let Some((dyn_slot, existing)) = self
528            .dynamic_descs
529            .iter()
530            .find(|(_, d)| d.key == key)
531            .cloned()
532        {
533            if !existing.matches_spec(&spec) {
534                return Err(WireError::SchemaMismatch { key: key.0 });
535            }
536            if !tx.store_mut().install_dynamic_table(dyn_slot, existing) {
537                return Err(WireError::SchemaMismatch { key: key.0 });
538            }
539            self.map[wire_slot as usize] = dyn_slot.0;
540            return Ok(());
541        }
542
543        // 2. Compiled static descriptors in `0..MAX_STATIC_TABLE_SLOTS` require full field equality.
544        if let Some((static_slot, existing)) = table::lookup_static(key) {
545            if !table::static_desc_matches(existing, &spec) {
546                return Err(WireError::SchemaMismatch { key: key.0 });
547            }
548            self.map[wire_slot as usize] = static_slot.0;
549            return Ok(());
550        }
551
552        // 3. Allocate a fresh per-session dynamic slot strictly inside
553        //    `MAX_STATIC_TABLE_SLOTS..MAX_TABLE_SLOTS` (disjoint from static slots, zero `Box::leak`).
554        let min_slot = table::MAX_STATIC_TABLE_SLOTS;
555        let mut chosen = None;
556        while !self.dynamic_exhausted {
557            let cand = self.next_dynamic_slot;
558            if (cand.0 as usize) < min_slot {
559                self.dynamic_exhausted = true;
560                break;
561            }
562            if cand.0 as usize == min_slot {
563                self.dynamic_exhausted = true;
564            } else {
565                self.next_dynamic_slot = TableSlot(cand.0 - 1);
566            }
567            if tx.store().table_meta(cand).is_none() {
568                chosen = Some(cand);
569                break;
570            }
571        }
572        let dyn_slot = chosen.ok_or(WireError::TableRegistry)?;
573        let desc = Arc::new(OwnedTableDesc {
574            key,
575            name: name.into(),
576            schema_hash,
577            storage,
578            flags: flags | table_flags::HOST_SLOT,
579            realization_priority,
580            defaults: defaults.into_boxed_slice(),
581            word_effects: effects.into_boxed_slice(),
582            str_words,
583            resource_words,
584        });
585        if !tx
586            .store_mut()
587            .install_dynamic_table(dyn_slot, Arc::clone(&desc))
588        {
589            return Err(WireError::SchemaMismatch { key: key.0 });
590        }
591        self.dynamic_descs.push((dyn_slot, desc));
592        self.map[wire_slot as usize] = dyn_slot.0;
593        Ok(())
594    }
595}