euv_core/dynamic/wasm/struct.rs
1use super::*;
2
3/// Sandbox safety, memory, fuel, timeout, retry, and caching configuration for dynamic WASM execution.
4#[derive(Clone, Copy, Data, Debug, Eq, Hash, PartialEq)]
5pub struct WasmSandboxConfig {
6 /// Maximum allowed `.wasm` payload size in bytes.
7 #[get(type(copy))]
8 pub(crate) max_binary_bytes: usize,
9 /// Maximum allowed linear memory allocation in bytes.
10 #[get(type(copy))]
11 pub(crate) max_memory_bytes: usize,
12 /// Maximum instructions executed per WASM call before terminating with `OutOfFuel`.
13 #[get(type(copy))]
14 pub(crate) max_fuel: u64,
15 /// Download timeout ceiling in milliseconds.
16 #[get(type(copy))]
17 pub(crate) timeout_ms: u64,
18 /// Automatic retry count for transient transport failures (`Timeout` / `HttpStatus >= 500`).
19 #[get(type(copy))]
20 pub(crate) max_retries: u32,
21 /// Whether verified cached `.wasm` entries may be served when the network is offline.
22 #[get(type(copy))]
23 pub(crate) allow_offline_cache: bool,
24 /// Whether non-empty `expected_signature` verification is mandatory.
25 #[get(type(copy))]
26 pub(crate) require_signature: bool,
27}
28
29/// Declarative request descriptor for downloading and executing a dynamic `.wasm` module.
30#[derive(Clone, Data, Debug, Eq, Hash, New, PartialEq)]
31pub struct WasmDownloadRequest {
32 /// Source URL (`https://`, `http://`, `euv-cdn://`, or `file://`).
33 pub(crate) url: String,
34 /// Execution scope (`Partial { slot_id }` or `Global`).
35 pub(crate) scope: WasmDynamicScope,
36 /// Monotonic release version (`>= 1`).
37 #[get(type(copy))]
38 pub(crate) version: u64,
39 /// Optional expected FNV-1a checksum (`0` disables checksum comparison).
40 #[new(skip)]
41 #[get(type(copy))]
42 pub(crate) expected_checksum: u64,
43 /// Optional expected signature tag (verified with `compute_wasm_signature`).
44 #[new(skip)]
45 pub(crate) expected_signature: String,
46 /// Whether this request may install a version `<=` the currently mounted version.
47 #[new(skip)]
48 #[get(type(copy))]
49 pub(crate) allow_downgrade: bool,
50 /// Optional cache key override (defaults to `url`).
51 #[new(skip)]
52 pub(crate) cache_key: String,
53}
54
55/// Raw downloaded `.wasm` payload returned by a `WasmFetcher` implementation.
56#[derive(Clone, Data, Debug, Eq, New, PartialEq)]
57pub struct WasmFetchedPayload {
58 /// Raw WebAssembly binary bytes.
59 pub(crate) bytes: Vec<u8>,
60 /// Optional ETag / content revision identifier.
61 #[new(skip)]
62 pub(crate) etag: String,
63 /// Whether this payload originated from cache.
64 #[new(skip)]
65 #[get(type(copy))]
66 pub(crate) from_cache: bool,
67}
68
69/// Parsed WebAssembly function signature `(param_count, result_count)`.
70#[derive(Clone, Copy, Data, Debug, Default, Eq, Hash, New, PartialEq)]
71pub struct WasmFuncSignature {
72 /// Number of `i32` parameters.
73 #[get(type(copy))]
74 pub(crate) param_count: usize,
75 /// Number of `i32` results (`0` or `1`).
76 #[get(type(copy))]
77 pub(crate) result_count: usize,
78}
79
80/// Parsed WebAssembly host import declaration.
81#[derive(Clone, Data, Debug, Eq, New, PartialEq)]
82pub struct WasmImportEntry {
83 /// Imported module namespace (e.g. `"env"`).
84 pub(crate) module: String,
85 /// Imported function name (e.g. `"euv_emit_ui"`).
86 pub(crate) name: String,
87 /// Type index inside the module's type table.
88 #[get(type(copy))]
89 pub(crate) type_index: u32,
90}
91
92/// Parsed WebAssembly global variable declaration (`i32`, mutable or immutable).
93#[derive(Clone, Copy, Data, Debug, Default, Eq, Hash, New, PartialEq)]
94pub struct WasmGlobalEntry {
95 /// WebAssembly value type byte (e.g. `0x7F` for `i32`).
96 #[get(type(copy))]
97 pub(crate) value_type: u8,
98 /// Whether this global allows `global.set` mutations (e.g. Rust `__stack_pointer`).
99 #[get(type(copy))]
100 pub(crate) mutable: bool,
101 /// Initial constant `i32` value decoded from the global's init expression.
102 #[get(type(copy))]
103 pub(crate) init_i32: i32,
104}
105
106/// Parsed WebAssembly active linear memory data segment.
107#[derive(Clone, Data, Debug, Eq, New, PartialEq)]
108pub struct WasmDataSegment {
109 /// Linear memory byte offset where `bytes` are initialized.
110 #[get(type(copy))]
111 pub(crate) offset: u32,
112 /// Raw data segment payload bytes.
113 pub(crate) bytes: Vec<u8>,
114}
115
116/// Parsed WebAssembly function body ready for sandbox interpretation.
117#[derive(Clone, Data, Debug, Eq, New, PartialEq)]
118pub struct WasmParsedFunction {
119 /// Type index inside the module's type table.
120 #[get(type(copy))]
121 pub(crate) type_index: u32,
122 /// Count of additional `i32` local variables declared in the body header.
123 #[get(type(copy))]
124 pub(crate) extra_locals: usize,
125 /// Raw WebAssembly bytecode instructions ending with `0x0B`.
126 pub(crate) body: Vec<u8>,
127 /// Precomputed flag set to `true` when `body` contains zero memory instructions and zero function calls.
128 #[new(skip)]
129 #[get(type(copy))]
130 pub(crate) pure_no_memory: bool,
131}
132
133/// Validated in-memory representation of a decoded `.wasm` binary module.
134#[derive(Clone, Data, Debug, Default, Eq, PartialEq)]
135pub struct WasmParsedModule {
136 /// Declared function signatures from the Type section.
137 pub(crate) types: Vec<WasmFuncSignature>,
138 /// Imported host functions from the Import section.
139 pub(crate) imports: Vec<WasmImportEntry>,
140 /// Defined function bodies paired with type indices.
141 pub(crate) functions: Vec<WasmParsedFunction>,
142 /// Exported function name -> absolute function index map.
143 pub(crate) exports: HashMap<String, u32>,
144 /// Minimum linear memory pages declared (`1 page = 64 KiB`).
145 #[get(type(copy))]
146 pub(crate) memory_min_pages: u32,
147 /// Declared global variables from the Global section (including Rust `__stack_pointer`).
148 pub(crate) globals: Vec<WasmGlobalEntry>,
149 /// Initialized linear memory data segments.
150 pub(crate) data_segments: Vec<WasmDataSegment>,
151 /// Custom sections keyed by section name.
152 pub(crate) custom_sections: HashMap<String, Vec<u8>>,
153}
154
155/// Output produced by executing an exported function inside the WASM sandbox.
156#[derive(Clone, Data, Debug, Default, PartialEq)]
157pub struct WasmExecutionOutput {
158 /// Optional `i32` return value from the invoked WASM function.
159 #[get(type(copy))]
160 pub(crate) return_value: i32,
161 /// Total instructions metered during execution.
162 #[get(type(copy))]
163 pub(crate) fuel_used: u64,
164 /// Native UI subtree emitted via `env::euv_emit_ui` (if any).
165 #[get(skip)]
166 pub(crate) emitted_spec: Option<DynamicNodeSpec>,
167 /// Native global app bundle emitted via `env::euv_emit_bundle` (if any).
168 #[get(skip)]
169 pub(crate) emitted_bundle: Option<DynamicUpdateBundle>,
170 /// Diagnostic messages emitted via `env::euv_log`.
171 pub(crate) logs: Vec<String>,
172}
173
174/// Verified `.wasm` binary and parsed module cached locally for instant reload, hot-swap, and offline fallback.
175#[derive(Clone, Data, Debug, Eq, New, PartialEq)]
176pub struct WasmCachedEntry {
177 /// Source URL.
178 pub(crate) url: String,
179 /// Verified release version.
180 #[get(type(copy))]
181 pub(crate) version: u64,
182 /// Verified FNV-1a checksum.
183 #[get(type(copy))]
184 pub(crate) checksum: u64,
185 /// Shared verified raw `.wasm` binary bytes avoiding per-lookup clones.
186 pub(crate) bytes: Rc<Vec<u8>>,
187 /// Shared validated parsed `.wasm` module skipping re-parsing on hot-swap and rollback.
188 pub(crate) parsed: Rc<WasmParsedModule>,
189 /// Server ETag / content identifier.
190 pub(crate) etag: String,
191}
192
193/// Verified mounted WASM revision snapshot stored on a partial slot or global rollback stack.
194#[derive(Clone, Data, Debug, PartialEq)]
195pub struct WasmMountedSnapshot {
196 /// Active release version.
197 #[get(type(copy))]
198 pub(crate) version: u64,
199 /// Source URL.
200 pub(crate) url: String,
201 /// Verified checksum.
202 #[get(type(copy))]
203 pub(crate) checksum: u64,
204 /// Shared parsed validated `.wasm` module kept ready for live `euv_on_event` callbacks.
205 pub(crate) module: Rc<WasmParsedModule>,
206 /// Current integer state value passed into `euv_render(state)` / updated by `euv_on_event`.
207 #[get(type(copy))]
208 pub(crate) state_value: i32,
209 /// Optional emitted partial spec snapshot.
210 #[get(skip)]
211 pub(crate) spec: Option<DynamicNodeSpec>,
212 /// Optional emitted global bundle snapshot.
213 #[get(skip)]
214 pub(crate) bundle: Option<DynamicUpdateBundle>,
215}
216
217/// Cumulative reactive telemetry counters for dynamic WASM loading, caching, sandboxing, and rollbacks.
218#[derive(Clone, Copy, Data, Debug, Default, Eq, Hash, PartialEq)]
219pub struct WasmDynamicTelemetry {
220 /// Total download attempts initiated.
221 #[get(type(copy))]
222 pub(crate) downloads_started: u64,
223 /// Total successful downloads + mounts.
224 #[get(type(copy))]
225 pub(crate) downloads_succeeded: u64,
226 /// Total verified offline/local cache hits.
227 #[get(type(copy))]
228 pub(crate) cache_hits: u64,
229 /// Total automatic transport retries executed.
230 #[get(type(copy))]
231 pub(crate) retries_performed: u64,
232 /// Total automatic or manual rollbacks executed.
233 #[get(type(copy))]
234 pub(crate) rollbacks_executed: u64,
235 /// Total WASM runtime traps isolated without harming host UI.
236 #[get(type(copy))]
237 pub(crate) sandbox_traps_caught: u64,
238 /// Total infinite-loop fuel exhaustions terminated cleanly.
239 #[get(type(copy))]
240 pub(crate) fuel_exhaustions_caught: u64,
241 /// Total checksum, signature, binary, or ABI rejections.
242 #[get(type(copy))]
243 pub(crate) integrity_rejections: u64,
244 /// Total interactive events dispatched into mounted WASM modules.
245 #[get(type(copy))]
246 pub(crate) events_handled: u64,
247}
248
249/// Registered entry inside `RegistryWasmFetcher` for deterministic cross-platform CDN and fault simulation.
250#[derive(Clone, Data, Debug, Eq, New, PartialEq)]
251pub struct RegistryWasmRecord {
252 /// Raw `.wasm` bytes served for this URL.
253 pub(crate) bytes: Vec<u8>,
254 /// ETag label returned with the payload.
255 pub(crate) etag: String,
256 /// Optional injected fault scenario.
257 #[get(type(copy))]
258 pub(crate) fault: WasmFaultKind,
259}
260
261/// Cross-platform in-memory WASM CDN registry and deterministic fault-injection fetcher.
262#[derive(Clone, Debug, Default)]
263pub struct RegistryWasmFetcher {
264 /// URL -> `.wasm` record registry.
265 pub(crate) records: Rc<RefCell<HashMap<String, RegistryWasmRecord>>>,
266 /// Global offline toggle simulating airplane mode across all URLs.
267 pub(crate) offline: Rc<RefCell<bool>>,
268}
269
270/// Native pure-std HTTP (`http://`) and local filesystem (`file://`) WASM fetcher with timeout and progress streaming.
271#[derive(Clone, Copy, Data, Debug, Default, Eq, Hash, PartialEq)]
272pub struct HttpWasmFetcher {
273 /// Socket connect/read timeout in milliseconds.
274 #[get(type(copy))]
275 pub(crate) timeout_ms: u64,
276}
277
278/// Internal interior-mutable state owned by `WasmDynamicManager`.
279#[derive(CustomDebug)]
280pub(crate) struct WasmDynamicManagerState {
281 /// Active `DynamicUpdateHub` receiving compiled native scene updates.
282 pub(crate) hub: DynamicUpdateHub,
283 /// Pluggable transport fetcher (`HttpWasmFetcher`, `RegistryWasmFetcher`, or custom CDN).
284 #[debug(skip)]
285 pub(crate) fetcher: Rc<dyn WasmFetcher>,
286 /// Sandbox fuel, memory, binary size, timeout, retry, and caching limits.
287 pub(crate) config: WasmSandboxConfig,
288 /// Monotonic request generation counter for cancellation and stale-response protection.
289 pub(crate) next_request_id: u64,
290 /// Active latest request generation per scope key.
291 pub(crate) active_request_ids: HashMap<String, u64>,
292 /// Verified `.wasm` binary cache keyed by cache key / URL.
293 pub(crate) cache: HashMap<String, WasmCachedEntry>,
294 /// Parsed validated module cache keyed by `(url, checksum)` so hot-swaps and rollbacks skip binary parsing.
295 pub(crate) parsed_cache: HashMap<(String, u64), Rc<WasmParsedModule>>,
296 /// Mounted revision stacks per partial slot ID.
297 pub(crate) partial_stacks: HashMap<String, Vec<WasmMountedSnapshot>>,
298 /// Mounted revision stack for global full-app WASM takeovers.
299 pub(crate) global_stack: Vec<WasmMountedSnapshot>,
300 /// Per-scope reactive `WasmLoadState` signals.
301 pub(crate) state_signals: HashMap<String, Signal<WasmLoadState>>,
302 /// Reactive global active version signal (`0` = built-in native shell).
303 pub(crate) global_version_signal: Signal<u64>,
304 /// Reactive telemetry snapshot signal.
305 pub(crate) telemetry_signal: Signal<WasmDynamicTelemetry>,
306 /// Last diagnostic log entries emitted by executed WASM modules.
307 pub(crate) last_logs: Signal<Vec<String>>,
308}
309
310/// Shared cross-platform manager orchestrating partial and global dynamic `.wasm` download, verification, execution, and native rendering.
311#[derive(Clone, CustomDebug)]
312pub struct WasmDynamicManager {
313 /// Interior-mutable manager state shared across slots, pages, and host shell.
314 pub(crate) inner: Rc<RefCell<WasmDynamicManagerState>>,
315}
316
317/// Spec-compliant `.wasm` binary encoder producing genuine executable WebAssembly modules for euv native rendering.
318#[derive(Clone, Data, Debug, Default)]
319pub struct WasmModuleBuilder {
320 /// ABI version returned by `euv_abi_version`.
321 #[get(type(copy))]
322 pub(crate) abi_version: u32,
323 /// Whether to export `euv_render`.
324 #[get(type(copy))]
325 pub(crate) export_render: bool,
326 /// Whether `euv_render` emits a global `DynamicUpdateBundle` instead of a partial `DynamicNodeSpec`.
327 #[get(type(copy))]
328 pub(crate) is_global_bundle: bool,
329 /// UTF-8 JSON UI payload placed in linear memory and emitted via host import.
330 pub(crate) ui_payload_json: String,
331 /// Optional second variant JSON payload emitted when interactive state is odd (`state & 1 != 0`).
332 pub(crate) alt_ui_payload_json: String,
333 /// Optional diagnostic log line emitted during `euv_render`.
334 pub(crate) log_message: String,
335 /// Optional fault behavior compiled directly into `euv_render` bytecode (`InfiniteLoopOutOfFuel` / `ExecutionTrap`).
336 #[get(type(copy))]
337 pub(crate) fault: WasmFaultKind,
338 /// Optional custom metadata section bytes.
339 pub(crate) custom_meta: Vec<u8>,
340}
341
342/// Mutable execution context threaded through sandboxed WASM interpreter invocations.
343pub(crate) struct WasmExecContext<'a> {
344 /// Active WASM linear memory buffer (supports `memory.grow` up to `memory_max_bytes`).
345 pub(crate) memory: &'a mut Vec<u8>,
346 /// Current logical byte length of active linear memory inside `memory`.
347 pub(crate) memory_len: usize,
348 /// Hard sandbox linear memory ceiling in bytes.
349 pub(crate) memory_max_bytes: usize,
350 /// Active mutable global variable values initialized from `WasmParsedModule::globals`.
351 pub(crate) globals: &'a mut [i32],
352 /// Accumulated host import outputs and logs.
353 pub(crate) out: &'a mut WasmExecutionOutput,
354 /// Running instruction fuel counter.
355 pub(crate) fuel_used: u64,
356 /// Hard instruction fuel limit.
357 pub(crate) max_fuel: u64,
358 /// Current recursion call depth.
359 pub(crate) depth: usize,
360 /// Exclusive high-water linear memory byte index written during execution for surgical re-zeroing.
361 pub(crate) dirty_end: usize,
362}
363
364/// Reusable thread-local linear memory backing store kept zeroed at rest between WASM invocations.
365#[derive(Debug, Default)]
366pub(crate) struct WasmMemoryPool {
367 /// Contiguous zeroed linear memory bytes reused across `execute_wasm_export` calls.
368 pub(crate) buffer: Vec<u8>,
369}
370
371/// Shared fetched or offline-cached `.wasm` payload bundle avoiding byte-vector copies.
372pub(crate) struct WasmFetchedShare {
373 /// Shared raw `.wasm` binary bytes.
374 pub(crate) bytes: Rc<Vec<u8>>,
375 /// Server ETag / content revision label.
376 pub(crate) etag: String,
377 /// Whether this payload originated from the verified offline cache.
378 pub(crate) from_cache: bool,
379}