adam_web_ui/binding/recording.rs
1//! Persists exact effective sources independently of aspiration-preserving recovery.
2//!
3//! Use [`super::SheetOwner::capture`] after acceptance, serialize [`Recording`]
4//! with serde, and pass it to [`super::SheetOwner::playback`] with the same schema.
5
6use super::{BindingError, CellEdit, HostRejection};
7use crate::{BuildError, BuiltSheet, RuntimeFailure, input::InputError};
8use serde::{Deserialize, Serialize};
9use std::collections::{HashMap, HashSet};
10
11/// Stores a compatible schema's exact effective source values by stable key.
12///
13/// Values own their encoded text; no runtime IDs or display-rounded values persist.
14/// The schema key identifies types, codecs, graph, and uncaptured initial values.
15///
16/// # Examples
17/// ```
18/// use adam_web_ui::binding::{CellEdit, Recording};
19/// let recording = Recording {
20/// schema_key: "example/v1".into(),
21/// values: vec![CellEdit { key: "count".into(), canonical: "10".into() }],
22/// };
23/// let json = serde_json::to_string(&recording).unwrap();
24/// assert_eq!(serde_json::from_str::<Recording>(&json).unwrap(), recording);
25/// ```
26#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Recording {
28 /// Host-defined schema and exact-codec identity.
29 pub schema_key: String,
30 /// Deduplicated effective sources, never input aspirations.
31 pub values: Vec<CellEdit>,
32}
33
34/// Distinguishes capture capabilities, encoding, schema, and model availability.
35///
36/// # Examples
37/// ```
38/// use adam_web_ui::binding::CaptureError;
39/// assert!(matches!(CaptureError::UnnamedSource, CaptureError::UnnamedSource));
40/// ```
41#[derive(Debug)]
42pub enum CaptureError {
43 /// A requested result lacks a live stable key.
44 UnknownResult(String),
45 /// A contributing source has no host-owned stable key.
46 UnnamedSource,
47 /// A contributing source lacks an exact scalar codec.
48 MissingCodec(String),
49 /// An exact typed read or encoding failed.
50 Encoding {
51 /// Stable source key.
52 key: String,
53 /// Structured codec diagnostic.
54 error: InputError,
55 },
56 /// The recording belongs to another schema or codec contract.
57 SchemaMismatch {
58 /// Requested model schema.
59 expected: String,
60 /// Persisted recording schema.
61 actual: String,
62 },
63 /// No accepted live model is available for capture.
64 Unavailable(BindingError),
65}
66
67/// Preserves construction, input rejection, capture, and fatal playback categories.
68///
69/// # Examples
70/// ```
71/// use adam_web_ui::binding::{CaptureError, PlaybackError};
72/// let error = PlaybackError::Capture(CaptureError::UnnamedSource);
73/// assert!(matches!(error, PlaybackError::Capture(_)));
74/// ```
75#[derive(Debug)]
76pub enum PlaybackError {
77 /// Recording compatibility validation failed.
78 Capture(CaptureError),
79 /// Fresh model construction failed.
80 Build(BuildError),
81 /// The captured group was rejected and its candidate discarded.
82 Rejected(HostRejection),
83 /// Runtime propagation failed without reconstruction or retry.
84 Fatal(RuntimeFailure),
85}
86
87/// Captures selected effective sources using only public source analysis and codecs.
88///
89/// # Errors
90/// Returns unknown results, unnamed sources, missing codecs, or exact encoding errors.
91///
92/// - Complexity: Public source-analysis cost plus expected O(results + keys +
93/// sources + encoded bytes) time and space.
94pub(super) fn capture<'a>(
95 built: &BuiltSheet,
96 schema_key: &str,
97 result_keys: impl Iterator<Item = &'a str>,
98) -> Result<Recording, CaptureError> {
99 let results = result_keys
100 .map(|key| {
101 built
102 .keys
103 .get(key)
104 .copied()
105 .ok_or_else(|| CaptureError::UnknownResult(key.into()))
106 })
107 .collect::<Result<Vec<_>, _>>()?;
108 let mut keys = HashMap::with_capacity(built.keys.len());
109 // Iterate the authoritative IndexMap in registration order; the reverse
110 // HashMap serves only lookups and never determines which alias wins.
111 for (key, &id) in &built.keys {
112 keys.entry(id).or_insert(key.as_str());
113 }
114 let mut seen = HashSet::new();
115 let values = built
116 .parsed
117 .source_cells(&results)
118 .filter(|id| seen.insert(*id))
119 .map(|id| {
120 let key = *keys.get(&id).ok_or(CaptureError::UnnamedSource)?;
121 let meta = built
122 .labels
123 .cells
124 .get(&id)
125 .filter(|meta| meta.codec_supported)
126 .ok_or_else(|| CaptureError::MissingCodec(key.into()))?;
127 let canonical =
128 (meta.capture)(&built.parsed).map_err(|error| CaptureError::Encoding {
129 key: key.into(),
130 error,
131 })?;
132 Ok(CellEdit {
133 key: key.into(),
134 canonical,
135 })
136 })
137 .collect::<Result<Vec<_>, _>>()?;
138 Ok(Recording {
139 schema_key: schema_key.into(),
140 values,
141 })
142}