Skip to main content

adam_web_ui/graph/
bridge.rs

1//! Container-scoped lifecycle and approval protocol for the graph view.
2//!
3//! Start a fresh monotonically numbered generation before submitting requests.
4//! Disposing a generation is terminal; unknown generations never create models.
5//!
6//! ```
7//! use adam_web_ui::graph::BridgeState;
8//! let mut bridge = BridgeState::default();
9//! bridge.start(1)?;
10//! bridge.dispose(1);
11//! # Ok::<(), adam_web_ui::graph::GraphFailure>(())
12//! ```
13
14use cel_euclid::{Point2D, Rect, Size2D};
15use serde::{Deserialize, Serialize};
16
17use super::GraphFailure;
18use super::{ViewAction, ViewConstraints, ViewInput, ViewOutput};
19/// Preserves thread-confined diagnostics through dispatch.
20type Result<T> = std::result::Result<T, GraphFailure>;
21
22/// A geometry snapshot and source action with a generation-local ordering key.
23///
24/// Bounds use ordered finite minimum/maximum endpoints; viewport sizes are positive.
25///
26/// # Examples
27/// ```
28/// # use adam_web_ui::graph::{ViewRequest, ViewAction};
29/// let request = ViewRequest { generation: 1, revision: 1, sequence: 1,
30///     bounds: [0.0, 0.0, 200.0, 100.0], viewport: [400.0, 300.0],
31///     action: ViewAction::Fit };
32/// assert_eq!(request.sequence, 1);
33/// ```
34#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
35pub struct ViewRequest {
36    /// The explicitly started lifecycle.
37    pub generation: u32,
38    /// The geometry revision measured by the renderer.
39    pub revision: u32,
40    /// The strictly increasing generation-local submission number.
41    pub sequence: u32,
42    /// Minimum x/y followed by maximum x/y.
43    pub bounds: [f64; 4],
44    /// Positive viewport width and height.
45    pub viewport: [f64; 2],
46    /// The requested source operation.
47    pub action: ViewAction,
48}
49
50/// Lifecycle and update messages for one mounted container channel.
51///
52/// # Examples
53/// ```
54/// use adam_web_ui::graph::ViewMessage;
55/// assert_eq!(serde_json::to_string(&ViewMessage::Start { generation: 1 })?,
56///     r#"{"kind":"start","generation":1}"#);
57/// # Ok::<(), serde_json::Error>(())
58/// ```
59#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
60#[serde(tag = "kind", rename_all = "snake_case")]
61pub enum ViewMessage {
62    /// Explicitly creates the generation's single cached model.
63    Start {
64        /// The new strictly greater generation.
65        generation: u32,
66    },
67    /// Evaluates one complete snapshot.
68    Update {
69        /// The geometry, action and ordering identity.
70        request: ViewRequest,
71    },
72    /// Ends the matching active generation without affecting another generation.
73    Dispose {
74        /// The generation to retire.
75        generation: u32,
76    },
77}
78
79/// An approval or explicit current-request failure carrying the original identity.
80///
81/// # Examples
82/// ```
83/// use adam_web_ui::graph::ViewReply;
84/// let reply = ViewReply::Failed { generation: 1, revision: 1, sequence: 1,
85///     message: "invalid viewport".into() };
86/// assert!(serde_json::to_string(&reply)?.contains(r#""kind":"failed""#));
87/// # Ok::<(), serde_json::Error>(())
88/// ```
89#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
90#[serde(tag = "kind", rename_all = "snake_case")]
91pub enum ViewReply {
92    /// Contains only fully evaluated model output.
93    Accepted {
94        /// The request generation.
95        generation: u32,
96        /// The request geometry revision.
97        revision: u32,
98        /// The request submission sequence.
99        sequence: u32,
100        /// The approved view and model-owned gesture limits.
101        output: ViewOutput,
102    },
103    /// Reports invalid current geometry or a model propagation failure.
104    Failed {
105        /// The request generation.
106        generation: u32,
107        /// The request geometry revision.
108        revision: u32,
109        /// The request submission sequence.
110        sequence: u32,
111        /// The diagnostic to report visibly and through the host error channel.
112        message: String,
113    },
114}
115
116/// Owns one cached model and lifecycle/order watermarks for one container.
117///
118/// # Examples
119/// ```
120/// let mut bridge = adam_web_ui::graph::BridgeState::default();
121/// bridge.start(1)?;
122/// assert!(bridge.start(1).is_err());
123/// # Ok::<(), adam_web_ui::graph::GraphFailure>(())
124/// ```
125#[derive(Default)]
126pub struct BridgeState {
127    /// The typed cause of the last failed reply, consumed by the application channel.
128    failure: Option<super::GraphFailure>,
129    /// The greatest successfully claimed generation, including disposed generations.
130    generation: Option<u32>,
131    /// The active generation's model, absent after disposal or failed startup.
132    model: Option<ViewConstraints>,
133    /// The last consumed sequence and geometry revision.
134    processed: Option<(u32, u32)>,
135}
136
137impl BridgeState {
138    /// Transfers a failed reply's typed cause to the host without serializing it.
139    pub(crate) fn take_failure(&mut self) -> Option<super::GraphFailure> {
140        self.failure.take()
141    }
142    /// Decodes a wire message or returns a JavaScript diagnostic as an error.
143    ///
144    /// # Errors
145    /// Returns errors for diagnostic strings, malformed messages, or startup failure.
146    ///
147    /// - Complexity: O(n + p) time and space in message size `n` and model work `p`.
148    pub(crate) fn receive(&mut self, payload: serde_json::Value) -> Result<Option<ViewReply>> {
149        if let Some(message) = payload.as_str() {
150            return Err(GraphFailure::Transport(message.into()));
151        }
152        self.process(
153            serde_json::from_value(payload)
154                .map_err(|error| GraphFailure::Transport(error.to_string()))?,
155        )
156    }
157
158    /// Dispatches a typed lifecycle message without framework-specific branching.
159    ///
160    /// # Errors
161    /// Returns startup errors; current update failures are explicit failed replies.
162    ///
163    /// - Complexity: O(p) time and space in model construction/propagation work.
164    ///
165    /// # Examples
166    /// ```
167    /// use adam_web_ui::graph::{BridgeState, ViewMessage};
168    /// assert!(BridgeState::default().process(ViewMessage::Start { generation: 1 })?.is_none());
169    /// # Ok::<(), adam_web_ui::graph::GraphFailure>(())
170    /// ```
171    pub fn process(&mut self, message: ViewMessage) -> Result<Option<ViewReply>> {
172        match message {
173            ViewMessage::Start { generation } => {
174                self.start(generation)?;
175                Ok(None)
176            }
177            ViewMessage::Update { request } => self.handle(request),
178            ViewMessage::Dispose { generation } => {
179                self.dispose(generation);
180                Ok(None)
181            }
182        }
183    }
184    /// Claims a strictly newer generation and parses its model exactly once.
185    ///
186    /// # Errors
187    /// Returns an error for a repeated/older generation or model initialization failure.
188    /// A failed initialization still retires the claimed generation.
189    ///
190    /// - Complexity: O(p) time and space for model initialization work `p`.
191    ///
192    /// # Examples
193    /// ```
194    /// let mut bridge = adam_web_ui::graph::BridgeState::default();
195    /// bridge.start(1)?;
196    /// # Ok::<(), adam_web_ui::graph::GraphFailure>(())
197    /// ```
198    pub fn start(&mut self, generation: u32) -> Result<()> {
199        if !self.generation.is_none_or(|last| generation > last) {
200            return Err(GraphFailure::InvalidInput(
201                "graph generation must increase monotonically".into(),
202            ));
203        }
204        self.generation = Some(generation);
205        self.failure = None;
206        self.processed = None;
207        self.model = None;
208        self.model = Some(ViewConstraints::new()?);
209        Ok(())
210    }
211
212    /// Evaluates current ordered work without implicitly starting a generation.
213    ///
214    /// Returns `None` only for inactive/unknown generations, consumed sequences,
215    /// or older geometry. Invalid current inputs produce a `Failed` reply.
216    /// Failed current requests consume their ordering identity too.
217    ///
218    /// # Errors
219    /// Reserves transport-level errors for the channel owner; model/input errors
220    /// are represented by `ViewReply::Failed`.
221    ///
222    /// - Complexity: O(p) time and space in cached model propagation work `p`.
223    ///
224    /// # Examples
225    /// ```
226    /// # use adam_web_ui::graph::{BridgeState, ViewAction, ViewRequest};
227    /// let mut bridge = BridgeState::default();
228    /// assert!(bridge.handle(ViewRequest { generation: 1, revision: 1, sequence: 1,
229    ///     bounds: [0.0, 0.0, 1.0, 1.0], viewport: [100.0, 100.0],
230    ///     action: ViewAction::Fit })?.is_none());
231    /// # Ok::<(), adam_web_ui::graph::GraphFailure>(())
232    /// ```
233    pub fn handle(&mut self, request: ViewRequest) -> Result<Option<ViewReply>> {
234        if self.generation != Some(request.generation) {
235            return Ok(None);
236        }
237        let Some(model) = self.model.as_mut() else {
238            return Ok(None);
239        };
240        if self.processed.is_some_and(|(sequence, revision)| {
241            request.sequence <= sequence || request.revision < revision
242        }) {
243            return Ok(None);
244        }
245        self.processed = Some((request.sequence, request.revision));
246        let [min_x, min_y, max_x, max_y] = request.bounds;
247        let result = (|| {
248            if !(request.bounds.iter().all(|v| v.is_finite()) && min_x <= max_x && min_y <= max_y) {
249                return Err(GraphFailure::InvalidInput("invalid graph bounds".into()));
250            }
251            model.update(ViewInput {
252                bounds: Rect::new(
253                    Point2D::new(min_x, min_y),
254                    Size2D::new(max_x - min_x, max_y - min_y),
255                ),
256                viewport: Size2D::new(request.viewport[0], request.viewport[1]),
257                action: request.action,
258            })
259        })();
260        Ok(Some(match result {
261            Ok(output) => ViewReply::Accepted {
262                generation: request.generation,
263                revision: request.revision,
264                sequence: request.sequence,
265                output,
266            },
267            Err(error) => {
268                let message = error.to_string();
269                self.failure = Some(error);
270                ViewReply::Failed {
271                    generation: request.generation,
272                    revision: request.revision,
273                    sequence: request.sequence,
274                    message,
275                }
276            }
277        }))
278    }
279
280    /// Retires only the matching generation, retaining its terminal watermark.
281    ///
282    /// # Examples
283    /// ```
284    /// let mut bridge = adam_web_ui::graph::BridgeState::default();
285    /// bridge.start(1)?;
286    /// bridge.dispose(1);
287    /// assert!(bridge.start(1).is_err());
288    /// # Ok::<(), adam_web_ui::graph::GraphFailure>(())
289    /// ```
290    pub fn dispose(&mut self, generation: u32) {
291        if self.generation == Some(generation) {
292            self.model = None;
293        }
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300    use crate::graph::{ViewAction, ViewTransform};
301
302    /// Invalid requests forward a typed cause while preserving the valid candidate.
303    #[test]
304    fn malformed_input_forwards_cause_without_retiring_model() {
305        let mut state = BridgeState::default();
306        state.start(1).unwrap();
307        let mut invalid = request(1, 1);
308        invalid.viewport = [0.0, 100.0];
309        assert!(matches!(
310            state.handle(invalid).unwrap(),
311            Some(ViewReply::Failed { .. })
312        ));
313        assert!(matches!(
314            state.take_failure(),
315            Some(GraphFailure::InvalidInput(_))
316        ));
317        assert!(matches!(
318            state.handle(request(1, 2)).unwrap(),
319            Some(ViewReply::Accepted { .. })
320        ));
321        assert!(state.take_failure().is_none());
322    }
323
324    /// Builds a valid absolute proposal with fixed geometry.
325    fn request(generation: u32, sequence: u32) -> ViewRequest {
326        ViewRequest {
327            generation,
328            revision: 1,
329            sequence,
330            bounds: [0.0, 0.0, 200.0, 100.0],
331            viewport: [400.0, 300.0],
332            action: ViewAction::Propose {
333                view: ViewTransform {
334                    x: 0.0,
335                    y: 50.0,
336                    k: 2.0,
337                },
338            },
339        }
340    }
341
342    /// Unknown generations never implicitly start a model.
343    #[test]
344    fn stale_generation_is_ignored() {
345        let mut state = BridgeState::default();
346        assert!(state.handle(request(1, 1)).unwrap().is_none());
347        state.start(2).unwrap();
348        assert!(state.handle(request(1, 1)).unwrap().is_none());
349        assert!(state.handle(request(3, 1)).unwrap().is_none());
350    }
351
352    /// Disposal is terminal even when a delayed Start arrives.
353    #[test]
354    fn disposed_generation_cannot_restart() {
355        let mut state = BridgeState::default();
356        state.start(1).unwrap();
357        state.dispose(1);
358        assert!(state.start(1).is_err());
359        assert!(state.handle(request(1, 1)).unwrap().is_none());
360        state.start(2).unwrap();
361        state.dispose(1);
362        assert!(state.handle(request(2, 1)).unwrap().is_some());
363    }
364
365    /// Old sequences and geometry never edit the retained source aspiration.
366    #[test]
367    fn stale_sequence_does_not_mutate_model() {
368        let mut state = BridgeState::default();
369        state.start(1).unwrap();
370        let first = state.handle(request(1, 2)).unwrap().unwrap();
371        let mut old = request(1, 1);
372        old.action = ViewAction::Fit;
373        assert!(state.handle(old).unwrap().is_none());
374        let mut old_geometry = request(1, 3);
375        old_geometry.revision = 0;
376        assert!(state.handle(old_geometry).unwrap().is_none());
377        let mut refresh = request(1, 4);
378        refresh.action = ViewAction::Refresh;
379        let Some(ViewReply::Accepted { output: actual, .. }) = state.handle(refresh).unwrap()
380        else {
381            panic!("refresh must be approved");
382        };
383        let ViewReply::Accepted {
384            output: expected, ..
385        } = first
386        else {
387            panic!("initial proposal must be approved");
388        };
389        assert_eq!(expected, actual);
390    }
391
392    /// Invalid current geometry returns a failure with the request identity.
393    #[test]
394    fn current_failure_is_a_failed_reply() {
395        let mut state = BridgeState::default();
396        state.start(1).unwrap();
397        let mut invalid = request(1, 1);
398        invalid.viewport[0] = 0.0;
399        assert!(matches!(
400            state.handle(invalid).unwrap(),
401            Some(ViewReply::Failed {
402                generation: 1,
403                sequence: 1,
404                ..
405            })
406        ));
407    }
408
409    /// Serde validates u32 fields rather than truncating hostile numbers.
410    #[test]
411    fn message_numbers_are_validated() {
412        for number in ["-1", "1.5", "4294967296"] {
413            assert!(
414                serde_json::from_str::<ViewMessage>(&format!(
415                    r#"{{"kind":"start","generation":{number}}}"#
416                ))
417                .is_err()
418            );
419        }
420    }
421
422    /// Malformed current messages and JS diagnostics are errors, never stale success.
423    #[test]
424    fn wire_errors_are_explicit_and_do_not_consume_valid_work() {
425        let mut state = BridgeState::default();
426        state.start(1).unwrap();
427        assert!(
428            state
429                .receive(serde_json::json!({
430                    "kind": "update", "request": { "generation": 1, "sequence": -1 }
431                }))
432                .is_err()
433        );
434        assert_eq!(
435            state
436                .receive(serde_json::json!("channel failed"))
437                .unwrap_err()
438                .to_string(),
439            "channel failed"
440        );
441        assert!(state.handle(request(1, 1)).unwrap().is_some());
442    }
443
444    /// Container owners retain independent models and sequence watermarks.
445    #[test]
446    fn two_containers_are_independent() {
447        let mut a = BridgeState::default();
448        let mut b = BridgeState::default();
449        a.start(1).unwrap();
450        b.start(1).unwrap();
451        a.dispose(1);
452        assert!(b.handle(request(1, 1)).unwrap().is_some());
453        assert!(a.handle(request(1, 1)).unwrap().is_none());
454    }
455
456    /// Shared fixtures encode the exact tags, field names, and action shapes.
457    #[test]
458    fn wire_fixtures_round_trip() {
459        let fixture: serde_json::Value =
460            serde_json::from_str(include_str!("../../../begin/js/graph-protocol.json")).unwrap();
461        let mut state = BridgeState::default();
462        for message in fixture["messages"].as_array().unwrap() {
463            let parsed: ViewMessage = serde_json::from_value(message.clone()).unwrap();
464            assert_eq!(serde_json::to_value(&parsed).unwrap(), *message);
465            assert!(state.process(parsed).is_ok());
466        }
467        for reply in fixture["replies"].as_array().unwrap() {
468            let parsed: ViewReply = serde_json::from_value(reply.clone()).unwrap();
469            assert_eq!(serde_json::to_value(parsed).unwrap(), *reply);
470        }
471    }
472}