Skip to main content

zero_client/client/
live_view.rs

1//! A view read as its query's Rust type and kept current (`LiveQuery` in
2//! the Swift client, `useQuery` in zero-react).
3
4use super::query_context::MaterializedView;
5use super::{Error, QueryError};
6use crate::ivm::{ResultType, ViewEntry, ViewValue};
7use crate::protocol::ErroredQuery;
8use crate::ttl::Ttl;
9use crate::typed::{QueryValue, ZeroValueError};
10use std::cell::{Cell, RefCell};
11use std::fmt;
12use std::rc::{Rc, Weak};
13
14/// Why a [`LiveView`]'s value may not be what the server has.
15#[derive(Clone, Debug, PartialEq)]
16pub enum LiveError {
17    /// The server could not run the query.
18    Query(ErroredQuery),
19    /// The rows could not be read as the query's result type. The value is
20    /// the last one read.
21    Decode(ZeroValueError),
22}
23
24impl fmt::Display for LiveError {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            LiveError::Query(e) => QueryError::new(Some(e.clone())).fmt(f),
28            LiveError::Decode(e) => e.fmt(f),
29        }
30    }
31}
32
33impl std::error::Error for LiveError {}
34
35type Listener<T> = Rc<dyn Fn(&T, ResultType)>;
36
37/// What a [`LiveView`] last read.
38struct State<T> {
39    value: Rc<T>,
40    /// The entries `value` was read from.
41    read: ViewValue,
42    /// The view's rows when they were read, which it shares until they
43    /// change. Unlike holding them, which would make the view copy them to
44    /// change them, it lets them change in place, into another allocation.
45    seen: Weak<Vec<ViewEntry>>,
46    result_type: ResultType,
47    error: Option<LiveError>,
48}
49
50fn rows_of(data: &ViewValue) -> Weak<Vec<ViewEntry>> {
51    match data {
52        ViewValue::Many(rows) => Rc::downgrade(rows),
53        _ => Weak::new(),
54    }
55}
56
57struct Inner<T> {
58    view: MaterializedView,
59    state: RefCell<State<T>>,
60    listeners: RefCell<Vec<(u64, Listener<T>)>>,
61    next_listener_id: Cell<u64>,
62}
63
64/// A query's rows, the row of a `one()` query, or the value of an
65/// aggregate, read as its Rust type and kept current, from
66/// [`Zero::live`](super::Zero::live) (`LiveQuery` in the Swift client,
67/// `useQuery` in zero-react).
68///
69/// Each update of the view is read into the value, reading only the rows
70/// whose entries changed. When the client replaces itself, the view moves
71/// to the new client, and the live view with it. Dropping it removes its
72/// listeners and destroys the view; the server keeps syncing the query for
73/// its TTL.
74pub struct LiveView<T> {
75    inner: Rc<Inner<T>>,
76    remove: Box<dyn Fn()>,
77}
78
79impl<T: QueryValue + 'static> LiveView<T> {
80    /// Reads `view`, and follows it. Fails, destroying it, when its rows
81    /// don't read as `T`.
82    pub(crate) fn new(view: MaterializedView) -> Result<Self, Error> {
83        let read = view.data();
84        let value = match T::from_view(&read) {
85            Ok(value) => value,
86            Err(e) => {
87                view.destroy();
88                return Err(Error::Message(e.0));
89            }
90        };
91        let inner = Rc::new(Inner {
92            state: RefCell::new(State {
93                value: Rc::new(value),
94                seen: rows_of(&read),
95                read,
96                result_type: view.result_type(),
97                error: view.error().map(LiveError::Query),
98            }),
99            view,
100            listeners: RefCell::default(),
101            next_listener_id: Cell::new(0),
102        });
103        let weak: Weak<Inner<T>> = Rc::downgrade(&inner);
104        let remove = inner.view.add_listener(move |data, result_type, error| {
105            if let Some(inner) = weak.upgrade() {
106                inner.update(data, result_type, error);
107            }
108        });
109        Ok(LiveView { inner, remove })
110    }
111}
112
113impl<T: 'static> LiveView<T> {
114    /// The value last read. Holding it past the next update makes that
115    /// update read every row again rather than only those that changed.
116    pub fn value(&self) -> Rc<T> {
117        self.inner.state.borrow().value.clone()
118    }
119
120    /// Whether the server has confirmed the rows on this connection
121    /// (`Complete`) or an earlier one (`Cached`), or not yet (`Unknown`), or
122    /// the query failed (`Error`).
123    pub fn result_type(&self) -> ResultType {
124        self.inner.state.borrow().result_type
125    }
126
127    /// Why the server could not run the query, or why the rows could not be
128    /// read as `T`, which keeps the value last read.
129    pub fn error(&self) -> Option<LiveError> {
130        self.inner.state.borrow().error.clone()
131    }
132
133    /// The view the value is read from.
134    pub fn view(&self) -> &MaterializedView {
135        &self.inner.view
136    }
137
138    /// Raises the query's TTL; a lower one is ignored.
139    pub fn update_ttl(&self, ttl: &Ttl) {
140        self.inner.view.update_ttl(ttl);
141    }
142
143    /// Calls `listener` with the value and result type now, and after every
144    /// update of the view, once the value is read. After a read that
145    /// failed, it gets the value kept, and [`error`](LiveView::error) says
146    /// why. Returns the function that removes it.
147    pub fn add_listener(&self, listener: impl Fn(&T, ResultType) + 'static) -> Box<dyn Fn()> {
148        let id = self.inner.next_listener_id.get();
149        self.inner.next_listener_id.set(id + 1);
150        let listener: Listener<T> = Rc::new(listener);
151        self.inner
152            .listeners
153            .borrow_mut()
154            .push((id, listener.clone()));
155        let (value, result_type) = {
156            let s = self.inner.state.borrow();
157            (s.value.clone(), s.result_type)
158        };
159        listener(&value, result_type);
160        let weak = Rc::downgrade(&self.inner);
161        Box::new(move || {
162            if let Some(inner) = weak.upgrade() {
163                inner.listeners.borrow_mut().retain(|(i, _)| *i != id);
164            }
165        })
166    }
167}
168
169impl<T: QueryValue> Inner<T> {
170    /// Reads the view's update, and tells the listeners.
171    fn update(&self, data: &ViewValue, result_type: ResultType, error: Option<&ErroredQuery>) {
172        let value = {
173            let mut state = self.state.borrow_mut();
174            let s = &mut *state;
175            s.result_type = result_type;
176            let unchanged = match data {
177                ViewValue::Many(rows) => std::ptr::eq(s.seen.as_ptr(), Rc::as_ptr(rows)),
178                data => s.read == *data,
179            };
180            let read = if unchanged {
181                Ok(())
182            } else {
183                let read = match Rc::get_mut(&mut s.value) {
184                    Some(value) => value.update_from_view(&mut s.read, data),
185                    // A value the app still holds is left as it is.
186                    None => T::from_view(data).map(|value| {
187                        s.value = Rc::new(value);
188                        s.read = data.clone();
189                    }),
190                };
191                if read.is_ok() {
192                    s.seen = rows_of(data);
193                }
194                read
195            };
196            s.error = match read {
197                Ok(()) => error.cloned().map(LiveError::Query),
198                Err(e) => Some(LiveError::Decode(e)),
199            };
200            s.value.clone()
201        };
202        // Each listener in turn, reading the list again after every call,
203        // as `MaterializedView` does.
204        let mut last: Option<u64> = None;
205        loop {
206            let next = self
207                .listeners
208                .borrow()
209                .iter()
210                .find(|(id, _)| last.is_none_or(|l| *id > l))
211                .cloned();
212            let Some((id, listener)) = next else { break };
213            last = Some(id);
214            listener(&value, result_type);
215        }
216    }
217}
218
219impl<T> Drop for LiveView<T> {
220    fn drop(&mut self) {
221        (self.remove)();
222        self.inner.listeners.borrow_mut().clear();
223        self.inner.view.destroy();
224    }
225}