1use super::*;
2
3impl fmt::Display for WasmDynamicError {
5 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
78impl Error for WasmDynamicError {}
80
81impl Default for WasmSandboxConfig {
83 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
101impl WasmDynamicScope {
103 #[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
121impl WasmDownloadRequest {
123 #[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 #[must_use]
150 pub fn global(url: String, version: u64) -> Self {
151 Self::new(url, WasmDynamicScope::Global, version)
152 }
153
154 #[must_use]
165 pub fn with_checksum(mut self, checksum: u64) -> Self {
166 self.set_expected_checksum(checksum);
167 self
168 }
169
170 #[must_use]
181 pub fn with_signature(mut self, signature: String) -> Self {
182 self.set_expected_signature(signature);
183 self
184 }
185
186 #[must_use]
197 pub fn with_allow_downgrade(mut self, allow: bool) -> Self {
198 self.set_allow_downgrade(allow);
199 self
200 }
201
202 #[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
221impl WasmExecutionOutput {
223 #[must_use]
233 pub fn emitted_spec(&self) -> Option<&DynamicNodeSpec> {
234 let Self { emitted_spec, .. } = self;
235 emitted_spec.as_ref()
236 }
237
238 #[must_use]
248 pub fn emitted_bundle(&self) -> Option<&DynamicUpdateBundle> {
249 let Self { emitted_bundle, .. } = self;
250 emitted_bundle.as_ref()
251 }
252}
253
254impl WasmMountedSnapshot {
256 #[must_use]
266 pub fn spec_ref(&self) -> Option<&DynamicNodeSpec> {
267 let Self { spec, .. } = self;
268 spec.as_ref()
269 }
270
271 #[must_use]
281 pub fn bundle_ref(&self) -> Option<&DynamicUpdateBundle> {
282 let Self { bundle, .. } = self;
283 bundle.as_ref()
284 }
285}
286
287impl WasmModuleBuilder {
289 #[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 #[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 #[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 #[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 #[must_use]
382 pub fn with_log(mut self, message: String) -> Self {
383 self.set_log_message(message);
384 self
385 }
386
387 #[must_use]
398 pub fn with_abi_version(mut self, abi: u32) -> Self {
399 self.set_abi_version(abi);
400 self
401 }
402
403 #[must_use]
413 pub fn without_render_export(mut self) -> Self {
414 self.set_export_render(false);
415 self
416 }
417
418 #[must_use]
429 pub fn with_fault(mut self, fault: WasmFaultKind) -> Self {
430 self.set_fault(fault);
431 self
432 }
433
434 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 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 #[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 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
646impl RegistryWasmFetcher {
648 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 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 #[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
697impl WasmFetcher for RegistryWasmFetcher {
699 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
767impl WasmFetcher for HttpWasmFetcher {
769 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
881impl WasmDynamicManager {
883 #[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 #[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 #[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 #[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 #[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 #[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 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 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 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 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 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 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 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 #[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 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 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 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}