Skip to main content

adam_web_ui/binding/
owner.rs

1//! Serializes transactions without exposing or reusing discarded candidates.
2//!
3//! [`SheetOwner`] keeps accepted inputs and views outside its mutable model.
4
5use super::types::*;
6use super::{CaptureError, PlaybackError, Recording, recording};
7use crate::build::validation_issues;
8use crate::{BuildError, BuiltSheet, Labels, RuntimeFailure, ValidationIssue};
9use adam_lang::ParsedSheet;
10use adam_rs::{CellId, Error};
11use std::{collections::HashSet, rc::Rc};
12
13/// Represents exclusive candidate ownership and distinguishes fatal retirement.
14enum ModelState {
15    /// Contains only an accepted live model.
16    Live(Box<BuiltSheet>),
17    /// Requires host-requested reconstruction.
18    Unavailable,
19    /// Forbids factory calls and further mutation.
20    Retired,
21    /// Reserves ownership while a transaction is in progress.
22    Mutating,
23}
24
25/// Owns one event-loop-confined model, accepted journal, and immutable publication.
26///
27/// Every rejection preserves published views and journal, but discards the live
28/// candidate. Only explicit restoration makes inspection available again.
29/// A fatal propagation error permanently forbids reconstruction and retry.
30/// The `Rc` factory and views intentionally make no `Send` or `Sync` promise.
31///
32/// # Examples
33/// ```
34/// use adam_web_ui::{binding::*, build_sheet};
35/// let mut owner = SheetOwner::new(std::rc::Rc::new(||
36///     build_sheet("sheet s { cell count: i32 = 1; }", "s.adm2")), "s/v1".into()).unwrap();
37/// let edit = CellEdit { key: "count".into(), canonical: "2".into() };
38/// assert!(matches!(owner.apply(&[edit], UpdateOrigin::User), HostOutcome::Accepted));
39/// assert_eq!(owner.views()[0].text, "2");
40/// ```
41pub struct SheetOwner {
42    factory: ModelFactory,
43    model: ModelState,
44    accepted: RecoveryState,
45    views: Vec<Rc<CellView>>,
46    recording_results: Option<Vec<String>>,
47    recordings: Vec<Rc<Recording>>,
48}
49
50impl SheetOwner {
51    /// Constructs and publishes one valid initial model without requiring outputs.
52    ///
53    /// # Errors
54    /// Returns construction errors or typed publication/capability-read failures.
55    ///
56    /// - Complexity: Factory cost plus publication over all named cells and their
57    ///   contributing graph traversals.
58    ///
59    /// # Examples
60    /// See [`SheetOwner`] for construction and a transaction.
61    pub fn new(factory: ModelFactory, schema_key: String) -> Result<Self, BuildError> {
62        let built = factory()?;
63        let views = publish(&built, &[]).map_err(|error| BuildError::Recovery(Box::new(error)))?;
64        Ok(Self {
65            factory,
66            model: ModelState::Live(Box::new(built)),
67            accepted: RecoveryState {
68                schema_key,
69                transactions: Vec::new(),
70            },
71            views,
72            recording_results: None,
73            recordings: Vec::new(),
74        })
75    }
76
77    /// Parses every edit, writes in order, and propagates once before acceptance.
78    ///
79    /// All accepted origins enter recovery history. Only `User` actions append
80    /// enabled recordings; playback and recovery suppress recording feedback.
81    /// An empty group is an accepted no-op on a live model and is not journaled.
82    ///
83    /// - Postcondition: Rejection leaves accepted views and history unchanged and
84    ///   makes inspection unavailable until explicit restoration.
85    /// - Postcondition: A propagation error retires the owner permanently.
86    /// - Postcondition: Recording failure preserves the newly accepted model,
87    ///   views, and history, stops recording, and returns `RecordingFailed`.
88    /// - Complexity: O(edit bytes + propagation + publication + enabled capture);
89    ///   retained history grows only by the accepted group and new recording,
90    ///   never by a copy of the prior journal.
91    ///
92    /// # Examples
93    /// See [`SheetOwner`] for submitting a canonical edit.
94    pub fn apply(&mut self, edits: &[CellEdit], origin: UpdateOrigin) -> HostOutcome {
95        if let Some(error) = state_error(&self.model) {
96            return HostOutcome::Rejected(HostRejection::Binding(error));
97        }
98        if edits.is_empty() {
99            return HostOutcome::Accepted;
100        }
101        let ModelState::Live(built) = std::mem::replace(&mut self.model, ModelState::Mutating)
102        else {
103            unreachable!("live state checked before taking exclusive ownership");
104        };
105        match transact(built, edits) {
106            Ok(built) => match publish(&built, &self.views) {
107                Ok(views) => {
108                    self.accepted.transactions.push(edits.to_vec());
109                    self.views = views;
110                    self.model = ModelState::Live(built);
111                    self.record_accepted(origin)
112                }
113                Err(error) => {
114                    self.model = ModelState::Unavailable;
115                    HostOutcome::Rejected(error)
116                }
117            },
118            Err(outcome) => {
119                self.model = if matches!(outcome, HostOutcome::Fatal(_)) {
120                    ModelState::Retired
121                } else {
122                    ModelState::Unavailable
123                };
124                outcome
125            }
126        }
127    }
128
129    /// Captures exact effective sources contributing to the selected stable keys.
130    ///
131    /// Empty selection captures all sources. Source order is unspecified; aliases
132    /// use the first registered stable key. Models must satisfy the fixed-point
133    /// replay contracts of [`adam_rs::Sheet::source_cells`].
134    ///
135    /// # Errors
136    /// Returns explicit result, source identity, codec, encoding, or availability errors.
137    ///
138    /// - Complexity: Source-analysis cost plus expected O(results + keys + sources
139    ///   + encoded bytes) time and space.
140    ///
141    /// # Examples
142    /// ```
143    /// use adam_web_ui::{binding::*, build_sheet};
144    /// let owner = SheetOwner::new(std::rc::Rc::new(||
145    ///     build_sheet("sheet s { cell x: i32 = 1; }", "s.adm2")), "s/v1".into()).unwrap();
146    /// assert_eq!(owner.capture(&["x"]).unwrap().values[0].canonical, "1");
147    /// ```
148    pub fn capture(&self, result_keys: &[&str]) -> Result<Recording, CaptureError> {
149        match &self.model {
150            ModelState::Live(built) => recording::capture(
151                built,
152                &self.accepted.schema_key,
153                result_keys.iter().copied(),
154            ),
155            other => Err(CaptureError::Unavailable(
156                state_error(other).expect("non-live state"),
157            )),
158        }
159    }
160
161    /// Enables subsequent accepted user-action capture after validating selection.
162    ///
163    /// Does not append an initial recording. A failed start preserves prior selection.
164    ///
165    /// # Errors
166    /// Returns the same capability, encoding, and availability errors as [`Self::capture`].
167    ///
168    /// - Complexity: Capture cost plus O(result-key bytes) retained space.
169    ///
170    /// # Examples
171    /// ```
172    /// use adam_web_ui::{binding::*, build_sheet};
173    /// let mut owner = SheetOwner::new(std::rc::Rc::new(||
174    ///     build_sheet("sheet s { cell x: i32 = 1; }", "s.adm2")), "s/v1".into()).unwrap();
175    /// owner.start_recording(&["x"]).unwrap();
176    /// let outcome = owner.apply(&[CellEdit { key: "x".into(), canonical: "2".into() }],
177    ///     UpdateOrigin::User);
178    /// assert!(matches!(outcome, HostOutcome::Accepted));
179    /// assert_eq!(owner.recordings()[0].values[0].canonical, "2");
180    /// owner.stop_recording();
181    /// ```
182    pub fn start_recording(&mut self, result_keys: &[&str]) -> Result<(), CaptureError> {
183        self.capture(result_keys)?;
184        self.recording_results = Some(result_keys.iter().map(|key| (*key).into()).collect());
185        Ok(())
186    }
187
188    /// Stops future action recording without deleting retained recordings.
189    ///
190    /// - Complexity: O(selected result-key bytes) destruction.
191    ///
192    /// # Examples
193    /// See [`Self::start_recording`]; call `owner.stop_recording()` to stop capture.
194    pub fn stop_recording(&mut self) {
195        self.recording_results = None;
196    }
197
198    /// Borrows shared immutable recordings without copying action history.
199    ///
200    /// # Examples
201    /// See [`Self::start_recording`]; `owner.recordings().is_empty()` holds before actions.
202    pub fn recordings(&self) -> &[Rc<Recording>] {
203        &self.recordings
204    }
205
206    /// Replays one effective source group on a fresh compatible owner without recording.
207    ///
208    /// Validates schema before construction and decodes every edit before mutation.
209    /// Writes all values before one propagation and requirement validation.
210    ///
211    /// # Errors
212    /// Returns schema, build, rejected-input/requirement, or fatal runtime errors.
213    /// Fatal failures never trigger a retry or reconstruction.
214    ///
215    /// - Complexity: Factory, transaction, and publication cost plus encoded bytes.
216    ///
217    /// # Examples
218    /// ```
219    /// use adam_web_ui::{binding::*, build_sheet};
220    /// let factory: ModelFactory = std::rc::Rc::new(||
221    ///     build_sheet("sheet s { cell x: i32 = 1; }", "s.adm2"));
222    /// let owner = SheetOwner::new(factory.clone(), "s/v1".into()).unwrap();
223    /// let recording = owner.capture(&[]).unwrap();
224    /// let replayed = SheetOwner::playback(factory, "s/v1".into(), &recording).unwrap();
225    /// assert!(replayed.recordings().is_empty());
226    /// ```
227    pub fn playback(
228        factory: ModelFactory,
229        schema_key: String,
230        recording: &Recording,
231    ) -> Result<Self, PlaybackError> {
232        if schema_key != recording.schema_key {
233            return Err(PlaybackError::Capture(CaptureError::SchemaMismatch {
234                expected: schema_key,
235                actual: recording.schema_key.clone(),
236            }));
237        }
238        let mut owner = Self::new(factory, schema_key).map_err(|error| match error {
239            BuildError::Runtime(failure) => PlaybackError::Fatal(*failure),
240            other => PlaybackError::Build(other),
241        })?;
242        match owner.apply(&recording.values, UpdateOrigin::Playback) {
243            HostOutcome::Accepted => Ok(owner),
244            HostOutcome::Rejected(error) => Err(PlaybackError::Rejected(error)),
245            HostOutcome::Fatal(error) => Err(PlaybackError::Fatal(error)),
246            HostOutcome::RecordingFailed(error) => Err(PlaybackError::Capture(error)),
247        }
248    }
249
250    /// Appends one user recording or explicitly stops a failed recorder.
251    ///
252    /// - Complexity: Capture cost.
253    fn record_accepted(&mut self, origin: UpdateOrigin) -> HostOutcome {
254        if origin != UpdateOrigin::User {
255            return HostOutcome::Accepted;
256        }
257        let Some(results) = &self.recording_results else {
258            return HostOutcome::Accepted;
259        };
260        let ModelState::Live(built) = &self.model else {
261            unreachable!("recording follows accepted publication");
262        };
263        match recording::capture(
264            built,
265            &self.accepted.schema_key,
266            results.iter().map(String::as_str),
267        ) {
268            Ok(recording) => {
269                self.recordings.push(Rc::new(recording));
270                HostOutcome::Accepted
271            }
272            Err(error) => {
273                self.stop_recording();
274                HostOutcome::RecordingFailed(error)
275            }
276        }
277    }
278
279    /// Reconstructs accepted ordered inputs only at the host's explicit request.
280    ///
281    /// Publication changes only after the factory and every replay group succeed.
282    /// Failed candidates are discarded, never substituted or inspected.
283    ///
284    /// # Errors
285    /// Returns typed construction, replay, or publication failures. A retired
286    /// owner rejects restoration without calling its factory. A fatal failure
287    /// during reconstruction or replay permanently retires the owner.
288    ///
289    /// - Complexity: O(history bytes + propagation per group + publication),
290    ///   plus factory and independently owned diagnostic metadata costs.
291    ///
292    /// # Examples
293    /// ```
294    /// use adam_web_ui::{binding::*, build_sheet};
295    /// let mut owner = SheetOwner::new(std::rc::Rc::new(||
296    ///     build_sheet("sheet s { cell x: i32 = 1; }", "s.adm2")), "s/v1".into()).unwrap();
297    /// let _ = owner.apply(&[CellEdit { key: "x".into(), canonical: "bad".into() }],
298    ///     UpdateOrigin::User);
299    /// owner.restore_accepted().unwrap();
300    /// assert_eq!(owner.views()[0].text, "1");
301    /// ```
302    pub fn restore_accepted(&mut self) -> Result<(), BuildError> {
303        match self.model {
304            ModelState::Retired => return Err(binding_build_error(BindingError::RetiredInstance)),
305            ModelState::Mutating => {
306                return Err(binding_build_error(BindingError::ReentrantMutation));
307            }
308            _ => {}
309        }
310        self.model = ModelState::Mutating;
311        let result = self.reconstruct();
312        match result {
313            Ok((built, views)) => {
314                self.model = ModelState::Live(built);
315                self.views = views;
316                Ok(())
317            }
318            Err(error) => {
319                self.model = if matches!(error, BuildError::Runtime(_)) {
320                    ModelState::Retired
321                } else {
322                    ModelState::Unavailable
323                };
324                Err(error)
325            }
326        }
327    }
328
329    /// Borrows host-owned accepted history without cloning it.
330    ///
331    /// # Examples
332    /// See [`SheetOwner`] for construction; a new owner's transactions are empty.
333    pub fn accepted_state(&self) -> &RecoveryState {
334        &self.accepted
335    }
336
337    /// Borrows immutable accepted cell views in stable schema-key order.
338    ///
339    /// Callers may clone individual `Rc`s without copying the journal or model.
340    ///
341    /// # Examples
342    /// See [`SheetOwner`] for reading the first published cell.
343    pub fn views(&self) -> &[Rc<CellView>] {
344        &self.views
345    }
346
347    /// Invokes a read-only callback only on an accepted live model.
348    ///
349    /// # Errors
350    /// Returns a typed unavailable, retired, or reentrant error without invoking
351    /// the callback when no accepted live model exists.
352    ///
353    /// # Examples
354    /// ```
355    /// use adam_web_ui::{binding::*, build_sheet};
356    /// let owner = SheetOwner::new(std::rc::Rc::new(||
357    ///     build_sheet("sheet s {}", "s.adm2")), "s/v1".into()).unwrap();
358    /// assert_eq!(owner.inspect(|parsed, _| parsed.cell_names.len()).unwrap(), 0);
359    /// ```
360    pub fn inspect<R>(
361        &self,
362        f: impl FnOnce(&ParsedSheet, &Labels) -> R,
363    ) -> Result<R, BindingError> {
364        match &self.model {
365            ModelState::Live(built) => Ok(f(&built.parsed, &built.labels)),
366            other => Err(state_error(other).expect("non-live states have a diagnostic")),
367        }
368    }
369
370    /// Builds and replays without changing publication or copying the journal.
371    ///
372    /// - Complexity: Factory cost plus O(history bytes + propagation per group +
373    ///   diagnostic metadata + publication).
374    fn reconstruct(&self) -> Result<(Box<BuiltSheet>, Vec<Rc<CellView>>), BuildError> {
375        let mut built = Box::new((self.factory)()?);
376        let diagnostics = built.diagnostics.clone();
377        let file_name = built.file_name.clone();
378        for edits in &self.accepted.transactions {
379            built = match transact(built, edits) {
380                Ok(built) => built,
381                Err(HostOutcome::Fatal(error)) => return Err(BuildError::Runtime(Box::new(error))),
382                Err(HostOutcome::Rejected(HostRejection::Validation(issues))) => {
383                    return Err(BuildError::Validation {
384                        issues,
385                        diagnostics: Box::new(diagnostics),
386                        file_name,
387                    });
388                }
389                Err(HostOutcome::Rejected(error)) => {
390                    return Err(BuildError::Recovery(Box::new(error)));
391                }
392                Err(HostOutcome::Accepted | HostOutcome::RecordingFailed(_)) => {
393                    unreachable!("transaction errors are never accepted")
394                }
395            };
396        }
397        let views =
398            publish(&built, &self.views).map_err(|error| BuildError::Recovery(Box::new(error)))?;
399        Ok((built, views))
400    }
401}
402
403/// Returns the lifetime diagnostic for a non-live model state.
404fn state_error(state: &ModelState) -> Option<BindingError> {
405    match state {
406        ModelState::Live(_) => None,
407        ModelState::Unavailable => Some(BindingError::Unavailable),
408        ModelState::Retired => Some(BindingError::RetiredInstance),
409        ModelState::Mutating => Some(BindingError::ReentrantMutation),
410    }
411}
412
413/// Wraps an owner-state failure for the construction/recovery boundary.
414fn binding_build_error(error: BindingError) -> BuildError {
415    BuildError::Recovery(Box::new(HostRejection::Binding(error)))
416}
417
418/// Moves pre-retained independent diagnostics out while discarding a candidate.
419fn runtime_failure(built: BuiltSheet, error: Error) -> RuntimeFailure {
420    RuntimeFailure {
421        error,
422        diagnostics: Box::new(built.diagnostics),
423        file_name: built.file_name,
424    }
425}
426
427/// Applies a fully prepared ordered transaction to an exclusively owned candidate.
428///
429/// - Complexity: O(edits + outputs + edit bytes + propagation + requirement validation).
430fn transact(
431    mut built: Box<BuiltSheet>,
432    edits: &[CellEdit],
433) -> Result<Box<BuiltSheet>, HostOutcome> {
434    let outputs: HashSet<_> = built.parsed.out_cells().collect();
435    let prepared = edits
436        .iter()
437        .map(|edit| {
438            let id = *built.keys.get(&edit.key).ok_or_else(|| {
439                HostRejection::Binding(BindingError::UnknownKey(edit.key.clone()))
440            })?;
441            let meta = built.labels.cells.get(&id).ok_or_else(|| {
442                HostRejection::Binding(BindingError::UnsupportedCodec(edit.key.clone()))
443            })?;
444            if !meta.codec_supported {
445                return Err(HostRejection::Binding(BindingError::UnsupportedCodec(
446                    edit.key.clone(),
447                )));
448            }
449            if outputs.contains(&id) {
450                return Err(HostRejection::Binding(BindingError::IncompatibleEditor(
451                    edit.key.clone(),
452                )));
453            }
454            (meta.prepare)(&edit.canonical)
455                .map(|write| (id, write))
456                .map_err(HostRejection::Input)
457        })
458        .collect::<Result<Vec<_>, _>>()
459        .map_err(HostOutcome::Rejected)?;
460    // Apply only after every conversion succeeds; order defines write recency.
461    for (id, write) in prepared {
462        if let Err(error) = write.apply(&mut built.parsed, id) {
463            return Err(HostOutcome::Rejected(HostRejection::Mutation(
464                runtime_failure(*built, error),
465            )));
466        }
467    }
468    if let Err(error) = built.parsed.propagate() {
469        return Err(HostOutcome::Fatal(runtime_failure(*built, error)));
470    }
471    let issues = validation_issues(&built.parsed);
472    if !issues.is_empty() {
473        return Err(HostOutcome::Rejected(HostRejection::Validation(issues)));
474    }
475    built.parsed.clear_changed();
476    Ok(built)
477}
478
479/// Publishes every named cell or reports a read error instead of substituting a value.
480///
481/// - Complexity: O(named cells + contributing graph traversals + encoded bytes).
482fn publish(
483    built: &BuiltSheet,
484    previous: &[Rc<CellView>],
485) -> Result<Vec<Rc<CellView>>, HostRejection> {
486    let sheet = &built.parsed;
487    let outputs: HashSet<CellId> = sheet.out_cells().collect();
488    let relevant: HashSet<CellId> = outputs
489        .iter()
490        .flat_map(|&id| sheet.contributing_cells(id))
491        .chain(sheet.requirement_relevant_cells())
492        .chain(
493            sheet
494                .conditionals()
495                .filter_map(|id| sheet.conditional_match_cells(id))
496                .flatten()
497                .copied(),
498        )
499        .collect();
500    let invalid: HashSet<CellId> = sheet
501        .filter_violation_cells()
502        .into_iter()
503        .chain(sheet.filter_violated_cells())
504        .collect();
505    built
506        .keys
507        .iter()
508        .enumerate()
509        .map(|(index, (key, &id))| {
510            let meta = built.labels.cells.get(&id).ok_or_else(|| {
511                HostRejection::Binding(BindingError::UnsupportedCodec(key.clone()))
512            })?;
513            let mut issues = Vec::new();
514            let text = if meta.codec_supported {
515                (meta.capture)(sheet).map_err(HostRejection::Input)?
516            } else {
517                (meta.display)(sheet)
518            };
519            if let Some(violation) = sheet.filter_violation(id) {
520                issues.push(ValidationIssue {
521                    key: key.clone(),
522                    requirement: None,
523                    labels: Vec::new(),
524                    message: format!("filter violation: {violation:?}"),
525                });
526            }
527            let forced = sheet.is_forced(id);
528            let relevant = outputs.is_empty() || relevant.contains(&id);
529            let range = meta
530                .exact_range
531                .as_ref()
532                .map(|range| range(sheet))
533                .transpose()
534                .map_err(HostRejection::Input)?;
535            let flags = CellFlags {
536                disabled: forced || !relevant,
537                readonly: outputs.contains(&id),
538                relevant,
539                invalid: invalid.contains(&id) || !issues.is_empty(),
540                forced,
541            };
542            let is_source = sheet.is_source(id);
543            if let Some(view) = previous.get(index).filter(|view| {
544                view.key == *key
545                    && view.text == text
546                    && view.is_source == is_source
547                    && view.flags == flags
548                    && view.number_kind == meta.number_kind
549                    && view.is_bool == meta.is_bool
550                    && view.codec_supported == meta.codec_supported
551                    && view.range == range
552                    && view.issues == issues
553            }) {
554                return Ok(Rc::clone(view));
555            }
556            Ok(Rc::new(CellView {
557                key: key.clone(),
558                text,
559                is_source,
560                flags,
561                number_kind: meta.number_kind,
562                is_bool: meta.is_bool,
563                codec_supported: meta.codec_supported,
564                range,
565                issues,
566            }))
567        })
568        .collect()
569}