Skip to main content

zero_client/ivm/
deferred_input.rs

1//! `DeferredInput` (`packages/zql/src/ivm/deferred-input.ts`).
2
3use super::*;
4use std::cell::{Cell, RefCell};
5use std::rc::{Rc, Weak};
6
7/// Builds a [`DeferredInput`]'s pipeline.
8pub type BuildPipeline = Box<dyn Fn() -> Result<Rc<dyn Input>, PipelineError>>;
9
10/// A placeholder input for a view whose pipeline is not built yet.
11///
12/// Until [`attach`](Self::attach) it behaves like an empty pipeline: `fetch`
13/// yields nothing and nothing is pushed. `attach` builds the real pipeline
14/// and hydrates the output with its rows as add changes, as if they had just
15/// arrived.
16pub struct DeferredInput {
17    schema: Rc<SourceSchema>,
18    build: BuildPipeline,
19    output: RefCell<Weak<dyn Output>>,
20    input: RefCell<Option<Rc<dyn Input>>>,
21    destroyed: Cell<bool>,
22}
23
24impl DeferredInput {
25    /// `schema` is what the built pipeline reports; `build` builds it.
26    pub fn new(schema: Rc<SourceSchema>, build: BuildPipeline) -> Rc<Self> {
27        Rc::new(DeferredInput {
28            schema,
29            build,
30            output: RefCell::new(no_output()),
31            input: RefCell::new(None),
32            destroyed: Cell::new(false),
33        })
34    }
35
36    pub fn attached(&self) -> bool {
37        self.input.borrow().is_some()
38    }
39
40    pub fn destroyed(&self) -> bool {
41        self.destroyed.get()
42    }
43
44    /// Builds the pipeline and pushes its rows to the output. Leaves this
45    /// input unattached when building or hydrating fails.
46    pub fn attach(&self) -> Result<(), PipelineError> {
47        assert!(!self.attached(), "DeferredInput: pipeline already attached");
48        assert!(
49            !self.destroyed.get(),
50            "DeferredInput: cannot attach after destroy"
51        );
52        let input = (self.build)()?;
53        let weak = self.output.borrow().clone();
54        let Some(output) = weak.upgrade() else {
55            *self.input.borrow_mut() = Some(input);
56            return Ok(());
57        };
58        input.set_output(weak);
59        let hydrated = capture(|| {
60            for node in input.fetch(&FetchRequest::default()) {
61                output.push(Change::Add(node), input.as_ref());
62            }
63        });
64        if let Err(e) = hydrated {
65            input.destroy();
66            return Err(e);
67        }
68        output.reconcile(input.as_ref());
69        *self.input.borrow_mut() = Some(input);
70        Ok(())
71    }
72}
73
74impl InputBase for DeferredInput {
75    fn get_schema(&self) -> Rc<SourceSchema> {
76        self.schema.clone()
77    }
78    fn destroy(&self) {
79        self.destroyed.set(true);
80        let input = self.input.borrow().clone();
81        if let Some(input) = input {
82            input.destroy();
83        }
84    }
85}
86
87impl Input for DeferredInput {
88    fn set_output(&self, output: Weak<dyn Output>) {
89        *self.output.borrow_mut() = output.clone();
90        let input = self.input.borrow().clone();
91        if let Some(input) = input {
92            input.set_output(output);
93        }
94    }
95
96    fn fetch(&self, req: &FetchRequest) -> NodeStream {
97        let input = self.input.borrow().clone();
98        match input {
99            Some(input) => input.fetch(req),
100            None => empty(),
101        }
102    }
103}