1use super::*;
2
3impl Default for HotUpdateProxyConfig {
5 fn default() -> Self {
11 Self {
12 server_url: DEFAULT_HOT_UPDATE_SERVER_URL.to_string(),
13 proxy_url: None,
14 proxy_auth: None,
15 channel: DEFAULT_HOT_UPDATE_CHANNEL.to_string(),
16 auto_apply: true,
17 poll_fallback_secs: DEFAULT_POLL_FALLBACK_SECS,
18 cache_dir: None,
19 }
20 }
21}
22
23impl HotUpdateProxyConfig {
25 #[must_use]
40 pub fn new(
41 server_url: String,
42 proxy_url: Option<String>,
43 proxy_auth: Option<String>,
44 channel: String,
45 auto_apply: bool,
46 poll_fallback_secs: u64,
47 ) -> Self {
48 let clean_server: String = server_url.trim().trim_end_matches('/').to_string();
49 let clean_proxy: Option<String> = proxy_url
50 .map(|text_value: String| text_value.trim().trim_end_matches('/').to_string())
51 .filter(|label_str: &String| !label_str.is_empty());
52 let clean_auth: Option<String> = proxy_auth
53 .map(|content_text: String| content_text.trim().to_string())
54 .filter(|alpha_val: &String| !alpha_val.is_empty());
55 let clean_channel: String = if channel.trim().is_empty() {
56 DEFAULT_HOT_UPDATE_CHANNEL.to_string()
57 } else {
58 channel.trim().to_string()
59 };
60 Self {
61 server_url: if clean_server.is_empty() {
62 DEFAULT_HOT_UPDATE_SERVER_URL.to_string()
63 } else {
64 clean_server
65 },
66 proxy_url: clean_proxy,
67 proxy_auth: clean_auth,
68 channel: clean_channel,
69 auto_apply,
70 poll_fallback_secs: poll_fallback_secs.max(1),
71 cache_dir: None,
72 }
73 }
74
75 #[must_use]
86 pub fn with_cache_dir(mut self, dir: Option<PathBuf>) -> Self {
87 let _: &mut Self = self.set_cache_dir(dir);
88 self
89 }
90
91 #[must_use]
101 pub fn cache_dir_path(&self) -> Option<&Path> {
102 let Self { cache_dir, .. } = self;
103 cache_dir.as_deref()
104 }
105
106 #[must_use]
116 pub fn proxy_url_str(&self) -> Option<&str> {
117 let Self { proxy_url, .. } = self;
118 proxy_url.as_deref()
119 }
120
121 #[must_use]
131 pub fn proxy_auth_str(&self) -> Option<&str> {
132 let Self { proxy_auth, .. } = self;
133 proxy_auth.as_deref()
134 }
135
136 #[must_use]
146 pub fn effective_web_base_url(&self) -> String {
147 if let Some(proxy) = self.proxy_url_str() {
148 let trimmed: &str = proxy.trim().trim_end_matches('/');
149 if !trimmed.is_empty() {
150 return trimmed.to_string();
151 }
152 }
153 self.get_server_url()
154 .trim()
155 .trim_end_matches('/')
156 .to_string()
157 }
158
159 #[must_use]
169 pub const fn recommended_delivery_mode(platform: PlatformKind) -> DeliveryChannelMode {
170 match platform {
171 PlatformKind::Ios
172 | PlatformKind::IpadOs
173 | PlatformKind::Wearable
174 | PlatformKind::MiniApp
175 | PlatformKind::QuickApp => DeliveryChannelMode::DeclarativeData,
176 PlatformKind::Web
177 | PlatformKind::Android
178 | PlatformKind::MacOs
179 | PlatformKind::Windows
180 | PlatformKind::Linux
181 | PlatformKind::HarmonyOs
182 | PlatformKind::Terminal
183 | PlatformKind::TerminalCli
184 | PlatformKind::Headless => DeliveryChannelMode::WasmComponent,
185 }
186 }
187
188 #[must_use]
198 pub fn platform_capability_tags(platform: PlatformKind) -> Vec<String> {
199 let capabilities: PlatformCapabilities = PlatformCapabilities::for_platform(platform);
200 let mut tags: Vec<String> = vec![format!("platform:{}", platform.as_str())];
201 if capabilities.get_hardware_gpu() {
202 tags.push("gpu".to_string());
203 }
204 if capabilities.get_touch() {
205 tags.push("touch".to_string());
206 }
207 if matches!(platform, PlatformKind::Terminal | PlatformKind::TerminalCli) {
208 tags.push("terminal".to_string());
209 }
210 tags
211 }
212
213 #[must_use]
225 pub fn to_client_config(&self, project: String, verify_key: Vec<u8>) -> UpdateClientConfig {
226 let mut config_spec: UpdateClientConfig = UpdateClientConfig::with_defaults(
227 self.get_server_url().clone(),
228 project,
229 self.get_channel().clone(),
230 verify_key,
231 );
232 if let Some(proxy) = self.proxy_url_str() {
233 let _: &mut UpdateClientConfig = config_spec.set_proxy_url(Some(proxy.to_string()));
234 }
235 if let Some(auth) = self.proxy_auth_str() {
236 let _: &mut UpdateClientConfig = config_spec.set_proxy_auth(Some(auth.to_string()));
237 }
238 if let Some(dir) = self.cache_dir_path() {
239 config_spec = config_spec.with_cache_dir(Some(dir.to_path_buf()));
240 }
241 config_spec
242 }
243
244 #[must_use]
256 pub fn to_platform_client_config(
257 &self,
258 platform: PlatformKind,
259 project: String,
260 verify_key: Vec<u8>,
261 ) -> UpdateClientConfig {
262 let mode: DeliveryChannelMode = Self::recommended_delivery_mode(platform);
263 let track: String = default_track_for(DYNAMIC_HOST_ABI_V1, mode);
264 let mut config_spec: UpdateClientConfig = self.to_client_config(project, verify_key);
265 let _: &mut UpdateClientConfig = config_spec
266 .set_delivery_mode(mode)
267 .set_preferred_track(Some(track))
268 .set_capabilities(Self::platform_capability_tags(platform));
269 config_spec
270 }
271}
272
273impl UpdateClientConfig {
275 #[must_use]
288 pub fn with_defaults(
289 base_url: String,
290 project: String,
291 channel: String,
292 verify_key: Vec<u8>,
293 ) -> Self {
294 let mut config_spec: Self = Self::new(base_url, project, channel, verify_key);
295 config_spec
296 .set_host_abi(DYNAMIC_HOST_ABI_V1)
297 .set_delivery_mode(DeliveryChannelMode::WasmComponent)
298 .set_max_artifact_bytes(DEFAULT_MAX_ARTIFACT_BYTES)
299 .set_mailbox_capacity(DEFAULT_CANDIDATE_MAILBOX_CAPACITY)
300 .set_reconnect_backoff_ms(DEFAULT_SSE_RECONNECT_MS)
301 .set_http_timeout_ms(DEFAULT_UPDATE_HTTP_TIMEOUT_MS)
302 .set_sandbox_config(WasmSandboxConfig::default());
303 config_spec
304 }
305
306 #[must_use]
312 pub fn preferred_track_str(&self) -> Option<&str> {
313 let Self {
314 preferred_track, ..
315 } = self;
316 preferred_track.as_deref()
317 }
318
319 #[must_use]
329 pub fn proxy_url_str(&self) -> Option<&str> {
330 let Self { proxy_url, .. } = self;
331 proxy_url.as_deref()
332 }
333
334 #[must_use]
344 pub fn proxy_auth_str(&self) -> Option<&str> {
345 let Self { proxy_auth, .. } = self;
346 proxy_auth.as_deref()
347 }
348
349 #[must_use]
361 pub fn with_proxy(mut self, proxy_url: Option<String>, proxy_auth: Option<String>) -> Self {
362 let _: &mut Self = self.set_proxy_url(proxy_url);
363 let _: &mut Self = self.set_proxy_auth(proxy_auth);
364 self
365 }
366
367 #[must_use]
378 pub fn with_cache_dir(mut self, dir: Option<PathBuf>) -> Self {
379 let _: &mut Self = self.set_cache_dir(dir);
380 self
381 }
382
383 #[must_use]
393 pub fn cache_dir_path(&self) -> Option<&Path> {
394 let Self { cache_dir, .. } = self;
395 cache_dir.as_deref()
396 }
397
398 #[must_use]
404 pub fn negotiation(&self) -> ClientNegotiation {
405 let mut neg: ClientNegotiation = ClientNegotiation::new(
406 DYNAMIC_PROTOCOL_VERSION_V1,
407 self.get_host_abi(),
408 self.get_delivery_mode(),
409 )
410 .with_capabilities(self.get_capabilities().clone());
411 if let Some(track) = self.preferred_track_str() {
412 neg = neg.with_preferred_track(track.to_string());
413 }
414 neg
415 }
416}
417
418impl HttpReleaseTransport {
420 #[must_use]
430 pub fn from_client_config(config: &UpdateClientConfig) -> Self {
431 let mut transport: Self =
432 Self::new(config.get_base_url().clone(), config.get_http_timeout_ms());
433 if let Some(proxy) = config.proxy_url_str() {
434 let _: &mut Self = transport.set_proxy_url(Some(proxy.to_string()));
435 }
436 if let Some(auth) = config.proxy_auth_str() {
437 let _: &mut Self = transport.set_proxy_auth(Some(auth.to_string()));
438 }
439 transport
440 }
441
442 #[must_use]
452 pub fn proxy_url_str(&self) -> Option<&str> {
453 let Self { proxy_url, .. } = self;
454 proxy_url.as_deref()
455 }
456
457 #[must_use]
467 pub fn proxy_auth_str(&self) -> Option<&str> {
468 let Self { proxy_auth, .. } = self;
469 proxy_auth.as_deref()
470 }
471}
472
473impl ReleaseTransport for HttpReleaseTransport {
475 fn fetch_manifest(
487 &self,
488 project: &str,
489 channel: &str,
490 negotiation: &ClientNegotiation,
491 ) -> Result<ReleaseManifest, DynamicReleaseError> {
492 #[cfg(not(target_arch = "wasm32"))]
493 {
494 let (authority, prefix): (&str, &str) = parse_http_base_url(self.get_base_url())?;
495 let base_prefix: String = if prefix.is_empty() {
496 String::new()
497 } else {
498 format!("/{prefix}")
499 };
500 let mode_tok: &str = delivery_mode_query_token(negotiation.get_delivery_mode());
501 let mut path: String = format!(
502 "{base_prefix}/v1/projects/{project}/channels/{channel}/manifest?protocol={}&abi={}&mode={mode_tok}",
503 negotiation.get_protocol_version(),
504 negotiation.get_host_abi()
505 );
506 if let Some(track) = negotiation.preferred_track_str() {
507 path.push_str(&format!("&track={track}"));
508 }
509 let (status, body): (u16, Vec<u8>) = http_get_once_with_proxy(
510 authority,
511 &path,
512 &[],
513 self.get_timeout_ms(),
514 self.proxy_url_str(),
515 self.proxy_auth_str(),
516 )?;
517 if status == 404 {
518 return Err(DynamicReleaseError::RouteNotFound(format!(
519 "{project}/{channel}"
520 )));
521 }
522 if status == 409 {
523 let reason: String = String::from_utf8_lossy(&body).into_owned();
524 return Err(DynamicReleaseError::ProtocolIncompatible(reason));
525 }
526 if status != 200 {
527 return Err(DynamicReleaseError::NetworkError(format!(
528 "{ERR_HTTP_NON_OK}: HTTP {status}"
529 )));
530 }
531 let text: &str = from_utf8(&body).map_err(|_| {
532 DynamicReleaseError::StorageError(ERR_MANIFEST_SERIALIZE.to_string())
533 })?;
534 match from_str::<ReleaseManifest>(text) {
535 Ok(parsed) => Ok(parsed),
536 Err(err) => Err(DynamicReleaseError::StorageError(format!(
537 "{ERR_MANIFEST_SERIALIZE}: {err}"
538 ))),
539 }
540 }
541 #[cfg(target_arch = "wasm32")]
542 {
543 let _: (&str, &str, &ClientNegotiation) = (project, channel, negotiation);
544 Err(DynamicReleaseError::NetworkError(
545 ERR_WASM32_SYNC_HTTP.to_string(),
546 ))
547 }
548 }
549
550 fn fetch_blob(&self, sha256: &str, range_start: u64) -> Result<Vec<u8>, DynamicReleaseError> {
561 #[cfg(not(target_arch = "wasm32"))]
562 {
563 let (authority, prefix): (&str, &str) = parse_http_base_url(self.get_base_url())?;
564 let base_prefix: String = if prefix.is_empty() {
565 String::new()
566 } else {
567 format!("/{prefix}")
568 };
569 let path: String = format!("{base_prefix}/v1/blobs/{sha256}");
570 let range_header: String = format!("bytes={range_start}-");
571 let headers: Vec<(&str, &str)> = if range_start > 0 {
572 vec![(HDR_RANGE, range_header.as_str())]
573 } else {
574 Vec::new()
575 };
576 let (status, body): (u16, Vec<u8>) = http_get_once_with_proxy(
577 authority,
578 &path,
579 &headers,
580 self.get_timeout_ms(),
581 self.proxy_url_str(),
582 self.proxy_auth_str(),
583 )?;
584 if status == 404 {
585 return Err(DynamicReleaseError::BlobMissing(sha256.to_string()));
586 }
587 if status != 200 && status != 206 {
588 return Err(DynamicReleaseError::NetworkError(format!(
589 "{ERR_HTTP_NON_OK}: HTTP {status}"
590 )));
591 }
592 Ok(body)
593 }
594 #[cfg(target_arch = "wasm32")]
595 {
596 let _: (&str, u64) = (sha256, range_start);
597 Err(DynamicReleaseError::NetworkError(
598 ERR_WASM32_SYNC_HTTP.to_string(),
599 ))
600 }
601 }
602}
603
604impl PreparedReleaseCandidate {
606 #[must_use]
616 pub fn is_restored_from_cache(&self) -> bool {
617 self.get_prepared_on_thread() == UPDATE_CACHE_RESTORE_SOURCE
618 }
619}
620
621impl DynamicUpdateHub {
623 pub fn apply_prepared_release(
634 &self,
635 candidate: &PreparedReleaseCandidate,
636 ) -> Result<usize, DynamicReleaseError> {
637 self.apply_prepared_release_with_sandbox(candidate, &WasmSandboxConfig::default())
638 }
639
640 pub fn apply_prepared_release_with_sandbox(
652 &self,
653 candidate: &PreparedReleaseCandidate,
654 sandbox_config: &WasmSandboxConfig,
655 ) -> Result<usize, DynamicReleaseError> {
656 let manifest: &ReleaseManifest = candidate.get_manifest();
657 let seq: u64 = manifest.get_release_seq().max(1);
658 let mut pages: Vec<DynamicPageUpdate> = Vec::new();
659 let mut components: Vec<DynamicComponentUpdate> = Vec::new();
660 let mut seen_pages: HashSet<String> = HashSet::new();
661 let mut seen_slots: HashSet<String> = HashSet::new();
662 for (route_path, route_manifest) in manifest.get_routes().iter() {
663 let entry_key: &str = route_manifest.get_entry_module().as_str();
664 if let Some(warmed) = candidate.get_warmed_artifacts().get(entry_key) {
665 match warmed {
666 WarmedArtifact::Declarative(spec) => {
667 if seen_pages.insert(route_path.clone()) {
668 let mut page_upd: DynamicPageUpdate = DynamicPageUpdate::new(
669 route_path.clone(),
670 format!("{} v{seq}", route_manifest.get_entry_module()),
671 seq,
672 spec.clone(),
673 );
674 let _: &mut DynamicPageUpdate = page_upd.set_allow_downgrade(true);
675 pages.push(page_upd);
676 }
677 }
678 WarmedArtifact::Wasm(parsed) => {
679 let entry: &str = manifest
680 .get_artifacts()
681 .get(entry_key)
682 .map(|art: &BlobArtifact| {
683 if art.get_entrypoint().is_empty() {
684 WASM_EXPORT_RENDER
685 } else {
686 art.get_entrypoint().as_str()
687 }
688 })
689 .unwrap_or(WASM_EXPORT_RENDER);
690 let exec_out: WasmExecutionOutput =
691 execute_wasm_export(parsed, entry, &[0], sandbox_config).map_err(
692 |err: WasmDynamicError| {
693 DynamicReleaseError::StorageError(err.to_string())
694 },
695 )?;
696 if let Some(emitted_bundle) = exec_out.emitted_bundle() {
697 for raw_page in emitted_bundle.get_pages().iter() {
698 if seen_pages.insert(raw_page.get_route().clone()) {
699 let mut page_upd: DynamicPageUpdate = raw_page.clone();
700 let _: &mut DynamicPageUpdate =
701 page_upd.set_version(seq).set_allow_downgrade(true);
702 page_upd.sign();
703 pages.push(page_upd);
704 }
705 }
706 for raw_comp in emitted_bundle.get_components().iter() {
707 if seen_slots.insert(raw_comp.get_id().clone()) {
708 let mut comp_upd: DynamicComponentUpdate = raw_comp.clone();
709 let _: &mut DynamicComponentUpdate =
710 comp_upd.set_version(seq).set_allow_downgrade(true);
711 comp_upd.sign();
712 components.push(comp_upd);
713 }
714 }
715 } else if let Some(spec) = exec_out.emitted_spec() {
716 if seen_pages.insert(route_path.clone()) {
717 let mut page_upd: DynamicPageUpdate = DynamicPageUpdate::new(
718 route_path.clone(),
719 format!("{} v{seq}", route_manifest.get_entry_module()),
720 seq,
721 spec.clone(),
722 );
723 let _: &mut DynamicPageUpdate = page_upd.set_allow_downgrade(true);
724 pages.push(page_upd);
725 }
726 } else {
727 return Err(DynamicReleaseError::StorageError(
728 ERR_WASM_EMIT_EMPTY.to_string(),
729 ));
730 }
731 }
732 WarmedArtifact::Asset(_) => {}
733 }
734 }
735 for (slot_key, art_key) in route_manifest.get_slot_bindings().iter() {
736 if !seen_slots.insert(slot_key.clone()) {
737 continue;
738 }
739 if let Some(warmed) = candidate.get_warmed_artifacts().get(art_key) {
740 match warmed {
741 WarmedArtifact::Declarative(spec) => {
742 let mut comp_upd: DynamicComponentUpdate =
743 DynamicComponentUpdate::new(slot_key.clone(), seq, spec.clone());
744 let _: &mut DynamicComponentUpdate = comp_upd.set_allow_downgrade(true);
745 components.push(comp_upd);
746 }
747 WarmedArtifact::Wasm(parsed) => {
748 let entry: &str = manifest
749 .get_artifacts()
750 .get(art_key)
751 .map(|art: &BlobArtifact| {
752 if art.get_entrypoint().is_empty() {
753 WASM_EXPORT_RENDER
754 } else {
755 art.get_entrypoint().as_str()
756 }
757 })
758 .unwrap_or(WASM_EXPORT_RENDER);
759 let exec_out: WasmExecutionOutput =
760 execute_wasm_export(parsed, entry, &[0], sandbox_config).map_err(
761 |err: WasmDynamicError| {
762 DynamicReleaseError::StorageError(err.to_string())
763 },
764 )?;
765 if let Some(spec) = exec_out.emitted_spec() {
766 let mut comp_upd: DynamicComponentUpdate =
767 DynamicComponentUpdate::new(
768 slot_key.clone(),
769 seq,
770 spec.clone(),
771 );
772 let _: &mut DynamicComponentUpdate =
773 comp_upd.set_allow_downgrade(true);
774 components.push(comp_upd);
775 } else if let Some(emitted_bundle) = exec_out.emitted_bundle() {
776 for raw_comp in emitted_bundle.get_components().iter() {
777 let mut comp_upd: DynamicComponentUpdate = raw_comp.clone();
778 let _: &mut DynamicComponentUpdate =
779 comp_upd.set_version(seq).set_allow_downgrade(true);
780 comp_upd.sign();
781 components.push(comp_upd);
782 }
783 for raw_page in emitted_bundle.get_pages().iter() {
784 if seen_pages.insert(raw_page.get_route().clone()) {
785 let mut page_upd: DynamicPageUpdate = raw_page.clone();
786 let _: &mut DynamicPageUpdate =
787 page_upd.set_version(seq).set_allow_downgrade(true);
788 page_upd.sign();
789 pages.push(page_upd);
790 }
791 }
792 } else {
793 return Err(DynamicReleaseError::StorageError(
794 ERR_WASM_EMIT_EMPTY.to_string(),
795 ));
796 }
797 }
798 WarmedArtifact::Asset(_) => {}
799 }
800 }
801 }
802 }
803 let applied_count: usize = pages.len() + components.len();
804 if applied_count == 0 {
805 return Ok(0);
806 }
807 let mut bundle: DynamicUpdateBundle =
808 DynamicUpdateBundle::new(format!("{}-{seq}", manifest.get_channel()), seq);
809 let _: &mut DynamicUpdateBundle = bundle.set_components(components).set_pages(pages);
810 let _: DynamicTelemetry =
811 self.apply_bundle(bundle)
812 .map_err(|err: DynamicUpdateError| {
813 DynamicReleaseError::StorageError(err.to_string())
814 })?;
815 Ok(applied_count)
816 }
817
818 pub fn sync_from_worker(
829 &self,
830 worker: &UpdateWorkerHandle,
831 ) -> Result<Option<PreparedReleaseCandidate>, DynamicReleaseError> {
832 let Some(candidate) = worker.try_take_ready_candidate() else {
833 return Ok(None);
834 };
835 let _: usize = self.apply_prepared_release(&candidate)?;
836 Ok(Some(candidate))
837 }
838
839 #[cfg_attr(not(target_arch = "wasm32"), inline)]
847 #[must_use]
848 pub fn needs_hot_update_poll(&self) -> bool {
849 let Self {
850 hot_update_attention,
851 ..
852 } = self;
853 hot_update_attention.load(Ordering::Acquire)
854 }
855
856 #[must_use]
866 pub fn hot_update_status_signal(&self) -> Signal<HotUpdateLiveStatus> {
867 let Self { inner, .. } = self;
868 match inner.try_borrow() {
869 Ok(guard) => guard.hot_update_status,
870 Err(_) => Signal::new_detached(HotUpdateLiveStatus::default()),
871 }
872 }
873
874 pub fn update_hot_update_status(&self, status: HotUpdateLiveStatus) {
881 let is_connected: bool = status.get_connected();
882 let sig: Signal<HotUpdateLiveStatus> = {
883 let Self { inner, .. } = self;
884 if let Ok(mut guard) = inner.try_borrow_mut() {
885 guard.hot_update_connected = is_connected;
886 guard.hot_update_status
887 } else {
888 self.hot_update_status_signal()
889 }
890 };
891 let _: bool = sig.set_if_changed(status);
892 }
893
894 #[must_use]
904 pub fn is_hot_updates_connected(&self) -> bool {
905 let Self { inner, .. } = self;
906 if let Ok(guard) = inner.try_borrow() {
907 return guard.hot_update_connected || guard.hot_update_worker.is_some();
908 }
909 false
910 }
911
912 #[must_use]
922 pub fn has_pending_hot_update(&self) -> bool {
923 if self.needs_hot_update_poll() {
924 return true;
925 }
926 let Self { inner, .. } = self;
927 if let Ok(guard) = inner.try_borrow() {
928 if guard.deferred_hot_candidate.is_some() {
929 return true;
930 }
931 if let Some(worker) = guard.hot_update_worker.as_ref() {
932 return worker.pending_candidate_count() > 0;
933 }
934 }
935 false
936 }
937
938 pub fn restore_cached_hot_updates(
949 &self,
950 config: &UpdateClientConfig,
951 ) -> Result<Option<PreparedReleaseCandidate>, DynamicReleaseError> {
952 #[cfg(not(target_arch = "wasm32"))]
953 {
954 let Some(restored) = load_persisted_release_with_blobs(config) else {
955 return Ok(None);
956 };
957 let candidate: PreparedReleaseCandidate = restored.candidate;
958 let _: usize =
959 self.apply_prepared_release_with_sandbox(&candidate, &config.get_sandbox_config())?;
960 let status_sig: Signal<HotUpdateLiveStatus> = self.hot_update_status_signal();
961 let mut next_status: HotUpdateLiveStatus = status_sig.get_untracked();
962 let next_applied: u64 = next_status.get_applied_count().saturating_add(1);
963 let _: &mut HotUpdateLiveStatus = next_status
964 .set_active_release_seq(candidate.get_manifest().get_release_seq())
965 .set_active_manifest_sha256(candidate.get_manifest_sha256().clone())
966 .set_applied_count(next_applied)
967 .set_restored_from_cache(true)
968 .set_pending_safe_boundary(false)
969 .set_last_error(String::new());
970 let _: bool = status_sig.set_if_changed(next_status);
971 Ok(Some(candidate))
972 }
973 #[cfg(target_arch = "wasm32")]
974 {
975 let _: &UpdateClientConfig = config;
976 Ok(None)
977 }
978 }
979
980 pub fn connect_hot_updates(
991 &self,
992 config: UpdateClientConfig,
993 ) -> Result<(), DynamicReleaseError> {
994 let server_url: String = config.get_base_url().clone();
995 let proxy_url: String = config.proxy_url_str().unwrap_or("").to_string();
996 let channel: String = config.get_channel().clone();
997 let cache_dir: Option<PathBuf> = config.cache_dir_path().map(Path::to_path_buf);
998 let sandbox: WasmSandboxConfig = config.get_sandbox_config();
999 let Self {
1000 inner,
1001 hot_update_attention,
1002 } = self;
1003 let handle: UpdateWorkerHandle = start_updates_with_attention(
1004 config,
1005 Arc::new(DefaultStateMigrator::default()),
1006 None,
1007 Arc::clone(hot_update_attention),
1008 )?;
1009 let status_sig: Signal<HotUpdateLiveStatus> = {
1010 let mut guard: RefMut<'_, DynamicHubState> = inner.borrow_mut();
1011 if let Some(mut prev) = guard.hot_update_worker.take() {
1012 prev.stop();
1013 }
1014 guard.hot_update_worker = Some(handle);
1015 guard.hot_update_cache_dir = cache_dir;
1016 guard.hot_update_sandbox = sandbox;
1017 guard.deferred_hot_candidate = None;
1018 guard.hot_update_connected = true;
1019 guard.hot_update_status
1020 };
1021 let mut next_status: HotUpdateLiveStatus = status_sig.get_untracked();
1022 let _: &mut HotUpdateLiveStatus = next_status
1023 .set_connected(true)
1024 .set_sse_live(false)
1025 .set_server_url(server_url)
1026 .set_proxy_url(proxy_url)
1027 .set_channel(channel)
1028 .set_pending_safe_boundary(false)
1029 .set_last_error(String::new());
1030 let _: bool = status_sig.set_if_changed(next_status);
1031 notify_frame_needed();
1032 Ok(())
1033 }
1034
1035 pub fn disconnect_hot_updates(&self) {
1041 let Self {
1042 inner,
1043 hot_update_attention,
1044 } = self;
1045 hot_update_attention.store(false, Ordering::Release);
1046 let status_sig: Signal<HotUpdateLiveStatus> = {
1047 if let Ok(mut guard) = inner.try_borrow_mut() {
1048 if let Some(mut prev) = guard.hot_update_worker.take() {
1049 prev.stop();
1050 }
1051 guard.deferred_hot_candidate = None;
1052 guard.hot_update_connected = false;
1053 guard.hot_update_status
1054 } else {
1055 return;
1056 }
1057 };
1058 let mut next_status: HotUpdateLiveStatus = status_sig.get_untracked();
1059 let _: &mut HotUpdateLiveStatus = next_status
1060 .set_connected(false)
1061 .set_sse_live(false)
1062 .set_pending_safe_boundary(false);
1063 let _: bool = status_sig.set_if_changed(next_status);
1064 }
1065
1066 pub fn request_hot_update_reconcile(&self) -> bool {
1076 let Self { inner, .. } = self;
1077 if let Ok(guard) = inner.try_borrow()
1078 && let Some(worker) = guard.hot_update_worker.as_ref()
1079 {
1080 worker.request_reconcile();
1081 return true;
1082 }
1083 false
1084 }
1085
1086 pub fn poll_hot_updates_at_safe_boundary(
1097 &self,
1098 boundary: &InteractionSafePoint,
1099 ) -> Result<Option<PreparedReleaseCandidate>, DynamicReleaseError> {
1100 let Self {
1101 inner,
1102 hot_update_attention,
1103 } = self;
1104 let _: bool = hot_update_attention.swap(false, Ordering::AcqRel);
1105 let (candidate_opt, sandbox, cache_dir, worker_err, worker_live, status_sig): (
1106 Option<PreparedReleaseCandidate>,
1107 WasmSandboxConfig,
1108 Option<PathBuf>,
1109 Option<String>,
1110 bool,
1111 Signal<HotUpdateLiveStatus>,
1112 ) = {
1113 let Ok(mut guard) = inner.try_borrow_mut() else {
1114 hot_update_attention.store(true, Ordering::Release);
1115 return Ok(None);
1116 };
1117 let fresh: Option<PreparedReleaseCandidate> = guard
1118 .hot_update_worker
1119 .as_ref()
1120 .and_then(UpdateWorkerHandle::try_take_ready_candidate);
1121 let err_msg: Option<String> = guard
1122 .hot_update_worker
1123 .as_ref()
1124 .and_then(UpdateWorkerHandle::last_error)
1125 .map(|err: DynamicReleaseError| err.to_string());
1126 let sse_is_live: bool = guard
1127 .hot_update_worker
1128 .as_ref()
1129 .is_some_and(UpdateWorkerHandle::is_sse_live);
1130 let next_cand: Option<PreparedReleaseCandidate> = match fresh {
1131 Some(cand) => Some(cand),
1132 None => guard.deferred_hot_candidate.take(),
1133 };
1134 if let Some(cand) = next_cand {
1135 if !boundary.is_safe_to_swap() {
1136 guard.deferred_hot_candidate = Some(cand);
1137 let sig: Signal<HotUpdateLiveStatus> = guard.hot_update_status;
1138 drop(guard);
1139 hot_update_attention.store(true, Ordering::Release);
1140 let mut st: HotUpdateLiveStatus = sig.get_untracked();
1141 let _: &mut HotUpdateLiveStatus =
1142 st.set_sse_live(sse_is_live).set_pending_safe_boundary(true);
1143 let _: bool = sig.set_if_changed(st);
1144 notify_frame_needed();
1145 return Ok(None);
1146 }
1147 (
1148 Some(cand),
1149 guard.hot_update_sandbox,
1150 guard.hot_update_cache_dir.clone(),
1151 err_msg,
1152 sse_is_live,
1153 guard.hot_update_status,
1154 )
1155 } else {
1156 (
1157 None,
1158 guard.hot_update_sandbox,
1159 guard.hot_update_cache_dir.clone(),
1160 err_msg,
1161 sse_is_live,
1162 guard.hot_update_status,
1163 )
1164 }
1165 };
1166 let Some(candidate) = candidate_opt else {
1167 let cur_status: HotUpdateLiveStatus = status_sig.get_untracked();
1168 let desired_err: String = worker_err.unwrap_or_default();
1169 if cur_status.get_last_error() != &desired_err
1170 || cur_status.get_sse_live() != worker_live
1171 {
1172 let mut next_status: HotUpdateLiveStatus = cur_status;
1173 let _: &mut HotUpdateLiveStatus = next_status
1174 .set_sse_live(worker_live)
1175 .set_last_error(desired_err);
1176 let _: bool = status_sig.set_if_changed(next_status);
1177 }
1178 return Ok(None);
1179 };
1180 match self.apply_prepared_release_with_sandbox(&candidate, &sandbox) {
1181 Ok(_) => {
1182 #[cfg(not(target_arch = "wasm32"))]
1183 let persist_err: String = if let Some(dir) = cache_dir.as_deref() {
1184 match persist_active_manifest(dir, candidate.get_manifest()) {
1185 Ok(()) => String::new(),
1186 Err(err) => err.to_string(),
1187 }
1188 } else {
1189 String::new()
1190 };
1191 #[cfg(target_arch = "wasm32")]
1192 let persist_err: String = {
1193 let _: &Option<PathBuf> = &cache_dir;
1194 String::new()
1195 };
1196 let mut next_status: HotUpdateLiveStatus = status_sig.get_untracked();
1197 let next_applied: u64 = next_status.get_applied_count().saturating_add(1);
1198 let _: &mut HotUpdateLiveStatus = next_status
1199 .set_sse_live(worker_live)
1200 .set_active_release_seq(candidate.get_manifest().get_release_seq())
1201 .set_active_manifest_sha256(candidate.get_manifest_sha256().clone())
1202 .set_applied_count(next_applied)
1203 .set_restored_from_cache(candidate.is_restored_from_cache())
1204 .set_pending_safe_boundary(false)
1205 .set_last_error(persist_err);
1206 let _: bool = status_sig.set_if_changed(next_status);
1207 Ok(Some(candidate))
1208 }
1209 Err(err) => {
1210 let mut next_status: HotUpdateLiveStatus = status_sig.get_untracked();
1211 let _: &mut HotUpdateLiveStatus = next_status
1212 .set_sse_live(worker_live)
1213 .set_pending_safe_boundary(false)
1214 .set_last_error(err.to_string());
1215 let _: bool = status_sig.set_if_changed(next_status);
1216 Err(err)
1217 }
1218 }
1219 }
1220}
1221
1222impl CandidateMailbox {
1224 #[must_use]
1235 pub fn new(capacity: usize, initial_seq: u64) -> Self {
1236 let inner: CandidateMailboxInner = CandidateMailboxInner {
1237 capacity: capacity.max(1),
1238 highest_seen_seq: initial_seq,
1239 queue: VecDeque::with_capacity(capacity.max(1)),
1240 };
1241 Self {
1242 inner: Arc::new(Mutex::new(inner)),
1243 }
1244 }
1245
1246 pub fn push_candidate(&self, candidate: PreparedReleaseCandidate) {
1252 let Self { inner } = self;
1253 if let Ok(mut guard) = inner.lock() {
1254 let incoming_seq: u64 = candidate.get_manifest().get_release_seq();
1255 if incoming_seq <= guard.highest_seen_seq {
1256 return;
1257 }
1258 guard.highest_seen_seq = incoming_seq;
1259 while guard.queue.len() >= guard.capacity {
1260 let _: Option<PreparedReleaseCandidate> = guard.queue.pop_front();
1261 }
1262 guard.queue.push_back(candidate);
1263 }
1264 }
1265
1266 #[must_use]
1272 pub fn try_recv_latest(&self) -> Option<PreparedReleaseCandidate> {
1273 let Self { inner } = self;
1274 let mut guard: MutexGuard<'_, CandidateMailboxInner> = inner.try_lock().ok()?;
1275 let mut latest: Option<PreparedReleaseCandidate> = None;
1276 while let Some(item) = guard.queue.pop_front() {
1277 latest = Some(item);
1278 }
1279 latest
1280 }
1281
1282 #[must_use]
1288 pub fn pending_count(&self) -> usize {
1289 let Self { inner } = self;
1290 inner
1291 .try_lock()
1292 .map(|green_val: MutexGuard<'_, CandidateMailboxInner>| green_val.queue.len())
1293 .unwrap_or(0)
1294 }
1295}
1296
1297impl UpdateWorkerHandle {
1299 pub fn check_update(
1310 &self,
1311 project: &str,
1312 channel: &str,
1313 ) -> Result<ReleaseManifest, DynamicReleaseError> {
1314 let Self { shared, .. } = self;
1315 let transport: HttpReleaseTransport =
1316 HttpReleaseTransport::from_client_config(&shared.config);
1317 let negotiation: ClientNegotiation = shared.config.negotiation();
1318 let manifest: ReleaseManifest = transport.fetch_manifest(project, channel, &negotiation)?;
1319 manifest.verify_signature(shared.config.get_verify_key())?;
1320 manifest.validate_for_host(
1321 shared.config.get_host_abi(),
1322 shared.config.get_capabilities(),
1323 shared.config.get_delivery_mode(),
1324 shared.config.get_max_artifact_bytes(),
1325 )?;
1326 Ok(manifest)
1327 }
1328
1329 pub fn prepare_release(
1340 &self,
1341 manifest: ReleaseManifest,
1342 snapshot: Option<NestedStateSnapshot>,
1343 ) -> Result<PreparedReleaseCandidate, DynamicReleaseError> {
1344 let Self { shared, .. } = self;
1345 let transport: HttpReleaseTransport =
1346 HttpReleaseTransport::from_client_config(&shared.config);
1347 prepare_release_with_shared(shared, &transport, manifest, snapshot)
1348 }
1349
1350 pub fn seed_verified_blobs(&self, blobs: BTreeMap<String, Vec<u8>>) {
1356 let Self { shared, .. } = self;
1357 if let Ok(mut cache) = shared.blob_cache.lock() {
1358 for (sha, bytes) in blobs.into_iter() {
1359 let _: Option<Arc<Vec<u8>>> = cache.insert(sha, Arc::new(bytes));
1360 }
1361 }
1362 }
1363
1364 pub fn submit_ui_snapshot(&self, snapshot: NestedStateSnapshot) {
1370 let Self { shared, .. } = self;
1371 if let Ok(mut slot) = shared.pending_snapshot.lock() {
1372 *slot = Some(snapshot);
1373 }
1374 }
1375
1376 #[must_use]
1382 pub fn try_take_ready_candidate(&self) -> Option<PreparedReleaseCandidate> {
1383 let Self { shared, .. } = self;
1384 shared.mailbox.try_recv_latest()
1385 }
1386
1387 #[must_use]
1393 pub fn pending_candidate_count(&self) -> usize {
1394 let Self { shared, .. } = self;
1395 shared.mailbox.pending_count()
1396 }
1397
1398 pub fn request_reconcile(&self) {
1400 let Self { shared, .. } = self;
1401 shared.reconcile_requested.store(true, Ordering::Release);
1402 }
1403
1404 #[must_use]
1410 pub fn last_event_id(&self) -> Option<String> {
1411 let Self { shared, .. } = self;
1412 shared
1413 .last_event_id
1414 .lock()
1415 .ok()
1416 .and_then(|text_value: MutexGuard<'_, Option<String>>| text_value.clone())
1417 }
1418
1419 pub fn set_last_event_id(&self, cursor: Option<String>) {
1425 let Self { shared, .. } = self;
1426 if let Ok(mut slot) = shared.last_event_id.lock() {
1427 *slot = cursor;
1428 }
1429 }
1430
1431 #[must_use]
1437 pub fn fetched_blob_hashes(&self) -> Vec<String> {
1438 let Self { shared, .. } = self;
1439 shared
1440 .fetched_hashes_log
1441 .lock()
1442 .map(|text_value: MutexGuard<'_, Vec<String>>| text_value.clone())
1443 .unwrap_or_default()
1444 }
1445
1446 #[must_use]
1452 pub fn sse_connect_count(&self) -> u64 {
1453 let Self { shared, .. } = self;
1454 shared.sse_connect_count.load(Ordering::Acquire)
1455 }
1456
1457 #[must_use]
1463 pub fn is_sse_live(&self) -> bool {
1464 let Self { shared, .. } = self;
1465 shared.sse_live.load(Ordering::Acquire)
1466 }
1467
1468 #[must_use]
1474 pub fn last_error(&self) -> Option<DynamicReleaseError> {
1475 let Self { shared, .. } = self;
1476 shared
1477 .last_error
1478 .lock()
1479 .ok()
1480 .and_then(|green_val: MutexGuard<'_, Option<DynamicReleaseError>>| green_val.clone())
1481 }
1482
1483 pub fn stop(&mut self) {
1485 let Self {
1486 shared,
1487 #[cfg(not(target_arch = "wasm32"))]
1488 worker_thread,
1489 } = self;
1490 shared.running.store(false, Ordering::Release);
1491 #[cfg(not(target_arch = "wasm32"))]
1492 if let Some(handle) = worker_thread.take() {
1493 let _: Result<(), Box<dyn Any + Send>> = handle.join();
1494 }
1495 }
1496}
1497
1498impl Drop for UpdateWorkerHandle {
1500 fn drop(&mut self) {
1502 self.stop();
1503 }
1504}
1505
1506impl DynamicReleaseRuntime {
1508 #[must_use]
1520 pub fn new(
1521 hub: DynamicUpdateHub,
1522 business_store: BusinessStateStore,
1523 sandbox_config: WasmSandboxConfig,
1524 ) -> Self {
1525 Self {
1526 hub,
1527 business_store,
1528 sandbox_config,
1529 active_release_seq: 0,
1530 generations: BTreeMap::new(),
1531 open_routes: BTreeMap::new(),
1532 restored_ui_states: BTreeMap::new(),
1533 deferred_candidate: None,
1534 next_hub_revision: 1,
1535 }
1536 }
1537
1538 #[must_use]
1544 pub fn business_store(&self) -> &BusinessStateStore {
1545 let Self { business_store, .. } = self;
1546 business_store
1547 }
1548
1549 #[must_use]
1555 pub fn active_release_seq(&self) -> u64 {
1556 let Self {
1557 active_release_seq, ..
1558 } = *self;
1559 active_release_seq
1560 }
1561
1562 #[must_use]
1568 pub fn retained_generation_count(&self) -> usize {
1569 let Self { generations, .. } = self;
1570 generations.len()
1571 }
1572
1573 #[must_use]
1579 pub fn has_deferred_candidate(&self) -> bool {
1580 let Self {
1581 deferred_candidate, ..
1582 } = self;
1583 deferred_candidate.is_some()
1584 }
1585
1586 #[must_use]
1596 pub fn restored_ui_state(&self, canonical_address: &str) -> Option<&ComponentUiStateSnapshot> {
1597 let Self {
1598 restored_ui_states, ..
1599 } = self;
1600 restored_ui_states.get(canonical_address)
1601 }
1602
1603 pub fn install_initial_release(
1615 &mut self,
1616 manifest: ReleaseManifest,
1617 blobs: &BTreeMap<String, Vec<u8>>,
1618 host_abi: u32,
1619 ) -> Result<u64, DynamicReleaseError> {
1620 let sandbox_cfg: WasmSandboxConfig = {
1621 let Self { sandbox_config, .. } = *self;
1622 sandbox_config
1623 };
1624 let mut warmed: BTreeMap<String, WarmedArtifact> = BTreeMap::new();
1625 for (art_key, artifact) in manifest.get_artifacts().iter() {
1626 let bytes: &Vec<u8> = blobs
1627 .get(artifact.get_sha256())
1628 .ok_or_else(|| DynamicReleaseError::BlobMissing(artifact.get_sha256().clone()))?;
1629 let item: WarmedArtifact =
1630 warm_verified_artifact(artifact, bytes.as_slice(), host_abi, &sandbox_cfg)?;
1631 let _: Option<WarmedArtifact> = warmed.insert(art_key.clone(), item);
1632 }
1633 let seq: u64 = manifest.get_release_seq();
1634 let generation: ReleaseGeneration = ReleaseGeneration {
1635 generation_id: seq,
1636 manifest,
1637 warmed_artifacts: warmed,
1638 active_route_pins: 0,
1639 active_in_flight_tasks: 0,
1640 };
1641 let Self {
1642 generations,
1643 active_release_seq,
1644 ..
1645 } = self;
1646 let _: Option<ReleaseGeneration> = generations.insert(seq, generation);
1647 *active_release_seq = seq;
1648 Ok(seq)
1649 }
1650
1651 pub fn open_route(
1662 &mut self,
1663 route_instance_id: &str,
1664 route: &str,
1665 ) -> Result<RoutePinHandle, DynamicReleaseError> {
1666 DynamicFrameMetrics::record_manifest_lookup();
1667 let normalized_route: String = normalize_dynamic_route(route);
1668 let target_gen_id: u64 = self.active_release_seq();
1669 if target_gen_id == 0 {
1670 return Err(DynamicReleaseError::RouteNotFound(
1671 ERR_NO_ACTIVE_GENERATION.to_string(),
1672 ));
1673 }
1674 let (entry_module, slot_bindings): (String, BTreeMap<String, String>) = {
1675 let Self { generations, .. } = self;
1676 let gen_mut: &mut ReleaseGeneration = generations
1677 .get_mut(&target_gen_id)
1678 .ok_or_else(|| DynamicReleaseError::RouteNotFound(normalized_route.clone()))?;
1679 let route_manifest: &RouteManifest = gen_mut
1680 .get_manifest()
1681 .get_routes()
1682 .get(&normalized_route)
1683 .ok_or_else(|| DynamicReleaseError::RouteNotFound(normalized_route.clone()))?;
1684 let entry: String = route_manifest.get_entry_module().clone();
1685 let slots: BTreeMap<String, String> = route_manifest.get_slot_bindings().clone();
1686 gen_mut.set_active_route_pins(gen_mut.get_active_route_pins().saturating_add(1));
1687 (entry, slots)
1688 };
1689 let handle: RoutePinHandle = RoutePinHandle {
1690 route_instance_id: route_instance_id.to_string(),
1691 route: normalized_route.clone(),
1692 generation_id: target_gen_id,
1693 entry_module,
1694 slot_bindings: slot_bindings.clone(),
1695 cancellation_token: Arc::new(AtomicBool::new(false)),
1696 };
1697 let Self { open_routes, .. } = self;
1698 let _: Option<RoutePinHandle> =
1699 open_routes.insert(route_instance_id.to_string(), handle.clone());
1700 self.apply_route_slots_to_hub(&normalized_route, target_gen_id, &slot_bindings)?;
1701 Ok(handle)
1702 }
1703
1704 pub fn close_route(&mut self, route_instance_id: &str) -> usize {
1714 let removed: Option<RoutePinHandle> = {
1715 let Self { open_routes, .. } = self;
1716 open_routes.remove(route_instance_id)
1717 };
1718 if let Some(pin) = removed {
1719 pin.get_cancellation_token().store(true, Ordering::Release);
1720 let gen_id: u64 = pin.get_generation_id();
1721 let Self { generations, .. } = self;
1722 if let Some(gen_mut) = generations.get_mut(&gen_id) {
1723 gen_mut.set_active_route_pins(gen_mut.get_active_route_pins().saturating_sub(1));
1724 }
1725 }
1726 self.gc_unreachable_generations()
1727 }
1728
1729 #[must_use]
1740 pub fn pinned_slot_artifact(&self, route_instance_id: &str, slot_key: &str) -> Option<String> {
1741 let Self { open_routes, .. } = self;
1742 open_routes
1743 .get(route_instance_id)
1744 .and_then(|pin: &RoutePinHandle| pin.get_slot_bindings().get(slot_key).cloned())
1745 }
1746
1747 #[must_use]
1757 pub fn pinned_generation_for_route(&self, route_instance_id: &str) -> Option<u64> {
1758 let Self { open_routes, .. } = self;
1759 open_routes
1760 .get(route_instance_id)
1761 .map(RoutePinHandle::get_generation_id)
1762 }
1763
1764 #[must_use]
1775 pub fn capture_nested_snapshot(
1776 &self,
1777 route: &str,
1778 ui_states: BTreeMap<String, ComponentUiStateSnapshot>,
1779 ) -> NestedStateSnapshot {
1780 let normalized: String = normalize_dynamic_route(route);
1781 let (rev, entity_snaps): (u64, BTreeMap<String, (u64, Value)>) =
1782 self.business_store().capture_entity_snapshots();
1783 let mut snap: NestedStateSnapshot =
1784 NestedStateSnapshot::new(normalized, self.active_release_seq(), rev);
1785 snap.set_entity_snapshots(entity_snaps)
1786 .set_ui_states(ui_states);
1787 snap
1788 }
1789
1790 pub fn activate_release(
1801 &mut self,
1802 candidate: PreparedReleaseCandidate,
1803 boundary: &InteractionSafePoint,
1804 ) -> Result<ActivationReport, DynamicReleaseError> {
1805 let target_seq: u64 = candidate.get_manifest().get_release_seq();
1806 if target_seq <= self.active_release_seq() {
1807 return Err(DynamicReleaseError::NonMonotonicRelease {
1808 current: self.active_release_seq(),
1809 incoming: target_seq,
1810 });
1811 }
1812 if let Some(reason) = boundary.defer_reason() {
1813 let Self {
1814 deferred_candidate,
1815 open_routes,
1816 ..
1817 } = self;
1818 *deferred_candidate = Some(candidate);
1819 let unchanged: Vec<String> = open_routes.keys().cloned().collect();
1820 return Ok(ActivationReport::new(
1821 target_seq,
1822 Vec::new(),
1823 unchanged,
1824 true,
1825 reason.to_string(),
1826 0,
1827 0,
1828 ));
1829 }
1830 let mut caught_up_deltas: usize = 0;
1831 for (entity_id, base_rev) in candidate.get_snapshot_entity_revisions().iter() {
1832 let deltas: Vec<BusinessStateDelta> =
1833 self.business_store().deltas_since(entity_id, *base_rev)?;
1834 caught_up_deltas = caught_up_deltas.saturating_add(deltas.len());
1835 }
1836 let prev_manifest: Option<ReleaseManifest> = {
1837 let Self {
1838 generations,
1839 active_release_seq,
1840 ..
1841 } = self;
1842 generations
1843 .get(active_release_seq)
1844 .map(|green_val: &ReleaseGeneration| green_val.get_manifest().clone())
1845 };
1846 let authoritative_affected: Vec<String> = candidate
1847 .get_manifest()
1848 .affected_routes_since(prev_manifest.as_ref());
1849 let new_generation: ReleaseGeneration = ReleaseGeneration {
1850 generation_id: target_seq,
1851 manifest: candidate.get_manifest().clone(),
1852 warmed_artifacts: candidate.get_warmed_artifacts().clone(),
1853 active_route_pins: 0,
1854 active_in_flight_tasks: 0,
1855 };
1856 {
1857 let Self {
1858 generations,
1859 active_release_seq,
1860 restored_ui_states,
1861 deferred_candidate,
1862 ..
1863 } = self;
1864 let _: Option<ReleaseGeneration> = generations.insert(target_seq, new_generation);
1865 *active_release_seq = target_seq;
1866 for (addr, ui_state) in candidate.get_migrated_ui_states().iter() {
1867 let _: Option<ComponentUiStateSnapshot> =
1868 restored_ui_states.insert(addr.clone(), ui_state.clone());
1869 }
1870 *deferred_candidate = None;
1871 }
1872 let mut swapped_routes: Vec<String> = Vec::new();
1873 let mut unchanged_pinned_routes: Vec<String> = Vec::new();
1874 let mut hub_updates: Vec<(String, BTreeMap<String, String>)> = Vec::new();
1875 let mut released_gens: Vec<u64> = Vec::new();
1876 {
1877 let Self {
1878 open_routes,
1879 generations,
1880 ..
1881 } = self;
1882 for (instance_id, pin) in open_routes.iter_mut() {
1883 let route_path: String = pin.get_route().clone();
1884 if authoritative_affected.contains(&route_path)
1885 && let Some(next_route_manifest) =
1886 candidate.get_manifest().get_routes().get(&route_path)
1887 {
1888 let old_gen_id: u64 = pin.get_generation_id();
1889 if let Some(old_gen) = generations.get_mut(&old_gen_id) {
1890 old_gen.set_active_route_pins(
1891 old_gen.get_active_route_pins().saturating_sub(1),
1892 );
1893 if old_gen.get_active_route_pins() == 0 {
1894 released_gens.push(old_gen_id);
1895 }
1896 }
1897 if let Some(new_gen) = generations.get_mut(&target_seq) {
1898 new_gen.set_active_route_pins(
1899 new_gen.get_active_route_pins().saturating_add(1),
1900 );
1901 }
1902 pin.get_cancellation_token().store(true, Ordering::Release);
1903 pin.set_generation_id(target_seq)
1904 .set_entry_module(next_route_manifest.get_entry_module().clone())
1905 .set_slot_bindings(next_route_manifest.get_slot_bindings().clone())
1906 .set_cancellation_token(Arc::new(AtomicBool::new(false)));
1907 swapped_routes.push(instance_id.clone());
1908 hub_updates.push((route_path, next_route_manifest.get_slot_bindings().clone()));
1909 } else {
1910 unchanged_pinned_routes.push(instance_id.clone());
1911 }
1912 }
1913 }
1914 for old_gen_id in released_gens.into_iter() {
1915 self.business_store()
1916 .cancel_generation_subscriptions(old_gen_id);
1917 }
1918 for (route_path, slot_bindings) in hub_updates.into_iter() {
1919 self.apply_route_slots_to_hub(&route_path, target_seq, &slot_bindings)?;
1920 }
1921 let gc_reclaimed: usize = self.gc_unreachable_generations();
1922 Ok(ActivationReport::new(
1923 target_seq,
1924 swapped_routes,
1925 unchanged_pinned_routes,
1926 false,
1927 String::new(),
1928 caught_up_deltas,
1929 gc_reclaimed,
1930 ))
1931 }
1932
1933 pub fn poll_mailbox_and_activate(
1944 &mut self,
1945 worker: &UpdateWorkerHandle,
1946 boundary: &InteractionSafePoint,
1947 ) -> Result<Option<ActivationReport>, DynamicReleaseError> {
1948 let incoming: Option<PreparedReleaseCandidate> = worker.try_take_ready_candidate();
1949 let next_candidate: Option<PreparedReleaseCandidate> = match incoming {
1950 Some(fresh) => Some(fresh),
1951 None => {
1952 let Self {
1953 deferred_candidate, ..
1954 } = self;
1955 deferred_candidate.take()
1956 }
1957 };
1958 let Some(candidate) = next_candidate else {
1959 return Ok(None);
1960 };
1961 let report: ActivationReport = self.activate_release(candidate, boundary)?;
1962 Ok(Some(report))
1963 }
1964
1965 pub fn dispatch_cross_route_action(
1977 &mut self,
1978 action: &CrossRouteAction,
1979 allowed_actions: &[String],
1980 target_instance_id: &str,
1981 ) -> Result<RoutePinHandle, DynamicReleaseError> {
1982 if action.get_cancellation_token().load(Ordering::Acquire) {
1983 return Err(DynamicReleaseError::UnsafeSwapPoint(
1984 ERR_ACTION_CANCELLED.to_string(),
1985 ));
1986 }
1987 if !allowed_actions
1988 .iter()
1989 .any(|text_value: &String| text_value == action.get_action_id())
1990 {
1991 return Err(DynamicReleaseError::MissingCapability(format!(
1992 "{ERR_ACTION_DENIED}: {}",
1993 action.get_action_id()
1994 )));
1995 }
1996 self.open_route(target_instance_id, action.get_target_route())
1997 }
1998
1999 pub fn gc_unreachable_generations(&mut self) -> usize {
2005 let Self {
2006 active_release_seq,
2007 generations,
2008 ..
2009 } = self;
2010 let active_seq: u64 = *active_release_seq;
2011 let to_remove: Vec<u64> = generations
2012 .iter()
2013 .filter(|(gid, gen_rec): &(&u64, &ReleaseGeneration)| {
2014 **gid != active_seq
2015 && gen_rec.get_active_route_pins() == 0
2016 && gen_rec.get_active_in_flight_tasks() == 0
2017 })
2018 .map(|(gid, _): (&u64, &ReleaseGeneration)| *gid)
2019 .collect();
2020 let removed_count: usize = to_remove.len();
2021 for gid in to_remove.into_iter() {
2022 let _: Option<ReleaseGeneration> = generations.remove(&gid);
2023 }
2024 removed_count
2025 }
2026
2027 fn apply_route_slots_to_hub(
2039 &mut self,
2040 route: &str,
2041 generation_id: u64,
2042 slot_bindings: &BTreeMap<String, String>,
2043 ) -> Result<(), DynamicReleaseError> {
2044 let mut specs_to_apply: Vec<(String, DynamicNodeSpec)> =
2045 Vec::with_capacity(slot_bindings.len());
2046 {
2047 let Self {
2048 generations,
2049 sandbox_config,
2050 ..
2051 } = self;
2052 let gen_rec: &ReleaseGeneration = generations
2053 .get(&generation_id)
2054 .ok_or_else(|| DynamicReleaseError::RouteNotFound(route.to_string()))?;
2055 for (slot_key, artifact_key) in slot_bindings.iter() {
2056 let Some(warmed) = gen_rec.get_warmed_artifacts().get(artifact_key) else {
2057 return Err(DynamicReleaseError::BrokenDependencyClosure(format!(
2058 "{ERR_MISSING_SLOT_ARTIFACT}: {artifact_key}"
2059 )));
2060 };
2061 let scoped_slot_id: String =
2062 SlotKey::from_str_key(slot_key).scoped_for_route(route);
2063 let spec: DynamicNodeSpec = match warmed {
2064 WarmedArtifact::Wasm(parsed) => {
2065 DynamicFrameMetrics::record_module_call();
2066 let entry: &str = gen_rec
2067 .get_manifest()
2068 .get_artifacts()
2069 .get(artifact_key)
2070 .map(|alpha_val: &BlobArtifact| {
2071 if alpha_val.get_entrypoint().is_empty() {
2072 WASM_EXPORT_RENDER
2073 } else {
2074 alpha_val.get_entrypoint().as_str()
2075 }
2076 })
2077 .unwrap_or(WASM_EXPORT_RENDER);
2078 let exec_out: WasmExecutionOutput =
2079 execute_wasm_export(parsed, entry, &[0], sandbox_config).map_err(
2080 |err: WasmDynamicError| {
2081 DynamicReleaseError::StorageError(err.to_string())
2082 },
2083 )?;
2084 DynamicFrameMetrics::record_serialization();
2085 exec_out.emitted_spec().cloned().ok_or_else(|| {
2086 DynamicReleaseError::StorageError(ERR_DECLARATIVE_JSON.to_string())
2087 })?
2088 }
2089 WarmedArtifact::Declarative(spec) => {
2090 DynamicFrameMetrics::record_module_call();
2091 spec.clone()
2092 }
2093 WarmedArtifact::Asset(_) => continue,
2094 };
2095 specs_to_apply.push((scoped_slot_id, spec));
2096 }
2097 }
2098 let Self {
2099 hub,
2100 next_hub_revision,
2101 ..
2102 } = self;
2103 for (scoped_slot_id, spec) in specs_to_apply.into_iter() {
2104 let rev: u64 = *next_hub_revision;
2105 *next_hub_revision = next_hub_revision.saturating_add(1);
2106 let mut upd: DynamicComponentUpdate =
2107 DynamicComponentUpdate::new(scoped_slot_id, rev, spec);
2108 upd.set_allow_downgrade(true);
2109 upd.sign();
2110 let _: u64 = hub
2111 .apply_component(upd)
2112 .map_err(|err: DynamicUpdateError| {
2113 DynamicReleaseError::StorageError(err.to_string())
2114 })?;
2115 }
2116 Ok(())
2117 }
2118}