Skip to main content

euv_core/dynamic/engine/
impl.rs

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