1use super::*;
2
3impl BusinessCommand {
5 #[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 #[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 #[must_use]
43 pub fn with_idempotency_key(mut self, key: String) -> Self {
44 self.set_idempotency_key(key);
45 self
46 }
47
48 #[must_use]
58 pub fn with_origin_generation(mut self, generation: u64) -> Self {
59 self.set_origin_generation(generation);
60 self
61 }
62}
63
64impl InFlightOperation {
66 #[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
80impl Default for BusinessStateStore {
82 fn default() -> Self {
88 Self::new(DEFAULT_STATE_DELTA_HISTORY_CAP)
89 }
90}
91
92impl BusinessStateStore {
94 #[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 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 #[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 #[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 #[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 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 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 #[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 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 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 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 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 #[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
544impl StableAddress {
546 #[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 #[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 #[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 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
637impl ComponentUiStateSnapshot {
639 #[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 #[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 #[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 #[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 #[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
714impl DefaultStateMigrator {
716 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 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
771impl StateMigrator for DefaultStateMigrator {
773 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
827impl Default for InteractionSafePoint {
829 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
845impl InteractionSafePoint {
847 #[must_use]
853 pub fn is_safe_to_swap(&self) -> bool {
854 self.defer_reason().is_none()
855 }
856
857 #[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}