Skip to main content

zero_client/ivm/
failure.rs

1//! Errors operators find while a pipeline is fetched or pushed.
2//!
3//! JS throws from inside a fetch, and the error comes out of whatever
4//! hydrates the view (`materialize`, `run`). Fetches here are lazy streams
5//! that can't fail, so an operator reports the error with [`report`] and
6//! yields nothing, and [`capture`], around the code that hydrates or pushes,
7//! returns it once that code is done.
8
9use std::cell::RefCell;
10use std::fmt;
11
12/// An error building or running a pipeline, with JS's message.
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct PipelineError(pub String);
15
16impl PipelineError {
17    pub fn new(message: impl Into<String>) -> Self {
18        PipelineError(message.into())
19    }
20}
21
22impl fmt::Display for PipelineError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        f.write_str(&self.0)
25    }
26}
27
28impl std::error::Error for PipelineError {}
29
30thread_local! {
31    /// The running captures, innermost last, each with the first error
32    /// reported to it.
33    static CAPTURES: RefCell<Vec<Option<PipelineError>>> = const { RefCell::new(Vec::new()) };
34}
35
36struct Frame;
37
38impl Drop for Frame {
39    fn drop(&mut self) {
40        CAPTURES.with(|c| c.borrow_mut().pop());
41    }
42}
43
44/// Runs `body`, and fails with the first error an operator reported while
45/// it ran.
46pub fn capture<T>(body: impl FnOnce() -> T) -> Result<T, PipelineError> {
47    CAPTURES.with(|c| c.borrow_mut().push(None));
48    let frame = Frame;
49    let result = body();
50    let error = CAPTURES.with(|c| c.borrow_mut().last_mut().and_then(Option::take));
51    drop(frame);
52    match error {
53        Some(e) => Err(e),
54        None => Ok(result),
55    }
56}
57
58/// Whether an operator reported an error to the running [`capture`]. Where
59/// JS's throw would unwind, a source stops pushing.
60pub fn has_failed() -> bool {
61    CAPTURES.with(|c| matches!(c.borrow().last(), Some(Some(_))))
62}
63
64/// Reports `message` to the running [`capture`]; the first one wins.
65/// Outside one (a pipeline driven directly) the error goes to stderr, and the
66/// operator yields nothing.
67pub fn report(message: impl Into<String>) {
68    let message = message.into();
69    CAPTURES.with(|c| match c.borrow_mut().last_mut() {
70        Some(slot) => {
71            if slot.is_none() {
72                *slot = Some(PipelineError(message));
73            }
74        }
75        None => eprintln!("zero-client: pipeline error: {message}"),
76    })
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    #[test]
84    fn the_innermost_capture_gets_the_first_report() {
85        let outer = capture(|| {
86            let inner = capture(|| {
87                report("a");
88                report("b");
89                assert!(has_failed());
90            });
91            assert_eq!(inner, Err(PipelineError::new("a")));
92            assert!(!has_failed());
93        });
94        assert_eq!(outer, Ok(()));
95    }
96}