1use super::*;
2
3impl fmt::Display for WasmDynamicError {
5 fn fmt(&self, factor_val: &mut Formatter<'_>) -> fmt::Result {
16 match self {
17 Self::InvalidUrl(url) => write!(factor_val, "invalid wasm URL: {url}"),
18 Self::NetworkOffline(url) => write!(factor_val, "network offline while fetching {url}"),
19 Self::HttpStatus { status, url } => {
20 write!(factor_val, "HTTP {status} downloading {url}")
21 }
22 Self::Timeout { url, timeout_ms } => {
23 write!(
24 factor_val,
25 "download timed out after {timeout_ms}ms for {url}"
26 )
27 }
28 Self::Cancelled { request_id } => {
29 write!(factor_val, "wasm request #{request_id} was cancelled")
30 }
31 Self::StaleResponse {
32 request_id,
33 active_request_id,
34 } => write!(
35 factor_val,
36 "discarded stale wasm response #{request_id} (active #{active_request_id})"
37 ),
38 Self::BinaryTooLarge { actual, limit } => {
39 write!(
40 factor_val,
41 "wasm binary {actual} bytes exceeds limit {limit}"
42 )
43 }
44 Self::InvalidWasmBinary(msg) => write!(factor_val, "invalid wasm binary: {msg}"),
45 Self::ChecksumMismatch { expected, actual } => {
46 write!(
47 factor_val,
48 "wasm checksum mismatch: expected {expected:#018x}, got {actual:#018x}"
49 )
50 }
51 Self::SignatureInvalid { expected, actual } => {
52 write!(
53 factor_val,
54 "wasm signature invalid: expected {expected}, got {actual}"
55 )
56 }
57 Self::AbiMismatch { expected, actual } => {
58 write!(
59 factor_val,
60 "wasm ABI mismatch: host v{expected}, module v{actual}"
61 )
62 }
63 Self::MissingExport(name) => {
64 write!(factor_val, "wasm module missing required export `{name}`")
65 }
66 Self::VersionRegression { current, incoming } => {
67 write!(
68 factor_val,
69 "wasm version regression blocked: active v{current}, incoming v{incoming}"
70 )
71 }
72 Self::MemoryLimitExceeded { requested, limit } => {
73 write!(
74 factor_val,
75 "wasm memory {requested} bytes exceeds limit {limit}"
76 )
77 }
78 Self::MemoryOutOfBounds {
79 addr,
80 len,
81 memory_size,
82 } => write!(
83 factor_val,
84 "wasm memory out of bounds: [{addr}..+{len}] > {memory_size}"
85 ),
86 Self::OutOfFuel { limit } => {
87 write!(
88 factor_val,
89 "wasm execution exceeded fuel budget ({limit} ops)"
90 )
91 }
92 Self::ExecutionTrap(msg) => write!(factor_val, "wasm runtime trap: {msg}"),
93 Self::InvalidUiPayload(msg) => {
94 write!(factor_val, "invalid wasm native UI payload: {msg}")
95 }
96 Self::NoRollbackSnapshot => {
97 write!(factor_val, "no prior verified wasm snapshot to roll back")
98 }
99 }
100 }
101}
102
103impl Error for WasmDynamicError {}
105
106impl Default for WasmSandboxConfig {
108 fn default() -> Self {
114 Self {
115 max_binary_bytes: WASM_DEFAULT_MAX_BINARY_BYTES,
116 max_memory_bytes: WASM_DEFAULT_MAX_MEMORY_BYTES,
117 max_fuel: WASM_DEFAULT_MAX_FUEL,
118 timeout_ms: WASM_DEFAULT_TIMEOUT_MS,
119 max_retries: WASM_DEFAULT_MAX_RETRIES,
120 allow_offline_cache: true,
121 require_signature: false,
122 }
123 }
124}
125
126impl WasmDynamicScope {
128 #[must_use]
138 pub fn key(&self) -> String {
139 match self {
140 Self::Partial { slot_id } => format!("partial:{slot_id}"),
141 Self::Global => "global".to_string(),
142 }
143 }
144}
145
146impl WasmDownloadRequest {
148 #[must_use]
160 pub fn partial(url: String, slot_id: String, version: u64) -> Self {
161 Self::new(url, WasmDynamicScope::Partial { slot_id }, version)
162 }
163
164 #[must_use]
175 pub fn global(url: String, version: u64) -> Self {
176 Self::new(url, WasmDynamicScope::Global, version)
177 }
178
179 #[must_use]
190 pub fn with_checksum(mut self, checksum: u64) -> Self {
191 self.set_expected_checksum(checksum);
192 self
193 }
194
195 #[must_use]
206 pub fn with_signature(mut self, signature: String) -> Self {
207 self.set_expected_signature(signature);
208 self
209 }
210
211 #[must_use]
222 pub fn with_allow_downgrade(mut self, allow: bool) -> Self {
223 self.set_allow_downgrade(allow);
224 self
225 }
226
227 #[must_use]
237 pub fn resolved_cache_key(&self) -> &str {
238 if self.get_cache_key().is_empty() {
239 self.get_url().as_str()
240 } else {
241 self.get_cache_key().as_str()
242 }
243 }
244}
245
246impl WasmExecutionOutput {
248 #[must_use]
258 pub fn emitted_spec(&self) -> Option<&DynamicNodeSpec> {
259 let Self { emitted_spec, .. } = self;
260 emitted_spec.as_ref()
261 }
262
263 #[must_use]
273 pub fn emitted_bundle(&self) -> Option<&DynamicUpdateBundle> {
274 let Self { emitted_bundle, .. } = self;
275 emitted_bundle.as_ref()
276 }
277}
278
279impl WasmMountedSnapshot {
281 #[must_use]
291 pub fn spec_ref(&self) -> Option<&DynamicNodeSpec> {
292 let Self { spec, .. } = self;
293 spec.as_ref()
294 }
295
296 #[must_use]
306 pub fn bundle_ref(&self) -> Option<&DynamicUpdateBundle> {
307 let Self { bundle, .. } = self;
308 bundle.as_ref()
309 }
310}
311
312impl WasmModuleBuilder {
314 #[must_use]
324 pub fn partial_spec(spec: &DynamicNodeSpec) -> Self {
325 let json: String = to_string(spec).unwrap_or_else(|_| "{}".to_string());
326 Self {
327 abi_version: WASM_ABI_VERSION,
328 export_render: true,
329 is_global_bundle: false,
330 ui_payload_json: json,
331 alt_ui_payload_json: String::new(),
332 log_message: String::new(),
333 fault: WasmFaultKind::None,
334 custom_meta: Vec::new(),
335 }
336 }
337
338 #[must_use]
348 pub fn global_bundle(bundle: &DynamicUpdateBundle) -> Self {
349 let json: String = to_string(bundle).unwrap_or_else(|_| "{}".to_string());
350 Self {
351 abi_version: WASM_ABI_VERSION,
352 export_render: true,
353 is_global_bundle: true,
354 ui_payload_json: json,
355 alt_ui_payload_json: String::new(),
356 log_message: String::new(),
357 fault: WasmFaultKind::None,
358 custom_meta: Vec::new(),
359 }
360 }
361
362 #[must_use]
373 pub fn with_alt_spec(mut self, alt: &DynamicNodeSpec) -> Self {
374 let json: String = to_string(alt).unwrap_or_else(|_| "{}".to_string());
375 self.set_alt_ui_payload_json(json);
376 self
377 }
378
379 #[must_use]
390 pub fn with_alt_bundle(mut self, bundle: &DynamicUpdateBundle) -> Self {
391 let json: String = bundle.to_json().unwrap_or_default();
392 self.set_alt_ui_payload_json(json);
393 self
394 }
395
396 #[must_use]
407 pub fn with_log(mut self, message: String) -> Self {
408 self.set_log_message(message);
409 self
410 }
411
412 #[must_use]
423 pub fn with_abi_version(mut self, abi: u32) -> Self {
424 self.set_abi_version(abi);
425 self
426 }
427
428 #[must_use]
438 pub fn without_render_export(mut self) -> Self {
439 self.set_export_render(false);
440 self
441 }
442
443 #[must_use]
454 pub fn with_fault(mut self, fault: WasmFaultKind) -> Self {
455 self.set_fault(fault);
456 self
457 }
458
459 fn push_section(out: &mut Vec<u8>, sec_id: u8, payload: &[u8]) {
467 out.push(sec_id);
468 write_uleb128(out, payload.len() as u32);
469 out.extend_from_slice(payload);
470 }
471
472 fn push_name(out: &mut Vec<u8>, name: &str) {
479 write_uleb128(out, name.len() as u32);
480 out.extend_from_slice(name.as_bytes());
481 }
482
483 #[must_use]
493 pub fn build(&self) -> Vec<u8> {
494 let mut out: Vec<u8> = Vec::with_capacity(512);
495 out.extend_from_slice(WASM_BINARY_MAGIC);
496 out.extend_from_slice(WASM_BINARY_VERSION);
497 let mut type_sec: Vec<u8> = Vec::new();
498 write_uleb128(&mut type_sec, 3);
499 type_sec.extend_from_slice(&[WASM_FUNCTYPE_TAG, 2, WASM_VALTYPE_I32, WASM_VALTYPE_I32, 0]);
500 type_sec.extend_from_slice(&[WASM_FUNCTYPE_TAG, 1, WASM_VALTYPE_I32, 1, WASM_VALTYPE_I32]);
501 type_sec.extend_from_slice(&[WASM_FUNCTYPE_TAG, 0, 1, WASM_VALTYPE_I32]);
502 Self::push_section(&mut out, WASM_SEC_TYPE, &type_sec);
503 let mut imp_sec: Vec<u8> = Vec::new();
504 write_uleb128(&mut imp_sec, 2);
505 let emit_name: &str = if self.get_is_global_bundle() {
506 WASM_IMPORT_EMIT_BUNDLE
507 } else {
508 WASM_IMPORT_EMIT_UI
509 };
510 Self::push_name(&mut imp_sec, WASM_IMPORT_MODULE_ENV);
511 Self::push_name(&mut imp_sec, emit_name);
512 imp_sec.push(0x00);
513 write_uleb128(&mut imp_sec, 0);
514 Self::push_name(&mut imp_sec, WASM_IMPORT_MODULE_ENV);
515 Self::push_name(&mut imp_sec, WASM_IMPORT_LOG);
516 imp_sec.push(0x00);
517 write_uleb128(&mut imp_sec, 0);
518 Self::push_section(&mut out, WASM_SEC_IMPORT, &imp_sec);
519 let mut func_sec: Vec<u8> = Vec::new();
520 write_uleb128(&mut func_sec, 3);
521 write_uleb128(&mut func_sec, 1);
522 write_uleb128(&mut func_sec, 1);
523 write_uleb128(&mut func_sec, 2);
524 Self::push_section(&mut out, WASM_SEC_FUNCTION, &func_sec);
525 let payload1: &[u8] = self.get_ui_payload_json().as_bytes();
526 let payload2: &[u8] = self.get_alt_ui_payload_json().as_bytes();
527 let log_bytes: &[u8] = self.get_log_message().as_bytes();
528 let ptr1: i32 = 256;
529 let ptr2: i32 = ptr1 + (payload1.len() as i32) + 16;
530 let ptr_log: i32 = ptr2 + (payload2.len() as i32) + 16;
531 let total_mem_needed: usize = (ptr_log as usize) + log_bytes.len() + 256;
532 let min_pages: u32 = ((total_mem_needed / WASM_PAGE_BYTES) as u32) + 1;
533 let mut mem_sec: Vec<u8> = Vec::new();
534 write_uleb128(&mut mem_sec, 1);
535 mem_sec.push(0x00);
536 write_uleb128(&mut mem_sec, min_pages);
537 Self::push_section(&mut out, WASM_SEC_MEMORY, &mem_sec);
538 let mut exp_sec: Vec<u8> = Vec::new();
539 let exp_count: u32 = if self.get_export_render() { 3 } else { 2 };
540 write_uleb128(&mut exp_sec, exp_count);
541 if self.get_export_render() {
542 Self::push_name(&mut exp_sec, WASM_EXPORT_RENDER);
543 exp_sec.push(0x00);
544 write_uleb128(&mut exp_sec, 2);
545 }
546 Self::push_name(&mut exp_sec, WASM_EXPORT_ON_EVENT);
547 exp_sec.push(0x00);
548 write_uleb128(&mut exp_sec, 3);
549 Self::push_name(&mut exp_sec, WASM_EXPORT_ABI);
550 exp_sec.push(0x00);
551 write_uleb128(&mut exp_sec, 4);
552 Self::push_section(&mut out, WASM_SEC_EXPORT, &exp_sec);
553 let mut render_body: Vec<u8> = vec![0x00];
554 match self.get_fault() {
555 WasmFaultKind::InfiniteLoopOutOfFuel => {
556 render_body.push(OP_LOOP);
557 render_body.push(0x40);
558 render_body.push(OP_BR);
559 write_uleb128(&mut render_body, 0);
560 render_body.push(OP_END);
561 render_body.push(OP_I32_CONST);
562 write_sleb128(&mut render_body, 0);
563 render_body.push(OP_END);
564 }
565 WasmFaultKind::ExecutionTrap => {
566 render_body.push(OP_UNREACHABLE);
567 render_body.push(OP_END);
568 }
569 _ => {
570 if !payload2.is_empty() {
571 render_body.push(OP_LOCAL_GET);
572 write_uleb128(&mut render_body, 0);
573 render_body.push(OP_IF);
574 render_body.push(0x40);
575 render_body.push(OP_I32_CONST);
576 write_sleb128(&mut render_body, ptr2);
577 render_body.push(OP_I32_CONST);
578 write_sleb128(&mut render_body, payload2.len() as i32);
579 render_body.push(OP_CALL);
580 write_uleb128(&mut render_body, 0);
581 render_body.push(OP_ELSE);
582 render_body.push(OP_I32_CONST);
583 write_sleb128(&mut render_body, ptr1);
584 render_body.push(OP_I32_CONST);
585 write_sleb128(&mut render_body, payload1.len() as i32);
586 render_body.push(OP_CALL);
587 write_uleb128(&mut render_body, 0);
588 render_body.push(OP_END);
589 } else {
590 render_body.push(OP_I32_CONST);
591 write_sleb128(&mut render_body, ptr1);
592 render_body.push(OP_I32_CONST);
593 write_sleb128(&mut render_body, payload1.len() as i32);
594 render_body.push(OP_CALL);
595 write_uleb128(&mut render_body, 0);
596 }
597 if !log_bytes.is_empty() {
598 render_body.push(OP_I32_CONST);
599 write_sleb128(&mut render_body, ptr_log);
600 render_body.push(OP_I32_CONST);
601 write_sleb128(&mut render_body, log_bytes.len() as i32);
602 render_body.push(OP_CALL);
603 write_uleb128(&mut render_body, 1);
604 }
605 render_body.push(OP_I32_CONST);
606 write_sleb128(&mut render_body, 1);
607 render_body.push(OP_END);
608 }
609 }
610 let mut event_body: Vec<u8> = vec![0x00];
611 event_body.push(OP_LOCAL_GET);
612 write_uleb128(&mut event_body, 0);
613 event_body.push(OP_I32_CONST);
614 write_sleb128(&mut event_body, 1);
615 event_body.push(OP_I32_ADD);
616 event_body.push(OP_END);
617 let mut abi_body: Vec<u8> = vec![0x00];
618 abi_body.push(OP_I32_CONST);
619 write_sleb128(&mut abi_body, self.get_abi_version() as i32);
620 abi_body.push(OP_END);
621 let mut code_sec: Vec<u8> = Vec::new();
622 write_uleb128(&mut code_sec, 3);
623 for body in [&render_body, &event_body, &abi_body] {
624 write_uleb128(&mut code_sec, body.len() as u32);
625 code_sec.extend_from_slice(body);
626 }
627 Self::push_section(&mut out, WASM_SEC_CODE, &code_sec);
628 let mut data_sec: Vec<u8> = Vec::new();
629 let mut seg_count: u32 = 1;
630 if !payload2.is_empty() {
631 seg_count += 1;
632 }
633 if !log_bytes.is_empty() {
634 seg_count += 1;
635 }
636 write_uleb128(&mut data_sec, seg_count);
637 Self::push_data_segment(&mut data_sec, ptr1, payload1);
638 if !payload2.is_empty() {
639 Self::push_data_segment(&mut data_sec, ptr2, payload2);
640 }
641 if !log_bytes.is_empty() {
642 Self::push_data_segment(&mut data_sec, ptr_log, log_bytes);
643 }
644 Self::push_section(&mut out, WASM_SEC_DATA, &data_sec);
645 if !self.get_custom_meta().is_empty() {
646 let mut custom_sec: Vec<u8> = Vec::new();
647 Self::push_name(&mut custom_sec, WASM_CUSTOM_META_SECTION);
648 custom_sec.extend_from_slice(self.get_custom_meta().as_slice());
649 Self::push_section(&mut out, WASM_SEC_CUSTOM, &custom_sec);
650 }
651 out
652 }
653
654 fn push_data_segment(out: &mut Vec<u8>, offset: i32, data: &[u8]) {
662 write_uleb128(out, 0);
663 out.push(OP_I32_CONST);
664 write_sleb128(out, offset);
665 out.push(OP_END);
666 write_uleb128(out, data.len() as u32);
667 out.extend_from_slice(data);
668 }
669}
670
671impl RegistryWasmFetcher {
673 pub fn register(&self, url: String, bytes: Vec<u8>, etag: String, fault: WasmFaultKind) {
683 let Self { records, .. } = self;
684 if let Ok(mut guard) = records.try_borrow_mut() {
685 let _: Option<RegistryWasmRecord> =
686 guard.insert(url, RegistryWasmRecord::new(bytes, etag, fault));
687 }
688 }
689
690 pub fn set_offline(&self, is_offline: bool) {
697 let Self { offline, .. } = self;
698 if let Ok(mut guard) = offline.try_borrow_mut() {
699 *guard = is_offline;
700 }
701 }
702
703 #[must_use]
713 pub fn is_offline(&self) -> bool {
714 let Self { offline, .. } = self;
715 offline
716 .try_borrow()
717 .map(|green_val: Ref<'_, bool>| *green_val)
718 .unwrap_or(false)
719 }
720}
721
722impl WasmFetcher for RegistryWasmFetcher {
724 fn fetch(
737 &self,
738 request: &WasmDownloadRequest,
739 attempt: u32,
740 on_progress: &mut dyn FnMut(u64, u64),
741 ) -> Result<WasmFetchedPayload, WasmDynamicError> {
742 if self.is_offline() {
743 return Err(WasmDynamicError::NetworkOffline(request.get_url().clone()));
744 }
745 let url_str: &str = request.get_url().as_str();
746 if url_str.starts_with(WASM_SCHEME_HTTP) || url_str.starts_with(WASM_SCHEME_FILE) {
747 return HttpWasmFetcher::default().fetch(request, attempt, on_progress);
748 }
749 let Self { records, .. } = self;
750 let rec_opt: Result<(Vec<u8>, String, WasmFaultKind), WasmDynamicError> = {
751 let guard: Ref<'_, HashMap<String, RegistryWasmRecord>> = records
752 .try_borrow()
753 .map_err(|_| WasmDynamicError::HttpStatus {
754 status: 404,
755 url: request.get_url().clone(),
756 })?;
757 let rec: &RegistryWasmRecord =
758 guard
759 .get(request.get_url())
760 .ok_or_else(|| WasmDynamicError::HttpStatus {
761 status: 404,
762 url: request.get_url().clone(),
763 })?;
764 match rec.get_fault() {
765 WasmFaultKind::NetworkOffline => {
766 return Err(WasmDynamicError::NetworkOffline(request.get_url().clone()));
767 }
768 WasmFaultKind::TimeoutOnceThenSucceed if attempt == 0 => {
769 return Err(WasmDynamicError::Timeout {
770 url: request.get_url().clone(),
771 timeout_ms: WASM_DEFAULT_TIMEOUT_MS,
772 });
773 }
774 WasmFaultKind::Http500 => {
775 return Err(WasmDynamicError::HttpStatus {
776 status: 500,
777 url: request.get_url().clone(),
778 });
779 }
780 fault => Ok((rec.get_bytes().clone(), rec.get_etag().clone(), fault)),
781 }
782 };
783 let (mut bytes, etag, fault): (Vec<u8>, String, WasmFaultKind) = rec_opt?;
784 if fault == WasmFaultKind::TamperedChecksum && !bytes.is_empty() {
785 let last_idx: usize = bytes.len() - 1;
786 bytes[last_idx] ^= 0xFF;
787 }
788 let total: u64 = bytes.len() as u64;
789 on_progress(total / 2, total);
790 on_progress(total, total);
791 let mut payload: WasmFetchedPayload = WasmFetchedPayload::new(bytes);
792 payload.set_etag(etag);
793 Ok(payload)
794 }
795}
796
797impl WasmFetcher for HttpWasmFetcher {
799 fn fetch(
812 &self,
813 request: &WasmDownloadRequest,
814 _attempt: u32,
815 on_progress: &mut dyn FnMut(u64, u64),
816 ) -> Result<WasmFetchedPayload, WasmDynamicError> {
817 let url: &str = request.get_url().as_str();
818 #[cfg(not(target_arch = "wasm32"))]
819 {
820 if let Some(path) = url.strip_prefix(WASM_SCHEME_FILE) {
821 let bytes: Vec<u8> = fs::read(path).map_err(|_| WasmDynamicError::HttpStatus {
822 status: 404,
823 url: url.to_string(),
824 })?;
825 let total: u64 = bytes.len() as u64;
826 on_progress(total, total);
827 return Ok(WasmFetchedPayload::new(bytes));
828 }
829 if let Some(rest) = url.strip_prefix(WASM_SCHEME_HTTP) {
830 let (host_port, req_path): (&str, String) = match rest.find('/') {
831 Some(idx) => (&rest[..idx], rest[idx..].to_string()),
832 None => (rest, "/".to_string()),
833 };
834 let connect_target: String = if host_port.contains(':') {
835 host_port.to_string()
836 } else {
837 format!("{host_port}:80")
838 };
839 let timeout_ms: u64 = self.get_timeout_ms().max(1_000);
840 let dur: Duration = Duration::from_millis(timeout_ms);
841 let addr: SocketAddr = match connect_target.to_socket_addrs() {
842 Ok(mut it) => it.next(),
843 Err(_) => None,
844 }
845 .ok_or_else(|| WasmDynamicError::NetworkOffline(url.to_string()))?;
846 let mut stream: TcpStream =
847 TcpStream::connect_timeout(&addr, dur).map_err(|_| {
848 WasmDynamicError::Timeout {
849 url: url.to_string(),
850 timeout_ms,
851 }
852 })?;
853 let _: Result<(), io::Error> = stream.set_read_timeout(Some(dur));
854 let _: Result<(), io::Error> = stream.set_write_timeout(Some(dur));
855 let req_str: String = format!(
856 "GET {req_path} HTTP/1.1\r\nHost: {host_port}\r\nConnection: close\r\nAccept: application/wasm\r\n\r\n"
857 );
858 stream
859 .write_all(req_str.as_bytes())
860 .map_err(|_| WasmDynamicError::NetworkOffline(url.to_string()))?;
861 let mut raw: Vec<u8> = Vec::new();
862 let mut chunk: [u8; 4096] = [0; 4096];
863 loop {
864 match stream.read(&mut chunk) {
865 Ok(0) => break,
866 Ok(item_count) => {
867 raw.extend_from_slice(&chunk[..item_count]);
868 on_progress(raw.len() as u64, 0);
869 }
870 Err(_) => {
871 return Err(WasmDynamicError::Timeout {
872 url: url.to_string(),
873 timeout_ms,
874 });
875 }
876 }
877 }
878 let sep_pos: usize = raw
879 .windows(4)
880 .position(|width_val: &[u8]| width_val == b"\r\n\r\n")
881 .ok_or_else(|| {
882 WasmDynamicError::InvalidWasmBinary("malformed HTTP response".to_string())
883 })?;
884 let header_str: &str = from_utf8(&raw[..sep_pos]).unwrap_or("");
885 let status_code: u16 = header_str
886 .lines()
887 .next()
888 .and_then(|line: &str| line.split_whitespace().nth(1))
889 .and_then(|code: &str| code.parse::<u16>().ok())
890 .unwrap_or(500);
891 if !(200..300).contains(&status_code) {
892 return Err(WasmDynamicError::HttpStatus {
893 status: status_code,
894 url: url.to_string(),
895 });
896 }
897 let body: Vec<u8> = raw[sep_pos + 4..].to_vec();
898 on_progress(body.len() as u64, body.len() as u64);
899 return Ok(WasmFetchedPayload::new(body));
900 }
901 Err(WasmDynamicError::InvalidUrl(url.to_string()))
902 }
903 #[cfg(target_arch = "wasm32")]
904 {
905 let _: &mut dyn FnMut(u64, u64) = on_progress;
906 Err(WasmDynamicError::NetworkOffline(url.to_string()))
907 }
908 }
909}
910
911impl WasmDynamicManager {
913 #[must_use]
925 pub fn new(
926 hub: DynamicUpdateHub,
927 fetcher: Rc<dyn WasmFetcher>,
928 config: WasmSandboxConfig,
929 ) -> Self {
930 Self {
931 inner: Rc::new(RefCell::new(WasmDynamicManagerState {
932 hub,
933 fetcher,
934 config,
935 next_request_id: 0,
936 active_request_ids: HashMap::new(),
937 cache: HashMap::new(),
938 parsed_cache: HashMap::new(),
939 partial_stacks: HashMap::new(),
940 global_stack: Vec::new(),
941 state_signals: HashMap::new(),
942 global_version_signal: Signal::new_detached(0),
943 telemetry_signal: Signal::new_detached(WasmDynamicTelemetry::default()),
944 last_logs: Signal::new_detached(Vec::new()),
945 })),
946 }
947 }
948
949 #[must_use]
960 pub fn state_signal(&self, scope: &WasmDynamicScope) -> Signal<WasmLoadState> {
961 let key: String = scope.key();
962 let Self { inner } = self;
963 if let Ok(mut guard) = inner.try_borrow_mut() {
964 return *guard
965 .state_signals
966 .entry(key)
967 .or_insert_with(|| Signal::new_detached(WasmLoadState::Idle));
968 }
969 Signal::new_detached(WasmLoadState::Idle)
970 }
971
972 #[must_use]
982 pub fn global_version_signal(&self) -> Signal<u64> {
983 let Self { inner } = self;
984 inner
985 .try_borrow()
986 .map(|green_val: Ref<'_, WasmDynamicManagerState>| green_val.global_version_signal)
987 .unwrap_or_else(|_| Signal::new_detached(0))
988 }
989
990 #[must_use]
1000 pub fn telemetry(&self) -> Signal<WasmDynamicTelemetry> {
1001 let Self { inner } = self;
1002 inner
1003 .try_borrow()
1004 .map(|green_val: Ref<'_, WasmDynamicManagerState>| green_val.telemetry_signal)
1005 .unwrap_or_else(|_| Signal::new_detached(WasmDynamicTelemetry::default()))
1006 }
1007
1008 #[must_use]
1018 pub fn last_logs(&self) -> Signal<Vec<String>> {
1019 let Self { inner } = self;
1020 inner
1021 .try_borrow()
1022 .map(|green_val: Ref<'_, WasmDynamicManagerState>| green_val.last_logs)
1023 .unwrap_or_else(|_| Signal::new_detached(Vec::new()))
1024 }
1025
1026 #[must_use]
1036 pub fn cache_len(&self) -> usize {
1037 let Self { inner } = self;
1038 inner
1039 .try_borrow()
1040 .map(|green_val: Ref<'_, WasmDynamicManagerState>| green_val.cache.len())
1041 .unwrap_or(0)
1042 }
1043
1044 pub fn cancel_scope(&self, scope: &WasmDynamicScope) -> u64 {
1055 let state_sig: Signal<WasmLoadState> = self.state_signal(scope);
1056 let key: String = scope.key();
1057 let Self { inner } = self;
1058 let next_id: u64 = if let Ok(mut guard) = inner.try_borrow_mut() {
1059 guard.next_request_id = guard.next_request_id.saturating_add(1);
1060 let id: u64 = guard.next_request_id;
1061 let _: Option<u64> = guard.active_request_ids.insert(key, id);
1062 id
1063 } else {
1064 0
1065 };
1066 let _: bool = state_sig.set(WasmLoadState::Failed(WasmDynamicError::Cancelled {
1067 request_id: next_id,
1068 }));
1069 next_id
1070 }
1071
1072 pub fn load_and_mount(
1084 &self,
1085 request: WasmDownloadRequest,
1086 signing_key: &str,
1087 ) -> Result<u64, WasmDynamicError> {
1088 let url_str: &str = request.get_url().trim();
1089 let valid_scheme: bool = url_str.starts_with("https://")
1090 || url_str.starts_with(WASM_SCHEME_HTTP)
1091 || url_str.starts_with("euv-cdn://")
1092 || url_str.starts_with(WASM_SCHEME_FILE);
1093 if url_str.is_empty() || !valid_scheme {
1094 let err: WasmDynamicError = WasmDynamicError::InvalidUrl(request.get_url().clone());
1095 self.record_failure(request.get_scope(), &err);
1096 return Err(err);
1097 }
1098 let scope: WasmDynamicScope = request.get_scope().clone();
1099 let scope_key: String = scope.key();
1100 let (req_id, config, fetcher, active_ver, state_sig): (
1101 u64,
1102 WasmSandboxConfig,
1103 Rc<dyn WasmFetcher>,
1104 u64,
1105 Signal<WasmLoadState>,
1106 ) = {
1107 let Self { inner } = self;
1108 let mut guard: RefMut<'_, WasmDynamicManagerState> = inner
1109 .try_borrow_mut()
1110 .map_err(|_| WasmDynamicError::ExecutionTrap("manager re-entrancy".to_string()))?;
1111 let sig: Signal<WasmLoadState> = *guard
1112 .state_signals
1113 .entry(scope_key.clone())
1114 .or_insert_with(|| Signal::new_detached(WasmLoadState::Idle));
1115 guard.next_request_id = guard.next_request_id.saturating_add(1);
1116 let id: u64 = guard.next_request_id;
1117 let _: Option<u64> = guard.active_request_ids.insert(scope_key.clone(), id);
1118 let cur_v: u64 = match &scope {
1119 WasmDynamicScope::Partial { slot_id } => guard
1120 .partial_stacks
1121 .get(slot_id)
1122 .and_then(|source_val: &Vec<WasmMountedSnapshot>| source_val.last())
1123 .map(WasmMountedSnapshot::get_version)
1124 .unwrap_or(0),
1125 WasmDynamicScope::Global => guard
1126 .global_stack
1127 .last()
1128 .map(WasmMountedSnapshot::get_version)
1129 .unwrap_or(0),
1130 };
1131 let _: bool = {
1132 if let Some(mut updated_value) = (guard.telemetry_signal).try_get_untracked() {
1133 {
1134 let blend_factor: &mut WasmDynamicTelemetry = &mut updated_value;
1135 blend_factor.downloads_started =
1136 blend_factor.downloads_started.saturating_add(1);
1137 }
1138 (guard.telemetry_signal).set(updated_value)
1139 } else {
1140 false
1141 }
1142 };
1143 (id, guard.config, guard.fetcher.clone(), cur_v, sig)
1144 };
1145 if !request.get_allow_downgrade() && active_ver > 0 && request.get_version() <= active_ver {
1146 let err: WasmDynamicError = WasmDynamicError::VersionRegression {
1147 current: active_ver,
1148 incoming: request.get_version(),
1149 };
1150 self.record_failure(&scope, &err);
1151 return Err(err);
1152 }
1153 if state_sig.has_subscribers() {
1154 let _: bool = state_sig.set(WasmLoadState::Downloading {
1155 received_bytes: 0,
1156 total_bytes: 0,
1157 });
1158 }
1159 let (fetched, cached_parsed_opt): (WasmFetchedShare, Option<Rc<WasmParsedModule>>) =
1160 match self.fetch_with_retry(&request, config, &fetcher, state_sig) {
1161 Ok(res) => res,
1162 Err(err) => {
1163 self.record_failure(&scope, &err);
1164 return Err(err);
1165 }
1166 };
1167 let current_active_id: u64 = self.active_request_id(&scope_key);
1168 if current_active_id != req_id {
1169 let err: WasmDynamicError = WasmDynamicError::StaleResponse {
1170 request_id: req_id,
1171 active_request_id: current_active_id,
1172 };
1173 return Err(err);
1174 }
1175 if state_sig.has_subscribers() {
1176 let _: bool = state_sig.set(WasmLoadState::Verifying);
1177 }
1178 let raw_bytes: &[u8] = fetched.bytes.as_slice();
1179 if raw_bytes.len() > config.get_max_binary_bytes() {
1180 let err: WasmDynamicError = WasmDynamicError::BinaryTooLarge {
1181 actual: raw_bytes.len(),
1182 limit: config.get_max_binary_bytes(),
1183 };
1184 self.record_failure(&scope, &err);
1185 return Err(err);
1186 }
1187 let computed_checksum: u64 = compute_wasm_checksum(raw_bytes);
1188 if request.get_expected_checksum() != 0
1189 && computed_checksum != request.get_expected_checksum()
1190 {
1191 let err: WasmDynamicError = WasmDynamicError::ChecksumMismatch {
1192 expected: request.get_expected_checksum(),
1193 actual: computed_checksum,
1194 };
1195 self.record_failure(&scope, &err);
1196 return Err(err);
1197 }
1198 if config.get_require_signature() || !request.get_expected_signature().is_empty() {
1199 let computed_sig: String =
1200 compute_wasm_signature(raw_bytes, request.get_version(), signing_key);
1201 if computed_sig != *request.get_expected_signature() {
1202 let err: WasmDynamicError = WasmDynamicError::SignatureInvalid {
1203 expected: request.get_expected_signature().clone(),
1204 actual: computed_sig,
1205 };
1206 self.record_failure(&scope, &err);
1207 return Err(err);
1208 }
1209 }
1210 if state_sig.has_subscribers() {
1211 let _: bool = state_sig.set(WasmLoadState::Compiling);
1212 }
1213 let cached_module: Option<Rc<WasmParsedModule>> = cached_parsed_opt.or_else(|| {
1214 self.lookup_cached_parsed_module(
1215 request.resolved_cache_key(),
1216 request.get_url().as_str(),
1217 computed_checksum,
1218 )
1219 });
1220 let parsed: Rc<WasmParsedModule> = match cached_module {
1221 Some(hit) => hit,
1222 None => match parse_wasm_binary(raw_bytes, &config) {
1223 Ok(matrix_elems) => Rc::new(matrix_elems),
1224 Err(err) => {
1225 self.record_failure(&scope, &err);
1226 return Err(err);
1227 }
1228 },
1229 };
1230 if parsed.get_exports().contains_key(WASM_EXPORT_ABI) {
1231 let abi_res: Result<WasmExecutionOutput, WasmDynamicError> =
1232 execute_wasm_export(parsed.as_ref(), WASM_EXPORT_ABI, &[], &config);
1233 match abi_res {
1234 Ok(abi_out) => {
1235 let mod_abi: u32 = abi_out.get_return_value().max(0) as u32;
1236 if mod_abi != WASM_ABI_VERSION {
1237 let err: WasmDynamicError = WasmDynamicError::AbiMismatch {
1238 expected: WASM_ABI_VERSION,
1239 actual: mod_abi,
1240 };
1241 self.record_failure(&scope, &err);
1242 return Err(err);
1243 }
1244 }
1245 Err(err) => {
1246 self.record_failure(&scope, &err);
1247 return Err(err);
1248 }
1249 }
1250 }
1251 if state_sig.has_subscribers() {
1252 let _: bool = state_sig.set(WasmLoadState::Executing);
1253 }
1254 let exec_out: WasmExecutionOutput =
1255 match execute_wasm_export(parsed.as_ref(), WASM_EXPORT_RENDER, &[0], &config) {
1256 Ok(out) => out,
1257 Err(err) => {
1258 self.record_failure(&scope, &err);
1259 return Err(err);
1260 }
1261 };
1262 self.commit_mounted_output(
1263 &request,
1264 fetched,
1265 computed_checksum,
1266 parsed,
1267 exec_out,
1268 state_sig,
1269 )
1270 }
1271
1272 pub fn dispatch_wasm_event(
1284 &self,
1285 scope: &WasmDynamicScope,
1286 action_code: i32,
1287 ) -> Result<i32, WasmDynamicError> {
1288 let (config, hub, snap_version, snap_state, snap_module): (
1289 WasmSandboxConfig,
1290 DynamicUpdateHub,
1291 u64,
1292 i32,
1293 Rc<WasmParsedModule>,
1294 ) = {
1295 let Self { inner } = self;
1296 let guard: Ref<'_, WasmDynamicManagerState> = inner.try_borrow().map_err(|_| {
1297 WasmDynamicError::ExecutionTrap(WASM_ERR_MANAGER_BORROW.to_string())
1298 })?;
1299 let snap: &WasmMountedSnapshot = match scope {
1300 WasmDynamicScope::Partial { slot_id } => guard
1301 .partial_stacks
1302 .get(slot_id)
1303 .and_then(|source_val: &Vec<WasmMountedSnapshot>| source_val.last())
1304 .ok_or(WasmDynamicError::NoRollbackSnapshot)?,
1305 WasmDynamicScope::Global => guard
1306 .global_stack
1307 .last()
1308 .ok_or(WasmDynamicError::NoRollbackSnapshot)?,
1309 };
1310 (
1311 guard.config,
1312 guard.hub.clone(),
1313 snap.get_version(),
1314 snap.get_state_value(),
1315 Rc::clone(snap.get_module()),
1316 )
1317 };
1318 let next_state: i32 = if snap_module.get_exports().contains_key(WASM_EXPORT_ON_EVENT) {
1319 let ev_out: WasmExecutionOutput = execute_wasm_export(
1320 snap_module.as_ref(),
1321 WASM_EXPORT_ON_EVENT,
1322 &[snap_state],
1323 &config,
1324 )?;
1325 let _: i32 = action_code;
1326 ev_out.get_return_value() % 2
1327 } else {
1328 (snap_state + 1) % 2
1329 };
1330 let render_out: WasmExecutionOutput = execute_wasm_export(
1331 snap_module.as_ref(),
1332 WASM_EXPORT_RENDER,
1333 &[next_state],
1334 &config,
1335 )?;
1336 let WasmExecutionOutput {
1337 emitted_spec,
1338 emitted_bundle,
1339 ..
1340 } = render_out;
1341 match scope {
1342 WasmDynamicScope::Partial { slot_id } => {
1343 if let Some(spec) = emitted_spec {
1344 let mut upd: DynamicComponentUpdate =
1345 DynamicComponentUpdate::new(slot_id.clone(), snap_version, spec);
1346 upd.set_allow_downgrade(true);
1347 upd.sign();
1348 let _: Result<u64, DynamicUpdateError> = hub.apply_component(upd);
1349 }
1350 }
1351 WasmDynamicScope::Global => {
1352 if let Some(mut patched) = emitted_bundle {
1353 for comp in patched.get_mut_components().iter_mut() {
1354 comp.set_allow_downgrade(true);
1355 comp.sign();
1356 }
1357 for page in patched.get_mut_pages().iter_mut() {
1358 page.set_allow_downgrade(true);
1359 page.sign();
1360 }
1361 let _: Result<DynamicTelemetry, DynamicUpdateError> = hub.apply_bundle(patched);
1362 }
1363 }
1364 }
1365 let Self { inner } = self;
1366 if let Ok(mut guard) = inner.try_borrow_mut() {
1367 match scope {
1368 WasmDynamicScope::Partial { slot_id } => {
1369 if let Some(stack) = guard.partial_stacks.get_mut(slot_id)
1370 && let Some(top) = stack.last_mut()
1371 {
1372 top.set_state_value(next_state);
1373 }
1374 }
1375 WasmDynamicScope::Global => {
1376 if let Some(top) = guard.global_stack.last_mut() {
1377 top.set_state_value(next_state);
1378 }
1379 }
1380 }
1381 let _: bool = {
1382 if let Some(mut updated_value) = (guard.telemetry_signal).try_get_untracked() {
1383 {
1384 let blend_factor: &mut WasmDynamicTelemetry = &mut updated_value;
1385 blend_factor.events_handled = blend_factor.events_handled.saturating_add(1);
1386 }
1387 (guard.telemetry_signal).set(updated_value)
1388 } else {
1389 false
1390 }
1391 };
1392 }
1393 Ok(next_state)
1394 }
1395
1396 pub fn rollback_partial(&self, slot_id: &str, reason: &str) -> Result<u64, WasmDynamicError> {
1408 let scope: WasmDynamicScope = WasmDynamicScope::Partial {
1409 slot_id: slot_id.to_string(),
1410 };
1411 let state_sig: Signal<WasmLoadState> = self.state_signal(&scope);
1412 let (hub, next_ver): (DynamicUpdateHub, 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 let stack: &mut Vec<WasmMountedSnapshot> = guard
1419 .partial_stacks
1420 .get_mut(slot_id)
1421 .ok_or(WasmDynamicError::NoRollbackSnapshot)?;
1422 if stack.pop().is_none() {
1423 return Err(WasmDynamicError::NoRollbackSnapshot);
1424 }
1425 let ver: u64 = stack
1426 .last()
1427 .map(WasmMountedSnapshot::get_version)
1428 .unwrap_or(0);
1429 let _: bool = {
1430 if let Some(mut updated_value) = (guard.telemetry_signal).try_get_untracked() {
1431 {
1432 let blend_factor: &mut WasmDynamicTelemetry = &mut updated_value;
1433 blend_factor.rollbacks_executed =
1434 blend_factor.rollbacks_executed.saturating_add(1);
1435 }
1436 (guard.telemetry_signal).set(updated_value)
1437 } else {
1438 false
1439 }
1440 };
1441 (guard.hub.clone(), ver)
1442 };
1443 let _: Result<u64, DynamicUpdateError> = hub.rollback_component(slot_id);
1444 let _: bool = state_sig.set(WasmLoadState::RolledBack {
1445 active_version: next_ver,
1446 reason: reason.to_string(),
1447 });
1448 Ok(next_ver)
1449 }
1450
1451 pub fn unmount_partial(&self, slot_id: &str) {
1458 let scope: WasmDynamicScope = WasmDynamicScope::Partial {
1459 slot_id: slot_id.to_string(),
1460 };
1461 let state_sig: Signal<WasmLoadState> = self.state_signal(&scope);
1462 let hub: Option<DynamicUpdateHub> = {
1463 let Self { inner } = self;
1464 if let Ok(mut guard) = inner.try_borrow_mut() {
1465 let _: Option<Vec<WasmMountedSnapshot>> = guard.partial_stacks.remove(slot_id);
1466 Some(guard.hub.clone())
1467 } else {
1468 None
1469 }
1470 };
1471 if let Some(height_val) = hub {
1472 while height_val.rollback_component(slot_id).is_ok() {}
1473 }
1474 let _: bool = state_sig.set(WasmLoadState::Idle);
1475 }
1476
1477 pub fn rollback_global(&self, reason: &str) -> Result<u64, WasmDynamicError> {
1488 let state_sig: Signal<WasmLoadState> = self.state_signal(&WasmDynamicScope::Global);
1489 let (hub, global_sig, next_ver): (DynamicUpdateHub, Signal<u64>, u64) = {
1490 let Self { inner } = self;
1491 let mut guard: RefMut<'_, WasmDynamicManagerState> =
1492 inner.try_borrow_mut().map_err(|_| {
1493 WasmDynamicError::ExecutionTrap(WASM_ERR_MANAGER_BORROW.to_string())
1494 })?;
1495 if guard.global_stack.pop().is_none() {
1496 return Err(WasmDynamicError::NoRollbackSnapshot);
1497 }
1498 let ver: u64 = guard
1499 .global_stack
1500 .last()
1501 .map(WasmMountedSnapshot::get_version)
1502 .unwrap_or(0);
1503 let _: bool = {
1504 if let Some(mut updated_value) = (guard.telemetry_signal).try_get_untracked() {
1505 {
1506 let blend_factor: &mut WasmDynamicTelemetry = &mut updated_value;
1507 blend_factor.rollbacks_executed =
1508 blend_factor.rollbacks_executed.saturating_add(1);
1509 }
1510 (guard.telemetry_signal).set(updated_value)
1511 } else {
1512 false
1513 }
1514 };
1515 (guard.hub.clone(), guard.global_version_signal, ver)
1516 };
1517 let _: Result<u64, DynamicUpdateError> = hub.rollback_component(WASM_GLOBAL_ROOT_SLOT);
1518 let _: bool = global_sig.set_if_changed(next_ver);
1519 let _: bool = state_sig.set(WasmLoadState::RolledBack {
1520 active_version: next_ver,
1521 reason: reason.to_string(),
1522 });
1523 Ok(next_ver)
1524 }
1525
1526 pub fn restore_native_global(&self) {
1532 let state_sig: Signal<WasmLoadState> = self.state_signal(&WasmDynamicScope::Global);
1533 let pair: Option<(DynamicUpdateHub, Signal<u64>)> = {
1534 let Self { inner } = self;
1535 if let Ok(mut guard) = inner.try_borrow_mut() {
1536 guard.global_stack.clear();
1537 let _: bool = {
1538 if let Some(mut updated_value) = (guard.telemetry_signal).try_get_untracked() {
1539 {
1540 let blend_factor: &mut WasmDynamicTelemetry = &mut updated_value;
1541 blend_factor.rollbacks_executed =
1542 blend_factor.rollbacks_executed.saturating_add(1);
1543 }
1544 (guard.telemetry_signal).set(updated_value)
1545 } else {
1546 false
1547 }
1548 };
1549 Some((guard.hub.clone(), guard.global_version_signal))
1550 } else {
1551 None
1552 }
1553 };
1554 if let Some((hub, global_sig)) = pair {
1555 while hub.rollback_component(WASM_GLOBAL_ROOT_SLOT).is_ok() {}
1556 let _: bool = global_sig.set_if_changed(0);
1557 }
1558 let _: bool = state_sig.set(WasmLoadState::RolledBack {
1559 active_version: 0,
1560 reason: "restored built-in native shell".to_string(),
1561 });
1562 }
1563
1564 #[must_use]
1575 fn active_request_id(&self, scope_key: &str) -> u64 {
1576 let Self { inner } = self;
1577 inner
1578 .try_borrow()
1579 .ok()
1580 .and_then(|green_val: Ref<'_, WasmDynamicManagerState>| {
1581 green_val.active_request_ids.get(scope_key).copied()
1582 })
1583 .unwrap_or(0)
1584 }
1585
1586 #[must_use]
1599 fn lookup_cached_parsed_module(
1600 &self,
1601 cache_key: &str,
1602 url: &str,
1603 checksum: u64,
1604 ) -> Option<Rc<WasmParsedModule>> {
1605 let Self { inner } = self;
1606 let guard: Ref<'_, WasmDynamicManagerState> = inner.try_borrow().ok()?;
1607 if let Some(entry) = guard.cache.get(cache_key)
1608 && entry.get_checksum() == checksum
1609 && entry.get_url().as_str() == url
1610 {
1611 return Some(Rc::clone(entry.get_parsed()));
1612 }
1613 if guard.parsed_cache.is_empty() {
1614 return None;
1615 }
1616 guard
1617 .parsed_cache
1618 .get(&(url.to_string(), checksum))
1619 .map(Rc::clone)
1620 }
1621
1622 fn fetch_with_retry(
1636 &self,
1637 request: &WasmDownloadRequest,
1638 config: WasmSandboxConfig,
1639 fetcher: &Rc<dyn WasmFetcher>,
1640 state_sig: Signal<WasmLoadState>,
1641 ) -> Result<(WasmFetchedShare, Option<Rc<WasmParsedModule>>), WasmDynamicError> {
1642 let mut last_err: WasmDynamicError =
1643 WasmDynamicError::NetworkOffline(request.get_url().clone());
1644 let max_attempts: u32 = config.get_max_retries().saturating_add(1);
1645 for attempt in 0..max_attempts {
1646 if attempt > 0 {
1647 let Self { inner } = self;
1648 if let Ok(guard) = inner.try_borrow() {
1649 let _: bool = {
1650 if let Some(mut updated_value) =
1651 (guard.telemetry_signal).try_get_untracked()
1652 {
1653 {
1654 let blend_factor: &mut WasmDynamicTelemetry = &mut updated_value;
1655 blend_factor.retries_performed =
1656 blend_factor.retries_performed.saturating_add(1);
1657 }
1658 (guard.telemetry_signal).set(updated_value)
1659 } else {
1660 false
1661 }
1662 };
1663 }
1664 }
1665 match fetcher.fetch(request, attempt, &mut |received: u64, total: u64| {
1666 if state_sig.has_subscribers() {
1667 let _: bool = state_sig.set(WasmLoadState::Downloading {
1668 received_bytes: received,
1669 total_bytes: total,
1670 });
1671 }
1672 }) {
1673 Ok(payload) => {
1674 let WasmFetchedPayload {
1675 bytes,
1676 etag,
1677 from_cache,
1678 } = payload;
1679 let shared: WasmFetchedShare = WasmFetchedShare {
1680 bytes: Rc::new(bytes),
1681 etag,
1682 from_cache,
1683 };
1684 return Ok((shared, None));
1685 }
1686 Err(err) => {
1687 let retryable: bool = matches!(
1688 err,
1689 WasmDynamicError::Timeout { .. }
1690 | WasmDynamicError::HttpStatus {
1691 status: 500..=599,
1692 ..
1693 }
1694 );
1695 last_err = err;
1696 if !retryable {
1697 break;
1698 }
1699 }
1700 }
1701 }
1702 if config.get_allow_offline_cache() {
1703 let Self { inner } = self;
1704 let hit: Option<(WasmFetchedShare, Rc<WasmParsedModule>)> =
1705 if let Ok(guard) = inner.try_borrow() {
1706 if let Some(cached) = guard.cache.get(request.resolved_cache_key()) {
1707 let _: bool = {
1708 if let Some(mut updated_value) =
1709 (guard.telemetry_signal).try_get_untracked()
1710 {
1711 {
1712 let time_step: &mut WasmDynamicTelemetry = &mut updated_value;
1713 time_step.cache_hits = time_step.cache_hits.saturating_add(1);
1714 }
1715 (guard.telemetry_signal).set(updated_value)
1716 } else {
1717 false
1718 }
1719 };
1720 let shared: WasmFetchedShare = WasmFetchedShare {
1721 bytes: Rc::clone(cached.get_bytes()),
1722 etag: cached.get_etag().clone(),
1723 from_cache: true,
1724 };
1725 Some((shared, Rc::clone(cached.get_parsed())))
1726 } else {
1727 None
1728 }
1729 } else {
1730 None
1731 };
1732 if let Some((shared, parsed)) = hit {
1733 return Ok((shared, Some(parsed)));
1734 }
1735 }
1736 Err(last_err)
1737 }
1738
1739 fn commit_mounted_output(
1755 &self,
1756 request: &WasmDownloadRequest,
1757 fetched: WasmFetchedShare,
1758 checksum: u64,
1759 parsed: Rc<WasmParsedModule>,
1760 exec_out: WasmExecutionOutput,
1761 state_sig: Signal<WasmLoadState>,
1762 ) -> Result<u64, WasmDynamicError> {
1763 let WasmFetchedShare {
1764 bytes: fetched_bytes,
1765 etag: fetched_etag,
1766 from_cache,
1767 } = fetched;
1768 let ver: u64 = request.get_version();
1769 let WasmExecutionOutput {
1770 fuel_used,
1771 emitted_spec,
1772 emitted_bundle,
1773 logs,
1774 ..
1775 } = exec_out;
1776 let hub: DynamicUpdateHub = {
1777 let Self { inner } = self;
1778 inner
1779 .try_borrow()
1780 .map(|green_val: Ref<'_, WasmDynamicManagerState>| green_val.hub.clone())
1781 .map_err(|_| WasmDynamicError::ExecutionTrap(WASM_ERR_MANAGER_BORROW.to_string()))?
1782 };
1783 let (spec_opt, bundle_opt): (Option<DynamicNodeSpec>, Option<DynamicUpdateBundle>) =
1784 match request.get_scope() {
1785 WasmDynamicScope::Partial { slot_id } => {
1786 let spec: DynamicNodeSpec = emitted_spec.ok_or_else(|| {
1787 WasmDynamicError::InvalidUiPayload(
1788 "partial wasm did not call env::euv_emit_ui".to_string(),
1789 )
1790 })?;
1791 let mut upd: DynamicComponentUpdate =
1792 DynamicComponentUpdate::new(slot_id.clone(), ver, spec.clone());
1793 upd.set_allow_downgrade(request.get_allow_downgrade());
1794 upd.sign();
1795 hub.apply_component(upd)
1796 .map_err(|event_ref: DynamicUpdateError| {
1797 WasmDynamicError::InvalidUiPayload(event_ref.to_string())
1798 })?;
1799 (Some(spec), None)
1800 }
1801 WasmDynamicScope::Global => {
1802 let bundle: DynamicUpdateBundle = emitted_bundle.ok_or_else(|| {
1803 WasmDynamicError::InvalidUiPayload(
1804 "global wasm did not call env::euv_emit_bundle".to_string(),
1805 )
1806 })?;
1807 let mut patched: DynamicUpdateBundle = bundle.clone();
1808 if request.get_allow_downgrade() {
1809 for comp in patched.get_mut_components().iter_mut() {
1810 comp.set_allow_downgrade(true);
1811 }
1812 for page in patched.get_mut_pages().iter_mut() {
1813 page.set_allow_downgrade(true);
1814 }
1815 }
1816 let _: DynamicTelemetry =
1817 hub.apply_bundle(patched)
1818 .map_err(|error_val: DynamicUpdateError| {
1819 WasmDynamicError::InvalidUiPayload(error_val.to_string())
1820 })?;
1821 (None, Some(bundle))
1822 }
1823 };
1824 let snap: WasmMountedSnapshot = WasmMountedSnapshot {
1825 version: ver,
1826 url: request.get_url().clone(),
1827 checksum,
1828 module: Rc::clone(&parsed),
1829 state_value: 0,
1830 spec: spec_opt,
1831 bundle: bundle_opt,
1832 };
1833 let Self { inner } = self;
1834 if let Ok(mut guard) = inner.try_borrow_mut() {
1835 let cache_key: &str = request.resolved_cache_key();
1836 let same_cached: bool =
1837 guard
1838 .cache
1839 .get(cache_key)
1840 .is_some_and(|entry_ref: &WasmCachedEntry| {
1841 entry_ref.get_checksum() == checksum
1842 && entry_ref.get_url() == request.get_url()
1843 });
1844 if same_cached {
1845 if let Some(existing) = guard.cache.get_mut(cache_key) {
1846 existing.set_version(ver);
1847 existing.set_etag(fetched_etag);
1848 }
1849 } else {
1850 let cache_entry: WasmCachedEntry = WasmCachedEntry::new(
1851 request.get_url().clone(),
1852 ver,
1853 checksum,
1854 fetched_bytes,
1855 Rc::clone(&parsed),
1856 fetched_etag,
1857 );
1858 let _: Option<WasmCachedEntry> =
1859 guard.cache.insert(cache_key.to_string(), cache_entry);
1860 let _: Option<Rc<WasmParsedModule>> = guard
1861 .parsed_cache
1862 .insert((request.get_url().clone(), checksum), parsed);
1863 }
1864 match request.get_scope() {
1865 WasmDynamicScope::Partial { slot_id } => {
1866 guard
1867 .partial_stacks
1868 .entry(slot_id.clone())
1869 .or_default()
1870 .push(snap);
1871 }
1872 WasmDynamicScope::Global => {
1873 guard.global_stack.push(snap);
1874 let _: bool = guard.global_version_signal.set_if_changed(ver);
1875 }
1876 }
1877 let _: bool = guard.last_logs.set_if_changed(logs);
1878 let _: bool = {
1879 if let Some(mut updated_value) = (guard.telemetry_signal).try_get_untracked() {
1880 {
1881 let blend_factor: &mut WasmDynamicTelemetry = &mut updated_value;
1882 blend_factor.downloads_succeeded =
1883 blend_factor.downloads_succeeded.saturating_add(1);
1884 }
1885 (guard.telemetry_signal).set(updated_value)
1886 } else {
1887 false
1888 }
1889 };
1890 }
1891 let _: bool = state_sig.set(WasmLoadState::Mounted {
1892 version: ver,
1893 from_cache,
1894 fuel_used,
1895 });
1896 Ok(ver)
1897 }
1898
1899 fn record_failure(&self, scope: &WasmDynamicScope, err: &WasmDynamicError) {
1907 let state_sig: Signal<WasmLoadState> = self.state_signal(scope);
1908 let mut active_global_lkg: u64 = 0;
1909 let Self { inner } = self;
1910 if let Ok(guard) = inner.try_borrow() {
1911 let _: bool = {
1912 if let Some(mut updated_value) = (guard.telemetry_signal).try_get_untracked() {
1913 {
1914 let blend_factor: &mut WasmDynamicTelemetry = &mut updated_value;
1915 match err {
1916 WasmDynamicError::OutOfFuel { .. } => {
1917 blend_factor.fuel_exhaustions_caught =
1918 blend_factor.fuel_exhaustions_caught.saturating_add(1);
1919 }
1920 WasmDynamicError::ExecutionTrap(_)
1921 | WasmDynamicError::MemoryOutOfBounds { .. }
1922 | WasmDynamicError::MemoryLimitExceeded { .. } => {
1923 blend_factor.sandbox_traps_caught =
1924 blend_factor.sandbox_traps_caught.saturating_add(1);
1925 }
1926 WasmDynamicError::ChecksumMismatch { .. }
1927 | WasmDynamicError::SignatureInvalid { .. }
1928 | WasmDynamicError::InvalidWasmBinary(_)
1929 | WasmDynamicError::AbiMismatch { .. }
1930 | WasmDynamicError::MissingExport(_)
1931 | WasmDynamicError::BinaryTooLarge { .. }
1932 | WasmDynamicError::VersionRegression { .. } => {
1933 blend_factor.integrity_rejections =
1934 blend_factor.integrity_rejections.saturating_add(1);
1935 }
1936 _ => {}
1937 };
1938 }
1939 (guard.telemetry_signal).set(updated_value)
1940 } else {
1941 false
1942 }
1943 };
1944 if *scope == WasmDynamicScope::Global {
1945 active_global_lkg = guard
1946 .global_stack
1947 .last()
1948 .map(WasmMountedSnapshot::get_version)
1949 .unwrap_or(0);
1950 }
1951 }
1952 if *scope == WasmDynamicScope::Global && active_global_lkg > 0 {
1953 let Self { inner } = self;
1954 if let Ok(guard) = inner.try_borrow() {
1955 let _: bool = {
1956 if let Some(mut updated_value) = (guard.telemetry_signal).try_get_untracked() {
1957 {
1958 let time_step: &mut WasmDynamicTelemetry = &mut updated_value;
1959 time_step.rollbacks_executed =
1960 time_step.rollbacks_executed.saturating_add(1);
1961 }
1962 (guard.telemetry_signal).set(updated_value)
1963 } else {
1964 false
1965 }
1966 };
1967 }
1968 let _: bool = state_sig.set(WasmLoadState::RolledBack {
1969 active_version: active_global_lkg,
1970 reason: format!("auto-kept LKG v{active_global_lkg} after error: {err}"),
1971 });
1972 } else {
1973 let _: bool = state_sig.set(WasmLoadState::Failed(err.clone()));
1974 }
1975 }
1976}