ferravex_render/
content.rs

1//! Optional authoring bridge. A Source polls only explicit local files or queued
2//! browser edits; ordinary frames do no filesystem work or source allocation.
3//!
4//! [`reload_state`] inspects the calling thread's bridge without consuming edits.
5//! The bridge serves one selected document: constructing a [`ContentSource`]
6//! selects it and resets its diagnostics. Poll that source on the same thread as
7//! [`queue`] and inspection. The existing Wasm status codes/exports are unchanged.
8use ferravex_play::authoring::{ContentError, MAX_SOURCE_BYTES};
9use std::cell::RefCell;
10
11/// Maximum UTF-8 bytes retained in a reload failure's error context.
12pub const MAX_RELOAD_CONTEXT_BYTES: usize = 4096;
13
14/// Latest bridge operation, using the existing browser status codes.
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16#[repr(u32)]
17pub enum ReloadStatus {
18    /// No document has been selected on this thread.
19    #[default]
20    Uninitialized = 0,
21    /// Embedded content, a successful replacement, or an unchanged edit.
22    Ready = 1,
23    /// An edit was queued for the game to validate.
24    Pending = 2,
25    /// An edit, file read, or replacement was rejected.
26    Rejected = 3,
27}
28
29/// Where a rejected reload originated.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum ReloadOrigin {
32    /// [`queue`] or the browser edit buffer.
33    QueuedEdit,
34    /// The explicitly configured native content file.
35    NativeFile,
36}
37
38/// The boundary that rejected a reload, independent of the domain error kind.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum ReloadStage {
41    /// Source length or NUL validation, including browser buffer length checks.
42    Input,
43    /// Opening or reading the native file.
44    Read,
45    /// Decoding UTF-8 bytes.
46    Decode,
47    /// The game's builder returned an error (including parsing/validation).
48    Build,
49    /// The accepted generation counter cannot advance without overflow.
50    Generation,
51}
52
53/// One retained failure; the diagnostic stores no failed source text or history.
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct ReloadFailure {
56    /// The input channel responsible for the failure.
57    pub origin: ReloadOrigin,
58    /// The operation that failed.
59    pub stage: ReloadStage,
60    /// Original error kind and source span. Context is clipped on a UTF-8
61    /// boundary to [`MAX_RELOAD_CONTEXT_BYTES`]; native read errors include the
62    /// path in this context. Use `context_truncated` when displaying it.
63    pub error: ContentError,
64    /// Whether any error context was omitted from this diagnostic.
65    pub context_truncated: bool,
66}
67impl ReloadFailure {
68    fn new(origin: ReloadOrigin, stage: ReloadStage, mut error: ContentError) -> Self {
69        let context_truncated = error.context.len() > MAX_RELOAD_CONTEXT_BYTES;
70        if context_truncated {
71            let mut end = MAX_RELOAD_CONTEXT_BYTES;
72            while !error.context.is_char_boundary(end) {
73                end -= 1;
74            }
75            error.context.truncate(end);
76        }
77        // Do not retain a builder's oversized backing allocation after clipping.
78        error.context = error.context.into_boxed_str().into_string();
79        Self {
80            origin,
81            stage,
82            error,
83            context_truncated,
84        }
85    }
86}
87
88/// An owned diagnostic snapshot of the calling thread's selected document.
89/// Source text is not copied. Inspection allocates only to clone retained error
90/// context when a failure is present; it never reads a file or consumes an edit.
91#[derive(Clone, Debug, PartialEq, Eq)]
92pub struct ReloadState {
93    /// Document selection counter, matching the existing Wasm export. Wraps.
94    pub document: u32,
95    /// Latest operation; pending work is reported separately below.
96    pub status: ReloadStatus,
97    /// Last-good content generation; starts at zero for embedded content and
98    /// advances once per successfully built, different source. Never wraps.
99    pub generation: u32,
100    /// Status change counter, matching the existing Wasm revision export. Wraps;
101    /// compare for inequality within a document, not for numeric ordering.
102    pub revision: u32,
103    /// Status revision at the last accepted replacement, or zero for embedded
104    /// content. Queues, failures and unchanged edits leave this value intact.
105    /// It has the same wrapping semantics as `revision`.
106    pub last_good_revision: u32,
107    /// An edit still awaits polling. This may be true even after rejection of a
108    /// newer invalid submission, or if a builder queues another edit.
109    pub has_pending_edit: bool,
110    /// Failure for the latest rejected operation; cleared by the next successful
111    /// queue, unchanged edit, or accepted replacement. Idle polls preserve it.
112    pub failure: Option<ReloadFailure>,
113}
114
115/// Inspect reload state without advancing the game or consuming queued work.
116///
117/// ```
118/// use ferravex_render::content::{queue, reload_state, ContentSource, ReloadStatus};
119///
120/// let mut source = ContentSource::new("embedded", None)?;
121/// queue("replacement")?;
122/// assert_eq!(reload_state().status, ReloadStatus::Pending);
123/// assert_eq!(source.poll(0.0, |text| Ok(text.len())), Some(11));
124/// let accepted = reload_state();
125/// assert_eq!(accepted.generation, 1);
126/// assert_eq!(accepted.last_good_revision, accepted.revision);
127/// queue("replacement")?;
128/// assert!(source.poll::<()>(0.0, |_| panic!("unchanged")).is_none());
129/// assert_eq!(reload_state().last_good_revision, accepted.last_good_revision);
130/// assert_eq!(source.generation(), 1);
131/// # Ok::<(), ferravex_play::authoring::ContentError>(())
132/// ```
133///
134/// Builders keep live game state outside the bridge; replace it only on `Some`.
135/// Structured errors retain the builder's kind/span and bounded context:
136///
137/// ```
138/// use ferravex_play::authoring::{ContentError, ErrorKind};
139/// use ferravex_render::content::{
140///     queue, reload_state, ContentSource, ReloadFailure, ReloadOrigin, ReloadStage,
141///     ReloadState, ReloadStatus, MAX_RELOAD_CONTEXT_BYTES,
142/// };
143/// let mut source = ContentSource::new("embedded", None)?;
144/// let mut live = 7;
145/// queue("invalid")?;
146/// if let Some(next) = source.poll(0.0, |_| Err(ContentError::domain("missing spawn"))) {
147///     live = next;
148/// }
149/// let state: ReloadState = reload_state();
150/// assert_eq!(state.status, ReloadStatus::Rejected);
151/// let failure: ReloadFailure = state.failure.unwrap();
152/// assert_eq!(failure.origin, ReloadOrigin::QueuedEdit);
153/// assert_eq!(failure.stage, ReloadStage::Build);
154/// assert_eq!(failure.error.kind, ErrorKind::Domain);
155/// assert!(!failure.context_truncated);
156/// assert!(failure.error.context.len() <= MAX_RELOAD_CONTEXT_BYTES);
157/// assert_eq!((live, source.current(), state.generation), (7, "embedded", 0));
158/// # Ok::<(), ContentError>(())
159/// ```
160pub fn reload_state() -> ReloadState {
161    BRIDGE.with(|b| {
162        let b = b.borrow();
163        ReloadState {
164            document: b.document,
165            status: b.reload_status,
166            generation: b.generation,
167            revision: b.revision,
168            last_good_revision: b.last_good_revision,
169            has_pending_edit: b.pending.is_some(),
170            failure: b.failure.clone(),
171        }
172    })
173}
174
175#[derive(Default)]
176struct Bridge {
177    source: String,
178    status: String,
179    generation: u32,
180    revision: u32,
181    document: u32,
182    reload_status: ReloadStatus,
183    last_good_revision: u32,
184    failure: Option<ReloadFailure>,
185    pending: Option<String>,
186    #[cfg(target_arch = "wasm32")]
187    buffer: Vec<u8>,
188}
189thread_local! {static BRIDGE:RefCell<Bridge>=RefCell::new(Bridge::default());}
190fn status(state: ReloadStatus, message: String, failure: Option<ReloadFailure>) {
191    BRIDGE.with(|b| {
192        let mut b = b.borrow_mut();
193        b.reload_status = state;
194        b.status = message;
195        b.failure = failure;
196        b.revision = b.revision.wrapping_add(1);
197    });
198}
199/// Queue a single edit; newer unapplied edits replace older ones. Parsing/game
200/// validation remains in the game, on its next poll. UTF-8 and size are checked.
201/// Rejected submissions update [`reload_state`] but preserve any pending edit.
202pub fn queue(source: &str) -> Result<(), ContentError> {
203    if source.len() > MAX_SOURCE_BYTES || source.contains('\0') {
204        let error = ContentError::domain("source exceeds 2 MiB or contains NUL");
205        reject_submission(error.clone(), ReloadStage::Input);
206        return Err(error);
207    }
208    BRIDGE.with(|b| b.borrow_mut().pending = Some(source.into()));
209    status(
210        ReloadStatus::Pending,
211        "Pending content validation.".into(),
212        None,
213    );
214    Ok(())
215}
216fn reject_submission(error: ContentError, stage: ReloadStage) {
217    let failure = ReloadFailure::new(ReloadOrigin::QueuedEdit, stage, error);
218    status(
219        ReloadStatus::Rejected,
220        failure.error.to_string(),
221        Some(failure),
222    );
223}
224/// The game supplies a builder that validates its domain and constructs *all*
225/// replacement state. Returning Err preserves source, generation and live game.
226pub struct ContentSource {
227    current: String,
228    generation: u32,
229    #[cfg(not(target_arch = "wasm32"))]
230    path: Option<std::path::PathBuf>,
231    #[cfg(not(target_arch = "wasm32"))]
232    elapsed: f64,
233    #[cfg(not(target_arch = "wasm32"))]
234    last_file: Option<Vec<u8>>,
235}
236impl ContentSource {
237    pub fn new(embedded: &str, native_path: Option<&str>) -> Result<Self, ContentError> {
238        if embedded.len() > MAX_SOURCE_BYTES || embedded.contains('\0') {
239            return Err(ContentError::domain("invalid embedded source size/UTF-8"));
240        }
241        BRIDGE.with(|b| {
242            let document = b.borrow().document.wrapping_add(1);
243            *b.borrow_mut() = Bridge {
244                source: embedded.into(),
245                status: "Embedded content loaded. Applying an edit restarts this game.".into(),
246                reload_status: ReloadStatus::Ready,
247                document,
248                ..Default::default()
249            }
250        });
251        #[cfg(target_arch = "wasm32")]
252        let _ = native_path;
253        Ok(Self {
254            current: embedded.into(),
255            generation: 0,
256            #[cfg(not(target_arch = "wasm32"))]
257            path: native_path.map(Into::into),
258            #[cfg(not(target_arch = "wasm32"))]
259            elapsed: 0.5,
260            #[cfg(not(target_arch = "wasm32"))]
261            last_file: None,
262        })
263    }
264    pub fn current(&self) -> &str {
265        &self.current
266    }
267    pub fn generation(&self) -> u32 {
268        self.generation
269    }
270    /// Build and adopt at most one different source. Only `Some` is an accepted
271    /// replacement. When this returns `None`, compare [`reload_state`]'s revision
272    /// before/after polling: rejection and unchanged edits update it; idle polls
273    /// retain the previous status. Invalid `dt` (non-finite or outside `0..=60`
274    /// seconds) leaves pending work and diagnostics untouched.
275    /// A builder must construct replacement state without mutating the live game.
276    pub fn poll<T>(
277        &mut self,
278        dt: f32,
279        build: impl FnOnce(&str) -> Result<T, ContentError>,
280    ) -> Option<T> {
281        if !dt.is_finite() || !(0. ..=60.).contains(&dt) {
282            return None;
283        }
284        #[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
285        let mut candidate = BRIDGE.with(|b| b.borrow_mut().pending.take());
286        #[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
287        let mut origin = ReloadOrigin::QueuedEdit;
288        #[cfg(not(target_arch = "wasm32"))]
289        {
290            self.elapsed = (self.elapsed + f64::from(dt)).min(0.5);
291            if candidate.is_none()
292                && self.elapsed >= 0.5
293                && let Some(path) = self.path.as_ref()
294            {
295                self.elapsed = 0.;
296                match read_source(path) {
297                    Ok(bytes) => {
298                        if self.last_file.as_ref() != Some(&bytes) {
299                            self.last_file = Some(bytes.clone());
300                            match String::from_utf8(bytes) {
301                                Ok(text) => {
302                                    candidate = Some(text);
303                                    origin = ReloadOrigin::NativeFile;
304                                }
305                                Err(_) => self.reject(
306                                    ContentError::domain("content file is not UTF-8"),
307                                    ReloadOrigin::NativeFile,
308                                    ReloadStage::Decode,
309                                ),
310                            }
311                        }
312                    }
313                    Err((stage, error)) => {
314                        // Reinspect restored bytes, even if they match the last
315                        // file read before this I/O/input failure.
316                        self.last_file = None;
317                        self.reject(error, ReloadOrigin::NativeFile, stage);
318                    }
319                }
320            }
321        }
322        let source = candidate?;
323        if source == self.current {
324            status(
325                ReloadStatus::Ready,
326                format!("Content unchanged; generation {}.", self.generation),
327                None,
328            );
329            return None;
330        }
331        let Some(generation) = self.generation.checked_add(1) else {
332            self.reject(
333                ContentError::domain("content generation exhausted"),
334                origin,
335                ReloadStage::Generation,
336            );
337            return None;
338        };
339        match build(&source) {
340            Ok(next) => {
341                self.current = source;
342                self.generation = generation;
343                BRIDGE.with(|b| {
344                    let mut b = b.borrow_mut();
345                    b.source.clone_from(&self.current);
346                    b.generation = generation;
347                });
348                status(
349                    ReloadStatus::Ready,
350                    format!("Loaded content generation {generation}; game restarted."),
351                    None,
352                );
353                BRIDGE.with(|b| {
354                    let mut b = b.borrow_mut();
355                    b.last_good_revision = b.revision;
356                });
357                Some(next)
358            }
359            Err(error) => {
360                self.reject(error, origin, ReloadStage::Build);
361                None
362            }
363        }
364    }
365    fn reject(&self, error: ContentError, origin: ReloadOrigin, stage: ReloadStage) {
366        let failure = ReloadFailure::new(origin, stage, error);
367        let message = format!(
368            "Rejected content; generation {} preserved.\n{}{}",
369            self.generation,
370            failure.error,
371            if failure.context_truncated {
372                " [context truncated]"
373            } else {
374                ""
375            },
376        );
377        #[cfg(not(target_arch = "wasm32"))]
378        if BRIDGE.with(|b| b.borrow().status != message) {
379            eprintln!("{message}");
380        }
381        status(ReloadStatus::Rejected, message, Some(failure));
382    }
383}
384#[cfg(not(target_arch = "wasm32"))]
385fn read_source(path: &std::path::Path) -> Result<Vec<u8>, (ReloadStage, ContentError)> {
386    use std::io::Read;
387    let read_error = |e| {
388        (
389            ReloadStage::Read,
390            ContentError::domain(format!("{}: {e}", path.display())),
391        )
392    };
393    let file = std::fs::File::open(path).map_err(read_error)?;
394    let mut bytes = Vec::new();
395    file.take((MAX_SOURCE_BYTES + 1) as u64)
396        .read_to_end(&mut bytes)
397        .map_err(read_error)?;
398    if bytes.len() > MAX_SOURCE_BYTES || bytes.contains(&0) {
399        return Err((
400            ReloadStage::Input,
401            ContentError::domain("content file exceeds 2 MiB or contains NUL"),
402        ));
403    }
404    Ok(bytes)
405}
406#[cfg(target_arch = "wasm32")]
407mod wasm {
408    use super::*;
409    /// Changes when a game selects another authored document, not on live edits.
410    #[unsafe(no_mangle)]
411    pub extern "C" fn ferravex_content_document() -> u32 {
412        BRIDGE.with(|b| b.borrow().document)
413    }
414    #[unsafe(no_mangle)]
415    pub extern "C" fn ferravex_content_source_len() -> u32 {
416        BRIDGE.with(|b| b.borrow().source.len() as u32)
417    }
418    #[unsafe(no_mangle)]
419    pub extern "C" fn ferravex_content_source() -> *const u8 {
420        BRIDGE.with(|b| b.borrow().source.as_ptr())
421    }
422    #[unsafe(no_mangle)]
423    pub extern "C" fn ferravex_content_generation() -> u32 {
424        BRIDGE.with(|b| b.borrow().generation)
425    }
426    #[unsafe(no_mangle)]
427    pub extern "C" fn ferravex_content_status() -> u32 {
428        BRIDGE.with(|b| b.borrow().reload_status as u32)
429    }
430    #[unsafe(no_mangle)]
431    pub extern "C" fn ferravex_content_revision() -> u32 {
432        BRIDGE.with(|b| b.borrow().revision)
433    }
434    #[unsafe(no_mangle)]
435    pub extern "C" fn ferravex_content_message_len() -> u32 {
436        BRIDGE.with(|b| b.borrow().status.len() as u32)
437    }
438    #[unsafe(no_mangle)]
439    pub extern "C" fn ferravex_content_message() -> *const u8 {
440        BRIDGE.with(|b| b.borrow().status.as_ptr())
441    }
442    #[unsafe(no_mangle)]
443    pub extern "C" fn ferravex_content_edit_buffer(len: u32) -> *mut u8 {
444        if len as usize > MAX_SOURCE_BYTES {
445            return std::ptr::null_mut();
446        }
447        BRIDGE.with(|b| {
448            let mut b = b.borrow_mut();
449            b.buffer.resize(len as usize, 0);
450            b.buffer.as_mut_ptr()
451        })
452    }
453    #[unsafe(no_mangle)]
454    pub extern "C" fn ferravex_content_submit(len: u32) -> u32 {
455        let source = BRIDGE.with(|b| {
456            let b = b.borrow();
457            if len as usize != b.buffer.len() || len as usize > MAX_SOURCE_BYTES {
458                return Err((
459                    ReloadStage::Input,
460                    ContentError::domain("invalid content edit length"),
461                ));
462            }
463            String::from_utf8(b.buffer.clone()).map_err(|_| {
464                (
465                    ReloadStage::Decode,
466                    ContentError::domain("content edit is not UTF-8"),
467                )
468            })
469        });
470        match source {
471            Ok(source) => u32::from(queue(&source).is_ok()),
472            Err((stage, error)) => {
473                reject_submission(error, stage);
474                0
475            }
476        }
477    }
478}
479#[cfg(test)]
480mod tests {
481    use super::*;
482    use ferravex_play::authoring::{ErrorKind, SourceSpan};
483
484    #[test]
485    fn inspection_tracks_rejection_recovery_and_last_good_revision() {
486        let mut source = ContentSource::new("initial", None).unwrap();
487        let initial = reload_state();
488        assert_eq!(initial.status, ReloadStatus::Ready);
489        assert_eq!(
490            (
491                initial.generation,
492                initial.revision,
493                initial.last_good_revision
494            ),
495            (0, 0, 0)
496        );
497        assert!(!initial.has_pending_edit);
498        assert!(initial.failure.is_none());
499
500        let error = ContentError {
501            kind: ErrorKind::Range,
502            span: SourceSpan {
503                line: 2,
504                column: 7,
505                offset: 12,
506            },
507            context: "spawn outside world".into(),
508        };
509        let mut live = String::from("initial game");
510        queue("bad").unwrap();
511        let pending = reload_state();
512        assert_eq!(pending.status, ReloadStatus::Pending);
513        assert!(pending.has_pending_edit);
514        assert_eq!(reload_state(), pending); // Inspection does not drain work.
515        if let Some(next) = source.poll(0., |_| Err(error.clone())) {
516            live = next;
517        }
518        let rejected = reload_state();
519        assert_eq!(rejected.status, ReloadStatus::Rejected);
520        assert_eq!(rejected.revision, pending.revision + 1);
521        assert_eq!(rejected.last_good_revision, 0);
522        assert!(!rejected.has_pending_edit);
523        assert_eq!(
524            rejected.failure,
525            Some(ReloadFailure {
526                origin: ReloadOrigin::QueuedEdit,
527                stage: ReloadStage::Build,
528                error,
529                context_truncated: false,
530            })
531        );
532        assert_eq!(live, "initial game");
533        assert_eq!(source.current(), "initial");
534        assert_eq!(source.generation(), 0);
535        assert!(source.poll::<()>(0., |_| panic!("no edit")).is_none());
536        assert_eq!(reload_state(), rejected);
537
538        queue("superseded").unwrap();
539        queue("good").unwrap();
540        assert!(reload_state().failure.is_none());
541        let queued_revision = reload_state().revision;
542        if let Some(next) = source.poll(0., |text| {
543            assert_eq!(text, "good");
544            Ok(String::from("new game"))
545        }) {
546            live = next;
547        }
548        let accepted = reload_state();
549        assert_eq!(live, "new game");
550        assert_eq!(accepted.status, ReloadStatus::Ready);
551        assert_eq!(accepted.generation, 1);
552        assert_eq!(accepted.revision, queued_revision + 1);
553        assert_eq!(accepted.last_good_revision, accepted.revision);
554        assert!(!accepted.has_pending_edit);
555        assert!(accepted.failure.is_none());
556        assert!(
557            source
558                .poll::<()>(0., |_| panic!("already consumed"))
559                .is_none()
560        );
561        assert_eq!(reload_state(), accepted);
562
563        queue("good").unwrap();
564        assert!(source.poll::<()>(0., |_| panic!("unchanged")).is_none());
565        let unchanged = reload_state();
566        assert_eq!(unchanged.status, ReloadStatus::Ready);
567        assert_eq!(unchanged.generation, 1);
568        assert_eq!(unchanged.last_good_revision, accepted.last_good_revision);
569        assert_eq!(unchanged.revision, accepted.revision + 2);
570        queue("bad again").unwrap();
571        assert!(
572            source
573                .poll::<()>(0., |_| Err(ContentError::domain("still bad")))
574                .is_none()
575        );
576        assert_eq!(
577            reload_state().last_good_revision,
578            accepted.last_good_revision
579        );
580        assert_eq!(source.current(), "good");
581        assert_eq!(source.generation(), 1);
582        // Previously returned snapshots remain useful after newer operations.
583        assert_eq!(rejected.failure.unwrap().error.kind, ErrorKind::Range);
584    }
585
586    #[test]
587    fn invalid_submissions_preserve_pending_work_and_last_good_content() {
588        let mut source = ContentSource::new("initial", None).unwrap();
589        queue("good").unwrap();
590        assert_eq!(source.poll(0., |_| Ok(1)), Some(1));
591        let accepted = reload_state();
592        queue("next").unwrap();
593        for input in [String::from("\0"), "x".repeat(MAX_SOURCE_BYTES + 1)] {
594            let revision = reload_state().revision;
595            let error = queue(&input).unwrap_err();
596            let state = reload_state();
597            assert_eq!(state.status, ReloadStatus::Rejected);
598            assert!(state.has_pending_edit);
599            assert_eq!(state.generation, 1);
600            assert_eq!(state.revision, revision + 1);
601            assert_eq!(state.last_good_revision, accepted.last_good_revision);
602            let failure = state.failure.unwrap();
603            assert_eq!(failure.origin, ReloadOrigin::QueuedEdit);
604            assert_eq!(failure.stage, ReloadStage::Input);
605            assert_eq!(failure.error, error);
606        }
607        assert_eq!(source.current(), "good");
608        assert_eq!(
609            source.poll(0., |text| Ok(text.to_owned())),
610            Some("next".into())
611        );
612        assert_eq!(source.generation(), 2);
613        assert!(reload_state().failure.is_none());
614    }
615
616    #[test]
617    fn invalid_poll_delta_does_not_consume_or_change_diagnostics() {
618        let mut source = ContentSource::new("initial", None).unwrap();
619        queue("next").unwrap();
620        assert!(queue("\0").is_err());
621        let before = reload_state();
622        for dt in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.1, 60.1] {
623            assert!(source.poll::<()>(dt, |_| panic!("invalid dt")).is_none());
624            assert_eq!(reload_state(), before);
625        }
626        assert_eq!(source.poll(0., |_| Ok(42)), Some(42));
627        assert_eq!(source.generation(), 1);
628    }
629
630    #[test]
631    fn accepted_generation_exhaustion_and_status_revision_wrap_are_separate() {
632        let mut source = ContentSource::new("initial", None).unwrap();
633        source.generation = u32::MAX - 1;
634        BRIDGE.with(|b| {
635            let mut b = b.borrow_mut();
636            b.generation = source.generation;
637            b.revision = u32::MAX - 1;
638        });
639        queue("last").unwrap();
640        assert_eq!(source.poll(0., |_| Ok(())), Some(()));
641        let accepted = reload_state();
642        assert_eq!(accepted.generation, u32::MAX);
643        assert_eq!((accepted.revision, accepted.last_good_revision), (0, 0));
644        queue("last").unwrap();
645        assert!(source.poll::<()>(0., |_| panic!("unchanged")).is_none());
646        assert_eq!(reload_state().status, ReloadStatus::Ready);
647        queue("overflow").unwrap();
648        assert!(
649            source
650                .poll::<()>(0., |_| panic!("generation overflow"))
651                .is_none()
652        );
653        let state = reload_state();
654        assert_eq!(state.status, ReloadStatus::Rejected);
655        assert_eq!(state.generation, u32::MAX);
656        assert_eq!(state.last_good_revision, accepted.last_good_revision);
657        assert_eq!(state.failure.unwrap().stage, ReloadStage::Generation);
658        assert_eq!(source.current(), "last");
659        assert_eq!(source.generation(), u32::MAX);
660        BRIDGE.with(|b| assert_eq!(b.borrow().source, "last"));
661    }
662
663    #[test]
664    fn selection_resets_diagnostics_and_invalid_selection_preserves_them() {
665        let mut source = ContentSource::new("initial", None).unwrap();
666        queue("good").unwrap();
667        assert_eq!(source.poll(0., |_| Ok(())), Some(()));
668        queue("pending").unwrap();
669        assert!(queue("\0").is_err());
670        let before = reload_state();
671        assert!(ContentSource::new("\0", None).is_err());
672        assert_eq!(reload_state(), before);
673        let mut next = ContentSource::new("another document", None).unwrap();
674        let state = reload_state();
675        assert_eq!(state.document, before.document.wrapping_add(1));
676        assert_eq!(state.status, ReloadStatus::Ready);
677        assert_eq!(
678            (state.generation, state.revision, state.last_good_revision),
679            (0, 0, 0)
680        );
681        assert!(!state.has_pending_edit);
682        assert!(state.failure.is_none());
683        assert!(
684            next.poll::<()>(0., |_| panic!("old document edit"))
685                .is_none()
686        );
687    }
688
689    #[test]
690    fn failure_context_is_bounded_without_splitting_utf8_or_losing_location() {
691        let mut source = ContentSource::new("initial", None).unwrap();
692        let span = SourceSpan {
693            line: 4,
694            column: 8,
695            offset: 27,
696        };
697        let prefix = "a".repeat(MAX_RELOAD_CONTEXT_BYTES - 1);
698        queue("bad").unwrap();
699        assert!(
700            source
701                .poll::<()>(0., |_| Err(ContentError {
702                    kind: ErrorKind::Syntax,
703                    span,
704                    context: format!("{prefix}🦀rest of error"),
705                }))
706                .is_none()
707        );
708        let failure = reload_state().failure.unwrap();
709        assert!(failure.context_truncated);
710        assert_eq!(failure.error.kind, ErrorKind::Syntax);
711        assert_eq!(failure.error.span, span);
712        assert_eq!(failure.error.context, prefix);
713        BRIDGE.with(|b| {
714            let b = b.borrow();
715            assert!(b.status.ends_with(" [context truncated]"));
716            assert!(
717                b.failure.as_ref().unwrap().error.context.capacity() <= MAX_RELOAD_CONTEXT_BYTES
718            );
719        });
720        queue("bad again").unwrap();
721        assert!(
722            source
723                .poll::<()>(0., |_| Err(ContentError::domain(
724                    "x".repeat(MAX_RELOAD_CONTEXT_BYTES)
725                )))
726                .is_none()
727        );
728        let failure = reload_state().failure.unwrap();
729        assert!(!failure.context_truncated);
730        assert_eq!(failure.error.context.len(), MAX_RELOAD_CONTEXT_BYTES);
731    }
732
733    #[test]
734    fn edits_queued_by_builder_remain_visible_and_advance_on_the_next_poll() {
735        let mut source = ContentSource::new("initial", None).unwrap();
736        queue("first").unwrap();
737        assert_eq!(
738            source.poll(0., |_| {
739                queue("second")?;
740                Ok(1)
741            }),
742            Some(1)
743        );
744        let state = reload_state();
745        assert_eq!(state.status, ReloadStatus::Ready);
746        assert!(state.has_pending_edit);
747        assert_eq!(state.generation, 1);
748        assert_eq!(
749            source.poll(0., |text| {
750                assert_eq!(text, "second");
751                Ok(2)
752            }),
753            Some(2)
754        );
755        assert!(!reload_state().has_pending_edit);
756        assert_eq!(source.generation(), 2);
757    }
758
759    #[test]
760    fn bridge_starts_uninitialized_on_other_threads_and_preserves_status_codes() {
761        ContentSource::new("main document", None).unwrap();
762        queue("pending").unwrap();
763        let before = reload_state();
764        std::thread::spawn(|| {
765            let state = reload_state();
766            assert_eq!(state.status, ReloadStatus::Uninitialized);
767            assert_eq!(
768                (state.document, state.generation, state.revision),
769                (0, 0, 0)
770            );
771            assert!(!state.has_pending_edit);
772            assert!(state.failure.is_none());
773            ContentSource::new("other document", None).unwrap();
774        })
775        .join()
776        .unwrap();
777        assert_eq!(reload_state(), before);
778        assert_eq!(ReloadStatus::Uninitialized as u32, 0);
779        assert_eq!(ReloadStatus::Ready as u32, 1);
780        assert_eq!(ReloadStatus::Pending as u32, 2);
781        assert_eq!(ReloadStatus::Rejected as u32, 3);
782    }
783
784    #[cfg(not(target_arch = "wasm32"))]
785    #[test]
786    fn native_failure_stages_and_same_bytes_recovery_preserve_last_good_revision() {
787        struct File(std::path::PathBuf);
788        impl Drop for File {
789            fn drop(&mut self) {
790                let _ = std::fs::remove_file(&self.0);
791            }
792        }
793        let file = File(std::env::temp_dir().join(format!(
794            "ferravex-content-inspection-{}-{:?}.fxscene",
795            std::process::id(),
796            std::thread::current().id(),
797        )));
798        std::fs::write(&file.0, "good").unwrap();
799        let mut source = ContentSource::new("initial", Some(file.0.to_str().unwrap())).unwrap();
800        assert_eq!(source.poll(0., |s| Ok(s.to_owned())), Some("good".into()));
801        let accepted = reload_state();
802
803        for (bytes, stage) in [
804            (vec![0xff], ReloadStage::Decode),
805            (vec![0], ReloadStage::Input),
806            (vec![b'x'; MAX_SOURCE_BYTES + 1], ReloadStage::Input),
807        ] {
808            std::fs::write(&file.0, bytes).unwrap();
809            assert!(source.poll::<()>(0.5, |_| panic!("invalid file")).is_none());
810            let state = reload_state();
811            assert_eq!(state.status, ReloadStatus::Rejected);
812            assert_eq!(state.generation, 1);
813            assert_eq!(state.last_good_revision, accepted.last_good_revision);
814            let failure = state.failure.unwrap();
815            assert_eq!(failure.origin, ReloadOrigin::NativeFile);
816            assert_eq!(failure.stage, stage);
817            assert_eq!(source.current(), "good");
818        }
819
820        std::fs::write(&file.0, "good").unwrap();
821        assert!(source.poll::<()>(0.5, |_| panic!("unchanged")).is_none());
822        assert_eq!(reload_state().status, ReloadStatus::Ready);
823        std::fs::remove_file(&file.0).unwrap();
824        assert!(source.poll::<()>(0.5, |_| panic!("missing file")).is_none());
825        let failure = reload_state().failure.unwrap();
826        assert_eq!(failure.origin, ReloadOrigin::NativeFile);
827        assert_eq!(failure.stage, ReloadStage::Read);
828        assert!(failure.error.context.contains(file.0.to_str().unwrap()));
829        std::fs::write(&file.0, "good").unwrap();
830        assert!(
831            source
832                .poll::<()>(0.5, |_| panic!("restored identical source"))
833                .is_none()
834        );
835        let restored = reload_state();
836        assert_eq!(restored.status, ReloadStatus::Ready);
837        assert!(restored.failure.is_none());
838        assert_eq!(restored.generation, 1);
839        assert_eq!(restored.last_good_revision, accepted.last_good_revision);
840
841        std::fs::write(&file.0, "bad").unwrap();
842        assert!(
843            source
844                .poll::<()>(0.5, |_| Err(ContentError::domain("invalid scene")))
845                .is_none()
846        );
847        let rejected = reload_state();
848        let failure = rejected.failure.as_ref().unwrap();
849        assert_eq!(failure.origin, ReloadOrigin::NativeFile);
850        assert_eq!(failure.stage, ReloadStage::Build);
851        assert!(
852            source
853                .poll::<()>(0.5, |_| panic!("same failed file"))
854                .is_none()
855        );
856        assert_eq!(reload_state(), rejected);
857        std::fs::write(&file.0, "next").unwrap();
858        assert_eq!(source.poll(0.5, |s| Ok(s.to_owned())), Some("next".into()));
859        let recovered = reload_state();
860        assert_eq!(recovered.generation, 2);
861        assert_eq!(recovered.status, ReloadStatus::Ready);
862        assert!(recovered.failure.is_none());
863        assert_eq!(recovered.last_good_revision, recovered.revision);
864        assert_eq!(source.current(), "next");
865    }
866
867    #[test]
868    fn reload_builds_before_adoption_and_rejected_edits_preserve_generation() {
869        let mut source = ContentSource::new("initial", None).unwrap();
870        queue("bad").unwrap();
871        assert!(
872            source
873                .poll::<u32>(0., |_| Err(ContentError::domain("domain validation")))
874                .is_none()
875        );
876        assert_eq!(source.current(), "initial");
877        assert_eq!(source.generation(), 0);
878        queue("valid").unwrap();
879        assert_eq!(source.poll(0., |s| Ok(s.len())), Some(5));
880        assert_eq!(source.generation(), 1);
881        assert_eq!(source.current(), "valid");
882        queue("valid").unwrap();
883        assert!(
884            source
885                .poll::<u32>(0., |_| panic!("unchanged source must not rebuild"))
886                .is_none()
887        );
888        assert!(queue(&"x".repeat(MAX_SOURCE_BYTES + 1)).is_err());
889        assert!(queue("\0").is_err());
890    }
891    #[test]
892    fn explicit_file_watch_detects_same_length_edits_and_keeps_last_good_data() {
893        let file = std::env::temp_dir().join(format!(
894            "ferravex-content-{}-{:?}.fxscene",
895            std::process::id(),
896            std::thread::current().id()
897        ));
898        std::fs::write(&file, "new").unwrap();
899        let mut source = ContentSource::new("old", file.to_str()).unwrap();
900        assert_eq!(source.poll(0., |v| Ok(v.to_owned())), Some("new".into()));
901        std::fs::write(&file, "bad").unwrap();
902        assert!(
903            source
904                .poll::<String>(0.5, |_| Err(ContentError::domain("bad content")))
905                .is_none()
906        );
907        assert_eq!(source.current(), "new");
908        assert_eq!(source.generation(), 1);
909        std::fs::write(&file, "yes").unwrap();
910        assert_eq!(source.poll(0.5, |v| Ok(v.to_owned())), Some("yes".into()));
911        std::fs::remove_file(file).unwrap();
912    }
913}