Skip to main content

tembra_runtime/
readable.rs

1//! Native reactive snapshots. References bound their observers; the kernel publishes revisions.
2use crate::{Error, Host, Result, core};
3use std::{
4    cell::{Cell, RefCell},
5    rc::{Rc, Weak},
6};
7
8type Read<T> = Rc<dyn Fn() -> Result<Rc<T>>>;
9type Check = Rc<dyn Fn() -> Result<()>>;
10
11pub(crate) struct Observer {
12    pub active: Cell<bool>,
13    pub invoke: Box<dyn Fn() -> Result<()>>,
14    host: Host,
15    object: core::Id,
16}
17
18impl Observer {
19    fn detach(&self) {
20        if self.active.replace(false) {
21            self.host.prune_observers(self.object);
22        }
23    }
24}
25
26#[derive(Default)]
27pub(crate) struct ReadLifetime {
28    pub released: Cell<bool>,
29    pub observers: RefCell<Vec<Weak<Observer>>>,
30}
31impl ReadLifetime {
32    pub fn close(&self) {
33        self.released.set(true);
34        for observer in self
35            .observers
36            .take()
37            .into_iter()
38            .filter_map(|observer| observer.upgrade())
39        {
40            observer.detach();
41        }
42    }
43}
44
45/// A detachable native observation. Dropping it stops future notifications.
46pub struct Observation(Rc<Observer>);
47impl Observation {
48    /// Stop receiving notifications; repeated detachment has no effect.
49    pub fn detach(&self) {
50        self.0.detach();
51    }
52}
53impl Drop for Observation {
54    fn drop(&mut self) {
55        self.detach();
56    }
57}
58
59/// A checked immutable state view or cached selection.
60pub struct Readable<T> {
61    host: Host,
62    object: core::Id,
63    read: Read<T>,
64    check: Check,
65    lifetime: Option<Rc<ReadLifetime>>,
66}
67impl<T> Clone for Readable<T> {
68    fn clone(&self) -> Self {
69        Self {
70            host: self.host.clone(),
71            object: self.object,
72            read: self.read.clone(),
73            check: self.check.clone(),
74            lifetime: self.lifetime.clone(),
75        }
76    }
77}
78
79impl<T: 'static> Readable<T> {
80    pub(crate) fn new(host: Host, object: core::Id, lifetime: Option<Rc<ReadLifetime>>) -> Self {
81        let reader = host.clone();
82        let checked = host.clone();
83        let claim = lifetime.clone();
84        Self {
85            host,
86            object,
87            lifetime,
88            read: Rc::new(move || reader.value(reader.kernel().snapshot(object)?.value)),
89            check: Rc::new(move || {
90                if claim.as_ref().is_some_and(|claim| claim.released.get()) {
91                    return Err(Error::new(
92                        core::Code::Released,
93                        core::Reason::Reference,
94                        "reference is released",
95                    ));
96                }
97                checked.kernel().snapshot(object).map(|_| ())
98            }),
99        }
100    }
101
102    /// Read the current snapshot while its owner and consuming reference remain valid.
103    pub fn value(&self) -> Result<Rc<T>> {
104        (self.check)()?;
105        (self.read)()
106    }
107
108    /// Compute a cached selection. Equal results retain their identity and do not notify observers.
109    pub fn select<U: PartialEq + 'static>(
110        &self,
111        select: impl Fn(&T) -> Result<U> + 'static,
112    ) -> Readable<U> {
113        let source = self.clone();
114        let cache = RefCell::new(None::<(Rc<T>, Rc<U>)>);
115        Readable {
116            host: self.host.clone(),
117            object: self.object,
118            check: self.check.clone(),
119            lifetime: self.lifetime.clone(),
120            read: Rc::new(move || {
121                let value = source.value()?;
122                if let Some((previous, selected)) = &*cache.borrow()
123                    && Rc::ptr_eq(previous, &value)
124                {
125                    return Ok(selected.clone());
126                }
127                let next = select(&value)?;
128                let retained = cache
129                    .borrow()
130                    .as_ref()
131                    .filter(|(_, selected)| **selected == next)
132                    .map(|(_, selected)| selected.clone())
133                    .unwrap_or_else(|| Rc::new(next));
134                *cache.borrow_mut() = Some((value, retained.clone()));
135                Ok(retained)
136            }),
137        }
138    }
139
140    /// Deliver the current value immediately and future changes after adoption.
141    /// Observer failures are reported by the host and never roll back adopted state.
142    pub fn subscribe(&self, handle: impl Fn(Rc<T>) -> Result<()> + 'static) -> Result<Observation> {
143        let value = self.value()?;
144        handle(value.clone())?;
145        let previous = RefCell::new(value);
146        let source = self.clone();
147        let observer = Rc::new(Observer {
148            active: Cell::new(true),
149            host: self.host.clone(),
150            object: self.object,
151            invoke: Box::new(move || {
152                let value = source.value()?;
153                if Rc::ptr_eq(&previous.borrow(), &value) {
154                    return Ok(());
155                }
156                *previous.borrow_mut() = value.clone();
157                handle(value)
158            }),
159        });
160        self.host.observe(self.object, Rc::downgrade(&observer));
161        if let Some(lifetime) = &self.lifetime {
162            lifetime
163                .observers
164                .borrow_mut()
165                .push(Rc::downgrade(&observer));
166        }
167        Ok(Observation(observer))
168    }
169}
170
171#[cfg(feature = "rpc")]
172impl Readable<serde_json::Value> {
173    pub(crate) fn portable(host: Host, object: core::Id, lifetime: Rc<ReadLifetime>) -> Self {
174        let reader = host.clone();
175        let checked = host.clone();
176        let claim = lifetime.clone();
177        let cache = RefCell::new(None::<(core::Id, Rc<serde_json::Value>)>);
178        Self {
179            host,
180            object,
181            lifetime: Some(lifetime),
182            read: Rc::new(move || {
183                let identity = reader.kernel().snapshot(object)?.value;
184                if let Some((previous, value)) = &*cache.borrow()
185                    && *previous == identity
186                {
187                    return Ok(value.clone());
188                }
189                let value = Rc::new(reader.portable_value(identity)?);
190                *cache.borrow_mut() = Some((identity, value.clone()));
191                Ok(value)
192            }),
193            check: Rc::new(move || {
194                if claim.released.get() {
195                    return Err(Error::new(
196                        core::Code::Released,
197                        core::Reason::Reference,
198                        "reference is released",
199                    ));
200                }
201                checked.kernel().snapshot(object).map(|_| ())
202            }),
203        }
204    }
205}