Skip to main content

euv_core/dynamic/state/
impl.rs

1use super::*;
2
3/// Builder and accessor methods for `BusinessCommand`.
4impl BusinessCommand {
5    /// Returns the optional expected optimistic concurrency revision.
6    ///
7    /// # Returns
8    ///
9    /// - `Option<u64>` - Expected entity revision if set.
10    #[must_use]
11    pub fn expected_revision_value(&self) -> Option<u64> {
12        let Self {
13            expected_revision, ..
14        } = *self;
15        expected_revision
16    }
17
18    /// Attaches an optimistic concurrency expected revision to this command.
19    ///
20    /// # Arguments
21    ///
22    /// - `u64` - Expected live entity revision.
23    ///
24    /// # Returns
25    ///
26    /// - `Self` - Updated command.
27    #[must_use]
28    pub fn with_expected_revision(mut self, revision: u64) -> Self {
29        self.set_expected_revision(Some(revision));
30        self
31    }
32
33    /// Attaches a caller-supplied idempotency key for deduplication across retries.
34    ///
35    /// # Arguments
36    ///
37    /// - `String` - Stable idempotency key.
38    ///
39    /// # Returns
40    ///
41    /// - `Self` - Updated command.
42    #[must_use]
43    pub fn with_idempotency_key(mut self, key: String) -> Self {
44        self.set_idempotency_key(key);
45        self
46    }
47
48    /// Records the release generation active on the originating route when this command was issued.
49    ///
50    /// # Arguments
51    ///
52    /// - `u64` - Originating release generation identifier.
53    ///
54    /// # Returns
55    ///
56    /// - `Self` - Updated command.
57    #[must_use]
58    pub fn with_origin_generation(mut self, generation: u64) -> Self {
59        self.set_origin_generation(generation);
60        self
61    }
62}
63
64/// Accessor helper for `InFlightOperation`.
65impl InFlightOperation {
66    /// Returns the optional expected revision captured when this operation started.
67    ///
68    /// # Returns
69    ///
70    /// - `Option<u64>` - Expected revision if set.
71    #[must_use]
72    pub fn expected_revision_value(&self) -> Option<u64> {
73        let Self {
74            expected_revision, ..
75        } = *self;
76        expected_revision
77    }
78}
79
80/// Default empty `BusinessStateStore`.
81impl Default for BusinessStateStore {
82    /// Creates a `BusinessStateStore` with `DEFAULT_STATE_DELTA_HISTORY_CAP`.
83    ///
84    /// # Returns
85    ///
86    /// - `Self` - Empty authoritative business state store.
87    fn default() -> Self {
88        Self::new(DEFAULT_STATE_DELTA_HISTORY_CAP)
89    }
90}
91
92/// Authoritative business state orchestration on `BusinessStateStore`.
93impl BusinessStateStore {
94    /// Creates a new `BusinessStateStore` retaining up to `delta_cap` historical deltas per entity.
95    ///
96    /// # Arguments
97    ///
98    /// - `usize` - Maximum per-entity delta history length.
99    ///
100    /// # Returns
101    ///
102    /// - `Self` - Initialized authoritative store.
103    #[must_use]
104    pub fn new(delta_cap: usize) -> Self {
105        let inner: BusinessStateStoreInner = BusinessStateStoreInner {
106            delta_cap: delta_cap.max(1),
107            next_op_id: 1,
108            next_sub_id: 1,
109            global_revision: 0,
110            entities: BTreeMap::new(),
111            idempotency_cache: HashMap::new(),
112            in_flight: BTreeMap::new(),
113            subscriptions: BTreeMap::new(),
114        };
115        Self {
116            inner: Arc::new(Mutex::new(inner)),
117        }
118    }
119
120    /// Seeds or initializes an authoritative entity at revision `1` if absent and returns its revision.
121    ///
122    /// # Arguments
123    ///
124    /// - `&str` - Entity identifier.
125    /// - `Value` - Initial authoritative state.
126    ///
127    /// # Returns
128    ///
129    /// - `Result<u64, DynamicReleaseError>` - Entity revision after seeding.
130    pub fn seed_entity(&self, entity_id: &str, state: Value) -> Result<u64, DynamicReleaseError> {
131        let trimmed: &str = entity_id.trim();
132        if trimmed.is_empty() {
133            return Err(DynamicReleaseError::StorageError(
134                ERR_EMPTY_ENTITY_ID.to_string(),
135            ));
136        }
137        let Self { inner } = self;
138        let mut guard: MutexGuard<'_, BusinessStateStoreInner> = inner
139            .lock()
140            .map_err(|_| DynamicReleaseError::StorageError(ERR_STATE_STORE_POISONED.to_string()))?;
141        if let Some(existing) = guard.entities.get(trimmed) {
142            return Ok(existing.revision);
143        }
144        guard.global_revision = guard.global_revision.saturating_add(1);
145        let record: EntityStateRecord = EntityStateRecord {
146            revision: 1,
147            state,
148            deltas: VecDeque::with_capacity(guard.delta_cap.min(32)),
149        };
150        let _: Option<EntityStateRecord> = guard.entities.insert(trimmed.to_string(), record);
151        Ok(1)
152    }
153
154    /// Reads the current authoritative `(revision, state)` pair for `entity_id`.
155    ///
156    /// # Arguments
157    ///
158    /// - `&str` - Entity identifier.
159    ///
160    /// # Returns
161    ///
162    /// - `Option<(u64, Value)>` - Revision and cloned authoritative state if present.
163    #[must_use]
164    pub fn read_entity(&self, entity_id: &str) -> Option<(u64, Value)> {
165        let Self { inner } = self;
166        let guard: MutexGuard<'_, BusinessStateStoreInner> = inner.lock().ok()?;
167        guard
168            .entities
169            .get(entity_id)
170            .map(|rec: &EntityStateRecord| (rec.revision, rec.state.clone()))
171    }
172
173    /// Returns the monotonic global store revision across all entities.
174    ///
175    /// # Returns
176    ///
177    /// - `u64` - Global authoritative revision number.
178    #[must_use]
179    pub fn global_revision(&self) -> u64 {
180        let Self { inner } = self;
181        inner
182            .lock()
183            .map(|g: MutexGuard<'_, BusinessStateStoreInner>| g.global_revision)
184            .unwrap_or(0)
185    }
186
187    /// Captures a read-only snapshot of all entities and the global revision `R`.
188    ///
189    /// # Returns
190    ///
191    /// - `(u64, BTreeMap<String, (u64, Value)>)` - Global revision `R` paired with per-entity snapshots.
192    #[must_use]
193    pub fn capture_entity_snapshots(&self) -> (u64, BTreeMap<String, (u64, Value)>) {
194        let Self { inner } = self;
195        let Ok(guard) = inner.lock() else {
196            return (0, BTreeMap::new());
197        };
198        let mut snaps: BTreeMap<String, (u64, Value)> = BTreeMap::new();
199        for (entity_id, rec) in guard.entities.iter() {
200            let _: Option<(u64, Value)> =
201                snaps.insert(entity_id.clone(), (rec.revision, rec.state.clone()));
202        }
203        (guard.global_revision, snaps)
204    }
205
206    /// Registers a field-filtered subscriber for `entity_id` owned by `generation_id`.
207    ///
208    /// # Arguments
209    ///
210    /// - `&str` - Target entity identifier.
211    /// - `u64` - Owning release generation identifier.
212    /// - `Vec<String>` - Subset of watched fields (empty watches all changes).
213    ///
214    /// # Returns
215    ///
216    /// - `Result<u64, DynamicReleaseError>` - Assigned subscription identifier.
217    pub fn subscribe_entity(
218        &self,
219        entity_id: &str,
220        generation_id: u64,
221        watched_fields: Vec<String>,
222    ) -> Result<u64, DynamicReleaseError> {
223        let Self { inner } = self;
224        let mut guard: MutexGuard<'_, BusinessStateStoreInner> = inner
225            .lock()
226            .map_err(|_| DynamicReleaseError::StorageError(ERR_STATE_STORE_POISONED.to_string()))?;
227        let sub_id: u64 = guard.next_sub_id;
228        guard.next_sub_id = guard.next_sub_id.saturating_add(1);
229        let mut sub: StateSubscription =
230            StateSubscription::new(sub_id, entity_id.to_string(), generation_id, watched_fields);
231        sub.set_active(true);
232        let _: Option<StateSubscription> = guard.subscriptions.insert(sub_id, sub);
233        Ok(sub_id)
234    }
235
236    /// Cancels all subscriptions belonging to `generation_id` so destroyed instances never receive callbacks.
237    ///
238    /// # Arguments
239    ///
240    /// - `u64` - Retired release generation identifier.
241    pub fn cancel_generation_subscriptions(&self, generation_id: u64) {
242        let Self { inner } = self;
243        if let Ok(mut guard) = inner.lock() {
244            for sub in guard.subscriptions.values_mut() {
245                if sub.get_generation_id() == generation_id {
246                    sub.set_active(false);
247                }
248            }
249        }
250    }
251
252    /// Returns the list of revisions delivered to subscription `subscription_id`.
253    ///
254    /// # Arguments
255    ///
256    /// - `u64` - Subscription identifier.
257    ///
258    /// # Returns
259    ///
260    /// - `Vec<u64>` - Delivered entity revision numbers.
261    #[must_use]
262    pub fn delivered_revisions(&self, subscription_id: u64) -> Vec<u64> {
263        let Self { inner } = self;
264        inner
265            .lock()
266            .ok()
267            .and_then(|g: MutexGuard<'_, BusinessStateStoreInner>| {
268                g.subscriptions
269                    .get(&subscription_id)
270                    .map(|s: &StateSubscription| s.get_delivered_revisions().clone())
271            })
272            .unwrap_or_default()
273    }
274
275    /// Accepts an asynchronous business command into host-owned in-flight tracking, returning its `OperationId`.
276    ///
277    /// # Arguments
278    ///
279    /// - `BusinessCommand` - Command submitted by a page or dynamic component.
280    ///
281    /// # Returns
282    ///
283    /// - `Result<CommandOutcome, DynamicReleaseError>` - `Pending` or deduplicated `Committed` / `Rejected*` outcome.
284    pub fn begin_operation(
285        &self,
286        command: BusinessCommand,
287    ) -> Result<CommandOutcome, DynamicReleaseError> {
288        let entity_id: String = command.get_entity_id().trim().to_string();
289        if entity_id.is_empty() {
290            return Err(DynamicReleaseError::StorageError(
291                ERR_EMPTY_ENTITY_ID.to_string(),
292            ));
293        }
294        let Self { inner } = self;
295        let mut guard: MutexGuard<'_, BusinessStateStoreInner> = inner
296            .lock()
297            .map_err(|_| DynamicReleaseError::StorageError(ERR_STATE_STORE_POISONED.to_string()))?;
298        let idem: String = command.get_idempotency_key().clone();
299        if !idem.is_empty()
300            && let Some(cached) = guard
301                .idempotency_cache
302                .get(&(entity_id.clone(), idem.clone()))
303        {
304            if let CommandOutcome::Committed {
305                operation_id,
306                entity_id: eid,
307                revision,
308                state,
309                ..
310            } = cached
311            {
312                return Ok(CommandOutcome::Committed {
313                    operation_id: *operation_id,
314                    entity_id: eid.clone(),
315                    revision: *revision,
316                    state: state.clone(),
317                    deduplicated: true,
318                });
319            }
320            return Ok(cached.clone());
321        }
322        let op_id: OperationId = OperationId::new(guard.next_op_id);
323        guard.next_op_id = guard.next_op_id.saturating_add(1);
324        let live_rev: u64 = guard
325            .entities
326            .get(&entity_id)
327            .map(|rec: &EntityStateRecord| rec.revision)
328            .unwrap_or(0);
329        if let Some(expected) = command.expected_revision_value()
330            && expected != live_rev
331        {
332            return Ok(CommandOutcome::RejectedRevisionConflict {
333                operation_id: op_id,
334                expected,
335                actual: live_rev,
336            });
337        }
338        let op: InFlightOperation = InFlightOperation::new(
339            op_id,
340            entity_id.clone(),
341            command.get_command_name().clone(),
342            idem,
343            command.get_origin_generation(),
344            command.expected_revision_value(),
345            false,
346        );
347        let _: Option<InFlightOperation> = guard.in_flight.insert(op_id, op);
348        Ok(CommandOutcome::Pending {
349            operation_id: op_id,
350            entity_id,
351            submitted_revision: live_rev,
352        })
353    }
354
355    /// Completes a previously accepted host-owned in-flight operation regardless of component hot-swaps.
356    ///
357    /// # Arguments
358    ///
359    /// - `OperationId` - Host-assigned operation identifier returned by `begin_operation`.
360    /// - `Value` - Authoritative post-operation entity state.
361    /// - `Vec<String>` - Field names mutated by this completion.
362    ///
363    /// # Returns
364    ///
365    /// - `Result<CommandOutcome, DynamicReleaseError>` - Committed outcome or conflict error.
366    pub fn complete_operation(
367        &self,
368        operation_id: OperationId,
369        next_state: Value,
370        changed_fields: Vec<String>,
371    ) -> Result<CommandOutcome, DynamicReleaseError> {
372        let Self { inner } = self;
373        let mut guard: MutexGuard<'_, BusinessStateStoreInner> = inner
374            .lock()
375            .map_err(|_| DynamicReleaseError::StorageError(ERR_STATE_STORE_POISONED.to_string()))?;
376        let Some(mut op) = guard.in_flight.remove(&operation_id) else {
377            return Err(DynamicReleaseError::StorageError(format!(
378                "{ERR_UNKNOWN_OPERATION}: {}",
379                operation_id.get_raw()
380            )));
381        };
382        let entity_id: String = op.get_entity_id().clone();
383        let live_rev: u64 = guard
384            .entities
385            .get(&entity_id)
386            .map(|rec: &EntityStateRecord| rec.revision)
387            .unwrap_or(0);
388        if let Some(expected) = op.expected_revision_value()
389            && expected != live_rev
390        {
391            return Ok(CommandOutcome::RejectedRevisionConflict {
392                operation_id,
393                expected,
394                actual: live_rev,
395            });
396        }
397        let next_rev: u64 = live_rev.saturating_add(1);
398        guard.global_revision = guard.global_revision.saturating_add(1);
399        let delta_cap: usize = guard.delta_cap;
400        let delta: BusinessStateDelta = BusinessStateDelta::new(
401            entity_id.clone(),
402            next_rev,
403            operation_id,
404            changed_fields.clone(),
405            next_state.clone(),
406        );
407        let entry: &mut EntityStateRecord =
408            guard
409                .entities
410                .entry(entity_id.clone())
411                .or_insert_with(|| EntityStateRecord {
412                    revision: 0,
413                    state: Value::Null,
414                    deltas: VecDeque::with_capacity(delta_cap.min(32)),
415                });
416        entry.revision = next_rev;
417        entry.state = next_state.clone();
418        if entry.deltas.len() >= delta_cap {
419            let _: Option<BusinessStateDelta> = entry.deltas.pop_front();
420        }
421        entry.deltas.push_back(delta);
422        for sub in guard.subscriptions.values_mut() {
423            if !sub.get_active() || sub.get_entity_id() != &entity_id {
424                continue;
425            }
426            let matches_field: bool = sub.get_watched_fields().is_empty()
427                || changed_fields.is_empty()
428                || sub
429                    .get_watched_fields()
430                    .iter()
431                    .any(|f: &String| changed_fields.contains(f));
432            if matches_field {
433                sub.get_mut_delivered_revisions().push(next_rev);
434            }
435        }
436        op.set_completed(true);
437        let outcome: CommandOutcome = CommandOutcome::Committed {
438            operation_id,
439            entity_id: entity_id.clone(),
440            revision: next_rev,
441            state: next_state,
442            deduplicated: false,
443        };
444        let idem: String = op.get_idempotency_key().clone();
445        if !idem.is_empty() {
446            let _: Option<CommandOutcome> = guard
447                .idempotency_cache
448                .insert((entity_id, idem), outcome.clone());
449        }
450        Ok(outcome)
451    }
452
453    /// Synchronously validates, commits, and deduplicates a typed command in a single atomic host step.
454    ///
455    /// # Arguments
456    ///
457    /// - `BusinessCommand` - Typed mutation command.
458    /// - `Value` - Resulting authoritative entity state.
459    /// - `Vec<String>` - Mutated field names.
460    ///
461    /// # Returns
462    ///
463    /// - `Result<CommandOutcome, DynamicReleaseError>` - Committed or rejected outcome.
464    pub fn commit_command(
465        &self,
466        command: BusinessCommand,
467        next_state: Value,
468        changed_fields: Vec<String>,
469    ) -> Result<CommandOutcome, DynamicReleaseError> {
470        match self.begin_operation(command)? {
471            CommandOutcome::Pending { operation_id, .. } => {
472                self.complete_operation(operation_id, next_state, changed_fields)
473            }
474            terminal => Ok(terminal),
475        }
476    }
477
478    /// Returns all authoritative deltas strictly newer than `base_revision` for `entity_id`, or `StateCatchUpConflict` if history wrapped.
479    ///
480    /// # Arguments
481    ///
482    /// - `&str` - Entity identifier.
483    /// - `u64` - Snapshot baseline revision `R`.
484    ///
485    /// # Returns
486    ///
487    /// - `Result<Vec<BusinessStateDelta>, DynamicReleaseError>` - Ordered catch-up deltas from `R+1` to `R+n`.
488    pub fn deltas_since(
489        &self,
490        entity_id: &str,
491        base_revision: u64,
492    ) -> Result<Vec<BusinessStateDelta>, DynamicReleaseError> {
493        let Self { inner } = self;
494        let guard: MutexGuard<'_, BusinessStateStoreInner> = inner
495            .lock()
496            .map_err(|_| DynamicReleaseError::StorageError(ERR_STATE_STORE_POISONED.to_string()))?;
497        let Some(rec) = guard.entities.get(entity_id) else {
498            return Ok(Vec::new());
499        };
500        if base_revision == rec.revision {
501            return Ok(Vec::new());
502        }
503        if base_revision > rec.revision {
504            return Err(DynamicReleaseError::StateCatchUpConflict {
505                base_revision,
506                live_revision: rec.revision,
507            });
508        }
509        let earliest_delta_rev: u64 = rec
510            .deltas
511            .front()
512            .map(BusinessStateDelta::get_revision)
513            .unwrap_or(u64::MAX);
514        if earliest_delta_rev > base_revision.saturating_add(1) {
515            return Err(DynamicReleaseError::StateCatchUpConflict {
516                base_revision,
517                live_revision: rec.revision,
518            });
519        }
520        let out: Vec<BusinessStateDelta> = rec
521            .deltas
522            .iter()
523            .filter(|d: &&BusinessStateDelta| d.get_revision() > base_revision)
524            .cloned()
525            .collect();
526        Ok(out)
527    }
528
529    /// Returns the number of currently active host-owned in-flight operations.
530    ///
531    /// # Returns
532    ///
533    /// - `usize` - Count of pending in-flight operations.
534    #[must_use]
535    pub fn active_in_flight_count(&self) -> usize {
536        let Self { inner } = self;
537        inner
538            .lock()
539            .map(|g: MutexGuard<'_, BusinessStateStoreInner>| g.in_flight.len())
540            .unwrap_or(0)
541    }
542}
543
544/// Construction, formatting, and parsing helpers for `StableAddress`.
545impl StableAddress {
546    /// Creates a new `StableAddress` from route instance, ancestor business keys, slot key, and optional child key.
547    ///
548    /// # Arguments
549    ///
550    /// - `String` - Route instance key (e.g. `"A#tab-1"`).
551    /// - `Vec<String>` - Ancestor logical business keys.
552    /// - `String` - Logical slot identifier.
553    /// - `Option<String>` - Optional child business ID key.
554    ///
555    /// # Returns
556    ///
557    /// - `Self` - Constructed stable address.
558    #[must_use]
559    pub fn new(
560        route_instance: String,
561        ancestor_keys: Vec<String>,
562        slot_key: String,
563        child_key: Option<String>,
564    ) -> Self {
565        Self {
566            route_instance,
567            ancestor_keys,
568            slot_key,
569            child_key,
570        }
571    }
572
573    /// Returns the optional child business key.
574    ///
575    /// # Returns
576    ///
577    /// - `Option<&str>` - Child key if present.
578    #[must_use]
579    pub fn child_key_str(&self) -> Option<&str> {
580        let Self { child_key, .. } = self;
581        child_key.as_deref()
582    }
583
584    /// Formats this stable address as a canonical slash-delimited string (`route#tab/entity/slot[/child]`).
585    ///
586    /// # Returns
587    ///
588    /// - `String` - Canonical stable address key.
589    #[must_use]
590    pub fn canonical(&self) -> String {
591        let mut parts: Vec<&str> = Vec::with_capacity(self.get_ancestor_keys().len() + 3);
592        parts.push(self.get_route_instance().as_str());
593        for ancestor in self.get_ancestor_keys().iter() {
594            parts.push(ancestor.as_str());
595        }
596        parts.push(self.get_slot_key().as_str());
597        if let Some(child) = self.child_key_str() {
598            parts.push(child);
599        }
600        parts.join("/")
601    }
602
603    /// Parses a canonical slash-delimited `StableAddress` string (`route#tab/[ancestors.../]slot`).
604    ///
605    /// # Arguments
606    ///
607    /// - `&str` - Canonical address string.
608    ///
609    /// # Returns
610    ///
611    /// - `Result<Self, DynamicReleaseError>` - Parsed stable address or error.
612    pub fn parse(raw: &str) -> Result<Self, DynamicReleaseError> {
613        let segments: Vec<&str> = raw
614            .split(STABLE_ADDR_SEP)
615            .filter(|s: &&str| !s.is_empty())
616            .collect();
617        if segments.len() < 2 {
618            return Err(DynamicReleaseError::StateMigrationFailed(
619                ERR_INVALID_STABLE_ADDRESS.to_string(),
620            ));
621        }
622        let route_instance: String = segments[0].to_string();
623        let slot_key: String = segments[segments.len() - 1].to_string();
624        let ancestor_keys: Vec<String> = segments[1..segments.len() - 1]
625            .iter()
626            .map(|s: &&str| (*s).to_string())
627            .collect();
628        Ok(Self {
629            route_instance,
630            ancestor_keys,
631            slot_key,
632            child_key: None,
633        })
634    }
635}
636
637/// Accessor and builder helpers for `ComponentUiStateSnapshot`.
638impl ComponentUiStateSnapshot {
639    /// Returns the optional scroll anchor business key.
640    ///
641    /// # Returns
642    ///
643    /// - `Option<&str>` - Scroll anchor key if set.
644    #[must_use]
645    pub fn scroll_anchor(&self) -> Option<&str> {
646        let Self {
647            scroll_anchor_key, ..
648        } = self;
649        scroll_anchor_key.as_deref()
650    }
651
652    /// Returns the optional focused logical node key.
653    ///
654    /// # Returns
655    ///
656    /// - `Option<&str>` - Focused node key if set.
657    #[must_use]
658    pub fn focused_node(&self) -> Option<&str> {
659        let Self {
660            focused_node_key, ..
661        } = self;
662        focused_node_key.as_deref()
663    }
664
665    /// Sets the scroll anchor business key and pixel offset on this snapshot.
666    ///
667    /// # Arguments
668    ///
669    /// - `String` - Business anchor key.
670    /// - `f32` - Logical scroll Y offset.
671    ///
672    /// # Returns
673    ///
674    /// - `Self` - Updated snapshot.
675    #[must_use]
676    pub fn with_scroll(mut self, anchor_key: String, offset_y: f32) -> Self {
677        self.set_scroll_anchor_key(Some(anchor_key))
678            .set_scroll_offset_y(offset_y);
679        self
680    }
681
682    /// Sets the focused logical node key on this snapshot.
683    ///
684    /// # Arguments
685    ///
686    /// - `String` - Focused node key.
687    ///
688    /// # Returns
689    ///
690    /// - `Self` - Updated snapshot.
691    #[must_use]
692    pub fn with_focus(mut self, node_key: String) -> Self {
693        self.set_focused_node_key(Some(node_key));
694        self
695    }
696
697    /// Inserts a form draft field into this snapshot.
698    ///
699    /// # Arguments
700    ///
701    /// - `String` - Draft field name.
702    /// - `String` - Draft field value.
703    ///
704    /// # Returns
705    ///
706    /// - `Self` - Updated snapshot.
707    #[must_use]
708    pub fn with_draft_field(mut self, key: String, value: String) -> Self {
709        let _: Option<String> = self.get_mut_form_draft().insert(key, value);
710        self
711    }
712}
713
714/// Configuration helpers for `DefaultStateMigrator`.
715impl DefaultStateMigrator {
716    /// Registers an explicit field rename mapping between `from_schema` and `to_schema`.
717    ///
718    /// # Arguments
719    ///
720    /// - `u32` - Source schema version.
721    /// - `u32` - Target schema version.
722    /// - `String` - Old form draft field name.
723    /// - `String` - New form draft field name.
724    ///
725    /// # Returns
726    ///
727    /// - `&mut Self` - Mutable migrator reference for chaining.
728    pub fn add_field_rename(
729        &mut self,
730        from_schema: u32,
731        to_schema: u32,
732        old_key: String,
733        new_key: String,
734    ) -> &mut Self {
735        let _: Option<String> = self
736            .get_mut_field_renames()
737            .entry((from_schema, to_schema))
738            .or_default()
739            .insert(old_key, new_key);
740        self
741    }
742
743    /// Registers a default field added when upgrading from `from_schema` to `to_schema`.
744    ///
745    /// # Arguments
746    ///
747    /// - `u32` - Source schema version.
748    /// - `u32` - Target schema version.
749    /// - `String` - Added field name.
750    /// - `String` - Default value for the newly added field.
751    ///
752    /// # Returns
753    ///
754    /// - `&mut Self` - Mutable migrator reference for chaining.
755    pub fn add_default_field(
756        &mut self,
757        from_schema: u32,
758        to_schema: u32,
759        field_key: String,
760        default_val: String,
761    ) -> &mut Self {
762        let _: Option<String> = self
763            .get_mut_default_additions()
764            .entry((from_schema, to_schema))
765            .or_default()
766            .insert(field_key, default_val);
767        self
768    }
769}
770
771/// Pure background migration logic for `DefaultStateMigrator`.
772impl StateMigrator for DefaultStateMigrator {
773    /// Purely transforms `snapshot` from `from_schema` to `to_schema`, refusing to drop unmapped user drafts.
774    ///
775    /// # Arguments
776    ///
777    /// - `u32` - Source schema version.
778    /// - `u32` - Target schema version.
779    /// - `&ComponentUiStateSnapshot` - Source immutable UI state snapshot.
780    ///
781    /// # Returns
782    ///
783    /// - `Result<ComponentUiStateSnapshot, DynamicReleaseError>` - Migrated state snapshot or failure.
784    fn migrate(
785        &self,
786        from_schema: u32,
787        to_schema: u32,
788        snapshot: &ComponentUiStateSnapshot,
789    ) -> Result<ComponentUiStateSnapshot, DynamicReleaseError> {
790        if from_schema == to_schema {
791            return Ok(snapshot.clone());
792        }
793        let renames: Option<&BTreeMap<String, String>> =
794            self.get_field_renames().get(&(from_schema, to_schema));
795        let additions: Option<&BTreeMap<String, String>> =
796            self.get_default_additions().get(&(from_schema, to_schema));
797        if renames.is_none()
798            && additions.is_none()
799            && !snapshot.get_form_draft().is_empty()
800            && to_schema > from_schema.saturating_add(1)
801        {
802            return Err(DynamicReleaseError::StateMigrationFailed(format!(
803                "{ERR_INCOMPATIBLE_SCHEMA_DRAFT}: v{from_schema} -> v{to_schema}"
804            )));
805        }
806        let mut next: ComponentUiStateSnapshot = snapshot.clone();
807        next.set_schema_version(to_schema);
808        if let Some(rename_map) = renames {
809            let mut remapped: BTreeMap<String, String> = BTreeMap::new();
810            for (k, v) in snapshot.get_form_draft().iter() {
811                let target_k: String = rename_map.get(k).cloned().unwrap_or_else(|| k.clone());
812                let _: Option<String> = remapped.insert(target_k, v.clone());
813            }
814            next.set_form_draft(remapped);
815        }
816        if let Some(add_map) = additions {
817            for (k, v) in add_map.iter() {
818                if !next.get_form_draft().contains_key(k) {
819                    let _: Option<String> = next.get_mut_form_draft().insert(k.clone(), v.clone());
820                }
821            }
822        }
823        Ok(next)
824    }
825}
826
827/// Safe default `InteractionSafePoint` representing an idle frame boundary with ample budget.
828impl Default for InteractionSafePoint {
829    /// Creates an idle `InteractionSafePoint` with full frame budget.
830    ///
831    /// # Returns
832    ///
833    /// - `Self` - Safe frame boundary descriptor.
834    fn default() -> Self {
835        Self {
836            active_gesture: false,
837            ime_composing: false,
838            active_transition: false,
839            blocking_in_flight_tx: 0,
840            frame_budget_remaining_us: 8_000,
841        }
842    }
843}
844
845/// Frame-boundary safety checks on `InteractionSafePoint`.
846impl InteractionSafePoint {
847    /// Returns `true` when swapping the UI subtree will not disrupt gestures, IME, transitions, blocking tx, or frame budget.
848    ///
849    /// # Returns
850    ///
851    /// - `bool` - Whether atomic hot-swap is safe at this boundary.
852    #[must_use]
853    pub fn is_safe_to_swap(&self) -> bool {
854        self.defer_reason().is_none()
855    }
856
857    /// Returns the human-readable reason why a swap must be deferred, or `None` if safe.
858    ///
859    /// # Returns
860    ///
861    /// - `Option<&'static str>` - Deferral reason if unsafe.
862    #[must_use]
863    pub fn defer_reason(&self) -> Option<&'static str> {
864        if self.get_active_gesture() {
865            return Some(DEFER_REASON_GESTURE);
866        }
867        if self.get_ime_composing() {
868            return Some(DEFER_REASON_IME);
869        }
870        if self.get_active_transition() {
871            return Some(DEFER_REASON_TRANSITION);
872        }
873        if self.get_blocking_in_flight_tx() > 0 {
874            return Some(DEFER_REASON_TX);
875        }
876        if self.get_frame_budget_remaining_us() < DEFAULT_SWAP_MIN_FRAME_BUDGET_US {
877            return Some(DEFER_REASON_BUDGET);
878        }
879        None
880    }
881}