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        }
19    }
20}
21
22/// Construction, proxy helpers, and client conversion on `HotUpdateProxyConfig`.
23impl HotUpdateProxyConfig {
24    /// Constructs a `HotUpdateProxyConfig` with explicit server, proxy, channel, and polling policy.
25    ///
26    /// # Arguments
27    ///
28    /// - `String` - Target update server base URL (direct or reverse-proxy prefix).
29    /// - `Option<String>` - Optional explicit HTTP forward proxy URL.
30    /// - `Option<String>` - Optional `Proxy-Authorization` credential string.
31    /// - `String` - Target release channel name.
32    /// - `bool` - Whether verified updates apply automatically.
33    /// - `u64` - Fallback manifest polling cadence in seconds.
34    ///
35    /// # Returns
36    ///
37    /// - `Self` - Configured hot-update proxy settings.
38    #[must_use]
39    pub fn new(
40        server_url: String,
41        proxy_url: Option<String>,
42        proxy_auth: Option<String>,
43        channel: String,
44        auto_apply: bool,
45        poll_fallback_secs: u64,
46    ) -> Self {
47        let clean_server: String = server_url.trim().trim_end_matches('/').to_string();
48        let clean_proxy: Option<String> = proxy_url
49            .map(|p: String| p.trim().trim_end_matches('/').to_string())
50            .filter(|p: &String| !p.is_empty());
51        let clean_auth: Option<String> = proxy_auth
52            .map(|a: String| a.trim().to_string())
53            .filter(|a: &String| !a.is_empty());
54        let clean_channel: String = if channel.trim().is_empty() {
55            DEFAULT_HOT_UPDATE_CHANNEL.to_string()
56        } else {
57            channel.trim().to_string()
58        };
59        Self {
60            server_url: if clean_server.is_empty() {
61                DEFAULT_HOT_UPDATE_SERVER_URL.to_string()
62            } else {
63                clean_server
64            },
65            proxy_url: clean_proxy,
66            proxy_auth: clean_auth,
67            channel: clean_channel,
68            auto_apply,
69            poll_fallback_secs: poll_fallback_secs.max(1),
70        }
71    }
72
73    /// Returns the optional configured HTTP forward proxy URL.
74    ///
75    /// # Arguments
76    ///
77    /// - `&Self` - Proxy configuration reference.
78    ///
79    /// # Returns
80    ///
81    /// - `Option<&str>` - Forward proxy URL when configured.
82    #[must_use]
83    pub fn proxy_url_str(&self) -> Option<&str> {
84        let Self { proxy_url, .. } = self;
85        proxy_url.as_deref()
86    }
87
88    /// Returns the optional configured `Proxy-Authorization` credential string.
89    ///
90    /// # Arguments
91    ///
92    /// - `&Self` - Proxy configuration reference.
93    ///
94    /// # Returns
95    ///
96    /// - `Option<&str>` - Proxy credential string when configured.
97    #[must_use]
98    pub fn proxy_auth_str(&self) -> Option<&str> {
99        let Self { proxy_auth, .. } = self;
100        proxy_auth.as_deref()
101    }
102
103    /// Resolves the effective base URL for Web `fetch` / `EventSource` clients (preferring a reverse-proxy base when provided).
104    ///
105    /// # Arguments
106    ///
107    /// - `&Self` - Proxy configuration reference.
108    ///
109    /// # Returns
110    ///
111    /// - `String` - Normalized browser-reachable base URL without trailing slash.
112    #[must_use]
113    pub fn effective_web_base_url(&self) -> String {
114        if let Some(proxy) = self.proxy_url_str() {
115            let trimmed: &str = proxy.trim().trim_end_matches('/');
116            if !trimmed.is_empty() {
117                return trimmed.to_string();
118            }
119        }
120        self.get_server_url()
121            .trim()
122            .trim_end_matches('/')
123            .to_string()
124    }
125
126    /// Converts this `HotUpdateProxyConfig` into an `UpdateClientConfig` ready for `start_updates`.
127    ///
128    /// # Arguments
129    ///
130    /// - `&Self` - Proxy configuration reference.
131    /// - `String` - Logical project identifier.
132    /// - `Vec<u8>` - Trusted HMAC-SHA256 manifest verification key bytes.
133    ///
134    /// # Returns
135    ///
136    /// - `UpdateClientConfig` - Ready background worker client configuration.
137    #[must_use]
138    pub fn to_client_config(&self, project: String, verify_key: Vec<u8>) -> UpdateClientConfig {
139        let mut cfg: UpdateClientConfig = UpdateClientConfig::with_defaults(
140            self.get_server_url().clone(),
141            project,
142            self.get_channel().clone(),
143            verify_key,
144        );
145        if let Some(proxy) = self.proxy_url_str() {
146            let _: &mut UpdateClientConfig = cfg.set_proxy_url(Some(proxy.to_string()));
147        }
148        if let Some(auth) = self.proxy_auth_str() {
149            let _: &mut UpdateClientConfig = cfg.set_proxy_auth(Some(auth.to_string()));
150        }
151        cfg
152    }
153}
154
155/// Safe defaults and builder helpers on `UpdateClientConfig`.
156impl UpdateClientConfig {
157    /// Creates a production-configured `UpdateClientConfig` with default ABI, WasmComponent mode, and budgets.
158    ///
159    /// # Arguments
160    ///
161    /// - `String` - Base HTTP server URL.
162    /// - `String` - Project identifier.
163    /// - `String` - Channel name.
164    /// - `Vec<u8>` - Trusted HMAC-SHA256 verification key.
165    ///
166    /// # Returns
167    ///
168    /// - `Self` - Configured update client settings.
169    #[must_use]
170    pub fn with_defaults(
171        base_url: String,
172        project: String,
173        channel: String,
174        verify_key: Vec<u8>,
175    ) -> Self {
176        let mut cfg: Self = Self::new(base_url, project, channel, verify_key);
177        cfg.set_host_abi(DYNAMIC_HOST_ABI_V1)
178            .set_delivery_mode(DeliveryChannelMode::WasmComponent)
179            .set_max_artifact_bytes(DEFAULT_MAX_ARTIFACT_BYTES)
180            .set_mailbox_capacity(DEFAULT_CANDIDATE_MAILBOX_CAP)
181            .set_reconnect_backoff_ms(DEFAULT_SSE_RECONNECT_MS)
182            .set_http_timeout_ms(DEFAULT_UPDATE_HTTP_TIMEOUT_MS)
183            .set_sandbox_config(WasmSandboxConfig::default());
184        cfg
185    }
186
187    /// Returns the optional preferred compatibility track name.
188    ///
189    /// # Returns
190    ///
191    /// - `Option<&str>` - Preferred track if set.
192    #[must_use]
193    pub fn preferred_track_str(&self) -> Option<&str> {
194        let Self {
195            preferred_track, ..
196        } = self;
197        preferred_track.as_deref()
198    }
199
200    /// Returns the optional explicit HTTP forward proxy URL.
201    ///
202    /// # Arguments
203    ///
204    /// - `&Self` - Client configuration reference.
205    ///
206    /// # Returns
207    ///
208    /// - `Option<&str>` - Forward proxy URL when configured.
209    #[must_use]
210    pub fn proxy_url_str(&self) -> Option<&str> {
211        let Self { proxy_url, .. } = self;
212        proxy_url.as_deref()
213    }
214
215    /// Returns the optional forward-proxy `Proxy-Authorization` credential string.
216    ///
217    /// # Arguments
218    ///
219    /// - `&Self` - Client configuration reference.
220    ///
221    /// # Returns
222    ///
223    /// - `Option<&str>` - Proxy credential string when configured.
224    #[must_use]
225    pub fn proxy_auth_str(&self) -> Option<&str> {
226        let Self { proxy_auth, .. } = self;
227        proxy_auth.as_deref()
228    }
229
230    /// Attaches an explicit HTTP forward proxy URL and optional credential string to this client configuration.
231    ///
232    /// # Arguments
233    ///
234    /// - `Self` - Source client configuration.
235    /// - `Option<String>` - Optional HTTP forward proxy URL (`http://proxy:port`).
236    /// - `Option<String>` - Optional `Proxy-Authorization` credential string.
237    ///
238    /// # Returns
239    ///
240    /// - `Self` - Updated client configuration.
241    #[must_use]
242    pub fn with_proxy(mut self, proxy_url: Option<String>, proxy_auth: Option<String>) -> Self {
243        let _: &mut Self = self.set_proxy_url(proxy_url);
244        let _: &mut Self = self.set_proxy_auth(proxy_auth);
245        self
246    }
247
248    /// Builds a `ClientNegotiation` descriptor from this client configuration.
249    ///
250    /// # Returns
251    ///
252    /// - `ClientNegotiation` - Protocol, ABI, delivery mode, and capability declaration.
253    #[must_use]
254    pub fn negotiation(&self) -> ClientNegotiation {
255        let mut neg: ClientNegotiation = ClientNegotiation::new(
256            DYNAMIC_PROTOCOL_VERSION_V1,
257            self.get_host_abi(),
258            self.get_delivery_mode(),
259        )
260        .with_capabilities(self.get_capabilities().clone());
261        if let Some(track) = self.preferred_track_str() {
262            neg = neg.with_preferred_track(track.to_string());
263        }
264        neg
265    }
266}
267
268/// Proxy accessor helpers on `HttpReleaseTransport`.
269impl HttpReleaseTransport {
270    /// Returns the optional explicit HTTP forward proxy URL.
271    ///
272    /// # Arguments
273    ///
274    /// - `&Self` - Transport reference.
275    ///
276    /// # Returns
277    ///
278    /// - `Option<&str>` - Forward proxy URL when configured.
279    #[must_use]
280    pub fn proxy_url_str(&self) -> Option<&str> {
281        let Self { proxy_url, .. } = self;
282        proxy_url.as_deref()
283    }
284
285    /// Returns the optional `Proxy-Authorization` credential string.
286    ///
287    /// # Arguments
288    ///
289    /// - `&Self` - Transport reference.
290    ///
291    /// # Returns
292    ///
293    /// - `Option<&str>` - Proxy credential string when configured.
294    #[must_use]
295    pub fn proxy_auth_str(&self) -> Option<&str> {
296        let Self { proxy_auth, .. } = self;
297        proxy_auth.as_deref()
298    }
299}
300
301/// Real pure-std HTTP/1.1 manifest and range-resumable blob fetching on `HttpReleaseTransport`.
302impl ReleaseTransport for HttpReleaseTransport {
303    /// Fetches a signed `ReleaseManifest` from `/v1/projects/{project}/channels/{channel}/manifest`.
304    ///
305    /// # Arguments
306    ///
307    /// - `&str` - Project identifier.
308    /// - `&str` - Channel name.
309    /// - `&ClientNegotiation` - Protocol, ABI, delivery mode, and track negotiation parameters.
310    ///
311    /// # Returns
312    ///
313    /// - `Result<ReleaseManifest, DynamicReleaseError>` - Deserialized manifest or typed error.
314    fn fetch_manifest(
315        &self,
316        project: &str,
317        channel: &str,
318        negotiation: &ClientNegotiation,
319    ) -> Result<ReleaseManifest, DynamicReleaseError> {
320        #[cfg(not(target_arch = "wasm32"))]
321        {
322            let (authority, prefix): (&str, &str) = parse_http_base_url(self.get_base_url())?;
323            let base_prefix: String = if prefix.is_empty() {
324                String::new()
325            } else {
326                format!("/{prefix}")
327            };
328            let mode_tok: &str = delivery_mode_query_token(negotiation.get_delivery_mode());
329            let mut path: String = format!(
330                "{base_prefix}/v1/projects/{project}/channels/{channel}/manifest?protocol={}&abi={}&mode={mode_tok}",
331                negotiation.get_protocol_version(),
332                negotiation.get_host_abi()
333            );
334            if let Some(track) = negotiation.preferred_track_str() {
335                path.push_str(&format!("&track={track}"));
336            }
337            let (status, body): (u16, Vec<u8>) = http_get_once_with_proxy(
338                authority,
339                &path,
340                &[],
341                self.get_timeout_ms(),
342                self.proxy_url_str(),
343                self.proxy_auth_str(),
344            )?;
345            if status == 409 {
346                let reason: String = String::from_utf8_lossy(&body).into_owned();
347                return Err(DynamicReleaseError::ProtocolIncompatible(reason));
348            }
349            if status != 200 {
350                return Err(DynamicReleaseError::NetworkError(format!(
351                    "{ERR_HTTP_NON_OK}: HTTP {status}"
352                )));
353            }
354            let text: &str = from_utf8(&body).map_err(|_| {
355                DynamicReleaseError::StorageError(ERR_MANIFEST_SERIALIZE.to_string())
356            })?;
357            match from_str::<ReleaseManifest>(text) {
358                Ok(parsed) => Ok(parsed),
359                Err(err) => Err(DynamicReleaseError::StorageError(format!(
360                    "{ERR_MANIFEST_SERIALIZE}: {err}"
361                ))),
362            }
363        }
364        #[cfg(target_arch = "wasm32")]
365        {
366            let _: (&str, &str, &ClientNegotiation) = (project, channel, negotiation);
367            Err(DynamicReleaseError::NetworkError(
368                ERR_WASM32_SYNC_HTTP.to_string(),
369            ))
370        }
371    }
372
373    /// Fetches immutable content-addressed blob bytes from `/v1/blobs/{sha256}` with optional byte-range resume.
374    ///
375    /// # Arguments
376    ///
377    /// - `&str` - Lowercase 64-character SHA-256 digest.
378    /// - `u64` - Starting byte offset (`0` for full download).
379    ///
380    /// # Returns
381    ///
382    /// - `Result<Vec<u8>, DynamicReleaseError>` - Downloaded bytes from `range_start` to EOF.
383    fn fetch_blob(&self, sha256: &str, range_start: u64) -> Result<Vec<u8>, DynamicReleaseError> {
384        #[cfg(not(target_arch = "wasm32"))]
385        {
386            let (authority, prefix): (&str, &str) = parse_http_base_url(self.get_base_url())?;
387            let base_prefix: String = if prefix.is_empty() {
388                String::new()
389            } else {
390                format!("/{prefix}")
391            };
392            let path: String = format!("{base_prefix}/v1/blobs/{sha256}");
393            let range_header: String = format!("bytes={range_start}-");
394            let headers: Vec<(&str, &str)> = if range_start > 0 {
395                vec![(HDR_RANGE, range_header.as_str())]
396            } else {
397                Vec::new()
398            };
399            let (status, body): (u16, Vec<u8>) = http_get_once_with_proxy(
400                authority,
401                &path,
402                &headers,
403                self.get_timeout_ms(),
404                self.proxy_url_str(),
405                self.proxy_auth_str(),
406            )?;
407            if status == 404 {
408                return Err(DynamicReleaseError::BlobMissing(sha256.to_string()));
409            }
410            if status != 200 && status != 206 {
411                return Err(DynamicReleaseError::NetworkError(format!(
412                    "{ERR_HTTP_NON_OK}: HTTP {status}"
413                )));
414            }
415            Ok(body)
416        }
417        #[cfg(target_arch = "wasm32")]
418        {
419            let _: (&str, u64) = (sha256, range_start);
420            Err(DynamicReleaseError::NetworkError(
421                ERR_WASM32_SYNC_HTTP.to_string(),
422            ))
423        }
424    }
425}
426
427/// Atomic release-candidate application bridge connecting `UpdateWorkerHandle` directly to `DynamicUpdateHub`.
428impl DynamicUpdateHub {
429    /// Atomically applies all declarative page and component artifacts from a verified `PreparedReleaseCandidate` into `DynamicUpdateHub`.
430    ///
431    /// # Arguments
432    ///
433    /// - `&Self` - Target live dynamic update hub.
434    /// - `&PreparedReleaseCandidate` - Verified, pre-warmed release candidate from `UpdateWorkerHandle`.
435    ///
436    /// # Returns
437    ///
438    /// - `Result<usize, DynamicReleaseError>` - Number of declarative pages and component slots atomically swapped.
439    pub fn apply_prepared_release(
440        &self,
441        candidate: &PreparedReleaseCandidate,
442    ) -> Result<usize, DynamicReleaseError> {
443        let manifest: &ReleaseManifest = candidate.get_manifest();
444        let seq: u64 = manifest.get_release_seq().max(1);
445        let mut pages: Vec<DynamicPageUpdate> = Vec::new();
446        let mut components: Vec<DynamicComponentUpdate> = Vec::new();
447        let mut seen_slots: HashSet<String> = HashSet::new();
448        for (route_path, route_manifest) in manifest.get_routes().iter() {
449            let entry_key: &str = route_manifest.get_entry_module().as_str();
450            if let Some(WarmedArtifact::Declarative(spec)) =
451                candidate.get_warmed_artifacts().get(entry_key)
452            {
453                let mut page_upd: DynamicPageUpdate = DynamicPageUpdate::new(
454                    route_path.clone(),
455                    format!("{} v{seq}", route_manifest.get_entry_module()),
456                    seq,
457                    spec.clone(),
458                );
459                let _: &mut DynamicPageUpdate = page_upd.set_allow_downgrade(true);
460                pages.push(page_upd);
461            }
462            for (slot_key, art_key) in route_manifest.get_slot_bindings().iter() {
463                if !seen_slots.insert(slot_key.clone()) {
464                    continue;
465                }
466                if let Some(WarmedArtifact::Declarative(spec)) =
467                    candidate.get_warmed_artifacts().get(art_key)
468                {
469                    let mut comp_upd: DynamicComponentUpdate =
470                        DynamicComponentUpdate::new(slot_key.clone(), seq, spec.clone());
471                    let _: &mut DynamicComponentUpdate = comp_upd.set_allow_downgrade(true);
472                    components.push(comp_upd);
473                }
474            }
475        }
476        let applied_count: usize = pages.len() + components.len();
477        if applied_count == 0 {
478            return Ok(0);
479        }
480        let mut bundle: DynamicUpdateBundle =
481            DynamicUpdateBundle::new(format!("{}-{seq}", manifest.get_channel()), seq);
482        let _: &mut DynamicUpdateBundle = bundle.set_components(components).set_pages(pages);
483        let _: DynamicTelemetry =
484            self.apply_bundle(bundle)
485                .map_err(|err: DynamicUpdateError| {
486                    DynamicReleaseError::StorageError(err.to_string())
487                })?;
488        Ok(applied_count)
489    }
490
491    /// Drains the newest verified release candidate from `worker` without blocking and atomically applies it into `DynamicUpdateHub`.
492    ///
493    /// # Arguments
494    ///
495    /// - `&Self` - Target live dynamic update hub.
496    /// - `&UpdateWorkerHandle` - Active background hot-update worker handle.
497    ///
498    /// # Returns
499    ///
500    /// - `Result<Option<PreparedReleaseCandidate>, DynamicReleaseError>` - Applied candidate when a new release was ready, or `None`.
501    pub fn sync_from_worker(
502        &self,
503        worker: &UpdateWorkerHandle,
504    ) -> Result<Option<PreparedReleaseCandidate>, DynamicReleaseError> {
505        let Some(candidate) = worker.try_take_ready_candidate() else {
506            return Ok(None);
507        };
508        let _: usize = self.apply_prepared_release(&candidate)?;
509        Ok(Some(candidate))
510    }
511}
512
513/// Bounded non-blocking mailbox operations on `CandidateMailbox`.
514impl CandidateMailbox {
515    /// Creates a bounded `CandidateMailbox` rejecting any candidate older than or equal to `initial_seq`.
516    ///
517    /// # Arguments
518    ///
519    /// - `usize` - Maximum number of buffered prepared candidates.
520    /// - `u64` - Initial active release sequence baseline.
521    ///
522    /// # Returns
523    ///
524    /// - `Self` - Initialized mailbox.
525    #[must_use]
526    pub fn new(capacity: usize, initial_seq: u64) -> Self {
527        let inner: CandidateMailboxInner = CandidateMailboxInner {
528            capacity: capacity.max(1),
529            highest_seen_seq: initial_seq,
530            queue: VecDeque::with_capacity(capacity.max(1)),
531        };
532        Self {
533            inner: Arc::new(Mutex::new(inner)),
534        }
535    }
536
537    /// Pushes a prepared candidate into the mailbox, discarding stale releases and coalescing when full.
538    ///
539    /// # Arguments
540    ///
541    /// - `PreparedReleaseCandidate` - Verified, warmed candidate from `UpdateWorker`.
542    pub fn push_candidate(&self, candidate: PreparedReleaseCandidate) {
543        let Self { inner } = self;
544        if let Ok(mut guard) = inner.lock() {
545            let incoming_seq: u64 = candidate.get_manifest().get_release_seq();
546            if incoming_seq <= guard.highest_seen_seq {
547                return;
548            }
549            guard.highest_seen_seq = incoming_seq;
550            while guard.queue.len() >= guard.capacity {
551                let _: Option<PreparedReleaseCandidate> = guard.queue.pop_front();
552            }
553            guard.queue.push_back(candidate);
554        }
555    }
556
557    /// Non-blockingly drains the mailbox on the UI thread and returns only the newest prepared candidate.
558    ///
559    /// # Returns
560    ///
561    /// - `Option<PreparedReleaseCandidate>` - Latest ready candidate, or `None` if empty or contended.
562    #[must_use]
563    pub fn try_recv_latest(&self) -> Option<PreparedReleaseCandidate> {
564        let Self { inner } = self;
565        let mut guard: MutexGuard<'_, CandidateMailboxInner> = inner.try_lock().ok()?;
566        let mut latest: Option<PreparedReleaseCandidate> = None;
567        while let Some(item) = guard.queue.pop_front() {
568            latest = Some(item);
569        }
570        latest
571    }
572
573    /// Returns the number of candidates currently waiting in the mailbox without blocking.
574    ///
575    /// # Returns
576    ///
577    /// - `usize` - Pending candidate count.
578    #[must_use]
579    pub fn pending_count(&self) -> usize {
580        let Self { inner } = self;
581        inner
582            .try_lock()
583            .map(|g: MutexGuard<'_, CandidateMailboxInner>| g.queue.len())
584            .unwrap_or(0)
585    }
586}
587
588/// Control and entrypoints on `UpdateWorkerHandle` (Sec 11.2 / 11.8).
589impl UpdateWorkerHandle {
590    /// Checks and fetches the latest compatible signed manifest for `(project, channel)` (Sec 11.2).
591    ///
592    /// # Arguments
593    ///
594    /// - `&str` - Logical project identifier.
595    /// - `&str` - Channel name.
596    ///
597    /// # Returns
598    ///
599    /// - `Result<ReleaseManifest, DynamicReleaseError>` - Verified signed manifest or error.
600    pub fn check_update(
601        &self,
602        project: &str,
603        channel: &str,
604    ) -> Result<ReleaseManifest, DynamicReleaseError> {
605        let Self { shared, .. } = self;
606        let transport: HttpReleaseTransport = HttpReleaseTransport::new(
607            shared.config.get_base_url().clone(),
608            shared.config.get_http_timeout_ms(),
609        );
610        let negotiation: ClientNegotiation = shared.config.negotiation();
611        let manifest: ReleaseManifest = transport.fetch_manifest(project, channel, &negotiation)?;
612        manifest.verify_signature(shared.config.get_verify_key())?;
613        manifest.validate_for_host(
614            shared.config.get_host_abi(),
615            shared.config.get_capabilities(),
616            shared.config.get_delivery_mode(),
617            shared.config.get_max_artifact_bytes(),
618        )?;
619        Ok(manifest)
620    }
621
622    /// Prepares a release candidate using the worker's verified cache, incremental hash diff, and pure migrator (Sec 11.2).
623    ///
624    /// # Arguments
625    ///
626    /// - `ReleaseManifest` - Signed target release manifest.
627    /// - `Option<NestedStateSnapshot>` - Optional captured route UI state snapshot at revision `R`.
628    ///
629    /// # Returns
630    ///
631    /// - `Result<PreparedReleaseCandidate, DynamicReleaseError>` - Ready candidate or typed error.
632    pub fn prepare_release(
633        &self,
634        manifest: ReleaseManifest,
635        snapshot: Option<NestedStateSnapshot>,
636    ) -> Result<PreparedReleaseCandidate, DynamicReleaseError> {
637        let Self { shared, .. } = self;
638        let transport: HttpReleaseTransport = HttpReleaseTransport::new(
639            shared.config.get_base_url().clone(),
640            shared.config.get_http_timeout_ms(),
641        );
642        prepare_release_with_shared(shared, &transport, manifest, snapshot)
643    }
644
645    /// Seeds verified content-addressed blobs into the worker's local cache (for built-in/offline startup).
646    ///
647    /// # Arguments
648    ///
649    /// - `BTreeMap<String, Vec<u8>>` - Map of SHA-256 hex digest to verified blob bytes.
650    pub fn seed_verified_blobs(&self, blobs: BTreeMap<String, Vec<u8>>) {
651        let Self { shared, .. } = self;
652        if let Ok(mut cache) = shared.blob_cache.lock() {
653            for (sha, bytes) in blobs.into_iter() {
654                let _: Option<Arc<Vec<u8>>> = cache.insert(sha, Arc::new(bytes));
655            }
656        }
657    }
658
659    /// Queues a captured route `NestedStateSnapshot` so the next background preparation migrates it off the UI thread.
660    ///
661    /// # Arguments
662    ///
663    /// - `NestedStateSnapshot` - Immutable snapshot captured at revision `R`.
664    pub fn submit_ui_snapshot(&self, snapshot: NestedStateSnapshot) {
665        let Self { shared, .. } = self;
666        if let Ok(mut slot) = shared.pending_snapshot.lock() {
667            *slot = Some(snapshot);
668        }
669    }
670
671    /// Non-blockingly polls the bounded candidate mailbox from the UI thread.
672    ///
673    /// # Returns
674    ///
675    /// - `Option<PreparedReleaseCandidate>` - Latest prepared candidate ready for frame-boundary swap.
676    #[must_use]
677    pub fn try_take_ready_candidate(&self) -> Option<PreparedReleaseCandidate> {
678        let Self { shared, .. } = self;
679        shared.mailbox.try_recv_latest()
680    }
681
682    /// Requests an immediate manifest reconciliation on the background worker (e.g. on foreground resume).
683    pub fn request_reconcile(&self) {
684        let Self { shared, .. } = self;
685        shared.reconcile_requested.store(true, Ordering::Release);
686    }
687
688    /// Returns the latest `Last-Event-ID` cursor accepted by the background SSE client.
689    ///
690    /// # Returns
691    ///
692    /// - `Option<String>` - Active `Last-Event-ID` cursor string.
693    #[must_use]
694    pub fn last_event_id(&self) -> Option<String> {
695        let Self { shared, .. } = self;
696        shared
697            .last_event_id
698            .lock()
699            .ok()
700            .and_then(|g: MutexGuard<'_, Option<String>>| g.clone())
701    }
702
703    /// Overrides the `Last-Event-ID` cursor (e.g. when restoring persisted resume state across restarts).
704    ///
705    /// # Arguments
706    ///
707    /// - `Option<String>` - Cursor string to send on the next SSE connection.
708    pub fn set_last_event_id(&self, cursor: Option<String>) {
709        let Self { shared, .. } = self;
710        if let Ok(mut slot) = shared.last_event_id.lock() {
711            *slot = cursor;
712        }
713    }
714
715    /// Returns the chronological log of SHA-256 digests actually downloaded over HTTP by this worker.
716    ///
717    /// # Returns
718    ///
719    /// - `Vec<String>` - Downloaded blob SHA-256 digests.
720    #[must_use]
721    pub fn fetched_blob_hashes(&self) -> Vec<String> {
722        let Self { shared, .. } = self;
723        shared
724            .fetched_hashes_log
725            .lock()
726            .map(|g: MutexGuard<'_, Vec<String>>| g.clone())
727            .unwrap_or_default()
728    }
729
730    /// Returns the number of established SSE sessions (incremented on initial connect and reconnects).
731    ///
732    /// # Returns
733    ///
734    /// - `u64` - Total SSE connect count.
735    #[must_use]
736    pub fn sse_connect_count(&self) -> u64 {
737        let Self { shared, .. } = self;
738        shared.sse_connect_count.load(Ordering::Acquire)
739    }
740
741    /// Returns the most recent background error recorded without interrupting the live UI.
742    ///
743    /// # Returns
744    ///
745    /// - `Option<DynamicReleaseError>` - Last recorded error if any.
746    #[must_use]
747    pub fn last_error(&self) -> Option<DynamicReleaseError> {
748        let Self { shared, .. } = self;
749        shared
750            .last_error
751            .lock()
752            .ok()
753            .and_then(|g: MutexGuard<'_, Option<DynamicReleaseError>>| g.clone())
754    }
755
756    /// Signals the dedicated background `UpdateWorker` thread to stop and joins it cleanly.
757    pub fn stop(&mut self) {
758        let Self {
759            shared,
760            #[cfg(not(target_arch = "wasm32"))]
761            worker_thread,
762        } = self;
763        shared.running.store(false, Ordering::Release);
764        #[cfg(not(target_arch = "wasm32"))]
765        if let Some(handle) = worker_thread.take() {
766            let _: Result<(), Box<dyn Any + Send>> = handle.join();
767        }
768    }
769}
770
771/// Automatic worker shutdown when `UpdateWorkerHandle` is dropped.
772impl Drop for UpdateWorkerHandle {
773    /// Stops and joins the background worker thread on drop.
774    fn drop(&mut self) {
775        self.stop();
776    }
777}
778
779/// Core per-route pinning, safe-point swapping, rollback, and GC orchestration on `DynamicReleaseRuntime`.
780impl DynamicReleaseRuntime {
781    /// Creates a new `DynamicReleaseRuntime` bound to `hub` and `business_store`.
782    ///
783    /// # Arguments
784    ///
785    /// - `DynamicUpdateHub` - Live UI dynamic update hub.
786    /// - `BusinessStateStore` - Host-owned authoritative business state store.
787    /// - `WasmSandboxConfig` - Sandbox limits applied when mounting dynamic Wasm modules.
788    ///
789    /// # Returns
790    ///
791    /// - `Self` - Initialized dynamic release runtime.
792    #[must_use]
793    pub fn new(
794        hub: DynamicUpdateHub,
795        business_store: BusinessStateStore,
796        sandbox_config: WasmSandboxConfig,
797    ) -> Self {
798        Self {
799            hub,
800            business_store,
801            sandbox_config,
802            active_release_seq: 0,
803            generations: BTreeMap::new(),
804            open_routes: BTreeMap::new(),
805            restored_ui_states: BTreeMap::new(),
806            deferred_candidate: None,
807            next_hub_revision: 1,
808        }
809    }
810
811    /// Returns a reference to the host-owned `BusinessStateStore`.
812    ///
813    /// # Returns
814    ///
815    /// - `&BusinessStateStore` - Shared authoritative business state store.
816    #[must_use]
817    pub fn business_store(&self) -> &BusinessStateStore {
818        let Self { business_store, .. } = self;
819        business_store
820    }
821
822    /// Returns the currently active release sequence number (`0` before initial install).
823    ///
824    /// # Returns
825    ///
826    /// - `u64` - Active release sequence.
827    #[must_use]
828    pub fn active_release_seq(&self) -> u64 {
829        let Self {
830            active_release_seq, ..
831        } = *self;
832        active_release_seq
833    }
834
835    /// Returns the number of release generations currently retained in memory.
836    ///
837    /// # Returns
838    ///
839    /// - `usize` - Count of retained `ReleaseGeneration` records.
840    #[must_use]
841    pub fn retained_generation_count(&self) -> usize {
842        let Self { generations, .. } = self;
843        generations.len()
844    }
845
846    /// Returns whether a candidate is currently deferred awaiting a safe frame boundary.
847    ///
848    /// # Returns
849    ///
850    /// - `bool` - `true` when a deferred candidate is pending.
851    #[must_use]
852    pub fn has_deferred_candidate(&self) -> bool {
853        let Self {
854            deferred_candidate, ..
855        } = self;
856        deferred_candidate.is_some()
857    }
858
859    /// Returns the restored UI state snapshot for a canonical `StableAddress`, if any.
860    ///
861    /// # Arguments
862    ///
863    /// - `&str` - Canonical `StableAddress` string.
864    ///
865    /// # Returns
866    ///
867    /// - `Option<&ComponentUiStateSnapshot>` - Restored UI state snapshot.
868    #[must_use]
869    pub fn restored_ui_state(&self, canonical_address: &str) -> Option<&ComponentUiStateSnapshot> {
870        let Self {
871            restored_ui_states, ..
872        } = self;
873        restored_ui_states.get(canonical_address)
874    }
875
876    /// Installs an initial built-in or cached signed release generation synchronously at startup.
877    ///
878    /// # Arguments
879    ///
880    /// - `ReleaseManifest` - Verified initial manifest (e.g. generation `101`).
881    /// - `&BTreeMap<String, Vec<u8>>` - Raw verified blob bytes keyed by SHA-256 hex digest.
882    /// - `u32` - Running host ABI version.
883    ///
884    /// # Returns
885    ///
886    /// - `Result<u64, DynamicReleaseError>` - Installed generation sequence number.
887    pub fn install_initial_release(
888        &mut self,
889        manifest: ReleaseManifest,
890        blobs: &BTreeMap<String, Vec<u8>>,
891        host_abi: u32,
892    ) -> Result<u64, DynamicReleaseError> {
893        let sandbox_cfg: WasmSandboxConfig = {
894            let Self { sandbox_config, .. } = *self;
895            sandbox_config
896        };
897        let mut warmed: BTreeMap<String, WarmedArtifact> = BTreeMap::new();
898        for (art_key, artifact) in manifest.get_artifacts().iter() {
899            let bytes: &Vec<u8> = blobs
900                .get(artifact.get_sha256())
901                .ok_or_else(|| DynamicReleaseError::BlobMissing(artifact.get_sha256().clone()))?;
902            let item: WarmedArtifact =
903                warm_verified_artifact(artifact, bytes.as_slice(), host_abi, &sandbox_cfg)?;
904            let _: Option<WarmedArtifact> = warmed.insert(art_key.clone(), item);
905        }
906        let seq: u64 = manifest.get_release_seq();
907        let generation: ReleaseGeneration = ReleaseGeneration {
908            generation_id: seq,
909            manifest,
910            warmed_artifacts: warmed,
911            active_route_pins: 0,
912            active_in_flight_tasks: 0,
913        };
914        let Self {
915            generations,
916            active_release_seq,
917            ..
918        } = self;
919        let _: Option<ReleaseGeneration> = generations.insert(seq, generation);
920        *active_release_seq = seq;
921        Ok(seq)
922    }
923
924    /// Opens a route instance pinned to the currently active release generation and mounts its slots into `DynamicUpdateHub`.
925    ///
926    /// # Arguments
927    ///
928    /// - `&str` - Stable route instance key (e.g. `"A#tab-1"` or `"B#tab-1"`).
929    /// - `&str` - Route path (e.g. `"/route-a"` or `"/route-b"`).
930    ///
931    /// # Returns
932    ///
933    /// - `Result<RoutePinHandle, DynamicReleaseError>` - Pinned route handle.
934    pub fn open_route(
935        &mut self,
936        route_instance_id: &str,
937        route: &str,
938    ) -> Result<RoutePinHandle, DynamicReleaseError> {
939        DynamicFrameMetrics::record_manifest_lookup();
940        let normalized_route: String = normalize_dynamic_route(route);
941        let target_gen_id: u64 = self.active_release_seq();
942        if target_gen_id == 0 {
943            return Err(DynamicReleaseError::RouteNotFound(
944                ERR_NO_ACTIVE_GENERATION.to_string(),
945            ));
946        }
947        let (entry_module, slot_bindings): (String, BTreeMap<String, String>) = {
948            let Self { generations, .. } = self;
949            let gen_mut: &mut ReleaseGeneration = generations
950                .get_mut(&target_gen_id)
951                .ok_or_else(|| DynamicReleaseError::RouteNotFound(normalized_route.clone()))?;
952            let route_manifest: &RouteManifest = gen_mut
953                .get_manifest()
954                .get_routes()
955                .get(&normalized_route)
956                .ok_or_else(|| DynamicReleaseError::RouteNotFound(normalized_route.clone()))?;
957            let entry: String = route_manifest.get_entry_module().clone();
958            let slots: BTreeMap<String, String> = route_manifest.get_slot_bindings().clone();
959            gen_mut.set_active_route_pins(gen_mut.get_active_route_pins().saturating_add(1));
960            (entry, slots)
961        };
962        let handle: RoutePinHandle = RoutePinHandle {
963            route_instance_id: route_instance_id.to_string(),
964            route: normalized_route.clone(),
965            generation_id: target_gen_id,
966            entry_module,
967            slot_bindings: slot_bindings.clone(),
968            cancellation_token: Arc::new(AtomicBool::new(false)),
969        };
970        let Self { open_routes, .. } = self;
971        let _: Option<RoutePinHandle> =
972            open_routes.insert(route_instance_id.to_string(), handle.clone());
973        self.apply_route_slots_to_hub(&normalized_route, target_gen_id, &slot_bindings)?;
974        Ok(handle)
975    }
976
977    /// Closes an open route instance, cancels its token, decrements its generation pin, and runs GC.
978    ///
979    /// # Arguments
980    ///
981    /// - `&str` - Route instance identifier to close.
982    ///
983    /// # Returns
984    ///
985    /// - `usize` - Number of unreachable old generations reclaimed by GC.
986    pub fn close_route(&mut self, route_instance_id: &str) -> usize {
987        let removed: Option<RoutePinHandle> = {
988            let Self { open_routes, .. } = self;
989            open_routes.remove(route_instance_id)
990        };
991        if let Some(pin) = removed {
992            pin.get_cancellation_token().store(true, Ordering::Release);
993            let gen_id: u64 = pin.get_generation_id();
994            let Self { generations, .. } = self;
995            if let Some(gen_mut) = generations.get_mut(&gen_id) {
996                gen_mut.set_active_route_pins(gen_mut.get_active_route_pins().saturating_sub(1));
997            }
998        }
999        self.gc_unreachable_generations()
1000    }
1001
1002    /// Returns the currently pinned artifact key (`"card@1.0.0"`) for `slot_key` on an open route instance.
1003    ///
1004    /// # Arguments
1005    ///
1006    /// - `&str` - Open route instance identifier.
1007    /// - `&str` - Logical slot key.
1008    ///
1009    /// # Returns
1010    ///
1011    /// - `Option<String>` - Exact pinned artifact key if the route and slot exist.
1012    #[must_use]
1013    pub fn pinned_slot_artifact(&self, route_instance_id: &str, slot_key: &str) -> Option<String> {
1014        let Self { open_routes, .. } = self;
1015        open_routes
1016            .get(route_instance_id)
1017            .and_then(|pin: &RoutePinHandle| pin.get_slot_bindings().get(slot_key).cloned())
1018    }
1019
1020    /// Returns the currently pinned release generation ID for an open route instance.
1021    ///
1022    /// # Arguments
1023    ///
1024    /// - `&str` - Open route instance identifier.
1025    ///
1026    /// # Returns
1027    ///
1028    /// - `Option<u64>` - Pinned release generation ID.
1029    #[must_use]
1030    pub fn pinned_generation_for_route(&self, route_instance_id: &str) -> Option<u64> {
1031        let Self { open_routes, .. } = self;
1032        open_routes
1033            .get(route_instance_id)
1034            .map(RoutePinHandle::get_generation_id)
1035    }
1036
1037    /// Captures a `NestedStateSnapshot` at the current authoritative business revision `R` for `route`.
1038    ///
1039    /// # Arguments
1040    ///
1041    /// - `&str` - Target route path.
1042    /// - `BTreeMap<String, ComponentUiStateSnapshot>` - Live per-instance UI states keyed by canonical `StableAddress`.
1043    ///
1044    /// # Returns
1045    ///
1046    /// - `NestedStateSnapshot` - Immutable snapshot ready to pass to the background worker.
1047    #[must_use]
1048    pub fn capture_nested_snapshot(
1049        &self,
1050        route: &str,
1051        ui_states: BTreeMap<String, ComponentUiStateSnapshot>,
1052    ) -> NestedStateSnapshot {
1053        let normalized: String = normalize_dynamic_route(route);
1054        let (rev, entity_snaps): (u64, BTreeMap<String, (u64, Value)>) =
1055            self.business_store().capture_entity_snapshots();
1056        let mut snap: NestedStateSnapshot =
1057            NestedStateSnapshot::new(normalized, self.active_release_seq(), rev);
1058        snap.set_entity_snapshots(entity_snaps)
1059            .set_ui_states(ui_states);
1060        snap
1061    }
1062
1063    /// 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).
1064    ///
1065    /// # Arguments
1066    ///
1067    /// - `PreparedReleaseCandidate` - Candidate prepared off the UI thread.
1068    /// - `&InteractionSafePoint` - Current frame-boundary safety probe.
1069    ///
1070    /// # Returns
1071    ///
1072    /// - `Result<ActivationReport, DynamicReleaseError>` - Activation or deferral report.
1073    pub fn activate_release(
1074        &mut self,
1075        candidate: PreparedReleaseCandidate,
1076        boundary: &InteractionSafePoint,
1077    ) -> Result<ActivationReport, DynamicReleaseError> {
1078        let target_seq: u64 = candidate.get_manifest().get_release_seq();
1079        if target_seq <= self.active_release_seq() {
1080            return Err(DynamicReleaseError::NonMonotonicRelease {
1081                current: self.active_release_seq(),
1082                incoming: target_seq,
1083            });
1084        }
1085        if let Some(reason) = boundary.defer_reason() {
1086            let Self {
1087                deferred_candidate,
1088                open_routes,
1089                ..
1090            } = self;
1091            *deferred_candidate = Some(candidate);
1092            let unchanged: Vec<String> = open_routes.keys().cloned().collect();
1093            return Ok(ActivationReport::new(
1094                target_seq,
1095                Vec::new(),
1096                unchanged,
1097                true,
1098                reason.to_string(),
1099                0,
1100                0,
1101            ));
1102        }
1103        let mut caught_up_deltas: usize = 0;
1104        for (entity_id, base_rev) in candidate.get_snapshot_entity_revisions().iter() {
1105            let deltas: Vec<BusinessStateDelta> =
1106                self.business_store().deltas_since(entity_id, *base_rev)?;
1107            caught_up_deltas = caught_up_deltas.saturating_add(deltas.len());
1108        }
1109        let prev_manifest: Option<ReleaseManifest> = {
1110            let Self {
1111                generations,
1112                active_release_seq,
1113                ..
1114            } = self;
1115            generations
1116                .get(active_release_seq)
1117                .map(|g: &ReleaseGeneration| g.get_manifest().clone())
1118        };
1119        let authoritative_affected: Vec<String> = candidate
1120            .get_manifest()
1121            .affected_routes_since(prev_manifest.as_ref());
1122        let new_generation: ReleaseGeneration = ReleaseGeneration {
1123            generation_id: target_seq,
1124            manifest: candidate.get_manifest().clone(),
1125            warmed_artifacts: candidate.get_warmed_artifacts().clone(),
1126            active_route_pins: 0,
1127            active_in_flight_tasks: 0,
1128        };
1129        {
1130            let Self {
1131                generations,
1132                active_release_seq,
1133                restored_ui_states,
1134                deferred_candidate,
1135                ..
1136            } = self;
1137            let _: Option<ReleaseGeneration> = generations.insert(target_seq, new_generation);
1138            *active_release_seq = target_seq;
1139            for (addr, ui_state) in candidate.get_migrated_ui_states().iter() {
1140                let _: Option<ComponentUiStateSnapshot> =
1141                    restored_ui_states.insert(addr.clone(), ui_state.clone());
1142            }
1143            *deferred_candidate = None;
1144        }
1145        let mut swapped_routes: Vec<String> = Vec::new();
1146        let mut unchanged_pinned_routes: Vec<String> = Vec::new();
1147        let mut hub_updates: Vec<(String, BTreeMap<String, String>)> = Vec::new();
1148        let mut released_gens: Vec<u64> = Vec::new();
1149        {
1150            let Self {
1151                open_routes,
1152                generations,
1153                ..
1154            } = self;
1155            for (instance_id, pin) in open_routes.iter_mut() {
1156                let route_path: String = pin.get_route().clone();
1157                if authoritative_affected.contains(&route_path)
1158                    && let Some(next_route_manifest) =
1159                        candidate.get_manifest().get_routes().get(&route_path)
1160                {
1161                    let old_gen_id: u64 = pin.get_generation_id();
1162                    if let Some(old_gen) = generations.get_mut(&old_gen_id) {
1163                        old_gen.set_active_route_pins(
1164                            old_gen.get_active_route_pins().saturating_sub(1),
1165                        );
1166                        if old_gen.get_active_route_pins() == 0 {
1167                            released_gens.push(old_gen_id);
1168                        }
1169                    }
1170                    if let Some(new_gen) = generations.get_mut(&target_seq) {
1171                        new_gen.set_active_route_pins(
1172                            new_gen.get_active_route_pins().saturating_add(1),
1173                        );
1174                    }
1175                    pin.get_cancellation_token().store(true, Ordering::Release);
1176                    pin.set_generation_id(target_seq)
1177                        .set_entry_module(next_route_manifest.get_entry_module().clone())
1178                        .set_slot_bindings(next_route_manifest.get_slot_bindings().clone())
1179                        .set_cancellation_token(Arc::new(AtomicBool::new(false)));
1180                    swapped_routes.push(instance_id.clone());
1181                    hub_updates.push((route_path, next_route_manifest.get_slot_bindings().clone()));
1182                } else {
1183                    unchanged_pinned_routes.push(instance_id.clone());
1184                }
1185            }
1186        }
1187        for old_gen_id in released_gens.into_iter() {
1188            self.business_store()
1189                .cancel_generation_subscriptions(old_gen_id);
1190        }
1191        for (route_path, slot_bindings) in hub_updates.into_iter() {
1192            self.apply_route_slots_to_hub(&route_path, target_seq, &slot_bindings)?;
1193        }
1194        let gc_reclaimed: usize = self.gc_unreachable_generations();
1195        Ok(ActivationReport::new(
1196            target_seq,
1197            swapped_routes,
1198            unchanged_pinned_routes,
1199            false,
1200            String::new(),
1201            caught_up_deltas,
1202            gc_reclaimed,
1203        ))
1204    }
1205
1206    /// Non-blockingly polls `worker` (or a previously deferred candidate) and activates at a safe frame boundary.
1207    ///
1208    /// # Arguments
1209    ///
1210    /// - `&UpdateWorkerHandle` - Running background update worker handle.
1211    /// - `&InteractionSafePoint` - Current frame-boundary safety probe.
1212    ///
1213    /// # Returns
1214    ///
1215    /// - `Result<Option<ActivationReport>, DynamicReleaseError>` - Report when a candidate was evaluated, or `None` when idle.
1216    pub fn poll_mailbox_and_activate(
1217        &mut self,
1218        worker: &UpdateWorkerHandle,
1219        boundary: &InteractionSafePoint,
1220    ) -> Result<Option<ActivationReport>, DynamicReleaseError> {
1221        let incoming: Option<PreparedReleaseCandidate> = worker.try_take_ready_candidate();
1222        let next_candidate: Option<PreparedReleaseCandidate> = match incoming {
1223            Some(fresh) => Some(fresh),
1224            None => {
1225                let Self {
1226                    deferred_candidate, ..
1227                } = self;
1228                deferred_candidate.take()
1229            }
1230        };
1231        let Some(candidate) = next_candidate else {
1232            return Ok(None);
1233        };
1234        let report: ActivationReport = self.activate_release(candidate, boundary)?;
1235        Ok(Some(report))
1236    }
1237
1238    /// Dispatches a host-validated cross-route action, opening the target route pinned to its OWN dependency graph (Sec 11.2).
1239    ///
1240    /// # Arguments
1241    ///
1242    /// - `&CrossRouteAction` - Action carrying target route, action ID, origin generation, and cancellation token.
1243    /// - `&[String]` - Permitted host action IDs.
1244    /// - `&str` - Stable instance identifier for the opened target route.
1245    ///
1246    /// # Returns
1247    ///
1248    /// - `Result<RoutePinHandle, DynamicReleaseError>` - Target route's independent pinned handle.
1249    pub fn dispatch_cross_route_action(
1250        &mut self,
1251        action: &CrossRouteAction,
1252        allowed_actions: &[String],
1253        target_instance_id: &str,
1254    ) -> Result<RoutePinHandle, DynamicReleaseError> {
1255        if action.get_cancellation_token().load(Ordering::Acquire) {
1256            return Err(DynamicReleaseError::UnsafeSwapPoint(
1257                ERR_ACTION_CANCELLED.to_string(),
1258            ));
1259        }
1260        if !allowed_actions
1261            .iter()
1262            .any(|a: &String| a == action.get_action_id())
1263        {
1264            return Err(DynamicReleaseError::MissingCapability(format!(
1265                "{ERR_ACTION_DENIED}: {}",
1266                action.get_action_id()
1267            )));
1268        }
1269        self.open_route(target_instance_id, action.get_target_route())
1270    }
1271
1272    /// Reclaims old release generations that are no longer active and have zero open route pins or in-flight tasks.
1273    ///
1274    /// # Returns
1275    ///
1276    /// - `usize` - Number of reclaimed generations.
1277    pub fn gc_unreachable_generations(&mut self) -> usize {
1278        let Self {
1279            active_release_seq,
1280            generations,
1281            ..
1282        } = self;
1283        let active_seq: u64 = *active_release_seq;
1284        let to_remove: Vec<u64> = generations
1285            .iter()
1286            .filter(|(gid, gen_rec): &(&u64, &ReleaseGeneration)| {
1287                **gid != active_seq
1288                    && gen_rec.get_active_route_pins() == 0
1289                    && gen_rec.get_active_in_flight_tasks() == 0
1290            })
1291            .map(|(gid, _): (&u64, &ReleaseGeneration)| *gid)
1292            .collect();
1293        let removed_count: usize = to_remove.len();
1294        for gid in to_remove.into_iter() {
1295            let _: Option<ReleaseGeneration> = generations.remove(&gid);
1296        }
1297        removed_count
1298    }
1299
1300    /// Applies a route's bound slot artifacts onto `DynamicUpdateHub` ONCE at mount or hot-swap boundary.
1301    ///
1302    /// # Arguments
1303    ///
1304    /// - `&str` - Normalized route path.
1305    /// - `u64` - Generation identifier holding the warmed artifacts.
1306    /// - `&BTreeMap<String, String>` - Logical slot key to pinned artifact key bindings.
1307    ///
1308    /// # Returns
1309    ///
1310    /// - `Result<(), DynamicReleaseError>` - `Ok(())` when every bound slot mounted cleanly.
1311    fn apply_route_slots_to_hub(
1312        &mut self,
1313        route: &str,
1314        generation_id: u64,
1315        slot_bindings: &BTreeMap<String, String>,
1316    ) -> Result<(), DynamicReleaseError> {
1317        let mut specs_to_apply: Vec<(String, DynamicNodeSpec)> =
1318            Vec::with_capacity(slot_bindings.len());
1319        {
1320            let Self {
1321                generations,
1322                sandbox_config,
1323                ..
1324            } = self;
1325            let gen_rec: &ReleaseGeneration = generations
1326                .get(&generation_id)
1327                .ok_or_else(|| DynamicReleaseError::RouteNotFound(route.to_string()))?;
1328            for (slot_key, artifact_key) in slot_bindings.iter() {
1329                let Some(warmed) = gen_rec.get_warmed_artifacts().get(artifact_key) else {
1330                    return Err(DynamicReleaseError::BrokenDependencyClosure(format!(
1331                        "{ERR_MISSING_SLOT_ARTIFACT}: {artifact_key}"
1332                    )));
1333                };
1334                let scoped_slot_id: String =
1335                    SlotKey::from_str_key(slot_key).scoped_for_route(route);
1336                let spec: DynamicNodeSpec = match warmed {
1337                    WarmedArtifact::Wasm(parsed) => {
1338                        DynamicFrameMetrics::record_module_call();
1339                        let entry: &str = gen_rec
1340                            .get_manifest()
1341                            .get_artifacts()
1342                            .get(artifact_key)
1343                            .map(|a: &BlobArtifact| {
1344                                if a.get_entrypoint().is_empty() {
1345                                    WASM_EXPORT_RENDER
1346                                } else {
1347                                    a.get_entrypoint().as_str()
1348                                }
1349                            })
1350                            .unwrap_or(WASM_EXPORT_RENDER);
1351                        let exec_out: WasmExecutionOutput =
1352                            execute_wasm_export(parsed, entry, &[0], sandbox_config).map_err(
1353                                |err: WasmDynamicError| {
1354                                    DynamicReleaseError::StorageError(err.to_string())
1355                                },
1356                            )?;
1357                        DynamicFrameMetrics::record_serialization();
1358                        exec_out.emitted_spec().cloned().ok_or_else(|| {
1359                            DynamicReleaseError::StorageError(ERR_DECLARATIVE_JSON.to_string())
1360                        })?
1361                    }
1362                    WarmedArtifact::Declarative(spec) => {
1363                        DynamicFrameMetrics::record_module_call();
1364                        spec.clone()
1365                    }
1366                    WarmedArtifact::Asset(_) => continue,
1367                };
1368                specs_to_apply.push((scoped_slot_id, spec));
1369            }
1370        }
1371        let Self {
1372            hub,
1373            next_hub_revision,
1374            ..
1375        } = self;
1376        for (scoped_slot_id, spec) in specs_to_apply.into_iter() {
1377            let rev: u64 = *next_hub_revision;
1378            *next_hub_revision = next_hub_revision.saturating_add(1);
1379            let mut upd: DynamicComponentUpdate =
1380                DynamicComponentUpdate::new(scoped_slot_id, rev, spec);
1381            upd.set_allow_downgrade(true);
1382            upd.sign();
1383            let _: u64 = hub
1384                .apply_component(upd)
1385                .map_err(|err: DynamicUpdateError| {
1386                    DynamicReleaseError::StorageError(err.to_string())
1387                })?;
1388        }
1389        Ok(())
1390    }
1391}