Skip to main content

plexus_ui_engine/live/
mod.rs

1//! UI-6: **`live()`** — a component's collection bound to Plexus streams:
2//! `{ rows, status }`.
3//!
4//! The snapshot method is called once (each data event's row is its one
5//! object-valued field — `summary`, `ticket` — and an event with none, a
6//! `page`, carries no row; PERF-15: a `rows { items }` event is a page's rows
7//! at once, each item read as its own event would be); the changes stream (opened first, with its own
8//! `changes_params`) is folded by the declaration's `on`:
9//!
10//! - `upsert:<field>` inserts or replaces, by `key`, the item at
11//!   `event.<field>` — only if it matches every key of the snapshot's
12//!   params that names a field of the item (`parent`, `epic`, `status`;
13//!   `summary` and `limit` name none), so a filtered collection ignores
14//!   what is not its own, and an item that stops matching is removed;
15//! - `remove:<field>` removes the id, or each id of the list, at
16//!   `event.<field>`;
17//! - `lagged` runs the snapshot again, `resyncing` meanwhile.
18//!
19//! `status` moves `pending → live`; `resyncing` on a `lagged`, or when the
20//! socket drops until [`LiveCache::reconnected`] has asked again.
21//!
22//! [`LiveCache`] shares one subscription between every reader asking the
23//! same snapshot, params, changes and changes params, and keeps it
24//! [`KEEP_MS`] past its last reader ([`LiveCache::sweep`] closes what has
25//! waited longer).
26//!
27//! STUDIO-16: a change is folded as it is heard, and published — the
28//! collection's value set, its readers drawn — once per animation frame
29//! ([`Clock::frame`]): what a collection heard within a frame crosses as
30//! one move, its deltas merged ([`Sub::merged`]). Any other move (an
31//! answer, a status) publishes at once, the changes waiting carried in it.
32
33use crate::signals::{Runtime, Signal};
34use crate::transport::{CallId, Wire, WireItem};
35use serde_json::{json, Map, Value};
36use std::cell::{Cell, RefCell};
37use std::collections::BTreeMap;
38use std::rc::{Rc, Weak};
39
40/// How long a subscription outlives its last reader, in milliseconds.
41pub const KEEP_MS: u64 = 5_000;
42
43/// Where a collection stands.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
45#[serde(rename_all = "snake_case")]
46pub enum Status {
47    Pending,
48    Live,
49    Resyncing,
50    Closed,
51    Error,
52    Refused,
53}
54
55impl Status {
56    /// Its name, as it is written in a collection's value.
57    pub fn as_str(self) -> &'static str {
58        match self {
59            Status::Pending => "pending",
60            Status::Live => "live",
61            Status::Resyncing => "resyncing",
62            Status::Closed => "closed",
63            Status::Error => "error",
64            Status::Refused => "refused",
65        }
66    }
67}
68
69/// `{ "rows": […], "status": "live" }` of `rows` — STUDIO-16: one clone of
70/// the rows, no serializer (each publish of a collection made it).
71fn value_of(rows: &[Value], status: Status) -> Value {
72    let mut o = Map::new();
73    o.insert("rows".into(), Value::Array(rows.to_vec()));
74    o.insert("status".into(), Value::String(status.as_str().into()));
75    Value::Object(o)
76}
77
78/// One `on` rule.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum FoldRule {
81    /// `upsert:<field>`.
82    Upsert(String),
83    /// `remove:<field>`.
84    Remove(String),
85}
86
87impl std::str::FromStr for FoldRule {
88    type Err = String;
89    fn from_str(s: &str) -> Result<Self, String> {
90        match s.split_once(':') {
91            Some(("upsert", f)) if !f.is_empty() => Ok(FoldRule::Upsert(f.into())),
92            Some(("remove", f)) if !f.is_empty() => Ok(FoldRule::Remove(f.into())),
93            _ => Err(format!("`{s}` is no fold: upsert:<field> or remove:<field>")),
94        }
95    }
96}
97
98/// A collection as a component reads it.
99#[derive(Debug, Clone, PartialEq)]
100pub struct Live {
101    pub rows: Vec<Value>,
102    pub status: Status,
103}
104
105impl Live {
106    /// `{ "rows": […], "status": "live" }` — what an expression reads.
107    pub fn to_value(&self) -> Value {
108        value_of(&self.rows, self.status)
109    }
110
111    /// From [`Self::to_value`]'s shape.
112    pub fn from_value(v: &Value) -> Option<Self> {
113        Some(Self { rows: v.get("rows")?.as_array()?.clone(), status: serde_json::from_value(v.get("status")?.clone()).ok()? })
114    }
115}
116
117/// A `live` declaration with its params evaluated: what a subscription is
118/// keyed by (snapshot, params, changes, changes params) and how it folds.
119#[derive(Debug, Clone, PartialEq)]
120pub struct LiveSpec {
121    pub snapshot: String,
122    pub params: Value,
123    /// UI-10: none — a one-shot read, no watch opened.
124    pub changes: Option<String>,
125    pub changes_params: Value,
126    pub key: String,
127    pub on: BTreeMap<String, FoldRule>,
128}
129
130impl LiveSpec {
131    /// From its parts; an `on` rule that is no `upsert:`/`remove:` is refused.
132    pub fn new(snapshot: &str, params: Value, changes: Option<&str>, changes_params: Value, key: &str, on: &[(&str, &str)]) -> Result<Self, String> {
133        let on = on.iter().map(|(t, r)| Ok((t.to_string(), r.parse()?))).collect::<Result<_, String>>()?;
134        let obj = |v: Value| if v.is_null() { json!({}) } else { v };
135        Ok(Self { snapshot: snapshot.into(), params: obj(params), changes: changes.map(str::to_string), changes_params: obj(changes_params), key: key.into(), on })
136    }
137
138    /// FRAME-12: what is shared — the whole spec: two folds of one stream
139    /// (another `key`, another `on`) are two collections.
140    fn cache_key(&self) -> String {
141        let on: Vec<String> = self.on.iter().map(|(t, r)| format!("{t}={r:?}")).collect();
142        format!(
143            "{}\u{0}{}\u{0}{}\u{0}{}\u{0}{}\u{0}{}",
144            self.snapshot,
145            self.params,
146            self.changes.as_deref().unwrap_or(""),
147            self.changes_params,
148            self.key,
149            on.join(",")
150        )
151    }
152
153    /// FRAME-12: a spec as a module writes it — `{ snapshot, params?,
154    /// changes?, changes_params?, key, on? }`; `params` and
155    /// `changes_params` left out are `{}` (and share with a spec that says
156    /// so); a field it does not know, or a fold that is none, is refused,
157    /// naming it.
158    pub fn from_value(v: &Value) -> Result<Self, String> {
159        let o = v.as_object().ok_or("a live spec is { snapshot, params?, changes?, changes_params?, key, on? }")?;
160        if let Some(k) = o.keys().find(|k| !["snapshot", "params", "changes", "changes_params", "key", "on"].contains(&k.as_str())) {
161            return Err(format!("a live spec has no `{k}`: {{ snapshot, params?, changes?, changes_params?, key, on? }}"));
162        }
163        let text = |k: &str| o.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or(format!("a live spec's `{k}` is a name"));
164        let changes = match o.get("changes") {
165            None | Some(Value::Null) => None,
166            Some(Value::String(c)) if !c.is_empty() => Some(c.as_str()),
167            Some(_) => return Err("a live spec's `changes` is a name".into()),
168        };
169        let map = |k: &str| match o.get(k) {
170            None | Some(Value::Null) => Ok(json!({})),
171            Some(m @ Value::Object(_)) => Ok(m.clone()),
172            Some(_) => Err(format!("a live spec's `{k}` is a map")),
173        };
174        let mut on = Vec::new();
175        match o.get("on") {
176            None | Some(Value::Null) => {}
177            Some(Value::Object(m)) => {
178                for (t, r) in m {
179                    on.push((t.as_str(), r.as_str().ok_or(format!("a live spec's on.{t} is a fold: upsert:<field> or remove:<field>"))?));
180                }
181            }
182            Some(_) => return Err("a live spec's `on` is a map of event type to fold".into()),
183        }
184        Self::new(text("snapshot")?, map("params")?, changes, map("changes_params")?, text("key")?, &on)
185    }
186
187    /// Whether `item` matches every snapshot param that names a field of it.
188    pub fn admits(&self, item: &Value) -> bool {
189        let (Some(params), Some(item)) = (self.params.as_object(), item.as_object()) else { return true };
190        params.iter().all(|(k, v)| item.get(k).is_none_or(|have| have == v))
191    }
192}
193
194/// The clock the cache keeps time by, and its timers (UI-10: a `live`'s
195/// `debounce_ms`).
196pub trait Clock {
197    fn now_ms(&self) -> u64;
198    /// Runs `f` once, `after_ms` from now.
199    fn schedule(&self, after_ms: u64, f: Box<dyn FnOnce()>);
200    /// STUDIO-16: runs `f` once at the next animation frame — the changes
201    /// heard until then published together. A clock with no frames (the
202    /// tests' [`ManualClock`] unless [`ManualClock::with_frames`]) runs it now.
203    fn frame(&self, f: Box<dyn FnOnce()>) {
204        f()
205    }
206}
207
208/// A timer of [`ManualClock`]: when it is due, its order, what it runs.
209type Timer = (u64, u64, Box<dyn FnOnce()>);
210
211/// The tests' clock: moves only when told, running each timer that comes
212/// due on the way, in order.
213#[derive(Clone, Default)]
214pub struct ManualClock {
215    now: Rc<Cell<u64>>,
216    timers: Rc<RefCell<Vec<Timer>>>,
217    seq: Rc<Cell<u64>>,
218    /// STUDIO-16: frames asked, run by [`Self::next_frame`] — when on.
219    frames: Option<Rc<RefCell<Vec<Box<dyn FnOnce()>>>>>,
220}
221
222impl std::fmt::Debug for ManualClock {
223    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224        write!(f, "ManualClock({} ms, {} timers)", self.now.get(), self.timers.borrow().len())
225    }
226}
227
228impl ManualClock {
229    pub fn new() -> Self {
230        Self::default()
231    }
232
233    /// STUDIO-16: a clock with animation frames — [`Clock::frame`] waits
234    /// for [`Self::next_frame`].
235    pub fn with_frames() -> Self {
236        Self { frames: Some(Rc::default()), ..Self::default() }
237    }
238
239    /// STUDIO-16: the next animation frame: what was asked for it runs.
240    pub fn next_frame(&self) {
241        let due = self.frames.as_ref().map(|f| std::mem::take(&mut *f.borrow_mut())).unwrap_or_default();
242        for f in due {
243            f();
244        }
245    }
246
247    /// Moves `ms` on, running the timers that come due (a timer set by one
248    /// that runs is run too, when due by the end).
249    pub fn advance(&self, ms: u64) {
250        let end = self.now.get() + ms;
251        loop {
252            let next = {
253                let mut t = self.timers.borrow_mut();
254                let i = t.iter().enumerate().filter(|(_, (due, _, _))| *due <= end).min_by_key(|(_, (due, seq, _))| (*due, *seq)).map(|(i, _)| i);
255                i.map(|i| t.remove(i))
256            };
257            let Some((due, _, f)) = next else { break };
258            self.now.set(due.max(self.now.get()));
259            f();
260        }
261        self.now.set(end);
262    }
263}
264
265impl Clock for ManualClock {
266    fn now_ms(&self) -> u64 {
267        self.now.get()
268    }
269    fn schedule(&self, after_ms: u64, f: Box<dyn FnOnce()>) {
270        let seq = self.seq.get() + 1;
271        self.seq.set(seq);
272        self.timers.borrow_mut().push((self.now.get() + after_ms, seq, f));
273    }
274    fn frame(&self, f: Box<dyn FnOnce()>) {
275        match &self.frames {
276            Some(frames) => frames.borrow_mut().push(f),
277            None => f(),
278        }
279    }
280}
281
282/// One kept subscription.
283struct Sub {
284    spec: LiveSpec,
285    signal: Signal<Value>,
286    rows: Vec<Value>,
287    status: Status,
288    readers: usize,
289    released_at: u64,
290    changes: Option<CallId>,
291    snapshot: Option<CallId>,
292    /// The snapshot's rows as they arrive.
293    buffer: Vec<Value>,
294    /// FRAME-48: the changes heard while the snapshot runs, folded again
295    /// over its answer — the changes stream is opened first so nothing is
296    /// missed, and an answer landing whole must not take back what came
297    /// on it meanwhile (a `shown` said as a watch opens, a row created
298    /// between the snapshot's read and its `done`). Upserts by key, in
299    /// order: folding one again over a snapshot that has it already moves
300    /// nothing. FRAME-48b: a remove heard meanwhile takes away only what an
301    /// upsert heard meanwhile put there, never a row of the answer — a
302    /// stream's opening word folded as a remove (menger's releases fold the
303    /// watch's `live { version }` as `remove:version`, the pointer as it
304    /// stands) took the live version out of the list.
305    during: Vec<Value>,
306    /// FRAME-48: which snapshot is the one asked last — each asked takes the
307    /// next number, and an answer to an earlier one (a `lagged` heard while
308    /// it ran asks again) is not heard: it neither fills the buffer nor
309    /// takes `during` nor ends the snapshot that is running.
310    asked: u64,
311    /// UI-8: why the last snapshot was refused — an in-band `error` event's
312    /// `message` (status `error`), or the call's refusal (status `refused`);
313    /// published as the collection's `message`.
314    message: Option<String>,
315    /// An in-band `error` heard while the snapshot runs.
316    erred: Option<String>,
317    /// FRAME-17: when (the page's clock) its first answer with rows came.
318    answered_at: Rc<Cell<Option<f64>>>,
319    /// FRAME-20: how many times its value has moved, and the last move.
320    moved: Moves,
321    /// STUDIO-16: the changes folded since it was last published, merged —
322    /// published at the next frame (or with the next move that cannot wait).
323    pending: Option<Delta>,
324}
325
326/// FRAME-20: a collection's moves — how many, and the last one.
327type Moves = Rc<RefCell<(u64, Delta)>>;
328
329/// FRAME-20: `value` set on `signal` as one more move, `delta`, recorded in
330/// `moved` before the signal's readers wake (they read it); a value equal to
331/// the one held is no move.
332fn moved_to(signal: &Signal<Value>, moved: &Moves, value: Value, delta: Delta) {
333    let prev = {
334        let mut m = moved.borrow_mut();
335        let next = (m.0 + 1, delta);
336        std::mem::replace(&mut *m, next)
337    };
338    if !signal.set_if(value) {
339        *moved.borrow_mut() = prev;
340    }
341}
342
343/// FRAME-12: the collection's value set on its signal with no borrow of
344/// the subscription held — a reader woken by it (a module's `subscribe`
345/// callback) may acquire, release or read the cache.
346fn publish(sub: &Rc<RefCell<Sub>>, delta: Delta) {
347    let (signal, value, moved) = {
348        let s = sub.borrow();
349        (s.signal.clone(), s.value(), s.moved.clone())
350    };
351    moved_to(&signal, &moved, value, delta);
352}
353
354/// STUDIO-16: a move published now, carrying the changes still waiting for
355/// their frame.
356fn publish_now(sub: &Rc<RefCell<Sub>>, delta: Delta) {
357    let delta = {
358        let mut s = sub.borrow_mut();
359        match s.pending.take() {
360            Some(p) => s.merged(p, delta),
361            None => delta,
362        }
363    };
364    publish(sub, delta);
365}
366
367/// FRAME-20: a move of the status alone — no row changed.
368fn status_only() -> Delta {
369    Delta::Change { upsert: Vec::new(), remove: Vec::new() }
370}
371
372impl Sub {
373    fn value(&self) -> Value {
374        let mut v = value_of(&self.rows, self.status);
375        if let (Some(m), Some(o)) = (&self.message, v.as_object_mut()) {
376            o.insert("message".into(), Value::String(m.clone()));
377        }
378        v
379    }
380
381    /// STUDIO-16: two moves as one, as `host.js`'s store applies a change
382    /// (its removes, then each upsert in place or last): a row upserted and
383    /// then removed is only removed; a row upserted twice is upserted once,
384    /// as it is last, where it was first; a key removed then upserted is in
385    /// both, so it goes and comes back last — as the fold left it.
386    fn merged(&self, a: Delta, b: Delta) -> Delta {
387        // Keys compared in place: no String made per comparison.
388        let k = &self.spec.key;
389        let same = |x: &Value, y: &Value| x.get(k).is_some() && x.get(k) == y.get(k);
390        let named = |row: &Value, key: &str| match row.get(k) {
391            Some(Value::String(s)) => s == key,
392            Some(other) => other.to_string() == key,
393            None => false,
394        };
395        match (a, b) {
396            (Delta::Change { upsert: mut up, remove: mut gone }, Delta::Change { upsert: up2, remove: gone2 }) => {
397                if !gone2.is_empty() {
398                    up.retain(|row| !gone2.iter().any(|g| named(row, g)));
399                    for g in gone2 {
400                        if !gone.contains(&g) {
401                            gone.push(g);
402                        }
403                    }
404                }
405                for row in up2 {
406                    match up.iter().position(|x| same(x, &row)) {
407                        Some(i) => up[i] = row,
408                        None => up.push(row),
409                    }
410                }
411                Delta::Change { upsert: up, remove: gone }
412            }
413            _ => Delta::Whole,
414        }
415    }
416
417    fn key_of(&self, item: &Value) -> Option<String> {
418        match item.get(&self.spec.key)? {
419            Value::String(s) => Some(s.clone()),
420            other => Some(other.to_string()),
421        }
422    }
423
424    fn position(&self, key: &str) -> Option<usize> {
425        // STUDIO-16: compared in place — key_of's String per row was a fold's
426        // cost, row by row.
427        self.rows.iter().position(|r| match r.get(&self.spec.key) {
428            Some(Value::String(s)) => s == key,
429            Some(other) => other.to_string() == key,
430            None => false,
431        })
432    }
433
434    /// FRAME-48b: `during` folded over a snapshot's answer — each upsert, and
435    /// each remove of a key only an upsert of `during` put there.
436    fn replay(&mut self, during: Vec<Value>) {
437        let mut put = std::collections::BTreeSet::new();
438        for event in during {
439            let Some(kind) = event.get("type").and_then(Value::as_str) else { continue };
440            match self.spec.on.get(kind).cloned() {
441                Some(FoldRule::Upsert(field)) => {
442                    let item = if field == "." { Some(event.clone()) } else { event.get(&field).cloned() };
443                    if let Some(k) = item.as_ref().and_then(|i| self.key_of(i)) {
444                        put.insert(k);
445                    }
446                    let _ = self.fold(&event);
447                }
448                Some(FoldRule::Remove(field)) => {
449                    let ids: Vec<String> = match event.get(&field) {
450                        Some(Value::Array(a)) => a.iter().map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).collect(),
451                        Some(Value::String(s)) => vec![s.clone()],
452                        Some(Value::Null) | None => continue,
453                        Some(v) => vec![v.to_string()],
454                    };
455                    let ours: Vec<Value> = ids.into_iter().filter(|k| put.remove(k)).map(Value::String).collect();
456                    if ours.is_empty() {
457                        continue;
458                    }
459                    let mut e = event.clone();
460                    if let Some(o) = e.as_object_mut() {
461                        o.insert(field, Value::Array(ours));
462                    }
463                    let _ = self.fold(&e);
464                }
465                None => {}
466            }
467        }
468    }
469
470    /// Folds one change event; what moved (FRAME-20: by key — a row
471    /// inserted or replaced, keys removed), none when nothing did.
472    fn fold(&mut self, event: &Value) -> Option<Delta> {
473        let Some(kind) = event.get("type").and_then(Value::as_str) else { return None };
474        match self.spec.on.get(kind).cloned() {
475            Some(FoldRule::Upsert(field)) => {
476                // UI-10: `upsert:.` — the event itself, less `type`, is the row.
477                let item = if field == "." {
478                    let mut flat = event.as_object().cloned().unwrap_or_default();
479                    flat.remove("type");
480                    Some(Value::Object(flat))
481                } else {
482                    event.get(&field).filter(|i| i.is_object()).cloned()
483                };
484                let item = item?;
485                let key = self.key_of(&item)?;
486                let at = self.position(&key);
487                match (self.spec.admits(&item), at) {
488                    // FRAME-20: the row as it is kept: nothing moved.
489                    (true, Some(i)) if self.rows[i] == item => None,
490                    (true, Some(i)) => {
491                        self.rows[i] = item.clone();
492                        Some(Delta::Change { upsert: vec![item], remove: Vec::new() })
493                    }
494                    (true, None) => {
495                        self.rows.push(item.clone());
496                        Some(Delta::Change { upsert: vec![item], remove: Vec::new() })
497                    }
498                    (false, Some(i)) => {
499                        self.rows.remove(i);
500                        Some(Delta::Change { upsert: Vec::new(), remove: vec![key] })
501                    }
502                    (false, None) => None,
503                }
504            }
505            Some(FoldRule::Remove(field)) => {
506                let ids: Vec<String> = match event.get(&field) {
507                    Some(Value::Array(a)) => a.iter().map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).collect(),
508                    Some(Value::String(s)) => vec![s.clone()],
509                    Some(Value::Null) | None => return None,
510                    Some(v) => vec![v.to_string()],
511                };
512                let key = self.spec.key.clone();
513                let mut removed = Vec::new();
514                self.rows.retain(|r| {
515                    let k = match r.get(&key) {
516                        Some(Value::String(s)) => s.clone(),
517                        Some(v) => v.to_string(),
518                        None => return true,
519                    };
520                    let keep = !ids.contains(&k);
521                    if !keep {
522                        removed.push(k);
523                    }
524                    keep
525                });
526                (!removed.is_empty()).then_some(Delta::Change { upsert: Vec::new(), remove: removed })
527            }
528            None => None,
529        }
530    }
531}
532
533/// A snapshot event's row, as the spec's rule for its type makes it from a
534/// change: `upsert:.` — the event itself less `type`; `upsert:<field>` —
535/// that field. With no rule for its type: its one object-valued field;
536/// else (a flat event) the event less `type` when it carries the key; else
537/// none (a `page`).
538fn row_of(event: &Value, spec: &LiveSpec) -> Option<Value> {
539    let o = event.as_object()?;
540    let flat = || {
541        let mut flat = o.clone();
542        flat.remove("type");
543        Value::Object(flat)
544    };
545    let kind = o.get("type").and_then(Value::as_str).unwrap_or_default();
546    match spec.on.get(kind) {
547        Some(FoldRule::Upsert(f)) if f == "." => return Some(flat()),
548        Some(FoldRule::Upsert(f)) => {
549            if let Some(row) = o.get(f).filter(|v| v.is_object()) {
550                return Some(row.clone());
551            }
552        }
553        _ => {}
554    }
555    let mut objects = o.iter().filter(|(k, v)| k.as_str() != "type" && v.is_object());
556    if let Some((_, row)) = objects.next() {
557        return objects.next().is_none().then(|| row.clone());
558    }
559    o.contains_key(&spec.key).then(flat)
560}
561
562/// Every `live` subscription of the page.
563pub struct LiveCache<W: Wire, C: Clock> {
564    rt: Runtime,
565    wire: W,
566    clock: C,
567    subs: RefCell<BTreeMap<String, Rc<RefCell<Sub>>>>,
568    /// FRAME-50: what runs once the snapshots running when it was asked
569    /// are answered — their keys, and it.
570    answered: RefCell<Vec<(Vec<String>, Box<dyn FnOnce()>)>>,
571    /// STUDIO-16: the collections with changes waiting for the frame, and
572    /// whether the frame is asked.
573    dirty: RefCell<Vec<String>>,
574    frame_asked: Cell<bool>,
575    me: Weak<Self>,
576}
577
578impl<W: Wire + Clone + 'static, C: Clock + Clone + 'static> LiveCache<W, C> {
579    pub fn new(rt: &Runtime, wire: W, clock: C) -> Rc<Self> {
580        Rc::new_cyclic(|me| Self { rt: rt.clone(), wire, clock, subs: RefCell::default(), answered: RefCell::default(), dirty: RefCell::default(), frame_asked: Cell::new(false), me: me.clone() })
581    }
582
583    /// FRAME-50: how many snapshots are asked and not yet answered (done,
584    /// refused or failed).
585    pub fn running(&self) -> usize {
586        self.running_keys().len()
587    }
588
589    fn running_keys(&self) -> Vec<String> {
590        self.subs.borrow().iter().filter(|(_, s)| s.borrow().snapshot.is_some()).map(|(k, _)| k.clone()).collect()
591    }
592
593    /// FRAME-50: `f` once every snapshot running now is answered (or let
594    /// go) — now, when none is; one asked later is not waited for.
595    pub fn when_answered(&self, f: Box<dyn FnOnce()>) {
596        let keys = self.running_keys();
597        if keys.is_empty() {
598            return f();
599        }
600        self.answered.borrow_mut().push((keys, f));
601    }
602
603    fn answered_check(&self) {
604        if self.answered.borrow().is_empty() {
605            return;
606        }
607        let running = self.running_keys();
608        let (done, wait): (Vec<_>, Vec<_>) = std::mem::take(&mut *self.answered.borrow_mut()).into_iter().partition(|(keys, _)| !keys.iter().any(|k| running.contains(k)));
609        self.answered.borrow_mut().extend(wait);
610        for (_, f) in done {
611            f();
612        }
613    }
614
615    /// A reader of `spec`'s collection: the subscription kept for it, else
616    /// a new one (changes opened, then the snapshot).
617    pub fn acquire(self: &Rc<Self>, spec: &LiveSpec) -> Reader {
618        let key = spec.cache_key();
619        let existing = self.subs.borrow().get(&key).cloned();
620        let sub = match existing {
621            Some(sub) => sub,
622            None => {
623                let signal = self.rt.signal(Live { rows: Vec::new(), status: Status::Pending }.to_value());
624                let sub = Rc::new(RefCell::new(Sub {
625                    spec: spec.clone(),
626                    signal,
627                    rows: Vec::new(),
628                    status: Status::Pending,
629                    readers: 0,
630                    released_at: 0,
631                    changes: None,
632                    snapshot: None,
633                    buffer: Vec::new(),
634                    during: Vec::new(),
635                    asked: 0,
636                    message: None,
637                    erred: None,
638                    answered_at: Rc::default(),
639                    moved: Rc::new(RefCell::new((0, Delta::Whole))),
640                    pending: None,
641                }));
642                self.subs.borrow_mut().insert(key.clone(), sub.clone());
643                self.open_changes(&key, &sub);
644                self.open_snapshot(&key, &sub);
645                sub
646            }
647        };
648        let (signal, answered_at, moved) = {
649            let mut s = sub.borrow_mut();
650            s.readers += 1;
651            (s.signal.clone(), s.answered_at.clone(), s.moved.clone())
652        };
653        let me = self.me.clone();
654        Reader {
655            signal,
656            answered_at,
657            moved,
658            release: Some(Box::new(move || {
659                if let Some(cache) = me.upgrade() {
660                    cache.release(&key);
661                }
662            })),
663        }
664    }
665
666    fn release(&self, key: &str) {
667        if let Some(sub) = self.subs.borrow().get(key) {
668            let mut s = sub.borrow_mut();
669            s.readers = s.readers.saturating_sub(1);
670            if s.readers == 0 {
671                s.released_at = self.clock.now_ms();
672            }
673        }
674    }
675
676    fn open_changes(&self, key: &str, sub: &Rc<RefCell<Sub>>) {
677        let (method, params) = {
678            let s = sub.borrow();
679            (s.spec.changes.clone(), s.spec.changes_params.clone())
680        };
681        // UI-10: a live without changes is a one-shot read: no watch.
682        let Some(method) = method else { return };
683        let (me, k) = (self.me.clone(), key.to_string());
684        let id = self.wire.open(&method, params, Box::new(move |item| {
685            if let Some(cache) = me.upgrade() {
686                cache.heard_change(&k, item);
687            }
688        }));
689        sub.borrow_mut().changes = Some(id);
690    }
691
692    fn open_snapshot(&self, key: &str, sub: &Rc<RefCell<Sub>>) {
693        let (method, params, asked) = {
694            let mut s = sub.borrow_mut();
695            s.buffer.clear();
696            // FRAME-48: what was heard before this snapshot was asked is in
697            // its answer, or older than it: never folded over it.
698            s.during.clear();
699            s.erred = None;
700            s.asked += 1;
701            (s.spec.snapshot.clone(), s.spec.params.clone(), s.asked)
702        };
703        let (me, k) = (self.me.clone(), key.to_string());
704        crate::marks::once("first-call");
705        let id = self.wire.open(&method, params, Box::new(move |item| {
706            if let Some(cache) = me.upgrade() {
707                cache.heard_snapshot(&k, asked, item);
708            }
709        }));
710        let mut s = sub.borrow_mut();
711        // A snapshot that answered at once (a fake, a cache) is done already.
712        if s.snapshot.is_none() && matches!(s.status, Status::Live) {
713            return;
714        }
715        s.snapshot = Some(id);
716    }
717
718    fn sub(&self, key: &str) -> Option<Rc<RefCell<Sub>>> {
719        self.subs.borrow().get(key).cloned()
720    }
721
722    fn heard_snapshot(&self, key: &str, asked: u64, item: WireItem) {
723        let Some(sub) = self.sub(key) else { return };
724        let mut s = sub.borrow_mut();
725        // FRAME-48: an earlier snapshot's answer, one asked again since.
726        if asked != s.asked {
727            return;
728        }
729        // FRAME-20: an answer is the whole collection; a refusal or a
730        // failure moves the status alone, the rows kept.
731        let mut delta = Delta::Whole;
732        match item {
733            WireItem::Data(event) => {
734                // UI-8: an in-band refusal (`{ type: "error", message }`, a
735                // filter not taken) makes the answer an error, not a row.
736                if event.get("type").and_then(Value::as_str) == Some("error") {
737                    s.erred = Some(event.get("message").and_then(Value::as_str).unwrap_or("refused").to_string());
738                    return;
739                }
740                // PERF-15: a page's rows as one event — `rows { items }`,
741                // each item the per-row event it stands for, its row taken
742                // as that event's would be. A page may be several (past the
743                // service's byte budget): each adds to the one buffer, and
744                // the page lands whole at `done`, one move.
745                if event.get("type").and_then(Value::as_str) == Some("rows") {
746                    let spec = s.spec.clone();
747                    let rows = event.get("items").and_then(Value::as_array).into_iter().flatten().filter_map(|item| row_of(item, &spec));
748                    s.buffer.extend(rows);
749                    return;
750                }
751                if let Some(row) = row_of(&event, &s.spec) {
752                    s.buffer.push(row);
753                }
754                return;
755            }
756            WireItem::Done => match s.erred.take() {
757                Some(m) => {
758                    s.buffer.clear();
759                    s.during.clear();
760                    s.rows.clear();
761                    s.status = Status::Error;
762                    s.message = Some(m);
763                }
764                None => {
765                    s.rows = std::mem::take(&mut s.buffer);
766                    // FRAME-48: what the changes said meanwhile, over it.
767                    let during = std::mem::take(&mut s.during);
768                    s.replay(during);
769                    s.status = Status::Live;
770                    s.message = None;
771                    if !s.rows.is_empty() && s.answered_at.get().is_none() {
772                        s.answered_at.set(Some(crate::marks::now()));
773                    }
774                }
775            },
776            WireItem::Refused(m) => {
777                s.during.clear();
778                s.status = Status::Refused;
779                s.message = Some(m);
780                delta = status_only();
781            }
782            WireItem::Failed(_) | WireItem::Dropped => {
783                s.during.clear();
784                s.status = Status::Resyncing;
785                delta = status_only();
786            }
787        }
788        s.snapshot = None;
789        // FRAME-17: rows a reader draws now (one asked at boot and not yet
790        // read is drawn by its mount: `swap` marks it there).
791        let drawn = (s.readers > 0 && s.status == Status::Live).then(|| s.answered_at.get()).flatten();
792        let snapshot = s.spec.snapshot.clone();
793        drop(s);
794        if let Some(at) = drawn {
795            crate::marks::once_at("first-answer", at);
796            crate::marks::once_at(&format!("answered:{snapshot}"), at);
797        }
798        publish_now(&sub, delta);
799        if drawn.is_some() {
800            crate::marks::once("first-row");
801            crate::marks::once(&format!("drawn:{snapshot}"));
802        }
803        self.answered_check();
804    }
805
806    fn heard_change(&self, key: &str, item: WireItem) {
807        let Some(sub) = self.sub(key) else { return };
808        match item {
809            WireItem::Data(event) if event.get("type").and_then(Value::as_str) == Some("lagged") => {
810                sub.borrow_mut().status = Status::Resyncing;
811                publish_now(&sub, status_only());
812                self.open_snapshot(key, &sub);
813            }
814            WireItem::Data(event) => {
815                let moved = {
816                    let mut s = sub.borrow_mut();
817                    // FRAME-48: kept to fold again over the snapshot's answer.
818                    if s.snapshot.is_some() || s.status == Status::Pending {
819                        s.during.push(event.clone());
820                    }
821                    s.fold(&event)
822                };
823                if let Some(delta) = moved {
824                    self.defer(key, &sub, delta);
825                }
826            }
827            WireItem::Done => sub.borrow_mut().changes = None,
828            WireItem::Refused(_) => {
829                let mut s = sub.borrow_mut();
830                s.changes = None;
831                s.status = Status::Refused;
832                drop(s);
833                publish_now(&sub, status_only());
834            }
835            WireItem::Failed(_) | WireItem::Dropped => {
836                let mut s = sub.borrow_mut();
837                s.changes = None;
838                s.status = Status::Resyncing;
839                drop(s);
840                publish_now(&sub, status_only());
841            }
842        }
843    }
844
845    /// STUDIO-16: a change folded into `sub`, published at the next frame
846    /// with whatever else it hears until then.
847    fn defer(&self, key: &str, sub: &Rc<RefCell<Sub>>, delta: Delta) {
848        let first = {
849            let mut s = sub.borrow_mut();
850            let (merged, first) = match s.pending.take() {
851                Some(p) => (s.merged(p, delta), false),
852                None => (delta, true),
853            };
854            s.pending = Some(merged);
855            first
856        };
857        if first {
858            self.dirty.borrow_mut().push(key.to_string());
859        }
860        if !self.frame_asked.replace(true) {
861            let me = self.me.clone();
862            self.clock.frame(Box::new(move || {
863                if let Some(cache) = me.upgrade() {
864                    cache.flush();
865                }
866            }));
867        }
868    }
869
870    /// STUDIO-16: the frame — every collection with changes waiting
871    /// published, its readers drawn once (one batch: a binding reading
872    /// several runs once).
873    pub fn flush(&self) {
874        self.frame_asked.set(false);
875        let keys = std::mem::take(&mut *self.dirty.borrow_mut());
876        if keys.is_empty() {
877            return;
878        }
879        self.rt.batch(|| {
880            for k in keys {
881                let Some(sub) = self.sub(&k) else { continue };
882                let pending = sub.borrow_mut().pending.take();
883                if let Some(delta) = pending {
884                    publish(&sub, delta);
885                }
886            }
887        });
888    }
889
890    /// Closes every subscription with no reader for longer than [`KEEP_MS`].
891    pub fn sweep(&self) {
892        let now = self.clock.now_ms();
893        let gone: Vec<(String, Rc<RefCell<Sub>>)> = self
894            .subs
895            .borrow()
896            .iter()
897            .filter(|(_, s)| {
898                let s = s.borrow();
899                s.readers == 0 && now.saturating_sub(s.released_at) > KEEP_MS
900            })
901            .map(|(k, s)| (k.clone(), s.clone()))
902            .collect();
903        for (k, sub) in gone {
904            self.subs.borrow_mut().remove(&k);
905            let (changes, snapshot) = {
906                let mut s = sub.borrow_mut();
907                s.status = Status::Closed;
908                (s.changes.take(), s.snapshot.take())
909            };
910            for id in [changes, snapshot].into_iter().flatten() {
911                self.wire.close(id);
912            }
913        }
914    }
915
916    /// The socket came back: every kept subscription `resyncing`, its
917    /// changes re-opened and its snapshot asked again.
918    pub fn reconnected(&self) {
919        let subs: Vec<(String, Rc<RefCell<Sub>>)> = self.subs.borrow().iter().map(|(k, s)| (k.clone(), s.clone())).collect();
920        for (k, sub) in subs {
921            let (changes, snapshot) = {
922                let mut s = sub.borrow_mut();
923                s.status = Status::Resyncing;
924                (s.changes.take(), s.snapshot.take())
925            };
926            for id in [changes, snapshot].into_iter().flatten() {
927                self.wire.close(id);
928            }
929            publish_now(&sub, status_only());
930            self.open_changes(&k, &sub);
931            self.open_snapshot(&k, &sub);
932        }
933    }
934
935    /// How many subscriptions are kept (read or waiting out their 5 s).
936    pub fn kept(&self) -> usize {
937        self.subs.borrow().len()
938    }
939}
940
941/// UI-10: a `live` as declared, before its params are known: the methods,
942/// the key, the folds, and how long its params must be quiet before it
943/// runs again.
944#[derive(Debug, Clone, PartialEq)]
945pub struct LiveQuery {
946    pub snapshot: String,
947    pub changes: Option<String>,
948    pub key: String,
949    pub on: Vec<(String, String)>,
950    pub debounce_ms: Option<u64>,
951}
952
953impl<W: Wire + Clone + 'static, C: Clock + Clone + 'static> LiveCache<W, C> {
954    /// UI-10: a collection whose params are `params()` — `(params,
955    /// changes_params)`, read in a binding: when a signal it read changes,
956    /// the snapshot runs again (after `debounce_ms` of quiet when given),
957    /// the old rows kept, `resyncing`, until the new snapshot lands.
958    pub fn follow(self: &Rc<Self>, query: LiveQuery, mut params: impl FnMut() -> (Value, Value) + 'static) -> Follow {
959        self.follow_held(query, move || Some(params()))
960    }
961
962    /// FRAME-16: [`Self::follow`], held while `params()` answers `None` (its
963    /// `when` is false): nothing is asked, and a reader it held is let go —
964    /// the rows stay as they were; answered again, it runs with the params
965    /// of that moment — after `debounce_ms` when it has one (a query typed
966    /// into a held palette is one call, not one per key).
967    pub fn follow_held(self: &Rc<Self>, query: LiveQuery, mut params: impl FnMut() -> Option<(Value, Value)> + 'static) -> Follow {
968        let out = self.rt.signal(Live { rows: Vec::new(), status: Status::Pending }.to_value());
969        let crossing: Moves = Rc::new(RefCell::new((0, Delta::Whole)));
970        let st: Rc<RefCell<Following>> = Rc::new(RefCell::new(Following { reader: None, mirror: None, generation: 0, last: None, stopped: false }));
971        let (me, st2, out2, q, cr2) = (Rc::downgrade(self), st.clone(), out.clone(), Rc::new(query), crossing.clone());
972        let rt = self.rt.clone();
973        let was_held = Rc::new(Cell::new(false));
974        let binding = self.rt.bind(move || {
975            let held = params();
976            let Some(cache) = me.upgrade() else { return };
977            let Some(p) = held else {
978                was_held.set(true);
979                let mut s = st2.borrow_mut();
980                if s.last.take().is_some() {
981                    s.generation += 1;
982                    if let Some(m) = s.mirror.take() {
983                        rt.dispose(m);
984                    }
985                    s.reader = None;
986                }
987                return;
988            };
989            let first = {
990                let mut s = st2.borrow_mut();
991                if s.last.as_ref() == Some(&p) {
992                    return;
993                }
994                let first = s.last.is_none();
995                s.last = Some(p.clone());
996                s.generation += 1;
997                first
998            };
999            let resumed = was_held.replace(false);
1000            match q.debounce_ms.filter(|_| !first || resumed) {
1001                None => rt.untracked(|| cache.switch(&st2, &out2, &cr2, &q, p, first)),
1002                Some(ms) => {
1003                    let generation = st2.borrow().generation;
1004                    let (me, st3, out3, q2, rt2, cr3) = (Rc::downgrade(&cache), st2.clone(), out2.clone(), q.clone(), rt.clone(), cr2.clone());
1005                    cache.clock.schedule(
1006                        ms,
1007                        Box::new(move || {
1008                            let current = { let s = st3.borrow(); !s.stopped && s.generation == generation };
1009                            if let (true, Some(cache)) = (current, me.upgrade()) {
1010                                rt2.untracked(|| cache.switch(&st3, &out3, &cr3, &q2, p, first));
1011                            }
1012                        }),
1013                    );
1014                }
1015            }
1016        });
1017        let rt = self.rt.clone();
1018        Follow {
1019            signal: out,
1020            crossing,
1021            st: st.clone(),
1022            stop: Some(Box::new(move || {
1023                rt.dispose(binding);
1024                let mut s = st.borrow_mut();
1025                s.stopped = true;
1026                if let Some(m) = s.mirror.take() {
1027                    rt.dispose(m);
1028                }
1029                s.reader = None;
1030            })),
1031        }
1032    }
1033
1034    /// The followed collection on the params `p`: a reader of their spec,
1035    /// mirrored into `out` — the old rows, `resyncing`, while the new one
1036    /// is pending.
1037    fn switch(self: &Rc<Self>, st: &Rc<RefCell<Following>>, out: &Signal<Value>, crossing: &Moves, q: &LiveQuery, p: (Value, Value), first: bool) {
1038        let on: Vec<(&str, &str)> = q.on.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect();
1039        let spec = match LiveSpec::new(&q.snapshot, p.0, q.changes.as_deref(), p.1, &q.key, &on) {
1040            Ok(spec) => spec,
1041            Err(_) => {
1042                moved_to(out, crossing, Live { rows: Vec::new(), status: Status::Error }.to_value(), Delta::Whole);
1043                return;
1044            }
1045        };
1046        let reader = self.acquire(&spec);
1047        let sig = reader.signal();
1048        let old_rows = if first { Vec::new() } else { Live::from_value(&out.peek()).map(|l| l.rows).unwrap_or_default() };
1049        let switching = Rc::new(Cell::new(!first));
1050        let (o, sw, cr, rm) = (out.clone(), switching.clone(), crossing.clone(), reader.moved.clone());
1051        // FRAME-20: the reader's move it saw last (none: this mirror's first
1052        // run, which crosses whole — another collection's rows).
1053        let seen = Cell::new(None::<u64>);
1054        let mirror = self.rt.bind(move || {
1055            let v = sig.get();
1056            let (at, delta) = rm.borrow().clone();
1057            let last = seen.replace(Some(at));
1058            // STUDIO-16: its status read in place (no copy of its rows).
1059            let pending = v.get("status").and_then(Value::as_str) == Some(Status::Pending.as_str());
1060            match pending {
1061                true if sw.get() => moved_to(&o, &cr, Live { rows: old_rows.clone(), status: Status::Resyncing }.to_value(), status_only()),
1062                _ => {
1063                    sw.set(false);
1064                    let delta = match last {
1065                        Some(p) if at == p + 1 => delta,
1066                        _ => Delta::Whole,
1067                    };
1068                    moved_to(&o, &cr, v, delta);
1069                }
1070            }
1071        });
1072        let mut s = st.borrow_mut();
1073        if let Some(old) = s.mirror.replace(mirror) {
1074            self.rt.dispose(old);
1075        }
1076        s.reader = Some(reader);
1077    }
1078}
1079
1080/// FRAME-19: a module's `live` spec — [`LiveSpec::from_value`]'s keys,
1081/// plus what rhx's `live` has: `when` (a boolean, `true` when left out;
1082/// `false` holds it — nothing asked) and `debounce_ms` (how long its params
1083/// must be quiet before it runs again). `when` and `debounce_ms` are not
1084/// part of what is shared: two modules asking the same spec, held or not,
1085/// read one collection once both ask.
1086#[derive(Debug, Clone, PartialEq)]
1087pub struct ModuleSpec {
1088    pub query: LiveQuery,
1089    pub params: Value,
1090    pub changes_params: Value,
1091    pub when: bool,
1092}
1093
1094impl ModuleSpec {
1095    /// From a module's spec as it crosses the bus (JSON): `{ snapshot,
1096    /// params?, changes?, changes_params?, key, on?, when?, debounce_ms? }`;
1097    /// a `when` that is no boolean, a `debounce_ms` that is no count, or a
1098    /// key it does not know is refused, naming it.
1099    pub fn from_value(v: &Value) -> Result<Self, String> {
1100        let o = v.as_object().ok_or("a live spec is { snapshot, params?, changes?, changes_params?, key, on?, when?, debounce_ms? }")?;
1101        let mut shared = o.clone();
1102        let when = match shared.remove("when") {
1103            None | Some(Value::Null) => true,
1104            Some(Value::Bool(b)) => b,
1105            Some(_) => return Err("a live spec's `when` is true or false".into()),
1106        };
1107        let debounce_ms = match shared.remove("debounce_ms") {
1108            None | Some(Value::Null) => None,
1109            Some(n) => Some(n.as_u64().ok_or("a live spec's `debounce_ms` is a count of milliseconds")?),
1110        };
1111        let s = LiveSpec::from_value(&Value::Object(shared)).map_err(|e| e.replace("on? }", "on?, when?, debounce_ms? }"))?;
1112        let on = o.get("on").and_then(Value::as_object).map(|m| m.iter().map(|(t, r)| (t.clone(), r.as_str().unwrap_or_default().to_string())).collect()).unwrap_or_default();
1113        Ok(Self {
1114            query: LiveQuery { snapshot: s.snapshot, changes: s.changes, key: s.key, on, debounce_ms },
1115            params: s.params,
1116            changes_params: s.changes_params,
1117            when,
1118        })
1119    }
1120
1121    /// This spec with `patch` — `{ params?, changes_params?, when? }` —
1122    /// over it; anything else in the patch refused, naming it.
1123    pub fn patched(&self, patch: &Value) -> Result<Self, String> {
1124        let p = patch.as_object().ok_or("a live's update is { params?, changes_params?, when? }")?;
1125        let mut next = self.clone();
1126        for (k, v) in p {
1127            match (k.as_str(), v) {
1128                ("params" | "changes_params", Value::Null) => *(if k == "params" { &mut next.params } else { &mut next.changes_params }) = json!({}),
1129                ("params", Value::Object(_)) => next.params = v.clone(),
1130                ("changes_params", Value::Object(_)) => next.changes_params = v.clone(),
1131                ("params" | "changes_params", _) => return Err(format!("a live's update: `{k}` is a map")),
1132                ("when", Value::Bool(b)) => next.when = *b,
1133                ("when", _) => return Err("a live's update: `when` is true or false".into()),
1134                _ => return Err(format!("a live's update has no `{k}`: {{ params?, changes_params?, when? }}")),
1135            }
1136        }
1137        Ok(next)
1138    }
1139}
1140
1141/// FRAME-19: a module's collection — [`LiveCache::follow_held`] over the
1142/// spec's params and `when`, which the module moves with
1143/// [`ModuleLive::update`]; the registry owns the timing (`debounce_ms`).
1144pub struct ModuleLive {
1145    follow: Follow,
1146    spec: Rc<RefCell<ModuleSpec>>,
1147    inputs: Signal<Value>,
1148}
1149
1150impl ModuleLive {
1151    /// `patch` — `{ params?, changes_params?, when? }` — over what the
1152    /// collection follows now; the keys left out stay as they are. A patch
1153    /// that changes nothing asks nothing.
1154    pub fn update(&self, patch: &Value) -> Result<(), String> {
1155        let next = self.spec.borrow().patched(patch)?;
1156        let value = json!({ "params": next.params, "changes_params": next.changes_params, "when": next.when });
1157        *self.spec.borrow_mut() = next;
1158        if self.inputs.peek() != value {
1159            self.inputs.set(value);
1160        }
1161        Ok(())
1162    }
1163
1164    /// The spec as it stands, every update applied.
1165    pub fn spec(&self) -> ModuleSpec {
1166        self.spec.borrow().clone()
1167    }
1168
1169    /// The collection as a signal of `{ rows, status }`.
1170    pub fn signal(&self) -> Signal<Value> {
1171        self.follow.signal()
1172    }
1173
1174    /// The collection now, untracked.
1175    pub fn live(&self) -> Live {
1176        self.follow.live()
1177    }
1178}
1179
1180/// FRAME-20: what crosses to a module when its collection moves — the
1181/// fold's own result by key, not the collection.
1182#[derive(Debug, Clone, PartialEq)]
1183pub enum Delta {
1184    /// The whole collection: the first page, a resync's snapshot, a switch
1185    /// to other params — or a subscriber that missed a move.
1186    Whole,
1187    /// The rows the fold inserted or replaced (each one whose value
1188    /// changed: an upsert equal to the row kept moves nothing), and the keys
1189    /// it removed (an upsert that stops matching the params is a remove).
1190    /// Both empty: only the status moved.
1191    Change { upsert: Vec<Value>, remove: Vec<String> },
1192}
1193
1194/// FRAME-20: a move of a module's collection as a subscriber that last saw
1195/// move `seen` receives it — `seq` the move it now stands at.
1196#[derive(Debug, Clone, PartialEq)]
1197pub struct Crossing {
1198    pub seq: u64,
1199    pub delta: Delta,
1200}
1201
1202impl ModuleLive {
1203    /// FRAME-20: how many times the collection has moved (0: never).
1204    pub fn seq(&self) -> u64 {
1205        self.follow.crossing.borrow().0
1206    }
1207
1208    /// FRAME-20: what crosses to a subscriber that last saw move `seen`:
1209    /// the last move's change when it is the only one since, else (several
1210    /// since, or the last one whole) [`Delta::Whole`].
1211    pub fn since(&self, seen: u64) -> Crossing {
1212        let (seq, delta) = self.follow.crossing.borrow().clone();
1213        let delta = if seq == seen {
1214            status_only()
1215        } else if seen != 0 && seq == seen + 1 {
1216            delta
1217        } else {
1218            Delta::Whole
1219        };
1220        Crossing { seq, delta }
1221    }
1222}
1223
1224impl<W: Wire + Clone + 'static, C: Clock + Clone + 'static> LiveCache<W, C> {
1225    /// FRAME-19: a module's collection, held by its `when` and its param
1226    /// changes coalesced by its `debounce_ms` — rhx's [`Self::follow_held`],
1227    /// its inputs a signal [`ModuleLive::update`] sets.
1228    pub fn follow_module(self: &Rc<Self>, spec: ModuleSpec) -> ModuleLive {
1229        let inputs = self.rt.signal(json!({ "params": spec.params, "changes_params": spec.changes_params, "when": spec.when }));
1230        let read = inputs.clone();
1231        let follow = self.follow_held(spec.query.clone(), move || {
1232            let v = read.get();
1233            (v["when"] != false).then(|| (v["params"].clone(), v["changes_params"].clone()))
1234        });
1235        ModuleLive { follow, spec: Rc::new(RefCell::new(spec)), inputs }
1236    }
1237}
1238
1239/// What a [`Follow`] holds: its reader now, the binding mirroring it, the
1240/// params last seen and how many times they changed (a debounced run
1241/// checks it is still the last).
1242struct Following {
1243    reader: Option<Reader>,
1244    mirror: Option<crate::signals::BindingId>,
1245    generation: u64,
1246    last: Option<(Value, Value)>,
1247    stopped: bool,
1248}
1249
1250/// UI-10: a collection that follows its params; dropping it stops that and
1251/// releases its reader.
1252pub struct Follow {
1253    signal: Signal<Value>,
1254    /// FRAME-20: the moves of `signal`.
1255    crossing: Moves,
1256    st: Rc<RefCell<Following>>,
1257    stop: Option<Box<dyn FnOnce()>>,
1258}
1259
1260impl Follow {
1261    /// The collection as a signal of `{ rows, status }` — the same signal
1262    /// whatever the params become.
1263    pub fn signal(&self) -> Signal<Value> {
1264        self.signal.clone()
1265    }
1266
1267    /// The collection now, untracked.
1268    pub fn live(&self) -> Live {
1269        Live::from_value(&self.signal.peek()).expect("a live collection's value")
1270    }
1271
1272    /// FRAME-17: when the collection it reads now first answered with rows.
1273    pub fn answered_at(&self) -> Option<f64> {
1274        self.st.borrow().reader.as_ref().and_then(Reader::answered_at)
1275    }
1276}
1277
1278impl Drop for Follow {
1279    fn drop(&mut self) {
1280        if let Some(stop) = self.stop.take() {
1281            stop();
1282        }
1283    }
1284}
1285
1286/// One reader of a collection; dropping it releases the subscription
1287/// (kept [`KEEP_MS`] more).
1288pub struct Reader {
1289    signal: Signal<Value>,
1290    /// FRAME-20: its collection's moves.
1291    moved: Moves,
1292    answered_at: Rc<Cell<Option<f64>>>,
1293    release: Option<Box<dyn FnOnce()>>,
1294}
1295
1296impl Reader {
1297    /// FRAME-17: when its collection's first answer with rows came (the
1298    /// page's clock), if it has.
1299    pub fn answered_at(&self) -> Option<f64> {
1300        self.answered_at.get()
1301    }
1302
1303    /// The collection as a signal of `{ rows, status }` (what the tree binds).
1304    pub fn signal(&self) -> Signal<Value> {
1305        self.signal.clone()
1306    }
1307
1308    /// The collection now, untracked.
1309    pub fn live(&self) -> Live {
1310        Live::from_value(&self.signal.peek()).expect("a live collection's value")
1311    }
1312}
1313
1314impl Drop for Reader {
1315    fn drop(&mut self) {
1316        if let Some(release) = self.release.take() {
1317            release();
1318        }
1319    }
1320}
1321
1322/// A `live` declaration's params resolved against the props: `{ "expr" }`
1323/// values evaluated (a prop by name, or a Rhai expression over the props).
1324pub fn resolve(params: &BTreeMap<String, Value>, props: &Map<String, Value>) -> Value {
1325    let mut out = Map::new();
1326    for (k, v) in params {
1327        let v = match v.as_object().and_then(|o| o.get("expr")).and_then(Value::as_str) {
1328            Some(e) => match props.get(e) {
1329                Some(p) => p.clone(),
1330                None => {
1331                    let mut scope = rhai::Scope::new();
1332                    for (pk, pv) in props {
1333                        scope.push_constant_dynamic(pk.clone(), crate::tree::expr::to_dynamic(pv));
1334                    }
1335                    crate::tree::expr::engine()
1336                        .eval_expression_with_scope::<rhai::Dynamic>(&mut scope, e)
1337                        .map(|d| crate::tree::expr::to_value(&d))
1338                        .unwrap_or(Value::Null)
1339                }
1340            },
1341            None => v.clone(),
1342        };
1343        out.insert(k.clone(), v);
1344    }
1345    Value::Object(out)
1346}
1347
1348#[cfg(test)]
1349mod tests;