ferravex_render/
status.rs

1//! Opt-in, read-only status. Games own facts, IDs, availability and accepted events.
2//!
3//! IDs are unique across *all* supplied facts and mapped widgets, including omitted
4//! items. Keep each ID attached to one meaning for one owner lifetime. `owner` is a
5//! nonzero game-assigned provenance token, not an authentication credential. Use a
6//! fresh token after replacing a game; do not reuse it while readers retain state.
7//! A bridge belongs to its Rust owner; browser publication belongs to the calling
8//! thread (single-threaded Wasm only). No scene discovery or input execution occurs.
9//!
10//! Epoch starts at 1; serial starts at 0 and increments only on changed, valid
11//! publication. It compares retained semantics, including order and truncation
12//! counts, not omitted source text or simulation ticks. Reset advances epoch,
13//! clears publication and resets serial to 0.
14//! Neither counter wraps: exhaustion is an error retaining last-good data. Browser
15//! reconnect reads the current complete snapshot; it does not replay announcements.
16//! Strings containing u64 values are decimal strings, never JS numbers.
17//!
18//! Runnable headless consumer (also see `tests/journey400_296.rs`):
19//! ```
20//! use ferravex_core::session::{GameSession, SessionState};
21//! use ferravex_render::status::*;
22//! let session = GameSession::new(64., 4, false);
23//! let lifecycle = match session.state() {
24//!     SessionState::Ready => "Ready", _ => "Started",
25//! };
26//! let items = [StatusItem { id: 1, kind: StatusKind::Lifecycle, label: lifecycle }];
27//! let mut bridge = StatusBridge::new(42)?;
28//! let facts = || StatusFacts { items: &items, ui: None, ui_actions: &[] };
29//! assert!(bridge.publish(Some(facts()))?.changed);
30//! assert!(!bridge.publish(Some(facts()))?.changed);
31//! assert!(std::str::from_utf8(bridge.bytes()).unwrap().contains("Ready"));
32//! bridge.publish_browser()?; // Explicit opt-in; host calls after its normal update.
33//! assert!(clear_browser(42)?); // Host teardown, on the same thread.
34//! # Ok::<(), StatusError>(())
35//! ```
36use crate::ui::{UiInspection, UiLabel, UiRole};
37use std::{
38    cell::RefCell,
39    fmt::{self, Write},
40};
41
42/// Hard source-entry/work ceiling; exceeding it rejects the entire snapshot.
43pub const MAX_SOURCE_ITEMS: usize = 128;
44/// Total full source-label bytes, including labels omitted by item capacity.
45pub const MAX_SOURCE_BYTES: usize = 32768;
46/// Retained/published item ceiling (declaration order, then explicit UI map order).
47pub const MAX_ITEMS: usize = 32;
48/// Retained bytes per label. A whole UTF-8 prefix is retained with an explicit flag.
49pub const MAX_LABEL_BYTES: usize = 256;
50/// Maximum JSON bytes, including worst-case control-character escaping.
51pub const MAX_WIRE_BYTES: usize = 57344;
52
53/// Explicit semantic category. Only lifecycle and result text is live-announced.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum StatusKind {
56    Lifecycle,
57    Objective,
58    Result,
59    Action,
60    Notice,
61    Telemetry,
62}
63impl StatusKind {
64    fn name(self) -> &'static str {
65        match self {
66            Self::Lifecycle => "lifecycle",
67            Self::Objective => "objective",
68            Self::Result => "result",
69            Self::Action => "action",
70            Self::Notice => "notice",
71            Self::Telemetry => "telemetry",
72        }
73    }
74}
75/// Borrowed game-authored fact. Action labels may include current remapping hints.
76#[derive(Clone, Copy, Debug)]
77pub struct StatusItem<'a> {
78    pub id: u64,
79    pub kind: StatusKind,
80    pub label: &'a str,
81}
82/// Explicit supported UI meaning; a button is not automatically a game action.
83#[derive(Clone, Copy, Debug)]
84pub struct UiAction {
85    pub widget_id: u64,
86    pub status_id: u64,
87}
88/// Complete current facts, not a patch. `None` passed to publish means unavailable;
89/// `Some` with empty slices means available and empty. Inspection is immutable and
90/// must be from the current finished composition. Host input blocking and semantic
91/// availability remain the game's responsibility: omit blocked mappings yourself.
92pub struct StatusFacts<'a> {
93    pub items: &'a [StatusItem<'a>],
94    pub ui: Option<UiInspection<'a>>,
95    pub ui_actions: &'a [UiAction],
96}
97/// Reported errors leave the last-good bridge/browser publication unchanged.
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub enum StatusError {
100    InvalidOwner,
101    OwnerConflict,
102    SourceItems,
103    SourceBytes,
104    DuplicateId(u64),
105    DuplicateWidget(u64),
106    MultipleSingletons,
107    InspectionUnavailable,
108    OutputCapacity { required_bytes: usize },
109    CounterExhausted,
110}
111/// Bounded publication outcome; truncation counts are for retained labels and
112/// omitted available items (including unavailable full UI labels), respectively.
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub struct StatusUpdate {
115    pub changed: bool,
116    pub epoch: u64,
117    pub serial: u64,
118    pub omitted: usize,
119    pub shortened: usize,
120}
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
122struct Item {
123    id: u64,
124    kind: StatusKind,
125    text: [u8; MAX_LABEL_BYTES],
126    len: usize,
127    truncated: bool,
128}
129const EMPTY: Item = Item {
130    id: 0,
131    kind: StatusKind::Objective,
132    text: [0; MAX_LABEL_BYTES],
133    len: 0,
134    truncated: false,
135};
136#[derive(Clone, Debug, PartialEq, Eq)]
137struct Snapshot {
138    available: bool,
139    items: [Item; MAX_ITEMS],
140    len: usize,
141    omitted: usize,
142    shortened: usize,
143}
144impl Snapshot {
145    fn new(available: bool) -> Self {
146        Self {
147            available,
148            items: [EMPTY; MAX_ITEMS],
149            len: 0,
150            omitted: 0,
151            shortened: 0,
152        }
153    }
154    fn push(&mut self, id: u64, kind: StatusKind, text: &str) {
155        if self.len == MAX_ITEMS {
156            self.omitted += 1;
157            return;
158        }
159        let mut len = text.len().min(MAX_LABEL_BYTES);
160        while !text.is_char_boundary(len) {
161            len -= 1;
162        }
163        let mut item = Item {
164            id,
165            kind,
166            len,
167            truncated: len < text.len(),
168            ..EMPTY
169        };
170        item.text[..len].copy_from_slice(&text.as_bytes()[..len]);
171        self.shortened += usize::from(item.truncated);
172        self.items[self.len] = item;
173        self.len += 1;
174    }
175}
176/// Fixed retained storage, no allocations during ordinary publication. See module
177/// example for complete usage. O(128² + 128×1025 + MAX_WIRE_BYTES) bounded work;
178/// labels are measured by byte length without scanning oversized source text.
179pub struct StatusBridge {
180    owner: u64,
181    epoch: u64,
182    serial: u64,
183    snapshot: Option<Snapshot>,
184    wire: [u8; MAX_WIRE_BYTES],
185    len: usize,
186}
187impl StatusBridge {
188    /// Start an unpublished bridge. No default snapshot or browser adoption.
189    ///
190    /// ```
191    /// use ferravex_render::{status::*, ui::*};
192    /// let mut ui = Ui::new();
193    /// ui.set_inspection_enabled(true);
194    /// ui.begin(Viewport::responsive([640., 480.], [0.; 4]).unwrap());
195    /// ui.button(7, UiRect { min: [20.; 2], size: [160., 48.] },
196    ///     "Resume", true, ButtonStyle::default()).unwrap();
197    /// ui.finish(false); // No input requested by this headless recipe.
198    /// let mappings = [UiAction { widget_id: 7, status_id: 20 }];
199    /// let mut status = StatusBridge::new(100)?;
200    /// status.publish(Some(StatusFacts { items: &[], ui: ui.inspect(),
201    ///     ui_actions: &mappings }))?;
202    /// let mut output = [0; 1024];
203    /// let length = status.write(&mut output)?;
204    /// assert!(std::str::from_utf8(&output[..length]).unwrap().contains("Resume"));
205    /// status.reset()?;
206    /// assert!(status.bytes().is_empty());
207    /// # Ok::<(), StatusError>(())
208    /// ```
209    pub fn new(owner: u64) -> Result<Self, StatusError> {
210        if owner == 0 {
211            return Err(StatusError::InvalidOwner);
212        }
213        Ok(Self {
214            owner,
215            epoch: 1,
216            serial: 0,
217            snapshot: None,
218            wire: [0; MAX_WIRE_BYTES],
219            len: 0,
220        })
221    }
222    /// Validate the entire bounded source before replacing publication. Rejects
223    /// duplicates even in the omitted suffix. At most one lifecycle and result.
224    /// UI maps select only registered, enabled, clipped-in buttons; absent/disabled
225    /// buttons are unavailable actions, not truncation. Missing full labels count
226    /// as omissions; their painter abbreviation is never substituted.
227    pub fn publish(&mut self, facts: Option<StatusFacts<'_>>) -> Result<StatusUpdate, StatusError> {
228        let mut next = Snapshot::new(facts.is_some());
229        if let Some(facts) = facts {
230            let count = facts
231                .items
232                .len()
233                .checked_add(facts.ui_actions.len())
234                .ok_or(StatusError::SourceItems)?;
235            if count > MAX_SOURCE_ITEMS {
236                return Err(StatusError::SourceItems);
237            }
238            let mut ids = [0; MAX_SOURCE_ITEMS];
239            let mut bytes = 0usize;
240            let mut lifecycle = false;
241            let mut result = false;
242            for (i, item) in facts.items.iter().enumerate() {
243                check_id(&ids[..i], item.id)?;
244                ids[i] = item.id;
245                let singleton = match item.kind {
246                    StatusKind::Lifecycle => Some(&mut lifecycle),
247                    StatusKind::Result => Some(&mut result),
248                    _ => None,
249                };
250                if let Some(seen) = singleton {
251                    if *seen {
252                        return Err(StatusError::MultipleSingletons);
253                    }
254                    *seen = true;
255                }
256                add_bytes(&mut bytes, item.label.len())?;
257                next.push(item.id, item.kind, item.label);
258            }
259            if !facts.ui_actions.is_empty() && facts.ui.is_none() {
260                return Err(StatusError::InspectionUnavailable);
261            }
262            for (i, action) in facts.ui_actions.iter().enumerate() {
263                let n = facts.items.len() + i;
264                check_id(&ids[..n], action.status_id)?;
265                ids[n] = action.status_id;
266                if facts.ui_actions[..i]
267                    .iter()
268                    .any(|a| a.widget_id == action.widget_id)
269                {
270                    return Err(StatusError::DuplicateWidget(action.widget_id));
271                }
272                // UiInspection has a hard 1025-entry limit. No generic iterator or
273                // callback can inject an unbounded scan or execute gameplay here.
274                let element = facts.ui.clone().and_then(|mut entries| {
275                    entries.find(|e| {
276                        e.id == Some(action.widget_id)
277                            && e.role == UiRole::Button
278                            && e.interaction_registered
279                    })
280                });
281                if let Some(e) = element.filter(|e| e.enabled && e.visible_bounds.is_some()) {
282                    match e.label {
283                        UiLabel::Full(label) => {
284                            add_bytes(&mut bytes, label.len())?;
285                            next.push(action.status_id, StatusKind::Action, label);
286                        }
287                        UiLabel::Unavailable { required_bytes } => {
288                            add_bytes(&mut bytes, required_bytes)?;
289                            next.omitted += 1;
290                        }
291                    }
292                }
293            }
294        }
295        let changed = self.snapshot.as_ref() != Some(&next);
296        if changed {
297            let serial = self
298                .serial
299                .checked_add(1)
300                .ok_or(StatusError::CounterExhausted)?;
301            // Serialize to private scratch first, never expose partially written data.
302            let mut scratch = [0; MAX_WIRE_BYTES];
303            let mut writer = Writer {
304                out: &mut scratch,
305                len: 0,
306            };
307            encode(&mut writer, self.owner, self.epoch, serial, &next)
308                .expect("fixed wire maximum covers bounded snapshot");
309            let len = writer.len;
310            self.wire.fill(0);
311            self.wire[..len].copy_from_slice(&scratch[..len]);
312            self.len = len;
313            self.serial = serial;
314        }
315        let update = StatusUpdate {
316            changed,
317            epoch: self.epoch,
318            serial: self.serial,
319            omitted: next.omitted,
320            shortened: next.shortened,
321        };
322        self.snapshot = Some(next);
323        Ok(update)
324    }
325    /// Current initialized JSON prefix only; empty before publish/after reset.
326    pub fn bytes(&self) -> &[u8] {
327        &self.wire[..self.len]
328    }
329    /// Atomic caller-buffer copy; tail is untouched and never part of the wire.
330    pub fn write(&self, output: &mut [u8]) -> Result<usize, StatusError> {
331        if output.len() < self.len {
332            return Err(StatusError::OutputCapacity {
333                required_bytes: self.len,
334            });
335        }
336        output[..self.len].copy_from_slice(self.bytes());
337        Ok(self.len)
338    }
339    /// New epoch; same owner and storage. Call publish_browser again if adopted
340    /// so readers see unavailable until the next complete publication.
341    pub fn reset(&mut self) -> Result<(), StatusError> {
342        self.epoch = self
343            .epoch
344            .checked_add(1)
345            .ok_or(StatusError::CounterExhausted)?;
346        self.serial = 0;
347        self.snapshot = None;
348        self.len = 0;
349        self.wire.fill(0);
350        Ok(())
351    }
352    /// Explicit copy to this thread's readonly export slot. Another owner must
353    /// clear its slot before replacement. Repeated identical copies are no-ops.
354    /// Host must call clear_browser on teardown; this does not retain `self`.
355    pub fn publish_browser(&self) -> Result<(), StatusError> {
356        BROWSER.with_borrow_mut(|slot| {
357            if let Some(current) = &slot.data {
358                if current.owner != self.owner {
359                    return Err(StatusError::OwnerConflict);
360                }
361                if current.len == self.len && current.wire[..current.len] == *self.bytes() {
362                    return Ok(());
363                }
364            }
365            let revision = slot
366                .revision
367                .checked_add(1)
368                .ok_or(StatusError::CounterExhausted)?;
369            let current = slot.data.get_or_insert_with(|| {
370                Box::new(BrowserData {
371                    owner: self.owner,
372                    wire: [0; MAX_WIRE_BYTES],
373                    len: 0,
374                })
375            });
376            current.wire.fill(0);
377            current.wire[..self.len].copy_from_slice(self.bytes());
378            current.len = self.len;
379            slot.revision = revision;
380            Ok(())
381        })
382    }
383}
384fn check_id(ids: &[u64], id: u64) -> Result<(), StatusError> {
385    if ids.contains(&id) {
386        Err(StatusError::DuplicateId(id))
387    } else {
388        Ok(())
389    }
390}
391fn add_bytes(total: &mut usize, len: usize) -> Result<(), StatusError> {
392    *total = total
393        .checked_add(len)
394        .filter(|n| *n <= MAX_SOURCE_BYTES)
395        .ok_or(StatusError::SourceBytes)?;
396    Ok(())
397}
398struct Writer<'a> {
399    out: &'a mut [u8],
400    len: usize,
401}
402impl Write for Writer<'_> {
403    fn write_str(&mut self, s: &str) -> fmt::Result {
404        let end = self
405            .len
406            .checked_add(s.len())
407            .filter(|n| *n <= self.out.len())
408            .ok_or(fmt::Error)?;
409        self.out[self.len..end].copy_from_slice(s.as_bytes());
410        self.len = end;
411        Ok(())
412    }
413}
414fn quoted(w: &mut impl Write, text: &str) -> fmt::Result {
415    w.write_char('"')?;
416    for c in text.chars() {
417        match c {
418            '"' => w.write_str("\\\"")?,
419            '\\' => w.write_str("\\\\")?,
420            c if c <= '\u{1f}' => write!(w, "\\u{:04x}", c as u32)?,
421            _ => w.write_char(c)?,
422        }
423    }
424    w.write_char('"')
425}
426fn encode(w: &mut impl Write, owner: u64, epoch: u64, serial: u64, s: &Snapshot) -> fmt::Result {
427    write!(
428        w,
429        "{{\"version\":1,\"provenance\":\"ferravex-status\",\"owner\":\"{owner}\",\"epoch\":\"{epoch}\",\"serial\":\"{serial}\",\"available\":{},\"omitted\":{},\"shortened\":{},\"items\":[",
430        s.available, s.omitted, s.shortened
431    )?;
432    for (i, item) in s.items[..s.len].iter().enumerate() {
433        if i != 0 {
434            w.write_char(',')?;
435        }
436        write!(
437            w,
438            "{{\"id\":\"{}\",\"kind\":\"{}\",\"truncated\":{},\"label\":",
439            item.id,
440            item.kind.name(),
441            item.truncated
442        )?;
443        quoted(
444            w,
445            std::str::from_utf8(&item.text[..item.len]).expect("whole UTF-8 prefix"),
446        )?;
447        w.write_char('}')?;
448    }
449    w.write_str("]}")
450}
451struct BrowserData {
452    owner: u64,
453    wire: [u8; MAX_WIRE_BYTES],
454    len: usize,
455}
456struct BrowserSlot {
457    revision: u64,
458    data: Option<Box<BrowserData>>,
459}
460thread_local! { static BROWSER: RefCell<BrowserSlot> = const { RefCell::new(BrowserSlot { revision: 0, data: None }) }; }
461/// Remove only this owner's publication, freeing storage. Checked revision never
462/// wraps. No listeners, loops or action exports exist. See module cleanup recipe.
463pub fn clear_browser(owner: u64) -> Result<bool, StatusError> {
464    BROWSER.with_borrow_mut(|slot| {
465        let Some(data) = &slot.data else {
466            return Ok(false);
467        };
468        if owner != data.owner {
469            return Err(StatusError::OwnerConflict);
470        }
471        slot.revision = slot
472            .revision
473            .checked_add(1)
474            .ok_or(StatusError::CounterExhausted)?;
475        slot.data = None;
476        Ok(true)
477    })
478}
479// One Wasm contract. Pointer/length describe only the initialized prefix until
480// next same-thread publish/clear. Read revision before/after copying. No threads,
481// shared-memory mutation, async borrow, C string, capacity scan or writer export.
482/// Readonly ABI version, always 1; this does not imply a publisher exists.
483#[cfg_attr(target_arch = "wasm32", unsafe(no_mangle))]
484pub extern "C" fn ferravex_status_v1_version() -> u32 {
485    1
486}
487/// Thread-local nonwrapping u64 publication stamp (Wasm i64 / JavaScript BigInt).
488/// Wasm returns the signed two's-complement BigInt view; compare that losslessly,
489/// or use BigInt.asUintN(64, value). Semantic JSON counters are decimal strings.
490/// Read before and after copying; stamp changes on copy/clear, not no-op copies.
491#[cfg_attr(target_arch = "wasm32", unsafe(no_mangle))]
492pub extern "C" fn ferravex_status_v1_revision() -> u64 {
493    BROWSER.with_borrow(|s| s.revision)
494}
495/// Borrowed initialized-prefix address, null when absent/reset. Valid only until
496/// the next same-thread publish/clear; reacquire current memory after growth.
497#[cfg_attr(target_arch = "wasm32", unsafe(no_mangle))]
498pub extern "C" fn ferravex_status_v1_ptr() -> *const u8 {
499    BROWSER.with_borrow(|s| {
500        s.data
501            .as_ref()
502            .filter(|d| d.len != 0)
503            .map_or(std::ptr::null(), |d| d.wire.as_ptr())
504    })
505}
506/// Initialized JSON byte length (no terminator), zero when absent/reset.
507#[cfg_attr(target_arch = "wasm32", unsafe(no_mangle))]
508pub extern "C" fn ferravex_status_v1_len() -> u32 {
509    BROWSER.with_borrow(|s| s.data.as_ref().map_or(0, |d| d.len as u32))
510}
511
512#[cfg(test)]
513mod tests {
514    use super::*;
515    #[test]
516    fn counters_never_wrap_and_errors_preserve_last_good() {
517        let mut bridge = StatusBridge::new(u64::MAX).unwrap();
518        bridge.serial = u64::MAX - 1;
519        assert_eq!(bridge.publish(None).unwrap().serial, u64::MAX);
520        let good = bridge.bytes().to_vec();
521        assert!(!bridge.publish(None).unwrap().changed);
522        assert_eq!(
523            bridge.publish(Some(StatusFacts {
524                items: &[],
525                ui: None,
526                ui_actions: &[]
527            })),
528            Err(StatusError::CounterExhausted)
529        );
530        assert_eq!(bridge.bytes(), good);
531        bridge.epoch = u64::MAX;
532        assert_eq!(bridge.reset(), Err(StatusError::CounterExhausted));
533        assert_eq!(bridge.bytes(), good);
534        BROWSER.with_borrow_mut(|s| s.revision = u64::MAX);
535        assert_eq!(bridge.publish_browser(), Err(StatusError::CounterExhausted));
536        assert_eq!(ferravex_status_v1_len(), 0);
537        BROWSER.with_borrow_mut(|s| s.revision = 0);
538        bridge.publish_browser().unwrap();
539        BROWSER.with_borrow_mut(|s| s.revision = u64::MAX);
540        assert_eq!(clear_browser(u64::MAX), Err(StatusError::CounterExhausted));
541        assert_eq!(ferravex_status_v1_len() as usize, good.len());
542        BROWSER.with_borrow_mut(|s| {
543            s.data = None;
544            s.revision = 0;
545        });
546    }
547    #[test]
548    fn wire_and_private_tail_bounds_at_maximal_counters() {
549        let mut bridge = StatusBridge::new(u64::MAX).unwrap();
550        bridge.epoch = u64::MAX;
551        bridge.serial = u64::MAX - 1;
552        let label = "\0".repeat(MAX_LABEL_BYTES);
553        let items: Vec<_> = (0..MAX_ITEMS)
554            .map(|i| StatusItem {
555                id: u64::MAX - i as u64,
556                kind: StatusKind::Notice,
557                label: &label,
558            })
559            .collect();
560        bridge
561            .publish(Some(StatusFacts {
562                items: &items,
563                ui: None,
564                ui_actions: &[],
565            }))
566            .unwrap();
567        assert!(bridge.len < MAX_WIRE_BYTES);
568        bridge.serial = 0;
569        bridge.publish(None).unwrap();
570        assert!(bridge.wire[bridge.len..].iter().all(|b| *b == 0));
571    }
572}