Skip to main content

euv_core/dynamic/engine/
impl.rs

1use super::*;
2
3/// Production defaults for `HotUpdateProxyConfig`.
4impl Default for HotUpdateProxyConfig {
5    /// Returns default local hot-update server and direct connection settings.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default hot-update proxy configuration.
10    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
23/// Construction, proxy helpers, and client conversion on `HotUpdateProxyConfig`.
24impl HotUpdateProxyConfig {
25    /// Constructs a `HotUpdateProxyConfig` with explicit server, proxy, channel, and polling policy.
26    ///
27    /// # Arguments
28    ///
29    /// - `String` - Target update server base URL (direct or reverse-proxy prefix).
30    /// - `Option<String>` - Optional explicit HTTP forward proxy URL.
31    /// - `Option<String>` - Optional `Proxy-Authorization` credential string.
32    /// - `String` - Target release channel name.
33    /// - `bool` - Whether verified updates apply automatically.
34    /// - `u64` - Fallback manifest polling cadence in seconds.
35    ///
36    /// # Returns
37    ///
38    /// - `Self` - Configured hot-update proxy settings.
39    #[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    /// Attaches an optional persistent on-device disk cache directory for verified blobs and manifests.
76    ///
77    /// # Arguments
78    ///
79    /// - `Self` - Source proxy configuration.
80    /// - `Option<PathBuf>` - Optional persistent cache directory path.
81    ///
82    /// # Returns
83    ///
84    /// - `Self` - Updated proxy configuration.
85    #[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    /// Returns the optional persistent on-device cache directory path.
92    ///
93    /// # Arguments
94    ///
95    /// - `&Self` - Proxy configuration reference.
96    ///
97    /// # Returns
98    ///
99    /// - `Option<&Path>` - Configured cache directory path when set.
100    #[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    /// Returns the optional configured HTTP forward proxy URL.
107    ///
108    /// # Arguments
109    ///
110    /// - `&Self` - Proxy configuration reference.
111    ///
112    /// # Returns
113    ///
114    /// - `Option<&str>` - Forward proxy URL when configured.
115    #[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    /// Returns the optional configured `Proxy-Authorization` credential string.
122    ///
123    /// # Arguments
124    ///
125    /// - `&Self` - Proxy configuration reference.
126    ///
127    /// # Returns
128    ///
129    /// - `Option<&str>` - Proxy credential string when configured.
130    #[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    /// Resolves the effective base URL for Web `fetch` / `EventSource` clients (preferring a reverse-proxy base when provided).
137    ///
138    /// # Arguments
139    ///
140    /// - `&Self` - Proxy configuration reference.
141    ///
142    /// # Returns
143    ///
144    /// - `String` - Normalized browser-reachable base URL without trailing slash.
145    #[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    /// Resolves the canonical `DeliveryChannelMode` permitted on `platform` (`DeclarativeData` on JIT/Wasm-restricted containers, `WasmComponent` elsewhere).
160    ///
161    /// # Arguments
162    ///
163    /// - `PlatformKind` - Target execution platform.
164    ///
165    /// # Returns
166    ///
167    /// - `DeliveryChannelMode` - Default channel delivery mode for `platform`.
168    #[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    /// Builds normalized capability tags advertised during manifest negotiation for `platform`.
189    ///
190    /// # Arguments
191    ///
192    /// - `PlatformKind` - Target execution platform.
193    ///
194    /// # Returns
195    ///
196    /// - `Vec<String>` - Capability tag list for `ClientNegotiation`.
197    #[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    /// Converts this `HotUpdateProxyConfig` into an `UpdateClientConfig` ready for `start_updates`.
214    ///
215    /// # Arguments
216    ///
217    /// - `&Self` - Proxy configuration reference.
218    /// - `String` - Logical project identifier.
219    /// - `Vec<u8>` - Trusted HMAC-SHA256 manifest verification key bytes.
220    ///
221    /// # Returns
222    ///
223    /// - `UpdateClientConfig` - Ready background worker client configuration.
224    #[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    /// Converts this `HotUpdateProxyConfig` into a platform-tailored `UpdateClientConfig` negotiating the platform's delivery mode, track, capabilities, and proxy credentials.
245    ///
246    /// # Arguments
247    ///
248    /// - `PlatformKind` - Target execution platform.
249    /// - `String` - Logical project identifier.
250    /// - `Vec<u8>` - Trusted HMAC-SHA256 manifest verification key bytes.
251    ///
252    /// # Returns
253    ///
254    /// - `UpdateClientConfig` - Platform-configured hot-update client settings.
255    #[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
273/// Safe defaults and builder helpers on `UpdateClientConfig`.
274impl UpdateClientConfig {
275    /// Creates a production-configured `UpdateClientConfig` with default ABI, WasmComponent mode, and budgets.
276    ///
277    /// # Arguments
278    ///
279    /// - `String` - Base HTTP server URL.
280    /// - `String` - Project identifier.
281    /// - `String` - Channel name.
282    /// - `Vec<u8>` - Trusted HMAC-SHA256 verification key.
283    ///
284    /// # Returns
285    ///
286    /// - `Self` - Configured update client settings.
287    #[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    /// Returns the optional preferred compatibility track name.
307    ///
308    /// # Returns
309    ///
310    /// - `Option<&str>` - Preferred track if set.
311    #[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    /// Returns the optional explicit HTTP forward proxy URL.
320    ///
321    /// # Arguments
322    ///
323    /// - `&Self` - Client configuration reference.
324    ///
325    /// # Returns
326    ///
327    /// - `Option<&str>` - Forward proxy URL when configured.
328    #[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    /// Returns the optional forward-proxy `Proxy-Authorization` credential string.
335    ///
336    /// # Arguments
337    ///
338    /// - `&Self` - Client configuration reference.
339    ///
340    /// # Returns
341    ///
342    /// - `Option<&str>` - Proxy credential string when configured.
343    #[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    /// Attaches an explicit HTTP forward proxy URL and optional credential string to this client configuration.
350    ///
351    /// # Arguments
352    ///
353    /// - `Self` - Source client configuration.
354    /// - `Option<String>` - Optional HTTP forward proxy URL (`http://proxy:port`).
355    /// - `Option<String>` - Optional `Proxy-Authorization` credential string.
356    ///
357    /// # Returns
358    ///
359    /// - `Self` - Updated client configuration.
360    #[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    /// Attaches an optional persistent on-device cache directory for verified OTA blobs and manifests.
368    ///
369    /// # Arguments
370    ///
371    /// - `Self` - Source client configuration.
372    /// - `Option<PathBuf>` - Optional cache directory path.
373    ///
374    /// # Returns
375    ///
376    /// - `Self` - Updated client configuration.
377    #[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    /// Returns the optional persistent on-device cache directory path.
384    ///
385    /// # Arguments
386    ///
387    /// - `&Self` - Client configuration reference.
388    ///
389    /// # Returns
390    ///
391    /// - `Option<&Path>` - Configured cache directory path when set.
392    #[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    /// Builds a `ClientNegotiation` descriptor from this client configuration.
399    ///
400    /// # Returns
401    ///
402    /// - `ClientNegotiation` - Protocol, ABI, delivery mode, and capability declaration.
403    #[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
418/// Proxy accessor helpers on `HttpReleaseTransport`.
419impl HttpReleaseTransport {
420    /// Builds an `HttpReleaseTransport` inheriting base URL, timeout, forward proxy URL, and proxy credentials from `config`.
421    ///
422    /// # Arguments
423    ///
424    /// - `&UpdateClientConfig` - Source update client configuration.
425    ///
426    /// # Returns
427    ///
428    /// - `Self` - Proxy-configured HTTP release transport.
429    #[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    /// Returns the optional explicit HTTP forward proxy URL.
443    ///
444    /// # Arguments
445    ///
446    /// - `&Self` - Transport reference.
447    ///
448    /// # Returns
449    ///
450    /// - `Option<&str>` - Forward proxy URL when configured.
451    #[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    /// Returns the optional `Proxy-Authorization` credential string.
458    ///
459    /// # Arguments
460    ///
461    /// - `&Self` - Transport reference.
462    ///
463    /// # Returns
464    ///
465    /// - `Option<&str>` - Proxy credential string when configured.
466    #[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
473/// Real pure-std HTTP/1.1 manifest and range-resumable blob fetching on `HttpReleaseTransport`.
474impl ReleaseTransport for HttpReleaseTransport {
475    /// Fetches a signed `ReleaseManifest` from `/v1/projects/{project}/channels/{channel}/manifest`.
476    ///
477    /// # Arguments
478    ///
479    /// - `&str` - Project identifier.
480    /// - `&str` - Channel name.
481    /// - `&ClientNegotiation` - Protocol, ABI, delivery mode, and track negotiation parameters.
482    ///
483    /// # Returns
484    ///
485    /// - `Result<ReleaseManifest, DynamicReleaseError>` - Deserialized manifest or typed error.
486    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    /// Fetches immutable content-addressed blob bytes from `/v1/blobs/{sha256}` with optional byte-range resume.
551    ///
552    /// # Arguments
553    ///
554    /// - `&str` - Lowercase 64-character SHA-256 digest.
555    /// - `u64` - Starting byte offset (`0` for full download).
556    ///
557    /// # Returns
558    ///
559    /// - `Result<Vec<u8>, DynamicReleaseError>` - Downloaded bytes from `range_start` to EOF.
560    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
604/// Inspection helpers on `PreparedReleaseCandidate`.
605impl PreparedReleaseCandidate {
606    /// Returns `true` when this candidate was restored offline from the persistent on-device release cache.
607    ///
608    /// # Arguments
609    ///
610    /// - `&Self` - Candidate reference.
611    ///
612    /// # Returns
613    ///
614    /// - `bool` - `true` for offline cache restores, `false` for live network preparations.
615    #[must_use]
616    pub fn is_restored_from_cache(&self) -> bool {
617        self.get_prepared_on_thread() == UPDATE_CACHE_RESTORE_SOURCE
618    }
619}
620
621/// Atomic release-candidate application and live hot-update worker orchestration on `DynamicUpdateHub`.
622impl DynamicUpdateHub {
623    /// Atomically applies all declarative and WASM page/component artifacts from a verified `PreparedReleaseCandidate` using default sandbox limits.
624    ///
625    /// # Arguments
626    ///
627    /// - `&Self` - Target live dynamic update hub.
628    /// - `&PreparedReleaseCandidate` - Verified, pre-warmed release candidate from `UpdateWorkerHandle`.
629    ///
630    /// # Returns
631    ///
632    /// - `Result<usize, DynamicReleaseError>` - Number of pages and component slots atomically swapped.
633    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    /// Atomically applies all declarative and WASM page/component artifacts from a verified `PreparedReleaseCandidate` under `sandbox_config`.
641    ///
642    /// # Arguments
643    ///
644    /// - `&Self` - Target live dynamic update hub.
645    /// - `&PreparedReleaseCandidate` - Verified, pre-warmed release candidate.
646    /// - `&WasmSandboxConfig` - Sandbox fuel and memory limits applied to warmed WASM modules.
647    ///
648    /// # Returns
649    ///
650    /// - `Result<usize, DynamicReleaseError>` - Number of pages and component slots atomically swapped.
651    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    /// Drains the newest verified release candidate from `worker` without blocking and atomically applies it into `DynamicUpdateHub`.
819    ///
820    /// # Arguments
821    ///
822    /// - `&Self` - Target live dynamic update hub.
823    /// - `&UpdateWorkerHandle` - Active background hot-update worker handle.
824    ///
825    /// # Returns
826    ///
827    /// - `Result<Option<PreparedReleaseCandidate>, DynamicReleaseError>` - Applied candidate when a new release was ready, or `None`.
828    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    /// Returns `true` when the lock-free hot-update attention flag indicates a queued candidate or state change.
840    ///
841    /// Executes as a single `AtomicBool::load` with zero `RefCell` borrows, zero mutex locks, and zero allocations.
842    ///
843    /// # Returns
844    ///
845    /// - `bool` - `true` only when `poll_hot_updates_at_safe_boundary` has work to drain.
846    #[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    /// Returns the reactive `Signal<HotUpdateLiveStatus>` tracking live OTA connection state, active release sequence, and diagnostics.
857    ///
858    /// # Arguments
859    ///
860    /// - `&Self` - Hub reference.
861    ///
862    /// # Returns
863    ///
864    /// - `Signal<HotUpdateLiveStatus>` - Live hot-update status signal.
865    #[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    /// Replaces the published `HotUpdateLiveStatus` snapshot (used by both native worker polling and `wasm32` browser `EventSource` transport).
875    ///
876    /// # Arguments
877    ///
878    /// - `&Self` - Hub reference.
879    /// - `HotUpdateLiveStatus` - Updated live status snapshot.
880    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    /// Returns `true` when a live background worker or browser `EventSource` hot-update session is currently connected.
895    ///
896    /// # Arguments
897    ///
898    /// - `&Self` - Hub reference.
899    ///
900    /// # Returns
901    ///
902    /// - `bool` - Whether live hot updates are connected.
903    #[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    /// Returns `true` when a prepared or safe-boundary-deferred hot-update candidate is waiting to be applied.
913    ///
914    /// # Arguments
915    ///
916    /// - `&Self` - Hub reference.
917    ///
918    /// # Returns
919    ///
920    /// - `bool` - Whether at least one verified candidate is queued.
921    #[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    /// Restores and atomically applies any verified cached release persisted under `config.cache_dir` (offline cold-start recovery).
939    ///
940    /// # Arguments
941    ///
942    /// - `&Self` - Target live dynamic update hub.
943    /// - `&UpdateClientConfig` - Client verification key, ABI, delivery mode, and `cache_dir`.
944    ///
945    /// # Returns
946    ///
947    /// - `Result<Option<PreparedReleaseCandidate>, DynamicReleaseError>` - Applied cached release when present, or `None`.
948    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    /// Starts (or reconnects) the hub-managed background `UpdateWorker` so `App::step_frame()` automatically applies incoming verified OTA releases.
981    ///
982    /// # Arguments
983    ///
984    /// - `&Self` - Hub reference.
985    /// - `UpdateClientConfig` - Server, proxy, verification key, delivery mode, sandbox, and cache settings.
986    ///
987    /// # Returns
988    ///
989    /// - `Result<(), DynamicReleaseError>` - `Ok(())` when the background worker started cleanly.
990    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    /// Stops any active hub-managed hot-update worker and clears deferred candidates cleanly.
1036    ///
1037    /// # Arguments
1038    ///
1039    /// - `&Self` - Hub reference.
1040    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    /// Requests an immediate manifest reconciliation on the hub-managed background hot-update worker.
1067    ///
1068    /// # Arguments
1069    ///
1070    /// - `&Self` - Hub reference.
1071    ///
1072    /// # Returns
1073    ///
1074    /// - `bool` - `true` when an active worker received the reconcile request.
1075    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    /// Non-blockingly drains the hub-managed hot-update mailbox (or a previously deferred candidate) and applies it atomically when `boundary` is safe.
1087    ///
1088    /// # Arguments
1089    ///
1090    /// - `&Self` - Hub reference.
1091    /// - `&InteractionSafePoint` - Current frame-boundary safety probe.
1092    ///
1093    /// # Returns
1094    ///
1095    /// - `Result<Option<PreparedReleaseCandidate>, DynamicReleaseError>` - Applied candidate when swapped on this frame, or `None` when idle/deferred.
1096    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
1222/// Bounded non-blocking mailbox operations on `CandidateMailbox`.
1223impl CandidateMailbox {
1224    /// Creates a bounded `CandidateMailbox` rejecting any candidate older than or equal to `initial_seq`.
1225    ///
1226    /// # Arguments
1227    ///
1228    /// - `usize` - Maximum number of buffered prepared candidates.
1229    /// - `u64` - Initial active release sequence baseline.
1230    ///
1231    /// # Returns
1232    ///
1233    /// - `Self` - Initialized mailbox.
1234    #[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    /// Pushes a prepared candidate into the mailbox, discarding stale releases and coalescing when full.
1247    ///
1248    /// # Arguments
1249    ///
1250    /// - `PreparedReleaseCandidate` - Verified, warmed candidate from `UpdateWorker`.
1251    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    /// Non-blockingly drains the mailbox on the UI thread and returns only the newest prepared candidate.
1267    ///
1268    /// # Returns
1269    ///
1270    /// - `Option<PreparedReleaseCandidate>` - Latest ready candidate, or `None` if empty or contended.
1271    #[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    /// Returns the number of candidates currently waiting in the mailbox without blocking.
1283    ///
1284    /// # Returns
1285    ///
1286    /// - `usize` - Pending candidate count.
1287    #[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
1297/// Control and entrypoints on `UpdateWorkerHandle` (Sec 11.2 / 11.8).
1298impl UpdateWorkerHandle {
1299    /// Checks and fetches the latest compatible signed manifest for `(project, channel)` (Sec 11.2).
1300    ///
1301    /// # Arguments
1302    ///
1303    /// - `&str` - Logical project identifier.
1304    /// - `&str` - Channel name.
1305    ///
1306    /// # Returns
1307    ///
1308    /// - `Result<ReleaseManifest, DynamicReleaseError>` - Verified signed manifest or error.
1309    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    /// Prepares a release candidate using the worker's verified cache, incremental hash diff, and pure migrator (Sec 11.2).
1330    ///
1331    /// # Arguments
1332    ///
1333    /// - `ReleaseManifest` - Signed target release manifest.
1334    /// - `Option<NestedStateSnapshot>` - Optional captured route UI state snapshot at revision `R`.
1335    ///
1336    /// # Returns
1337    ///
1338    /// - `Result<PreparedReleaseCandidate, DynamicReleaseError>` - Ready candidate or typed error.
1339    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    /// Seeds verified content-addressed blobs into the worker's local cache (for built-in/offline startup).
1351    ///
1352    /// # Arguments
1353    ///
1354    /// - `BTreeMap<String, Vec<u8>>` - Map of SHA-256 hex digest to verified blob bytes.
1355    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    /// Queues a captured route `NestedStateSnapshot` so the next background preparation migrates it off the UI thread.
1365    ///
1366    /// # Arguments
1367    ///
1368    /// - `NestedStateSnapshot` - Immutable snapshot captured at revision `R`.
1369    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    /// Non-blockingly polls the bounded candidate mailbox from the UI thread.
1377    ///
1378    /// # Returns
1379    ///
1380    /// - `Option<PreparedReleaseCandidate>` - Latest prepared candidate ready for frame-boundary swap.
1381    #[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    /// Returns the number of prepared release candidates currently queued in the non-blocking mailbox.
1388    ///
1389    /// # Returns
1390    ///
1391    /// - `usize` - Number of buffered ready candidates.
1392    #[must_use]
1393    pub fn pending_candidate_count(&self) -> usize {
1394        let Self { shared, .. } = self;
1395        shared.mailbox.pending_count()
1396    }
1397
1398    /// Requests an immediate manifest reconciliation on the background worker (e.g. on foreground resume).
1399    pub fn request_reconcile(&self) {
1400        let Self { shared, .. } = self;
1401        shared.reconcile_requested.store(true, Ordering::Release);
1402    }
1403
1404    /// Returns the latest `Last-Event-ID` cursor accepted by the background SSE client.
1405    ///
1406    /// # Returns
1407    ///
1408    /// - `Option<String>` - Active `Last-Event-ID` cursor string.
1409    #[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    /// Overrides the `Last-Event-ID` cursor (e.g. when restoring persisted resume state across restarts).
1420    ///
1421    /// # Arguments
1422    ///
1423    /// - `Option<String>` - Cursor string to send on the next SSE connection.
1424    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    /// Returns the chronological log of SHA-256 digests actually downloaded over HTTP by this worker.
1432    ///
1433    /// # Returns
1434    ///
1435    /// - `Vec<String>` - Downloaded blob SHA-256 digests.
1436    #[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    /// Returns the number of established SSE sessions (incremented on initial connect and reconnects).
1447    ///
1448    /// # Returns
1449    ///
1450    /// - `u64` - Total SSE connect count.
1451    #[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    /// Returns `true` while the background SSE stream holds an established HTTP 200 session.
1458    ///
1459    /// # Returns
1460    ///
1461    /// - `bool` - Whether SSE is currently connected live.
1462    #[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    /// Returns the most recent background error recorded without interrupting the live UI.
1469    ///
1470    /// # Returns
1471    ///
1472    /// - `Option<DynamicReleaseError>` - Last recorded error if any.
1473    #[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    /// Signals the dedicated background `UpdateWorker` thread to stop and joins it cleanly.
1484    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
1498/// Automatic worker shutdown when `UpdateWorkerHandle` is dropped.
1499impl Drop for UpdateWorkerHandle {
1500    /// Stops and joins the background worker thread on drop.
1501    fn drop(&mut self) {
1502        self.stop();
1503    }
1504}
1505
1506/// Core per-route pinning, safe-point swapping, rollback, and GC orchestration on `DynamicReleaseRuntime`.
1507impl DynamicReleaseRuntime {
1508    /// Creates a new `DynamicReleaseRuntime` bound to `hub` and `business_store`.
1509    ///
1510    /// # Arguments
1511    ///
1512    /// - `DynamicUpdateHub` - Live UI dynamic update hub.
1513    /// - `BusinessStateStore` - Host-owned authoritative business state store.
1514    /// - `WasmSandboxConfig` - Sandbox limits applied when mounting dynamic Wasm modules.
1515    ///
1516    /// # Returns
1517    ///
1518    /// - `Self` - Initialized dynamic release runtime.
1519    #[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    /// Returns a reference to the host-owned `BusinessStateStore`.
1539    ///
1540    /// # Returns
1541    ///
1542    /// - `&BusinessStateStore` - Shared authoritative business state store.
1543    #[must_use]
1544    pub fn business_store(&self) -> &BusinessStateStore {
1545        let Self { business_store, .. } = self;
1546        business_store
1547    }
1548
1549    /// Returns the currently active release sequence number (`0` before initial install).
1550    ///
1551    /// # Returns
1552    ///
1553    /// - `u64` - Active release sequence.
1554    #[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    /// Returns the number of release generations currently retained in memory.
1563    ///
1564    /// # Returns
1565    ///
1566    /// - `usize` - Count of retained `ReleaseGeneration` records.
1567    #[must_use]
1568    pub fn retained_generation_count(&self) -> usize {
1569        let Self { generations, .. } = self;
1570        generations.len()
1571    }
1572
1573    /// Returns whether a candidate is currently deferred awaiting a safe frame boundary.
1574    ///
1575    /// # Returns
1576    ///
1577    /// - `bool` - `true` when a deferred candidate is pending.
1578    #[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    /// Returns the restored UI state snapshot for a canonical `StableAddress`, if any.
1587    ///
1588    /// # Arguments
1589    ///
1590    /// - `&str` - Canonical `StableAddress` string.
1591    ///
1592    /// # Returns
1593    ///
1594    /// - `Option<&ComponentUiStateSnapshot>` - Restored UI state snapshot.
1595    #[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    /// Installs an initial built-in or cached signed release generation synchronously at startup.
1604    ///
1605    /// # Arguments
1606    ///
1607    /// - `ReleaseManifest` - Verified initial manifest (e.g. generation `101`).
1608    /// - `&BTreeMap<String, Vec<u8>>` - Raw verified blob bytes keyed by SHA-256 hex digest.
1609    /// - `u32` - Running host ABI version.
1610    ///
1611    /// # Returns
1612    ///
1613    /// - `Result<u64, DynamicReleaseError>` - Installed generation sequence number.
1614    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    /// Opens a route instance pinned to the currently active release generation and mounts its slots into `DynamicUpdateHub`.
1652    ///
1653    /// # Arguments
1654    ///
1655    /// - `&str` - Stable route instance key (e.g. `"A#tab-1"` or `"B#tab-1"`).
1656    /// - `&str` - Route path (e.g. `"/route-a"` or `"/route-b"`).
1657    ///
1658    /// # Returns
1659    ///
1660    /// - `Result<RoutePinHandle, DynamicReleaseError>` - Pinned route handle.
1661    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    /// Closes an open route instance, cancels its token, decrements its generation pin, and runs GC.
1705    ///
1706    /// # Arguments
1707    ///
1708    /// - `&str` - Route instance identifier to close.
1709    ///
1710    /// # Returns
1711    ///
1712    /// - `usize` - Number of unreachable old generations reclaimed by GC.
1713    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    /// Returns the currently pinned artifact key (`"card@1.0.0"`) for `slot_key` on an open route instance.
1730    ///
1731    /// # Arguments
1732    ///
1733    /// - `&str` - Open route instance identifier.
1734    /// - `&str` - Logical slot key.
1735    ///
1736    /// # Returns
1737    ///
1738    /// - `Option<String>` - Exact pinned artifact key if the route and slot exist.
1739    #[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    /// Returns the currently pinned release generation ID for an open route instance.
1748    ///
1749    /// # Arguments
1750    ///
1751    /// - `&str` - Open route instance identifier.
1752    ///
1753    /// # Returns
1754    ///
1755    /// - `Option<u64>` - Pinned release generation ID.
1756    #[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    /// Captures a `NestedStateSnapshot` at the current authoritative business revision `R` for `route`.
1765    ///
1766    /// # Arguments
1767    ///
1768    /// - `&str` - Target route path.
1769    /// - `BTreeMap<String, ComponentUiStateSnapshot>` - Live per-instance UI states keyed by canonical `StableAddress`.
1770    ///
1771    /// # Returns
1772    ///
1773    /// - `NestedStateSnapshot` - Immutable snapshot ready to pass to the background worker.
1774    #[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    /// Atomically activates a prepared candidate at a safe frame boundary, swapping ONLY affected routes while keeping unaffected routes pinned (Sec 11.2, 11.4, 11.6, 11.8).
1791    ///
1792    /// # Arguments
1793    ///
1794    /// - `PreparedReleaseCandidate` - Candidate prepared off the UI thread.
1795    /// - `&InteractionSafePoint` - Current frame-boundary safety probe.
1796    ///
1797    /// # Returns
1798    ///
1799    /// - `Result<ActivationReport, DynamicReleaseError>` - Activation or deferral report.
1800    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    /// Non-blockingly polls `worker` (or a previously deferred candidate) and activates at a safe frame boundary.
1934    ///
1935    /// # Arguments
1936    ///
1937    /// - `&UpdateWorkerHandle` - Running background update worker handle.
1938    /// - `&InteractionSafePoint` - Current frame-boundary safety probe.
1939    ///
1940    /// # Returns
1941    ///
1942    /// - `Result<Option<ActivationReport>, DynamicReleaseError>` - Report when a candidate was evaluated, or `None` when idle.
1943    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    /// Dispatches a host-validated cross-route action, opening the target route pinned to its OWN dependency graph (Sec 11.2).
1966    ///
1967    /// # Arguments
1968    ///
1969    /// - `&CrossRouteAction` - Action carrying target route, action ID, origin generation, and cancellation token.
1970    /// - `&[String]` - Permitted host action IDs.
1971    /// - `&str` - Stable instance identifier for the opened target route.
1972    ///
1973    /// # Returns
1974    ///
1975    /// - `Result<RoutePinHandle, DynamicReleaseError>` - Target route's independent pinned handle.
1976    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    /// Reclaims old release generations that are no longer active and have zero open route pins or in-flight tasks.
2000    ///
2001    /// # Returns
2002    ///
2003    /// - `usize` - Number of reclaimed generations.
2004    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    /// Applies a route's bound slot artifacts onto `DynamicUpdateHub` ONCE at mount or hot-swap boundary.
2028    ///
2029    /// # Arguments
2030    ///
2031    /// - `&str` - Normalized route path.
2032    /// - `u64` - Generation identifier holding the warmed artifacts.
2033    /// - `&BTreeMap<String, String>` - Logical slot key to pinned artifact key bindings.
2034    ///
2035    /// # Returns
2036    ///
2037    /// - `Result<(), DynamicReleaseError>` - `Ok(())` when every bound slot mounted cleanly.
2038    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}