Skip to main content

euv_core/dynamic/wasm/
impl.rs

1use super::*;
2
3/// Human-readable diagnostic formatting for `WasmDynamicError`.
4impl fmt::Display for WasmDynamicError {
5    /// Formats a descriptive error string for logs and UI error boundaries.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Error variant reference.
10    /// - `&mut Formatter<'_>` - Output formatter.
11    ///
12    /// # Returns
13    ///
14    /// - `fmt::Result` - Formatting result.
15    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
16        match self {
17            Self::InvalidUrl(url) => write!(f, "invalid wasm URL: {url}"),
18            Self::NetworkOffline(url) => write!(f, "network offline while fetching {url}"),
19            Self::HttpStatus { status, url } => write!(f, "HTTP {status} downloading {url}"),
20            Self::Timeout { url, timeout_ms } => {
21                write!(f, "download timed out after {timeout_ms}ms for {url}")
22            }
23            Self::Cancelled { request_id } => write!(f, "wasm request #{request_id} was cancelled"),
24            Self::StaleResponse {
25                request_id,
26                active_request_id,
27            } => write!(
28                f,
29                "discarded stale wasm response #{request_id} (active #{active_request_id})"
30            ),
31            Self::BinaryTooLarge { actual, limit } => {
32                write!(f, "wasm binary {actual} bytes exceeds limit {limit}")
33            }
34            Self::InvalidWasmBinary(msg) => write!(f, "invalid wasm binary: {msg}"),
35            Self::ChecksumMismatch { expected, actual } => {
36                write!(
37                    f,
38                    "wasm checksum mismatch: expected {expected:#018x}, got {actual:#018x}"
39                )
40            }
41            Self::SignatureInvalid { expected, actual } => {
42                write!(
43                    f,
44                    "wasm signature invalid: expected {expected}, got {actual}"
45                )
46            }
47            Self::AbiMismatch { expected, actual } => {
48                write!(f, "wasm ABI mismatch: host v{expected}, module v{actual}")
49            }
50            Self::MissingExport(name) => write!(f, "wasm module missing required export `{name}`"),
51            Self::VersionRegression { current, incoming } => {
52                write!(
53                    f,
54                    "wasm version regression blocked: active v{current}, incoming v{incoming}"
55                )
56            }
57            Self::MemoryLimitExceeded { requested, limit } => {
58                write!(f, "wasm memory {requested} bytes exceeds limit {limit}")
59            }
60            Self::MemoryOutOfBounds {
61                addr,
62                len,
63                memory_size,
64            } => write!(
65                f,
66                "wasm memory out of bounds: [{addr}..+{len}] > {memory_size}"
67            ),
68            Self::OutOfFuel { limit } => {
69                write!(f, "wasm execution exceeded fuel budget ({limit} ops)")
70            }
71            Self::ExecutionTrap(msg) => write!(f, "wasm runtime trap: {msg}"),
72            Self::InvalidUiPayload(msg) => write!(f, "invalid wasm native UI payload: {msg}"),
73            Self::NoRollbackSnapshot => write!(f, "no prior verified wasm snapshot to roll back"),
74        }
75    }
76}
77
78/// Standard `Error` marker implementation for `WasmDynamicError`.
79impl Error for WasmDynamicError {}
80
81/// Safe production defaults for `WasmSandboxConfig`.
82impl Default for WasmSandboxConfig {
83    /// Returns balanced production sandbox ceilings (8 MiB binary, 4 MiB memory, 100k fuel, 2 retries, offline cache on).
84    ///
85    /// # Returns
86    ///
87    /// - `Self` - Default `WasmSandboxConfig`.
88    fn default() -> Self {
89        Self {
90            max_binary_bytes: WASM_DEFAULT_MAX_BINARY_BYTES,
91            max_memory_bytes: WASM_DEFAULT_MAX_MEMORY_BYTES,
92            max_fuel: WASM_DEFAULT_MAX_FUEL,
93            timeout_ms: WASM_DEFAULT_TIMEOUT_MS,
94            max_retries: WASM_DEFAULT_MAX_RETRIES,
95            allow_offline_cache: true,
96            require_signature: false,
97        }
98    }
99}
100
101/// Scope key formatting helpers for `WasmDynamicScope`.
102impl WasmDynamicScope {
103    /// Returns a stable unique registry key identifying this scope.
104    ///
105    /// # Arguments
106    ///
107    /// - `&Self` - Scope reference.
108    ///
109    /// # Returns
110    ///
111    /// - `String` - Scope registry key.
112    #[must_use]
113    pub fn key(&self) -> String {
114        match self {
115            Self::Partial { slot_id } => format!("partial:{slot_id}"),
116            Self::Global => "global".to_string(),
117        }
118    }
119}
120
121/// Fluent builder helpers for `WasmDownloadRequest`.
122impl WasmDownloadRequest {
123    /// Creates a scoped partial-slot `.wasm` download request.
124    ///
125    /// # Arguments
126    ///
127    /// - `String` - Source `.wasm` URL.
128    /// - `String` - Target partial slot ID.
129    /// - `u64` - Release version number.
130    ///
131    /// # Returns
132    ///
133    /// - `Self` - Configured partial download request.
134    #[must_use]
135    pub fn partial(url: String, slot_id: String, version: u64) -> Self {
136        Self::new(url, WasmDynamicScope::Partial { slot_id }, version)
137    }
138
139    /// Creates a global full-app `.wasm` download request.
140    ///
141    /// # Arguments
142    ///
143    /// - `String` - Source `.wasm` URL.
144    /// - `u64` - Release version number.
145    ///
146    /// # Returns
147    ///
148    /// - `Self` - Configured global download request.
149    #[must_use]
150    pub fn global(url: String, version: u64) -> Self {
151        Self::new(url, WasmDynamicScope::Global, version)
152    }
153
154    /// Attaches an expected FNV-1a checksum for integrity verification.
155    ///
156    /// # Arguments
157    ///
158    /// - `Self` - Source request.
159    /// - `u64` - Expected checksum.
160    ///
161    /// # Returns
162    ///
163    /// - `Self` - Updated request.
164    #[must_use]
165    pub fn with_checksum(mut self, checksum: u64) -> Self {
166        self.set_expected_checksum(checksum);
167        self
168    }
169
170    /// Attaches an expected signature tag for authenticated verification.
171    ///
172    /// # Arguments
173    ///
174    /// - `Self` - Source request.
175    /// - `String` - Expected signature string.
176    ///
177    /// # Returns
178    ///
179    /// - `Self` - Updated request.
180    #[must_use]
181    pub fn with_signature(mut self, signature: String) -> Self {
182        self.set_expected_signature(signature);
183        self
184    }
185
186    /// Allows installing a version lower than or equal to the currently mounted version.
187    ///
188    /// # Arguments
189    ///
190    /// - `Self` - Source request.
191    /// - `bool` - Downgrade permission flag.
192    ///
193    /// # Returns
194    ///
195    /// - `Self` - Updated request.
196    #[must_use]
197    pub fn with_allow_downgrade(mut self, allow: bool) -> Self {
198        self.set_allow_downgrade(allow);
199        self
200    }
201
202    /// Resolves the effective cache lookup key (`cache_key` if non-empty, otherwise `url`).
203    ///
204    /// # Arguments
205    ///
206    /// - `&Self` - Request reference.
207    ///
208    /// # Returns
209    ///
210    /// - `&str` - Effective cache key.
211    #[must_use]
212    pub fn resolved_cache_key(&self) -> &str {
213        if self.get_cache_key().is_empty() {
214            self.get_url().as_str()
215        } else {
216            self.get_cache_key().as_str()
217        }
218    }
219}
220
221/// Accessor helpers for `WasmExecutionOutput`.
222impl WasmExecutionOutput {
223    /// Returns the optional emitted partial `DynamicNodeSpec`.
224    ///
225    /// # Arguments
226    ///
227    /// - `&Self` - Execution output reference.
228    ///
229    /// # Returns
230    ///
231    /// - `Option<&DynamicNodeSpec>` - Emitted spec reference.
232    #[must_use]
233    pub fn emitted_spec(&self) -> Option<&DynamicNodeSpec> {
234        let Self { emitted_spec, .. } = self;
235        emitted_spec.as_ref()
236    }
237
238    /// Returns the optional emitted global `DynamicUpdateBundle`.
239    ///
240    /// # Arguments
241    ///
242    /// - `&Self` - Execution output reference.
243    ///
244    /// # Returns
245    ///
246    /// - `Option<&DynamicUpdateBundle>` - Emitted bundle reference.
247    #[must_use]
248    pub fn emitted_bundle(&self) -> Option<&DynamicUpdateBundle> {
249        let Self { emitted_bundle, .. } = self;
250        emitted_bundle.as_ref()
251    }
252}
253
254/// Accessor helpers for `WasmMountedSnapshot`.
255impl WasmMountedSnapshot {
256    /// Returns the mounted partial spec if present.
257    ///
258    /// # Arguments
259    ///
260    /// - `&Self` - Snapshot reference.
261    ///
262    /// # Returns
263    ///
264    /// - `Option<&DynamicNodeSpec>` - Mounted spec reference.
265    #[must_use]
266    pub fn spec_ref(&self) -> Option<&DynamicNodeSpec> {
267        let Self { spec, .. } = self;
268        spec.as_ref()
269    }
270
271    /// Returns the mounted global bundle if present.
272    ///
273    /// # Arguments
274    ///
275    /// - `&Self` - Snapshot reference.
276    ///
277    /// # Returns
278    ///
279    /// - `Option<&DynamicUpdateBundle>` - Mounted bundle reference.
280    #[must_use]
281    pub fn bundle_ref(&self) -> Option<&DynamicUpdateBundle> {
282        let Self { bundle, .. } = self;
283        bundle.as_ref()
284    }
285}
286
287/// Spec-compliant WebAssembly binary encoder methods for `WasmModuleBuilder`.
288impl WasmModuleBuilder {
289    /// Starts building a partial-slot `.wasm` module emitting `spec` through `env::euv_emit_ui`.
290    ///
291    /// # Arguments
292    ///
293    /// - `&DynamicNodeSpec` - Primary native UI subtree specification.
294    ///
295    /// # Returns
296    ///
297    /// - `Self` - Configured `.wasm` builder.
298    #[must_use]
299    pub fn partial_spec(spec: &DynamicNodeSpec) -> Self {
300        let json: String = to_string(spec).unwrap_or_else(|_| "{}".to_string());
301        Self {
302            abi_version: WASM_ABI_VERSION,
303            export_render: true,
304            is_global_bundle: false,
305            ui_payload_json: json,
306            alt_ui_payload_json: String::new(),
307            log_message: String::new(),
308            fault: WasmFaultKind::None,
309            custom_meta: Vec::new(),
310        }
311    }
312
313    /// Starts building a global full-app `.wasm` module emitting `bundle` through `env::euv_emit_bundle`.
314    ///
315    /// # Arguments
316    ///
317    /// - `&DynamicUpdateBundle` - Full-app dynamic bundle specification.
318    ///
319    /// # Returns
320    ///
321    /// - `Self` - Configured global `.wasm` builder.
322    #[must_use]
323    pub fn global_bundle(bundle: &DynamicUpdateBundle) -> Self {
324        let json: String = to_string(bundle).unwrap_or_else(|_| "{}".to_string());
325        Self {
326            abi_version: WASM_ABI_VERSION,
327            export_render: true,
328            is_global_bundle: true,
329            ui_payload_json: json,
330            alt_ui_payload_json: String::new(),
331            log_message: String::new(),
332            fault: WasmFaultKind::None,
333            custom_meta: Vec::new(),
334        }
335    }
336
337    /// Attaches an alternate interactive UI spec rendered whenever `euv_render(state)` receives a non-zero state.
338    ///
339    /// # Arguments
340    ///
341    /// - `Self` - Source builder.
342    /// - `&DynamicNodeSpec` - Alternate interactive state UI spec.
343    ///
344    /// # Returns
345    ///
346    /// - `Self` - Updated builder.
347    #[must_use]
348    pub fn with_alt_spec(mut self, alt: &DynamicNodeSpec) -> Self {
349        let json: String = to_string(alt).unwrap_or_else(|_| "{}".to_string());
350        self.set_alt_ui_payload_json(json);
351        self
352    }
353
354    /// Attaches an alternate global `DynamicUpdateBundle` JSON payload emitted when `euv_on_event` toggles state.
355    ///
356    /// # Arguments
357    ///
358    /// - `Self` - Source builder.
359    /// - `&DynamicUpdateBundle` - Alternate global bundle for odd state ticks.
360    ///
361    /// # Returns
362    ///
363    /// - `Self` - Updated builder.
364    #[must_use]
365    pub fn with_alt_bundle(mut self, bundle: &DynamicUpdateBundle) -> Self {
366        let json: String = bundle.to_json().unwrap_or_default();
367        self.set_alt_ui_payload_json(json);
368        self
369    }
370
371    /// Attaches a diagnostic log message emitted via `env::euv_log` during render.
372    ///
373    /// # Arguments
374    ///
375    /// - `Self` - Source builder.
376    /// - `String` - Log line text.
377    ///
378    /// # Returns
379    ///
380    /// - `Self` - Updated builder.
381    #[must_use]
382    pub fn with_log(mut self, message: String) -> Self {
383        self.set_log_message(message);
384        self
385    }
386
387    /// Overrides the reported ABI version (used to test ABI mismatch rejection).
388    ///
389    /// # Arguments
390    ///
391    /// - `Self` - Source builder.
392    /// - `u32` - ABI version returned by `euv_abi_version`.
393    ///
394    /// # Returns
395    ///
396    /// - `Self` - Updated builder.
397    #[must_use]
398    pub fn with_abi_version(mut self, abi: u32) -> Self {
399        self.set_abi_version(abi);
400        self
401    }
402
403    /// Omits the `euv_render` export (used to test missing export rejection).
404    ///
405    /// # Arguments
406    ///
407    /// - `Self` - Source builder.
408    ///
409    /// # Returns
410    ///
411    /// - `Self` - Updated builder.
412    #[must_use]
413    pub fn without_render_export(mut self) -> Self {
414        self.set_export_render(false);
415        self
416    }
417
418    /// Compiles a deterministic sandbox fault (`InfiniteLoopOutOfFuel` / `ExecutionTrap`) into `euv_render`.
419    ///
420    /// # Arguments
421    ///
422    /// - `Self` - Source builder.
423    /// - `WasmFaultKind` - Fault behavior to compile.
424    ///
425    /// # Returns
426    ///
427    /// - `Self` - Updated builder.
428    #[must_use]
429    pub fn with_fault(mut self, fault: WasmFaultKind) -> Self {
430        self.set_fault(fault);
431        self
432    }
433
434    /// Appends a WebAssembly section with length prefix into `out`.
435    ///
436    /// # Arguments
437    ///
438    /// - `&mut Vec<u8>` - Destination binary stream.
439    /// - `u8` - WASM section ID.
440    /// - `&[u8]` - Encoded section payload bytes.
441    fn push_section(out: &mut Vec<u8>, sec_id: u8, payload: &[u8]) {
442        out.push(sec_id);
443        write_uleb128(out, payload.len() as u32);
444        out.extend_from_slice(payload);
445    }
446
447    /// Encodes a UTF-8 WASM identifier name into `out`.
448    ///
449    /// # Arguments
450    ///
451    /// - `&mut Vec<u8>` - Destination byte vector.
452    /// - `&str` - Identifier text.
453    fn push_name(out: &mut Vec<u8>, name: &str) {
454        write_uleb128(out, name.len() as u32);
455        out.extend_from_slice(name.as_bytes());
456    }
457
458    /// Emits a complete spec-compliant executable `.wasm` binary buffer.
459    ///
460    /// # Arguments
461    ///
462    /// - `&Self` - Configured builder.
463    ///
464    /// # Returns
465    ///
466    /// - `Vec<u8>` - Valid WebAssembly MVP binary bytes (`\0asm\x01\0\0\0...`).
467    #[must_use]
468    pub fn build(&self) -> Vec<u8> {
469        let mut out: Vec<u8> = Vec::with_capacity(512);
470        out.extend_from_slice(WASM_BINARY_MAGIC);
471        out.extend_from_slice(WASM_BINARY_VERSION);
472        let mut type_sec: Vec<u8> = Vec::new();
473        write_uleb128(&mut type_sec, 3);
474        type_sec.extend_from_slice(&[WASM_FUNCTYPE_TAG, 2, WASM_VALTYPE_I32, WASM_VALTYPE_I32, 0]);
475        type_sec.extend_from_slice(&[WASM_FUNCTYPE_TAG, 1, WASM_VALTYPE_I32, 1, WASM_VALTYPE_I32]);
476        type_sec.extend_from_slice(&[WASM_FUNCTYPE_TAG, 0, 1, WASM_VALTYPE_I32]);
477        Self::push_section(&mut out, WASM_SEC_TYPE, &type_sec);
478        let mut imp_sec: Vec<u8> = Vec::new();
479        write_uleb128(&mut imp_sec, 2);
480        let emit_name: &str = if self.get_is_global_bundle() {
481            WASM_IMPORT_EMIT_BUNDLE
482        } else {
483            WASM_IMPORT_EMIT_UI
484        };
485        Self::push_name(&mut imp_sec, WASM_IMPORT_MODULE_ENV);
486        Self::push_name(&mut imp_sec, emit_name);
487        imp_sec.push(0x00);
488        write_uleb128(&mut imp_sec, 0);
489        Self::push_name(&mut imp_sec, WASM_IMPORT_MODULE_ENV);
490        Self::push_name(&mut imp_sec, WASM_IMPORT_LOG);
491        imp_sec.push(0x00);
492        write_uleb128(&mut imp_sec, 0);
493        Self::push_section(&mut out, WASM_SEC_IMPORT, &imp_sec);
494        let mut func_sec: Vec<u8> = Vec::new();
495        write_uleb128(&mut func_sec, 3);
496        write_uleb128(&mut func_sec, 1);
497        write_uleb128(&mut func_sec, 1);
498        write_uleb128(&mut func_sec, 2);
499        Self::push_section(&mut out, WASM_SEC_FUNCTION, &func_sec);
500        let payload1: &[u8] = self.get_ui_payload_json().as_bytes();
501        let payload2: &[u8] = self.get_alt_ui_payload_json().as_bytes();
502        let log_bytes: &[u8] = self.get_log_message().as_bytes();
503        let ptr1: i32 = 256;
504        let ptr2: i32 = ptr1 + (payload1.len() as i32) + 16;
505        let ptr_log: i32 = ptr2 + (payload2.len() as i32) + 16;
506        let total_mem_needed: usize = (ptr_log as usize) + log_bytes.len() + 256;
507        let min_pages: u32 = ((total_mem_needed / WASM_PAGE_BYTES) as u32) + 1;
508        let mut mem_sec: Vec<u8> = Vec::new();
509        write_uleb128(&mut mem_sec, 1);
510        mem_sec.push(0x00);
511        write_uleb128(&mut mem_sec, min_pages);
512        Self::push_section(&mut out, WASM_SEC_MEMORY, &mem_sec);
513        let mut exp_sec: Vec<u8> = Vec::new();
514        let exp_count: u32 = if self.get_export_render() { 3 } else { 2 };
515        write_uleb128(&mut exp_sec, exp_count);
516        if self.get_export_render() {
517            Self::push_name(&mut exp_sec, WASM_EXPORT_RENDER);
518            exp_sec.push(0x00);
519            write_uleb128(&mut exp_sec, 2);
520        }
521        Self::push_name(&mut exp_sec, WASM_EXPORT_ON_EVENT);
522        exp_sec.push(0x00);
523        write_uleb128(&mut exp_sec, 3);
524        Self::push_name(&mut exp_sec, WASM_EXPORT_ABI);
525        exp_sec.push(0x00);
526        write_uleb128(&mut exp_sec, 4);
527        Self::push_section(&mut out, WASM_SEC_EXPORT, &exp_sec);
528        let mut render_body: Vec<u8> = vec![0x00];
529        match self.get_fault() {
530            WasmFaultKind::InfiniteLoopOutOfFuel => {
531                render_body.push(OP_LOOP);
532                render_body.push(0x40);
533                render_body.push(OP_BR);
534                write_uleb128(&mut render_body, 0);
535                render_body.push(OP_END);
536                render_body.push(OP_I32_CONST);
537                write_sleb128(&mut render_body, 0);
538                render_body.push(OP_END);
539            }
540            WasmFaultKind::ExecutionTrap => {
541                render_body.push(OP_UNREACHABLE);
542                render_body.push(OP_END);
543            }
544            _ => {
545                if !payload2.is_empty() {
546                    render_body.push(OP_LOCAL_GET);
547                    write_uleb128(&mut render_body, 0);
548                    render_body.push(OP_IF);
549                    render_body.push(0x40);
550                    render_body.push(OP_I32_CONST);
551                    write_sleb128(&mut render_body, ptr2);
552                    render_body.push(OP_I32_CONST);
553                    write_sleb128(&mut render_body, payload2.len() as i32);
554                    render_body.push(OP_CALL);
555                    write_uleb128(&mut render_body, 0);
556                    render_body.push(OP_ELSE);
557                    render_body.push(OP_I32_CONST);
558                    write_sleb128(&mut render_body, ptr1);
559                    render_body.push(OP_I32_CONST);
560                    write_sleb128(&mut render_body, payload1.len() as i32);
561                    render_body.push(OP_CALL);
562                    write_uleb128(&mut render_body, 0);
563                    render_body.push(OP_END);
564                } else {
565                    render_body.push(OP_I32_CONST);
566                    write_sleb128(&mut render_body, ptr1);
567                    render_body.push(OP_I32_CONST);
568                    write_sleb128(&mut render_body, payload1.len() as i32);
569                    render_body.push(OP_CALL);
570                    write_uleb128(&mut render_body, 0);
571                }
572                if !log_bytes.is_empty() {
573                    render_body.push(OP_I32_CONST);
574                    write_sleb128(&mut render_body, ptr_log);
575                    render_body.push(OP_I32_CONST);
576                    write_sleb128(&mut render_body, log_bytes.len() as i32);
577                    render_body.push(OP_CALL);
578                    write_uleb128(&mut render_body, 1);
579                }
580                render_body.push(OP_I32_CONST);
581                write_sleb128(&mut render_body, 1);
582                render_body.push(OP_END);
583            }
584        }
585        let mut event_body: Vec<u8> = vec![0x00];
586        event_body.push(OP_LOCAL_GET);
587        write_uleb128(&mut event_body, 0);
588        event_body.push(OP_I32_CONST);
589        write_sleb128(&mut event_body, 1);
590        event_body.push(OP_I32_ADD);
591        event_body.push(OP_END);
592        let mut abi_body: Vec<u8> = vec![0x00];
593        abi_body.push(OP_I32_CONST);
594        write_sleb128(&mut abi_body, self.get_abi_version() as i32);
595        abi_body.push(OP_END);
596        let mut code_sec: Vec<u8> = Vec::new();
597        write_uleb128(&mut code_sec, 3);
598        for body in [&render_body, &event_body, &abi_body] {
599            write_uleb128(&mut code_sec, body.len() as u32);
600            code_sec.extend_from_slice(body);
601        }
602        Self::push_section(&mut out, WASM_SEC_CODE, &code_sec);
603        let mut data_sec: Vec<u8> = Vec::new();
604        let mut seg_count: u32 = 1;
605        if !payload2.is_empty() {
606            seg_count += 1;
607        }
608        if !log_bytes.is_empty() {
609            seg_count += 1;
610        }
611        write_uleb128(&mut data_sec, seg_count);
612        Self::push_data_segment(&mut data_sec, ptr1, payload1);
613        if !payload2.is_empty() {
614            Self::push_data_segment(&mut data_sec, ptr2, payload2);
615        }
616        if !log_bytes.is_empty() {
617            Self::push_data_segment(&mut data_sec, ptr_log, log_bytes);
618        }
619        Self::push_section(&mut out, WASM_SEC_DATA, &data_sec);
620        if !self.get_custom_meta().is_empty() {
621            let mut custom_sec: Vec<u8> = Vec::new();
622            Self::push_name(&mut custom_sec, WASM_CUSTOM_META_SECTION);
623            custom_sec.extend_from_slice(self.get_custom_meta().as_slice());
624            Self::push_section(&mut out, WASM_SEC_CUSTOM, &custom_sec);
625        }
626        out
627    }
628
629    /// Appends one active WASM linear memory data segment into `out`.
630    ///
631    /// # Arguments
632    ///
633    /// - `&mut Vec<u8>` - Data section accumulator.
634    /// - `i32` - Linear memory base offset.
635    /// - `&[u8]` - Data bytes to initialize.
636    fn push_data_segment(out: &mut Vec<u8>, offset: i32, data: &[u8]) {
637        write_uleb128(out, 0);
638        out.push(OP_I32_CONST);
639        write_sleb128(out, offset);
640        out.push(OP_END);
641        write_uleb128(out, data.len() as u32);
642        out.extend_from_slice(data);
643    }
644}
645
646/// Registry management methods for `RegistryWasmFetcher`.
647impl RegistryWasmFetcher {
648    /// Registers a `.wasm` payload under `url` with an ETag and optional fault behavior.
649    ///
650    /// # Arguments
651    ///
652    /// - `&Self` - Registry fetcher reference.
653    /// - `String` - Target bundle URL.
654    /// - `Vec<u8>` - Raw `.wasm` bytes.
655    /// - `String` - ETag identifier.
656    /// - `WasmFaultKind` - Fault mode (`WasmFaultKind::None` for healthy delivery).
657    pub fn register(&self, url: String, bytes: Vec<u8>, etag: String, fault: WasmFaultKind) {
658        let Self { records, .. } = self;
659        if let Ok(mut guard) = records.try_borrow_mut() {
660            let _: Option<RegistryWasmRecord> =
661                guard.insert(url, RegistryWasmRecord::new(bytes, etag, fault));
662        }
663    }
664
665    /// Toggles simulated global network offline state.
666    ///
667    /// # Arguments
668    ///
669    /// - `&Self` - Registry fetcher reference.
670    /// - `bool` - When `true`, all fetch calls return `NetworkOffline`.
671    pub fn set_offline(&self, is_offline: bool) {
672        let Self { offline, .. } = self;
673        if let Ok(mut guard) = offline.try_borrow_mut() {
674            *guard = is_offline;
675        }
676    }
677
678    /// Returns whether simulated offline mode is currently enabled.
679    ///
680    /// # Arguments
681    ///
682    /// - `&Self` - Registry fetcher reference.
683    ///
684    /// # Returns
685    ///
686    /// - `bool` - Offline flag.
687    #[must_use]
688    pub fn is_offline(&self) -> bool {
689        let Self { offline, .. } = self;
690        offline
691            .try_borrow()
692            .map(|g: Ref<'_, bool>| *g)
693            .unwrap_or(false)
694    }
695}
696
697/// `WasmFetcher` implementation serving verified `.wasm` payloads and deterministic fault cases across all 7 platforms.
698impl WasmFetcher for RegistryWasmFetcher {
699    /// Fetches a registered `.wasm` module with realistic chunked progress notifications and fault injection.
700    ///
701    /// # Arguments
702    ///
703    /// - `&Self` - Registry fetcher reference.
704    /// - `&WasmDownloadRequest` - Download request.
705    /// - `u32` - Retry attempt number.
706    /// - `&mut dyn FnMut(u64, u64)` - Streaming progress callback.
707    ///
708    /// # Returns
709    ///
710    /// - `Result<WasmFetchedPayload, WasmDynamicError>` - Downloaded payload or injected transport error.
711    fn fetch(
712        &self,
713        request: &WasmDownloadRequest,
714        attempt: u32,
715        on_progress: &mut dyn FnMut(u64, u64),
716    ) -> Result<WasmFetchedPayload, WasmDynamicError> {
717        if self.is_offline() {
718            return Err(WasmDynamicError::NetworkOffline(request.get_url().clone()));
719        }
720        let url_str: &str = request.get_url().as_str();
721        if url_str.starts_with(WASM_SCHEME_HTTP) || url_str.starts_with(WASM_SCHEME_FILE) {
722            return HttpWasmFetcher::default().fetch(request, attempt, on_progress);
723        }
724        let Self { records, .. } = self;
725        let rec: RegistryWasmRecord = records
726            .try_borrow()
727            .ok()
728            .and_then(|g: Ref<'_, HashMap<String, RegistryWasmRecord>>| {
729                g.get(request.get_url()).cloned()
730            })
731            .ok_or_else(|| WasmDynamicError::HttpStatus {
732                status: 404,
733                url: request.get_url().clone(),
734            })?;
735        match rec.get_fault() {
736            WasmFaultKind::NetworkOffline => {
737                return Err(WasmDynamicError::NetworkOffline(request.get_url().clone()));
738            }
739            WasmFaultKind::TimeoutOnceThenSucceed if attempt == 0 => {
740                return Err(WasmDynamicError::Timeout {
741                    url: request.get_url().clone(),
742                    timeout_ms: WASM_DEFAULT_TIMEOUT_MS,
743                });
744            }
745            WasmFaultKind::Http500 => {
746                return Err(WasmDynamicError::HttpStatus {
747                    status: 500,
748                    url: request.get_url().clone(),
749                });
750            }
751            _ => {}
752        }
753        let mut bytes: Vec<u8> = rec.get_bytes().clone();
754        if rec.get_fault() == WasmFaultKind::TamperedChecksum && !bytes.is_empty() {
755            let last_idx: usize = bytes.len() - 1;
756            bytes[last_idx] ^= 0xFF;
757        }
758        let total: u64 = bytes.len() as u64;
759        on_progress(total / 2, total);
760        on_progress(total, total);
761        let mut payload: WasmFetchedPayload = WasmFetchedPayload::new(bytes);
762        payload.set_etag(rec.get_etag().clone());
763        Ok(payload)
764    }
765}
766
767/// Pure-std `http://` and `file://` transport implementation for `HttpWasmFetcher`.
768impl WasmFetcher for HttpWasmFetcher {
769    /// Downloads a `.wasm` binary over real TCP HTTP or local `file://` path with socket timeout and progress streaming.
770    ///
771    /// # Arguments
772    ///
773    /// - `&Self` - HTTP fetcher reference.
774    /// - `&WasmDownloadRequest` - Target download descriptor.
775    /// - `u32` - Retry attempt counter.
776    /// - `&mut dyn FnMut(u64, u64)` - Byte progress callback.
777    ///
778    /// # Returns
779    ///
780    /// - `Result<WasmFetchedPayload, WasmDynamicError>` - Downloaded bytes or typed transport error.
781    fn fetch(
782        &self,
783        request: &WasmDownloadRequest,
784        _attempt: u32,
785        on_progress: &mut dyn FnMut(u64, u64),
786    ) -> Result<WasmFetchedPayload, WasmDynamicError> {
787        let url: &str = request.get_url().as_str();
788        #[cfg(not(target_arch = "wasm32"))]
789        {
790            if let Some(path) = url.strip_prefix(WASM_SCHEME_FILE) {
791                let bytes: Vec<u8> = fs::read(path).map_err(|_| WasmDynamicError::HttpStatus {
792                    status: 404,
793                    url: url.to_string(),
794                })?;
795                let total: u64 = bytes.len() as u64;
796                on_progress(total, total);
797                return Ok(WasmFetchedPayload::new(bytes));
798            }
799            if let Some(rest) = url.strip_prefix(WASM_SCHEME_HTTP) {
800                let (host_port, req_path): (&str, String) = match rest.find('/') {
801                    Some(idx) => (&rest[..idx], rest[idx..].to_string()),
802                    None => (rest, "/".to_string()),
803                };
804                let connect_target: String = if host_port.contains(':') {
805                    host_port.to_string()
806                } else {
807                    format!("{host_port}:80")
808                };
809                let timeout_ms: u64 = self.get_timeout_ms().max(1_000);
810                let dur: Duration = Duration::from_millis(timeout_ms);
811                let addr: SocketAddr = match connect_target.to_socket_addrs() {
812                    Ok(mut it) => it.next(),
813                    Err(_) => None,
814                }
815                .ok_or_else(|| WasmDynamicError::NetworkOffline(url.to_string()))?;
816                let mut stream: TcpStream =
817                    TcpStream::connect_timeout(&addr, dur).map_err(|_| {
818                        WasmDynamicError::Timeout {
819                            url: url.to_string(),
820                            timeout_ms,
821                        }
822                    })?;
823                let _: Result<(), io::Error> = stream.set_read_timeout(Some(dur));
824                let _: Result<(), io::Error> = stream.set_write_timeout(Some(dur));
825                let req_str: String = format!(
826                    "GET {req_path} HTTP/1.1\r\nHost: {host_port}\r\nConnection: close\r\nAccept: application/wasm\r\n\r\n"
827                );
828                stream
829                    .write_all(req_str.as_bytes())
830                    .map_err(|_| WasmDynamicError::NetworkOffline(url.to_string()))?;
831                let mut raw: Vec<u8> = Vec::new();
832                let mut chunk: [u8; 4096] = [0; 4096];
833                loop {
834                    match stream.read(&mut chunk) {
835                        Ok(0) => break,
836                        Ok(n) => {
837                            raw.extend_from_slice(&chunk[..n]);
838                            on_progress(raw.len() as u64, 0);
839                        }
840                        Err(_) => {
841                            return Err(WasmDynamicError::Timeout {
842                                url: url.to_string(),
843                                timeout_ms,
844                            });
845                        }
846                    }
847                }
848                let sep_pos: usize = raw
849                    .windows(4)
850                    .position(|w: &[u8]| w == b"\r\n\r\n")
851                    .ok_or_else(|| {
852                        WasmDynamicError::InvalidWasmBinary("malformed HTTP response".to_string())
853                    })?;
854                let header_str: &str = from_utf8(&raw[..sep_pos]).unwrap_or("");
855                let status_code: u16 = header_str
856                    .lines()
857                    .next()
858                    .and_then(|line: &str| line.split_whitespace().nth(1))
859                    .and_then(|code: &str| code.parse::<u16>().ok())
860                    .unwrap_or(500);
861                if !(200..300).contains(&status_code) {
862                    return Err(WasmDynamicError::HttpStatus {
863                        status: status_code,
864                        url: url.to_string(),
865                    });
866                }
867                let body: Vec<u8> = raw[sep_pos + 4..].to_vec();
868                on_progress(body.len() as u64, body.len() as u64);
869                return Ok(WasmFetchedPayload::new(body));
870            }
871            Err(WasmDynamicError::InvalidUrl(url.to_string()))
872        }
873        #[cfg(target_arch = "wasm32")]
874        {
875            let _: &mut dyn FnMut(u64, u64) = on_progress;
876            Err(WasmDynamicError::NetworkOffline(url.to_string()))
877        }
878    }
879}
880
881/// Complete partial & global dynamic `.wasm` lifecycle orchestration for `WasmDynamicManager`.
882impl WasmDynamicManager {
883    /// Creates a `WasmDynamicManager` bound to `hub` and `fetcher` with `config`.
884    ///
885    /// # Arguments
886    ///
887    /// - `DynamicUpdateHub` - Target native scene dynamic update hub.
888    /// - `Rc<dyn WasmFetcher>` - Transport fetcher for `.wasm` downloads.
889    /// - `WasmSandboxConfig` - Sandbox limits and retry/cache configuration.
890    ///
891    /// # Returns
892    ///
893    /// - `Self` - Initialized dynamic WASM manager.
894    #[must_use]
895    pub fn new(
896        hub: DynamicUpdateHub,
897        fetcher: Rc<dyn WasmFetcher>,
898        config: WasmSandboxConfig,
899    ) -> Self {
900        Self {
901            inner: Rc::new(RefCell::new(WasmDynamicManagerState {
902                hub,
903                fetcher,
904                config,
905                next_request_id: 0,
906                active_request_ids: HashMap::new(),
907                cache: HashMap::new(),
908                partial_stacks: HashMap::new(),
909                global_stack: Vec::new(),
910                state_signals: HashMap::new(),
911                global_version_signal: Signal::new_detached(0),
912                telemetry_signal: Signal::new_detached(WasmDynamicTelemetry::default()),
913                last_logs: Signal::new_detached(Vec::new()),
914            })),
915        }
916    }
917
918    /// Returns the reactive `WasmLoadState` signal for `scope`.
919    ///
920    /// # Arguments
921    ///
922    /// - `&Self` - Manager reference.
923    /// - `&WasmDynamicScope` - Target partial slot or global scope.
924    ///
925    /// # Returns
926    ///
927    /// - `Signal<WasmLoadState>` - Live reactive lifecycle signal.
928    #[must_use]
929    pub fn state_signal(&self, scope: &WasmDynamicScope) -> Signal<WasmLoadState> {
930        let key: String = scope.key();
931        let Self { inner } = self;
932        if let Ok(mut guard) = inner.try_borrow_mut() {
933            return *guard
934                .state_signals
935                .entry(key)
936                .or_insert_with(|| Signal::new_detached(WasmLoadState::Idle));
937        }
938        Signal::new_detached(WasmLoadState::Idle)
939    }
940
941    /// Returns the reactive global WASM active version signal (`0` = built-in native shell).
942    ///
943    /// # Arguments
944    ///
945    /// - `&Self` - Manager reference.
946    ///
947    /// # Returns
948    ///
949    /// - `Signal<u64>` - Global active version signal.
950    #[must_use]
951    pub fn global_version_signal(&self) -> Signal<u64> {
952        let Self { inner } = self;
953        inner
954            .try_borrow()
955            .map(|g: Ref<'_, WasmDynamicManagerState>| g.global_version_signal)
956            .unwrap_or_else(|_| Signal::new_detached(0))
957    }
958
959    /// Returns the reactive `WasmDynamicTelemetry` signal.
960    ///
961    /// # Arguments
962    ///
963    /// - `&Self` - Manager reference.
964    ///
965    /// # Returns
966    ///
967    /// - `Signal<WasmDynamicTelemetry>` - Cumulative telemetry signal.
968    #[must_use]
969    pub fn telemetry(&self) -> Signal<WasmDynamicTelemetry> {
970        let Self { inner } = self;
971        inner
972            .try_borrow()
973            .map(|g: Ref<'_, WasmDynamicManagerState>| g.telemetry_signal)
974            .unwrap_or_else(|_| Signal::new_detached(WasmDynamicTelemetry::default()))
975    }
976
977    /// Returns the reactive signal carrying diagnostic logs from the last executed WASM module.
978    ///
979    /// # Arguments
980    ///
981    /// - `&Self` - Manager reference.
982    ///
983    /// # Returns
984    ///
985    /// - `Signal<Vec<String>>` - Diagnostic log lines signal.
986    #[must_use]
987    pub fn last_logs(&self) -> Signal<Vec<String>> {
988        let Self { inner } = self;
989        inner
990            .try_borrow()
991            .map(|g: Ref<'_, WasmDynamicManagerState>| g.last_logs)
992            .unwrap_or_else(|_| Signal::new_detached(Vec::new()))
993    }
994
995    /// Returns the number of verified cached `.wasm` entries.
996    ///
997    /// # Arguments
998    ///
999    /// - `&Self` - Manager reference.
1000    ///
1001    /// # Returns
1002    ///
1003    /// - `usize` - Cached module count.
1004    #[must_use]
1005    pub fn cache_len(&self) -> usize {
1006        let Self { inner } = self;
1007        inner
1008            .try_borrow()
1009            .map(|g: Ref<'_, WasmDynamicManagerState>| g.cache.len())
1010            .unwrap_or(0)
1011    }
1012
1013    /// Cancels any active request for `scope`, advancing its generation ID so stale responses are discarded.
1014    ///
1015    /// # Arguments
1016    ///
1017    /// - `&Self` - Manager reference.
1018    /// - `&WasmDynamicScope` - Scope to cancel.
1019    ///
1020    /// # Returns
1021    ///
1022    /// - `u64` - Newly allocated cancellation generation ID.
1023    pub fn cancel_scope(&self, scope: &WasmDynamicScope) -> u64 {
1024        let state_sig: Signal<WasmLoadState> = self.state_signal(scope);
1025        let key: String = scope.key();
1026        let Self { inner } = self;
1027        let next_id: u64 = if let Ok(mut guard) = inner.try_borrow_mut() {
1028            guard.next_request_id = guard.next_request_id.saturating_add(1);
1029            let id: u64 = guard.next_request_id;
1030            let _: Option<u64> = guard.active_request_ids.insert(key, id);
1031            id
1032        } else {
1033            0
1034        };
1035        let _: bool = state_sig.set(WasmLoadState::Failed(WasmDynamicError::Cancelled {
1036            request_id: next_id,
1037        }));
1038        next_id
1039    }
1040
1041    /// Downloads, verifies, compiles, executes in sandbox, and natively mounts a partial or global `.wasm` module.
1042    ///
1043    /// # Arguments
1044    ///
1045    /// - `&Self` - Manager reference.
1046    /// - `WasmDownloadRequest` - Target URL, scope, version, checksum, and signature policy.
1047    /// - `&str` - Signing key used when verifying `expected_signature`.
1048    ///
1049    /// # Returns
1050    ///
1051    /// - `Result<u64, WasmDynamicError>` - Mounted version number on success, or typed error (with automatic global LKG rollback).
1052    pub fn load_and_mount(
1053        &self,
1054        request: WasmDownloadRequest,
1055        signing_key: &str,
1056    ) -> Result<u64, WasmDynamicError> {
1057        let url_str: &str = request.get_url().trim();
1058        let valid_scheme: bool = url_str.starts_with("https://")
1059            || url_str.starts_with(WASM_SCHEME_HTTP)
1060            || url_str.starts_with("euv-cdn://")
1061            || url_str.starts_with(WASM_SCHEME_FILE);
1062        if url_str.is_empty() || !valid_scheme {
1063            let err: WasmDynamicError = WasmDynamicError::InvalidUrl(request.get_url().clone());
1064            self.record_failure(request.get_scope(), &err);
1065            return Err(err);
1066        }
1067        let scope: WasmDynamicScope = request.get_scope().clone();
1068        let scope_key: String = scope.key();
1069        let state_sig: Signal<WasmLoadState> = self.state_signal(&scope);
1070        let (req_id, config, fetcher, active_ver, cached_entry): (
1071            u64,
1072            WasmSandboxConfig,
1073            Rc<dyn WasmFetcher>,
1074            u64,
1075            Option<WasmCachedEntry>,
1076        ) = {
1077            let Self { inner } = self;
1078            let mut guard: RefMut<'_, WasmDynamicManagerState> = inner
1079                .try_borrow_mut()
1080                .map_err(|_| WasmDynamicError::ExecutionTrap("manager re-entrancy".to_string()))?;
1081            guard.next_request_id = guard.next_request_id.saturating_add(1);
1082            let id: u64 = guard.next_request_id;
1083            let _: Option<u64> = guard.active_request_ids.insert(scope_key.clone(), id);
1084            let cur_v: u64 = match &scope {
1085                WasmDynamicScope::Partial { slot_id } => guard
1086                    .partial_stacks
1087                    .get(slot_id)
1088                    .and_then(|s: &Vec<WasmMountedSnapshot>| s.last())
1089                    .map(WasmMountedSnapshot::get_version)
1090                    .unwrap_or(0),
1091                WasmDynamicScope::Global => guard
1092                    .global_stack
1093                    .last()
1094                    .map(WasmMountedSnapshot::get_version)
1095                    .unwrap_or(0),
1096            };
1097            let cached: Option<WasmCachedEntry> =
1098                guard.cache.get(request.resolved_cache_key()).cloned();
1099            let _: bool = guard
1100                .telemetry_signal
1101                .update(|t: &mut WasmDynamicTelemetry| {
1102                    t.downloads_started = t.downloads_started.saturating_add(1);
1103                });
1104            (id, guard.config, guard.fetcher.clone(), cur_v, cached)
1105        };
1106        if !request.get_allow_downgrade() && active_ver > 0 && request.get_version() <= active_ver {
1107            let err: WasmDynamicError = WasmDynamicError::VersionRegression {
1108                current: active_ver,
1109                incoming: request.get_version(),
1110            };
1111            self.record_failure(&scope, &err);
1112            return Err(err);
1113        }
1114        let _: bool = state_sig.set(WasmLoadState::Downloading {
1115            received_bytes: 0,
1116            total_bytes: 0,
1117        });
1118        let fetched: WasmFetchedPayload =
1119            match self.fetch_with_retry(&request, config, &fetcher, cached_entry, state_sig) {
1120                Ok(p) => p,
1121                Err(err) => {
1122                    self.record_failure(&scope, &err);
1123                    return Err(err);
1124                }
1125            };
1126        let current_active_id: u64 = self.active_request_id(&scope_key);
1127        if current_active_id != req_id {
1128            let err: WasmDynamicError = WasmDynamicError::StaleResponse {
1129                request_id: req_id,
1130                active_request_id: current_active_id,
1131            };
1132            return Err(err);
1133        }
1134        let _: bool = state_sig.set(WasmLoadState::Verifying);
1135        let raw_bytes: &[u8] = fetched.get_bytes().as_slice();
1136        if raw_bytes.len() > config.get_max_binary_bytes() {
1137            let err: WasmDynamicError = WasmDynamicError::BinaryTooLarge {
1138                actual: raw_bytes.len(),
1139                limit: config.get_max_binary_bytes(),
1140            };
1141            self.record_failure(&scope, &err);
1142            return Err(err);
1143        }
1144        let computed_checksum: u64 = compute_wasm_checksum(raw_bytes);
1145        if request.get_expected_checksum() != 0
1146            && computed_checksum != request.get_expected_checksum()
1147        {
1148            let err: WasmDynamicError = WasmDynamicError::ChecksumMismatch {
1149                expected: request.get_expected_checksum(),
1150                actual: computed_checksum,
1151            };
1152            self.record_failure(&scope, &err);
1153            return Err(err);
1154        }
1155        if config.get_require_signature() || !request.get_expected_signature().is_empty() {
1156            let computed_sig: String =
1157                compute_wasm_signature(raw_bytes, request.get_version(), signing_key);
1158            if computed_sig != *request.get_expected_signature() {
1159                let err: WasmDynamicError = WasmDynamicError::SignatureInvalid {
1160                    expected: request.get_expected_signature().clone(),
1161                    actual: computed_sig,
1162                };
1163                self.record_failure(&scope, &err);
1164                return Err(err);
1165            }
1166        }
1167        let _: bool = state_sig.set(WasmLoadState::Compiling);
1168        let parsed: WasmParsedModule = match parse_wasm_binary(raw_bytes, &config) {
1169            Ok(m) => m,
1170            Err(err) => {
1171                self.record_failure(&scope, &err);
1172                return Err(err);
1173            }
1174        };
1175        if parsed.get_exports().contains_key(WASM_EXPORT_ABI) {
1176            let abi_res: Result<WasmExecutionOutput, WasmDynamicError> =
1177                execute_wasm_export(&parsed, WASM_EXPORT_ABI, &[], &config);
1178            match abi_res {
1179                Ok(abi_out) => {
1180                    let mod_abi: u32 = abi_out.get_return_value().max(0) as u32;
1181                    if mod_abi != WASM_ABI_VERSION {
1182                        let err: WasmDynamicError = WasmDynamicError::AbiMismatch {
1183                            expected: WASM_ABI_VERSION,
1184                            actual: mod_abi,
1185                        };
1186                        self.record_failure(&scope, &err);
1187                        return Err(err);
1188                    }
1189                }
1190                Err(err) => {
1191                    self.record_failure(&scope, &err);
1192                    return Err(err);
1193                }
1194            }
1195        }
1196        let _: bool = state_sig.set(WasmLoadState::Executing);
1197        let exec_out: WasmExecutionOutput =
1198            match execute_wasm_export(&parsed, WASM_EXPORT_RENDER, &[0], &config) {
1199                Ok(out) => out,
1200                Err(err) => {
1201                    self.record_failure(&scope, &err);
1202                    return Err(err);
1203                }
1204            };
1205        self.commit_mounted_output(
1206            &request,
1207            fetched,
1208            computed_checksum,
1209            parsed,
1210            exec_out,
1211            state_sig,
1212        )
1213    }
1214
1215    /// Executes an interactive click/event inside a mounted WASM module (`euv_on_event`), re-rendering native UI live.
1216    ///
1217    /// # Arguments
1218    ///
1219    /// - `&Self` - Manager reference.
1220    /// - `&WasmDynamicScope` - Mounted partial or global WASM scope.
1221    /// - `i32` - Action code passed into `euv_on_event`.
1222    ///
1223    /// # Returns
1224    ///
1225    /// - `Result<i32, WasmDynamicError>` - Updated WASM module state value or sandbox error.
1226    pub fn dispatch_wasm_event(
1227        &self,
1228        scope: &WasmDynamicScope,
1229        action_code: i32,
1230    ) -> Result<i32, WasmDynamicError> {
1231        let (config, snapshot, hub): (WasmSandboxConfig, WasmMountedSnapshot, DynamicUpdateHub) = {
1232            let Self { inner } = self;
1233            let guard: Ref<'_, WasmDynamicManagerState> = inner.try_borrow().map_err(|_| {
1234                WasmDynamicError::ExecutionTrap(WASM_ERR_MANAGER_BORROW.to_string())
1235            })?;
1236            let snap: WasmMountedSnapshot = match scope {
1237                WasmDynamicScope::Partial { slot_id } => guard
1238                    .partial_stacks
1239                    .get(slot_id)
1240                    .and_then(|s: &Vec<WasmMountedSnapshot>| s.last())
1241                    .cloned()
1242                    .ok_or(WasmDynamicError::NoRollbackSnapshot)?,
1243                WasmDynamicScope::Global => guard
1244                    .global_stack
1245                    .last()
1246                    .cloned()
1247                    .ok_or(WasmDynamicError::NoRollbackSnapshot)?,
1248            };
1249            (guard.config, snap, guard.hub.clone())
1250        };
1251        let next_state: i32 = if snapshot
1252            .get_module()
1253            .get_exports()
1254            .contains_key(WASM_EXPORT_ON_EVENT)
1255        {
1256            let ev_out: WasmExecutionOutput = execute_wasm_export(
1257                snapshot.get_module(),
1258                WASM_EXPORT_ON_EVENT,
1259                &[snapshot.get_state_value()],
1260                &config,
1261            )?;
1262            let _: i32 = action_code;
1263            ev_out.get_return_value() % 2
1264        } else {
1265            (snapshot.get_state_value() + 1) % 2
1266        };
1267        let render_out: WasmExecutionOutput = execute_wasm_export(
1268            snapshot.get_module(),
1269            WASM_EXPORT_RENDER,
1270            &[next_state],
1271            &config,
1272        )?;
1273        match scope {
1274            WasmDynamicScope::Partial { slot_id } => {
1275                if let Some(spec) = render_out.emitted_spec() {
1276                    let mut upd: DynamicComponentUpdate = DynamicComponentUpdate::new(
1277                        slot_id.clone(),
1278                        snapshot.get_version(),
1279                        spec.clone(),
1280                    );
1281                    upd.set_allow_downgrade(true);
1282                    upd.sign();
1283                    let _: Result<u64, DynamicUpdateError> = hub.apply_component(upd);
1284                }
1285            }
1286            WasmDynamicScope::Global => {
1287                if let Some(bundle) = render_out.emitted_bundle() {
1288                    let mut patched: DynamicUpdateBundle = bundle.clone();
1289                    for comp in patched.get_mut_components().iter_mut() {
1290                        comp.set_allow_downgrade(true);
1291                        comp.sign();
1292                    }
1293                    for page in patched.get_mut_pages().iter_mut() {
1294                        page.set_allow_downgrade(true);
1295                        page.sign();
1296                    }
1297                    let _: Result<DynamicTelemetry, DynamicUpdateError> = hub.apply_bundle(patched);
1298                }
1299            }
1300        }
1301        let Self { inner } = self;
1302        if let Ok(mut guard) = inner.try_borrow_mut() {
1303            match scope {
1304                WasmDynamicScope::Partial { slot_id } => {
1305                    if let Some(stack) = guard.partial_stacks.get_mut(slot_id)
1306                        && let Some(top) = stack.last_mut()
1307                    {
1308                        top.set_state_value(next_state);
1309                    }
1310                }
1311                WasmDynamicScope::Global => {
1312                    if let Some(top) = guard.global_stack.last_mut() {
1313                        top.set_state_value(next_state);
1314                    }
1315                }
1316            }
1317            let _: bool = guard
1318                .telemetry_signal
1319                .update(|t: &mut WasmDynamicTelemetry| {
1320                    t.events_handled = t.events_handled.saturating_add(1);
1321                });
1322        }
1323        Ok(next_state)
1324    }
1325
1326    /// Rolls back a partial slot to its previous verified WASM version or compiled native fallback.
1327    ///
1328    /// # Arguments
1329    ///
1330    /// - `&Self` - Manager reference.
1331    /// - `&str` - Target partial slot ID.
1332    /// - `&str` - Human-readable rollback reason.
1333    ///
1334    /// # Returns
1335    ///
1336    /// - `Result<u64, WasmDynamicError>` - Active version after rollback (`0` = compiled fallback).
1337    pub fn rollback_partial(&self, slot_id: &str, reason: &str) -> Result<u64, WasmDynamicError> {
1338        let scope: WasmDynamicScope = WasmDynamicScope::Partial {
1339            slot_id: slot_id.to_string(),
1340        };
1341        let state_sig: Signal<WasmLoadState> = self.state_signal(&scope);
1342        let (hub, next_ver): (DynamicUpdateHub, u64) = {
1343            let Self { inner } = self;
1344            let mut guard: RefMut<'_, WasmDynamicManagerState> =
1345                inner.try_borrow_mut().map_err(|_| {
1346                    WasmDynamicError::ExecutionTrap(WASM_ERR_MANAGER_BORROW.to_string())
1347                })?;
1348            let stack: &mut Vec<WasmMountedSnapshot> = guard
1349                .partial_stacks
1350                .get_mut(slot_id)
1351                .ok_or(WasmDynamicError::NoRollbackSnapshot)?;
1352            if stack.pop().is_none() {
1353                return Err(WasmDynamicError::NoRollbackSnapshot);
1354            }
1355            let ver: u64 = stack
1356                .last()
1357                .map(WasmMountedSnapshot::get_version)
1358                .unwrap_or(0);
1359            let _: bool = guard
1360                .telemetry_signal
1361                .update(|t: &mut WasmDynamicTelemetry| {
1362                    t.rollbacks_executed = t.rollbacks_executed.saturating_add(1);
1363                });
1364            (guard.hub.clone(), ver)
1365        };
1366        let _: Result<u64, DynamicUpdateError> = hub.rollback_component(slot_id);
1367        let _: bool = state_sig.set(WasmLoadState::RolledBack {
1368            active_version: next_ver,
1369            reason: reason.to_string(),
1370        });
1371        Ok(next_ver)
1372    }
1373
1374    /// Unmounts a partial WASM slot completely, freeing its snapshot stack and restoring the compiled native fallback.
1375    ///
1376    /// # Arguments
1377    ///
1378    /// - `&Self` - Manager reference.
1379    /// - `&str` - Target partial slot ID.
1380    pub fn unmount_partial(&self, slot_id: &str) {
1381        let scope: WasmDynamicScope = WasmDynamicScope::Partial {
1382            slot_id: slot_id.to_string(),
1383        };
1384        let state_sig: Signal<WasmLoadState> = self.state_signal(&scope);
1385        let hub: Option<DynamicUpdateHub> = {
1386            let Self { inner } = self;
1387            if let Ok(mut guard) = inner.try_borrow_mut() {
1388                let _: Option<Vec<WasmMountedSnapshot>> = guard.partial_stacks.remove(slot_id);
1389                Some(guard.hub.clone())
1390            } else {
1391                None
1392            }
1393        };
1394        if let Some(h) = hub {
1395            while h.rollback_component(slot_id).is_ok() {}
1396        }
1397        let _: bool = state_sig.set(WasmLoadState::Idle);
1398    }
1399
1400    /// Rolls back the global full-app WASM shell to the previous LKG snapshot (or built-in native shell when empty).
1401    ///
1402    /// # Arguments
1403    ///
1404    /// - `&Self` - Manager reference.
1405    /// - `&str` - Rollback reason string.
1406    ///
1407    /// # Returns
1408    ///
1409    /// - `Result<u64, WasmDynamicError>` - Remaining global version (`0` = built-in native shell).
1410    pub fn rollback_global(&self, reason: &str) -> Result<u64, WasmDynamicError> {
1411        let state_sig: Signal<WasmLoadState> = self.state_signal(&WasmDynamicScope::Global);
1412        let (hub, global_sig, next_ver): (DynamicUpdateHub, Signal<u64>, u64) = {
1413            let Self { inner } = self;
1414            let mut guard: RefMut<'_, WasmDynamicManagerState> =
1415                inner.try_borrow_mut().map_err(|_| {
1416                    WasmDynamicError::ExecutionTrap(WASM_ERR_MANAGER_BORROW.to_string())
1417                })?;
1418            if guard.global_stack.pop().is_none() {
1419                return Err(WasmDynamicError::NoRollbackSnapshot);
1420            }
1421            let ver: u64 = guard
1422                .global_stack
1423                .last()
1424                .map(WasmMountedSnapshot::get_version)
1425                .unwrap_or(0);
1426            let _: bool = guard
1427                .telemetry_signal
1428                .update(|t: &mut WasmDynamicTelemetry| {
1429                    t.rollbacks_executed = t.rollbacks_executed.saturating_add(1);
1430                });
1431            (guard.hub.clone(), guard.global_version_signal, ver)
1432        };
1433        let _: Result<u64, DynamicUpdateError> = hub.rollback_component(WASM_GLOBAL_ROOT_SLOT);
1434        let _: bool = global_sig.set_if_changed(next_ver);
1435        let _: bool = state_sig.set(WasmLoadState::RolledBack {
1436            active_version: next_ver,
1437            reason: reason.to_string(),
1438        });
1439        Ok(next_ver)
1440    }
1441
1442    /// Restores the built-in compiled native application shell, clearing all global WASM overlays cleanly.
1443    ///
1444    /// # Arguments
1445    ///
1446    /// - `&Self` - Manager reference.
1447    pub fn restore_native_global(&self) {
1448        let state_sig: Signal<WasmLoadState> = self.state_signal(&WasmDynamicScope::Global);
1449        let pair: Option<(DynamicUpdateHub, Signal<u64>)> = {
1450            let Self { inner } = self;
1451            if let Ok(mut guard) = inner.try_borrow_mut() {
1452                guard.global_stack.clear();
1453                let _: bool = guard
1454                    .telemetry_signal
1455                    .update(|t: &mut WasmDynamicTelemetry| {
1456                        t.rollbacks_executed = t.rollbacks_executed.saturating_add(1);
1457                    });
1458                Some((guard.hub.clone(), guard.global_version_signal))
1459            } else {
1460                None
1461            }
1462        };
1463        if let Some((hub, global_sig)) = pair {
1464            while hub.rollback_component(WASM_GLOBAL_ROOT_SLOT).is_ok() {}
1465            let _: bool = global_sig.set_if_changed(0);
1466        }
1467        let _: bool = state_sig.set(WasmLoadState::RolledBack {
1468            active_version: 0,
1469            reason: "restored built-in native shell".to_string(),
1470        });
1471    }
1472
1473    /// Returns the currently active request generation ID for `scope_key`.
1474    ///
1475    /// # Arguments
1476    ///
1477    /// - `&Self` - Manager reference.
1478    /// - `&str` - Scope registry key.
1479    ///
1480    /// # Returns
1481    ///
1482    /// - `u64` - Active request ID.
1483    #[must_use]
1484    fn active_request_id(&self, scope_key: &str) -> u64 {
1485        let Self { inner } = self;
1486        inner
1487            .try_borrow()
1488            .ok()
1489            .and_then(|g: Ref<'_, WasmDynamicManagerState>| {
1490                g.active_request_ids.get(scope_key).copied()
1491            })
1492            .unwrap_or(0)
1493    }
1494
1495    /// Executes the download with exponential retry on transient failures and verified offline cache fallback.
1496    ///
1497    /// # Arguments
1498    ///
1499    /// - `&Self` - Manager reference.
1500    /// - `&WasmDownloadRequest` - Target download request.
1501    /// - `WasmSandboxConfig` - Retry and offline cache settings.
1502    /// - `&Rc<dyn WasmFetcher>` - Transport implementation.
1503    /// - `Option<WasmCachedEntry>` - Optional cached verified `.wasm`.
1504    /// - `Signal<WasmLoadState>` - Live progress signal.
1505    ///
1506    /// # Returns
1507    ///
1508    /// - `Result<WasmFetchedPayload, WasmDynamicError>` - Fetched or cached bytes.
1509    fn fetch_with_retry(
1510        &self,
1511        request: &WasmDownloadRequest,
1512        config: WasmSandboxConfig,
1513        fetcher: &Rc<dyn WasmFetcher>,
1514        cached_entry: Option<WasmCachedEntry>,
1515        state_sig: Signal<WasmLoadState>,
1516    ) -> Result<WasmFetchedPayload, WasmDynamicError> {
1517        let mut last_err: WasmDynamicError =
1518            WasmDynamicError::NetworkOffline(request.get_url().clone());
1519        let max_attempts: u32 = config.get_max_retries().saturating_add(1);
1520        for attempt in 0..max_attempts {
1521            if attempt > 0 {
1522                let Self { inner } = self;
1523                if let Ok(guard) = inner.try_borrow() {
1524                    let _: bool = guard
1525                        .telemetry_signal
1526                        .update(|t: &mut WasmDynamicTelemetry| {
1527                            t.retries_performed = t.retries_performed.saturating_add(1);
1528                        });
1529                }
1530            }
1531            match fetcher.fetch(request, attempt, &mut |received: u64, total: u64| {
1532                let _: bool = state_sig.set(WasmLoadState::Downloading {
1533                    received_bytes: received,
1534                    total_bytes: total,
1535                });
1536            }) {
1537                Ok(payload) => return Ok(payload),
1538                Err(err) => {
1539                    let retryable: bool = matches!(
1540                        err,
1541                        WasmDynamicError::Timeout { .. }
1542                            | WasmDynamicError::HttpStatus {
1543                                status: 500..=599,
1544                                ..
1545                            }
1546                    );
1547                    last_err = err;
1548                    if !retryable {
1549                        break;
1550                    }
1551                }
1552            }
1553        }
1554        if config.get_allow_offline_cache()
1555            && let Some(cached) = cached_entry
1556        {
1557            let Self { inner } = self;
1558            if let Ok(guard) = inner.try_borrow() {
1559                let _: bool = guard
1560                    .telemetry_signal
1561                    .update(|t: &mut WasmDynamicTelemetry| {
1562                        t.cache_hits = t.cache_hits.saturating_add(1);
1563                    });
1564            }
1565            let mut payload: WasmFetchedPayload =
1566                WasmFetchedPayload::new(cached.get_bytes().clone());
1567            payload
1568                .set_etag(cached.get_etag().clone())
1569                .set_from_cache(true);
1570            return Ok(payload);
1571        }
1572        Err(last_err)
1573    }
1574
1575    /// Commits a verified executed WASM output into `DynamicUpdateHub`, updates cache & rollback stacks, and emits telemetry.
1576    ///
1577    /// # Arguments
1578    ///
1579    /// - `&Self` - Manager reference.
1580    /// - `&WasmDownloadRequest` - Origin request.
1581    /// - `WasmFetchedPayload` - Verified payload bytes.
1582    /// - `u64` - Verified FNV-1a checksum.
1583    /// - `WasmParsedModule` - Validated `.wasm` module.
1584    /// - `WasmExecutionOutput` - Executed render output.
1585    /// - `Signal<WasmLoadState>` - Live scope status signal.
1586    ///
1587    /// # Returns
1588    ///
1589    /// - `Result<u64, WasmDynamicError>` - Mounted version number.
1590    fn commit_mounted_output(
1591        &self,
1592        request: &WasmDownloadRequest,
1593        fetched: WasmFetchedPayload,
1594        checksum: u64,
1595        parsed: WasmParsedModule,
1596        exec_out: WasmExecutionOutput,
1597        state_sig: Signal<WasmLoadState>,
1598    ) -> Result<u64, WasmDynamicError> {
1599        let ver: u64 = request.get_version();
1600        let fuel_used: u64 = exec_out.get_fuel_used();
1601        let from_cache: bool = fetched.get_from_cache();
1602        let logs: Vec<String> = exec_out.get_logs().clone();
1603        let hub: DynamicUpdateHub = {
1604            let Self { inner } = self;
1605            inner
1606                .try_borrow()
1607                .map(|g: Ref<'_, WasmDynamicManagerState>| g.hub.clone())
1608                .map_err(|_| WasmDynamicError::ExecutionTrap(WASM_ERR_MANAGER_BORROW.to_string()))?
1609        };
1610        let (spec_opt, bundle_opt): (Option<DynamicNodeSpec>, Option<DynamicUpdateBundle>) =
1611            match request.get_scope() {
1612                WasmDynamicScope::Partial { slot_id } => {
1613                    let spec: DynamicNodeSpec =
1614                        exec_out.emitted_spec().cloned().ok_or_else(|| {
1615                            WasmDynamicError::InvalidUiPayload(
1616                                "partial wasm did not call env::euv_emit_ui".to_string(),
1617                            )
1618                        })?;
1619                    let mut upd: DynamicComponentUpdate =
1620                        DynamicComponentUpdate::new(slot_id.clone(), ver, spec.clone());
1621                    upd.set_allow_downgrade(request.get_allow_downgrade());
1622                    upd.sign();
1623                    hub.apply_component(upd).map_err(|e: DynamicUpdateError| {
1624                        WasmDynamicError::InvalidUiPayload(e.to_string())
1625                    })?;
1626                    (Some(spec), None)
1627                }
1628                WasmDynamicScope::Global => {
1629                    let bundle: DynamicUpdateBundle =
1630                        exec_out.emitted_bundle().cloned().ok_or_else(|| {
1631                            WasmDynamicError::InvalidUiPayload(
1632                                "global wasm did not call env::euv_emit_bundle".to_string(),
1633                            )
1634                        })?;
1635                    let mut patched: DynamicUpdateBundle = bundle.clone();
1636                    if request.get_allow_downgrade() {
1637                        for comp in patched.get_mut_components().iter_mut() {
1638                            comp.set_allow_downgrade(true);
1639                        }
1640                        for page in patched.get_mut_pages().iter_mut() {
1641                            page.set_allow_downgrade(true);
1642                        }
1643                    }
1644                    let _: DynamicTelemetry =
1645                        hub.apply_bundle(patched).map_err(|e: DynamicUpdateError| {
1646                            WasmDynamicError::InvalidUiPayload(e.to_string())
1647                        })?;
1648                    (None, Some(bundle))
1649                }
1650            };
1651        let snap: WasmMountedSnapshot = WasmMountedSnapshot {
1652            version: ver,
1653            url: request.get_url().clone(),
1654            checksum,
1655            module: parsed,
1656            state_value: 0,
1657            spec: spec_opt,
1658            bundle: bundle_opt,
1659        };
1660        let cache_entry: WasmCachedEntry = WasmCachedEntry::new(
1661            request.get_url().clone(),
1662            ver,
1663            checksum,
1664            fetched.get_bytes().clone(),
1665            fetched.get_etag().clone(),
1666        );
1667        let Self { inner } = self;
1668        if let Ok(mut guard) = inner.try_borrow_mut() {
1669            let _: Option<WasmCachedEntry> = guard
1670                .cache
1671                .insert(request.resolved_cache_key().to_string(), cache_entry);
1672            match request.get_scope() {
1673                WasmDynamicScope::Partial { slot_id } => {
1674                    guard
1675                        .partial_stacks
1676                        .entry(slot_id.clone())
1677                        .or_default()
1678                        .push(snap);
1679                }
1680                WasmDynamicScope::Global => {
1681                    guard.global_stack.push(snap);
1682                    let _: bool = guard.global_version_signal.set_if_changed(ver);
1683                }
1684            }
1685            let _: bool = guard.last_logs.set(logs);
1686            let _: bool = guard
1687                .telemetry_signal
1688                .update(|t: &mut WasmDynamicTelemetry| {
1689                    t.downloads_succeeded = t.downloads_succeeded.saturating_add(1);
1690                });
1691        }
1692        let _: bool = state_sig.set(WasmLoadState::Mounted {
1693            version: ver,
1694            from_cache,
1695            fuel_used,
1696        });
1697        Ok(ver)
1698    }
1699
1700    /// Records telemetry counters and updates scope state (with automatic Global LKG rollback signaling).
1701    ///
1702    /// # Arguments
1703    ///
1704    /// - `&Self` - Manager reference.
1705    /// - `&WasmDynamicScope` - Failing scope.
1706    /// - `&WasmDynamicError` - Typed error.
1707    fn record_failure(&self, scope: &WasmDynamicScope, err: &WasmDynamicError) {
1708        let state_sig: Signal<WasmLoadState> = self.state_signal(scope);
1709        let mut active_global_lkg: u64 = 0;
1710        let Self { inner } = self;
1711        if let Ok(guard) = inner.try_borrow() {
1712            let _: bool = guard
1713                .telemetry_signal
1714                .update(|t: &mut WasmDynamicTelemetry| match err {
1715                    WasmDynamicError::OutOfFuel { .. } => {
1716                        t.fuel_exhaustions_caught = t.fuel_exhaustions_caught.saturating_add(1);
1717                    }
1718                    WasmDynamicError::ExecutionTrap(_)
1719                    | WasmDynamicError::MemoryOutOfBounds { .. }
1720                    | WasmDynamicError::MemoryLimitExceeded { .. } => {
1721                        t.sandbox_traps_caught = t.sandbox_traps_caught.saturating_add(1);
1722                    }
1723                    WasmDynamicError::ChecksumMismatch { .. }
1724                    | WasmDynamicError::SignatureInvalid { .. }
1725                    | WasmDynamicError::InvalidWasmBinary(_)
1726                    | WasmDynamicError::AbiMismatch { .. }
1727                    | WasmDynamicError::MissingExport(_)
1728                    | WasmDynamicError::BinaryTooLarge { .. }
1729                    | WasmDynamicError::VersionRegression { .. } => {
1730                        t.integrity_rejections = t.integrity_rejections.saturating_add(1);
1731                    }
1732                    _ => {}
1733                });
1734            if *scope == WasmDynamicScope::Global {
1735                active_global_lkg = guard
1736                    .global_stack
1737                    .last()
1738                    .map(WasmMountedSnapshot::get_version)
1739                    .unwrap_or(0);
1740            }
1741        }
1742        if *scope == WasmDynamicScope::Global && active_global_lkg > 0 {
1743            let Self { inner } = self;
1744            if let Ok(guard) = inner.try_borrow() {
1745                let _: bool = guard
1746                    .telemetry_signal
1747                    .update(|t: &mut WasmDynamicTelemetry| {
1748                        t.rollbacks_executed = t.rollbacks_executed.saturating_add(1);
1749                    });
1750            }
1751            let _: bool = state_sig.set(WasmLoadState::RolledBack {
1752                active_version: active_global_lkg,
1753                reason: format!("auto-kept LKG v{active_global_lkg} after error: {err}"),
1754            });
1755        } else {
1756            let _: bool = state_sig.set(WasmLoadState::Failed(err.clone()));
1757        }
1758    }
1759}