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 active linear memory data segment.
93#[derive(Clone, Data, Debug, Eq, New, PartialEq)]
94pub struct WasmDataSegment {
95 /// Linear memory byte offset where `bytes` are initialized.
96 #[get(type(copy))]
97 pub(crate) offset: u32,
98 /// Raw data segment payload bytes.
99 pub(crate) bytes: Vec<u8>,
100}
101
102/// Parsed WebAssembly function body ready for sandbox interpretation.
103#[derive(Clone, Data, Debug, Eq, New, PartialEq)]
104pub struct WasmParsedFunction {
105 /// Type index inside the module's type table.
106 #[get(type(copy))]
107 pub(crate) type_index: u32,
108 /// Count of additional `i32` local variables declared in the body header.
109 #[get(type(copy))]
110 pub(crate) extra_locals: usize,
111 /// Raw WebAssembly bytecode instructions ending with `0x0B`.
112 pub(crate) body: Vec<u8>,
113 /// Precomputed flag set to `true` when `body` contains zero memory instructions and zero function calls.
114 #[new(skip)]
115 #[get(type(copy))]
116 pub(crate) pure_no_memory: bool,
117}
118
119/// Validated in-memory representation of a decoded `.wasm` binary module.
120#[derive(Clone, Data, Debug, Default, Eq, PartialEq)]
121pub struct WasmParsedModule {
122 /// Declared function signatures from the Type section.
123 pub(crate) types: Vec<WasmFuncSignature>,
124 /// Imported host functions from the Import section.
125 pub(crate) imports: Vec<WasmImportEntry>,
126 /// Defined function bodies paired with type indices.
127 pub(crate) functions: Vec<WasmParsedFunction>,
128 /// Exported function name -> absolute function index map.
129 pub(crate) exports: HashMap<String, u32>,
130 /// Minimum linear memory pages declared (`1 page = 64 KiB`).
131 #[get(type(copy))]
132 pub(crate) memory_min_pages: u32,
133 /// Initialized linear memory data segments.
134 pub(crate) data_segments: Vec<WasmDataSegment>,
135 /// Custom sections keyed by section name.
136 pub(crate) custom_sections: HashMap<String, Vec<u8>>,
137}
138
139/// Output produced by executing an exported function inside the WASM sandbox.
140#[derive(Clone, Data, Debug, Default, PartialEq)]
141pub struct WasmExecutionOutput {
142 /// Optional `i32` return value from the invoked WASM function.
143 #[get(type(copy))]
144 pub(crate) return_value: i32,
145 /// Total instructions metered during execution.
146 #[get(type(copy))]
147 pub(crate) fuel_used: u64,
148 /// Native UI subtree emitted via `env::euv_emit_ui` (if any).
149 #[get(skip)]
150 pub(crate) emitted_spec: Option<DynamicNodeSpec>,
151 /// Native global app bundle emitted via `env::euv_emit_bundle` (if any).
152 #[get(skip)]
153 pub(crate) emitted_bundle: Option<DynamicUpdateBundle>,
154 /// Diagnostic messages emitted via `env::euv_log`.
155 pub(crate) logs: Vec<String>,
156}
157
158/// Verified `.wasm` binary and parsed module cached locally for instant reload, hot-swap, and offline fallback.
159#[derive(Clone, Data, Debug, Eq, New, PartialEq)]
160pub struct WasmCachedEntry {
161 /// Source URL.
162 pub(crate) url: String,
163 /// Verified release version.
164 #[get(type(copy))]
165 pub(crate) version: u64,
166 /// Verified FNV-1a checksum.
167 #[get(type(copy))]
168 pub(crate) checksum: u64,
169 /// Shared verified raw `.wasm` binary bytes avoiding per-lookup clones.
170 pub(crate) bytes: Rc<Vec<u8>>,
171 /// Shared validated parsed `.wasm` module skipping re-parsing on hot-swap and rollback.
172 pub(crate) parsed: Rc<WasmParsedModule>,
173 /// Server ETag / content identifier.
174 pub(crate) etag: String,
175}
176
177/// Verified mounted WASM revision snapshot stored on a partial slot or global rollback stack.
178#[derive(Clone, Data, Debug, PartialEq)]
179pub struct WasmMountedSnapshot {
180 /// Active release version.
181 #[get(type(copy))]
182 pub(crate) version: u64,
183 /// Source URL.
184 pub(crate) url: String,
185 /// Verified checksum.
186 #[get(type(copy))]
187 pub(crate) checksum: u64,
188 /// Shared parsed validated `.wasm` module kept ready for live `euv_on_event` callbacks.
189 pub(crate) module: Rc<WasmParsedModule>,
190 /// Current integer state value passed into `euv_render(state)` / updated by `euv_on_event`.
191 #[get(type(copy))]
192 pub(crate) state_value: i32,
193 /// Optional emitted partial spec snapshot.
194 #[get(skip)]
195 pub(crate) spec: Option<DynamicNodeSpec>,
196 /// Optional emitted global bundle snapshot.
197 #[get(skip)]
198 pub(crate) bundle: Option<DynamicUpdateBundle>,
199}
200
201/// Cumulative reactive telemetry counters for dynamic WASM loading, caching, sandboxing, and rollbacks.
202#[derive(Clone, Copy, Data, Debug, Default, Eq, Hash, PartialEq)]
203pub struct WasmDynamicTelemetry {
204 /// Total download attempts initiated.
205 #[get(type(copy))]
206 pub(crate) downloads_started: u64,
207 /// Total successful downloads + mounts.
208 #[get(type(copy))]
209 pub(crate) downloads_succeeded: u64,
210 /// Total verified offline/local cache hits.
211 #[get(type(copy))]
212 pub(crate) cache_hits: u64,
213 /// Total automatic transport retries executed.
214 #[get(type(copy))]
215 pub(crate) retries_performed: u64,
216 /// Total automatic or manual rollbacks executed.
217 #[get(type(copy))]
218 pub(crate) rollbacks_executed: u64,
219 /// Total WASM runtime traps isolated without harming host UI.
220 #[get(type(copy))]
221 pub(crate) sandbox_traps_caught: u64,
222 /// Total infinite-loop fuel exhaustions terminated cleanly.
223 #[get(type(copy))]
224 pub(crate) fuel_exhaustions_caught: u64,
225 /// Total checksum, signature, binary, or ABI rejections.
226 #[get(type(copy))]
227 pub(crate) integrity_rejections: u64,
228 /// Total interactive events dispatched into mounted WASM modules.
229 #[get(type(copy))]
230 pub(crate) events_handled: u64,
231}
232
233/// Registered entry inside `RegistryWasmFetcher` for deterministic cross-platform CDN and fault simulation.
234#[derive(Clone, Data, Debug, Eq, New, PartialEq)]
235pub struct RegistryWasmRecord {
236 /// Raw `.wasm` bytes served for this URL.
237 pub(crate) bytes: Vec<u8>,
238 /// ETag label returned with the payload.
239 pub(crate) etag: String,
240 /// Optional injected fault scenario.
241 #[get(type(copy))]
242 pub(crate) fault: WasmFaultKind,
243}
244
245/// Cross-platform in-memory WASM CDN registry and deterministic fault-injection fetcher.
246#[derive(Clone, Debug, Default)]
247pub struct RegistryWasmFetcher {
248 /// URL -> `.wasm` record registry.
249 pub(crate) records: Rc<RefCell<HashMap<String, RegistryWasmRecord>>>,
250 /// Global offline toggle simulating airplane mode across all URLs.
251 pub(crate) offline: Rc<RefCell<bool>>,
252}
253
254/// Native pure-std HTTP (`http://`) and local filesystem (`file://`) WASM fetcher with timeout and progress streaming.
255#[derive(Clone, Copy, Data, Debug, Default, Eq, Hash, PartialEq)]
256pub struct HttpWasmFetcher {
257 /// Socket connect/read timeout in milliseconds.
258 #[get(type(copy))]
259 pub(crate) timeout_ms: u64,
260}
261
262/// Internal interior-mutable state owned by `WasmDynamicManager`.
263#[derive(CustomDebug)]
264pub(crate) struct WasmDynamicManagerState {
265 /// Active `DynamicUpdateHub` receiving compiled native scene updates.
266 pub(crate) hub: DynamicUpdateHub,
267 /// Pluggable transport fetcher (`HttpWasmFetcher`, `RegistryWasmFetcher`, or custom CDN).
268 #[debug(skip)]
269 pub(crate) fetcher: Rc<dyn WasmFetcher>,
270 /// Sandbox fuel, memory, binary size, timeout, retry, and caching limits.
271 pub(crate) config: WasmSandboxConfig,
272 /// Monotonic request generation counter for cancellation and stale-response protection.
273 pub(crate) next_request_id: u64,
274 /// Active latest request generation per scope key.
275 pub(crate) active_request_ids: HashMap<String, u64>,
276 /// Verified `.wasm` binary cache keyed by cache key / URL.
277 pub(crate) cache: HashMap<String, WasmCachedEntry>,
278 /// Parsed validated module cache keyed by `(url, checksum)` so hot-swaps and rollbacks skip binary parsing.
279 pub(crate) parsed_cache: HashMap<(String, u64), Rc<WasmParsedModule>>,
280 /// Mounted revision stacks per partial slot ID.
281 pub(crate) partial_stacks: HashMap<String, Vec<WasmMountedSnapshot>>,
282 /// Mounted revision stack for global full-app WASM takeovers.
283 pub(crate) global_stack: Vec<WasmMountedSnapshot>,
284 /// Per-scope reactive `WasmLoadState` signals.
285 pub(crate) state_signals: HashMap<String, Signal<WasmLoadState>>,
286 /// Reactive global active version signal (`0` = built-in native shell).
287 pub(crate) global_version_signal: Signal<u64>,
288 /// Reactive telemetry snapshot signal.
289 pub(crate) telemetry_signal: Signal<WasmDynamicTelemetry>,
290 /// Last diagnostic log entries emitted by executed WASM modules.
291 pub(crate) last_logs: Signal<Vec<String>>,
292}
293
294/// Shared cross-platform manager orchestrating partial and global dynamic `.wasm` download, verification, execution, and native rendering.
295#[derive(Clone, CustomDebug)]
296pub struct WasmDynamicManager {
297 /// Interior-mutable manager state shared across slots, pages, and host shell.
298 pub(crate) inner: Rc<RefCell<WasmDynamicManagerState>>,
299}
300
301/// Spec-compliant `.wasm` binary encoder producing genuine executable WebAssembly modules for euv native rendering.
302#[derive(Clone, Data, Debug, Default)]
303pub struct WasmModuleBuilder {
304 /// ABI version returned by `euv_abi_version`.
305 #[get(type(copy))]
306 pub(crate) abi_version: u32,
307 /// Whether to export `euv_render`.
308 #[get(type(copy))]
309 pub(crate) export_render: bool,
310 /// Whether `euv_render` emits a global `DynamicUpdateBundle` instead of a partial `DynamicNodeSpec`.
311 #[get(type(copy))]
312 pub(crate) is_global_bundle: bool,
313 /// UTF-8 JSON UI payload placed in linear memory and emitted via host import.
314 pub(crate) ui_payload_json: String,
315 /// Optional second variant JSON payload emitted when interactive state is odd (`state & 1 != 0`).
316 pub(crate) alt_ui_payload_json: String,
317 /// Optional diagnostic log line emitted during `euv_render`.
318 pub(crate) log_message: String,
319 /// Optional fault behavior compiled directly into `euv_render` bytecode (`InfiniteLoopOutOfFuel` / `ExecutionTrap`).
320 #[get(type(copy))]
321 pub(crate) fault: WasmFaultKind,
322 /// Optional custom metadata section bytes.
323 pub(crate) custom_meta: Vec<u8>,
324}
325
326/// Mutable execution context threaded through sandboxed WASM interpreter invocations.
327pub(crate) struct WasmExecContext<'a> {
328 /// Active WASM linear memory byte slice.
329 pub(crate) memory: &'a mut [u8],
330 /// Accumulated host import outputs and logs.
331 pub(crate) out: &'a mut WasmExecutionOutput,
332 /// Running instruction fuel counter.
333 pub(crate) fuel_used: u64,
334 /// Hard instruction fuel limit.
335 pub(crate) max_fuel: u64,
336 /// Current recursion call depth.
337 pub(crate) depth: usize,
338 /// Exclusive high-water linear memory byte index written during execution for surgical re-zeroing.
339 pub(crate) dirty_end: usize,
340}
341
342/// Reusable thread-local linear memory backing store kept zeroed at rest between WASM invocations.
343#[derive(Debug, Default)]
344pub(crate) struct WasmMemoryPool {
345 /// Contiguous zeroed linear memory bytes reused across `execute_wasm_export` calls.
346 pub(crate) buffer: Vec<u8>,
347}
348
349/// Shared fetched or offline-cached `.wasm` payload bundle avoiding byte-vector copies.
350pub(crate) struct WasmFetchedShare {
351 /// Shared raw `.wasm` binary bytes.
352 pub(crate) bytes: Rc<Vec<u8>>,
353 /// Server ETag / content revision label.
354 pub(crate) etag: String,
355 /// Whether this payload originated from the verified offline cache.
356 pub(crate) from_cache: bool,
357}