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 failure moves the
730        // status alone, the rows kept; KEEL-59: a refusal clears them.
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                // KEEL-59 (N5): refused, the page keeps nothing it was
778                // shown under a right it no longer has.
779                s.during.clear();
780                s.buffer.clear();
781                s.rows.clear();
782                s.status = Status::Refused;
783                s.message = Some(m);
784            }
785            WireItem::Failed(_) | WireItem::Dropped => {
786                s.during.clear();
787                s.status = Status::Resyncing;
788                delta = status_only();
789            }
790        }
791        s.snapshot = None;
792        // FRAME-17: rows a reader draws now (one asked at boot and not yet
793        // read is drawn by its mount: `swap` marks it there).
794        let drawn = (s.readers > 0 && s.status == Status::Live).then(|| s.answered_at.get()).flatten();
795        let snapshot = s.spec.snapshot.clone();
796        drop(s);
797        if let Some(at) = drawn {
798            crate::marks::once_at("first-answer", at);
799            crate::marks::once_at(&format!("answered:{snapshot}"), at);
800        }
801        publish_now(&sub, delta);
802        if drawn.is_some() {
803            crate::marks::once("first-row");
804            crate::marks::once(&format!("drawn:{snapshot}"));
805        }
806        self.answered_check();
807    }
808
809    fn heard_change(&self, key: &str, item: WireItem) {
810        let Some(sub) = self.sub(key) else { return };
811        match item {
812            WireItem::Data(event) if event.get("type").and_then(Value::as_str) == Some("lagged") => {
813                sub.borrow_mut().status = Status::Resyncing;
814                publish_now(&sub, status_only());
815                self.open_snapshot(key, &sub);
816            }
817            WireItem::Data(event) => {
818                let moved = {
819                    let mut s = sub.borrow_mut();
820                    // FRAME-48: kept to fold again over the snapshot's answer.
821                    if s.snapshot.is_some() || s.status == Status::Pending {
822                        s.during.push(event.clone());
823                    }
824                    s.fold(&event)
825                };
826                if let Some(delta) = moved {
827                    self.defer(key, &sub, delta);
828                }
829            }
830            WireItem::Done => sub.borrow_mut().changes = None,
831            WireItem::Refused(m, _) => {
832                // KEEL-59 (N5): the service ended the changes — a grant
833                // revoked mid-stream, a sign-in ended: the rows go with
834                // the right they were shown under, and the refusal shows.
835                let mut s = sub.borrow_mut();
836                s.changes = None;
837                s.rows.clear();
838                s.buffer.clear();
839                s.during.clear();
840                s.status = Status::Refused;
841                s.message = Some(m);
842                drop(s);
843                publish_now(&sub, Delta::Whole);
844            }
845            WireItem::Failed(_) | WireItem::Dropped => {
846                let mut s = sub.borrow_mut();
847                s.changes = None;
848                s.status = Status::Resyncing;
849                drop(s);
850                publish_now(&sub, status_only());
851            }
852        }
853    }
854
855    /// STUDIO-16: a change folded into `sub`, published at the next frame
856    /// with whatever else it hears until then.
857    fn defer(&self, key: &str, sub: &Rc<RefCell<Sub>>, delta: Delta) {
858        let first = {
859            let mut s = sub.borrow_mut();
860            let (merged, first) = match s.pending.take() {
861                Some(p) => (s.merged(p, delta), false),
862                None => (delta, true),
863            };
864            s.pending = Some(merged);
865            first
866        };
867        if first {
868            self.dirty.borrow_mut().push(key.to_string());
869        }
870        if !self.frame_asked.replace(true) {
871            let me = self.me.clone();
872            self.clock.frame(Box::new(move || {
873                if let Some(cache) = me.upgrade() {
874                    cache.flush();
875                }
876            }));
877        }
878    }
879
880    /// STUDIO-16: the frame — every collection with changes waiting
881    /// published, its readers drawn once (one batch: a binding reading
882    /// several runs once).
883    pub fn flush(&self) {
884        self.frame_asked.set(false);
885        let keys = std::mem::take(&mut *self.dirty.borrow_mut());
886        if keys.is_empty() {
887            return;
888        }
889        self.rt.batch(|| {
890            for k in keys {
891                let Some(sub) = self.sub(&k) else { continue };
892                let pending = sub.borrow_mut().pending.take();
893                if let Some(delta) = pending {
894                    publish(&sub, delta);
895                }
896            }
897        });
898    }
899
900    /// Closes every subscription with no reader for longer than [`KEEP_MS`].
901    pub fn sweep(&self) {
902        let now = self.clock.now_ms();
903        let gone: Vec<(String, Rc<RefCell<Sub>>)> = self
904            .subs
905            .borrow()
906            .iter()
907            .filter(|(_, s)| {
908                let s = s.borrow();
909                s.readers == 0 && now.saturating_sub(s.released_at) > KEEP_MS
910            })
911            .map(|(k, s)| (k.clone(), s.clone()))
912            .collect();
913        for (k, sub) in gone {
914            self.subs.borrow_mut().remove(&k);
915            let (changes, snapshot) = {
916                let mut s = sub.borrow_mut();
917                s.status = Status::Closed;
918                (s.changes.take(), s.snapshot.take())
919            };
920            for id in [changes, snapshot].into_iter().flatten() {
921                self.wire.close(id);
922            }
923        }
924    }
925
926    /// The socket came back: every kept subscription `resyncing`, its
927    /// changes re-opened and its snapshot asked again.
928    pub fn reconnected(&self) {
929        let subs: Vec<(String, Rc<RefCell<Sub>>)> = self.subs.borrow().iter().map(|(k, s)| (k.clone(), s.clone())).collect();
930        for (k, sub) in subs {
931            let (changes, snapshot) = {
932                let mut s = sub.borrow_mut();
933                s.status = Status::Resyncing;
934                (s.changes.take(), s.snapshot.take())
935            };
936            for id in [changes, snapshot].into_iter().flatten() {
937                self.wire.close(id);
938            }
939            publish_now(&sub, status_only());
940            self.open_changes(&k, &sub);
941            self.open_snapshot(&k, &sub);
942        }
943    }
944
945    /// How many subscriptions are kept (read or waiting out their 5 s).
946    pub fn kept(&self) -> usize {
947        self.subs.borrow().len()
948    }
949}
950
951/// UI-10: a `live` as declared, before its params are known: the methods,
952/// the key, the folds, and how long its params must be quiet before it
953/// runs again.
954#[derive(Debug, Clone, PartialEq)]
955pub struct LiveQuery {
956    pub snapshot: String,
957    pub changes: Option<String>,
958    pub key: String,
959    pub on: Vec<(String, String)>,
960    pub debounce_ms: Option<u64>,
961}
962
963impl<W: Wire + Clone + 'static, C: Clock + Clone + 'static> LiveCache<W, C> {
964    /// UI-10: a collection whose params are `params()` — `(params,
965    /// changes_params)`, read in a binding: when a signal it read changes,
966    /// the snapshot runs again (after `debounce_ms` of quiet when given),
967    /// the old rows kept, `resyncing`, until the new snapshot lands.
968    pub fn follow(self: &Rc<Self>, query: LiveQuery, mut params: impl FnMut() -> (Value, Value) + 'static) -> Follow {
969        self.follow_held(query, move || Some(params()))
970    }
971
972    /// FRAME-16: [`Self::follow`], held while `params()` answers `None` (its
973    /// `when` is false): nothing is asked, and a reader it held is let go —
974    /// the rows stay as they were; answered again, it runs with the params
975    /// of that moment — after `debounce_ms` when it has one (a query typed
976    /// into a held palette is one call, not one per key).
977    pub fn follow_held(self: &Rc<Self>, query: LiveQuery, mut params: impl FnMut() -> Option<(Value, Value)> + 'static) -> Follow {
978        let out = self.rt.signal(Live { rows: Vec::new(), status: Status::Pending }.to_value());
979        let crossing: Moves = Rc::new(RefCell::new((0, Delta::Whole)));
980        let st: Rc<RefCell<Following>> = Rc::new(RefCell::new(Following { reader: None, mirror: None, generation: 0, last: None, stopped: false }));
981        let (me, st2, out2, q, cr2) = (Rc::downgrade(self), st.clone(), out.clone(), Rc::new(query), crossing.clone());
982        let rt = self.rt.clone();
983        let was_held = Rc::new(Cell::new(false));
984        let binding = self.rt.bind(move || {
985            let held = params();
986            let Some(cache) = me.upgrade() else { return };
987            let Some(p) = held else {
988                was_held.set(true);
989                let mut s = st2.borrow_mut();
990                if s.last.take().is_some() {
991                    s.generation += 1;
992                    if let Some(m) = s.mirror.take() {
993                        rt.dispose(m);
994                    }
995                    s.reader = None;
996                }
997                return;
998            };
999            let first = {
1000                let mut s = st2.borrow_mut();
1001                if s.last.as_ref() == Some(&p) {
1002                    return;
1003                }
1004                let first = s.last.is_none();
1005                s.last = Some(p.clone());
1006                s.generation += 1;
1007                first
1008            };
1009            let resumed = was_held.replace(false);
1010            match q.debounce_ms.filter(|_| !first || resumed) {
1011                None => rt.untracked(|| cache.switch(&st2, &out2, &cr2, &q, p, first)),
1012                Some(ms) => {
1013                    let generation = st2.borrow().generation;
1014                    let (me, st3, out3, q2, rt2, cr3) = (Rc::downgrade(&cache), st2.clone(), out2.clone(), q.clone(), rt.clone(), cr2.clone());
1015                    cache.clock.schedule(
1016                        ms,
1017                        Box::new(move || {
1018                            let current = { let s = st3.borrow(); !s.stopped && s.generation == generation };
1019                            if let (true, Some(cache)) = (current, me.upgrade()) {
1020                                rt2.untracked(|| cache.switch(&st3, &out3, &cr3, &q2, p, first));
1021                            }
1022                        }),
1023                    );
1024                }
1025            }
1026        });
1027        let rt = self.rt.clone();
1028        Follow {
1029            signal: out,
1030            crossing,
1031            st: st.clone(),
1032            stop: Some(Box::new(move || {
1033                rt.dispose(binding);
1034                let mut s = st.borrow_mut();
1035                s.stopped = true;
1036                if let Some(m) = s.mirror.take() {
1037                    rt.dispose(m);
1038                }
1039                s.reader = None;
1040            })),
1041        }
1042    }
1043
1044    /// The followed collection on the params `p`: a reader of their spec,
1045    /// mirrored into `out` — the old rows, `resyncing`, while the new one
1046    /// is pending.
1047    fn switch(self: &Rc<Self>, st: &Rc<RefCell<Following>>, out: &Signal<Value>, crossing: &Moves, q: &LiveQuery, p: (Value, Value), first: bool) {
1048        let on: Vec<(&str, &str)> = q.on.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect();
1049        let spec = match LiveSpec::new(&q.snapshot, p.0, q.changes.as_deref(), p.1, &q.key, &on) {
1050            Ok(spec) => spec,
1051            Err(_) => {
1052                moved_to(out, crossing, Live { rows: Vec::new(), status: Status::Error }.to_value(), Delta::Whole);
1053                return;
1054            }
1055        };
1056        let reader = self.acquire(&spec);
1057        let sig = reader.signal();
1058        let old_rows = if first { Vec::new() } else { Live::from_value(&out.peek()).map(|l| l.rows).unwrap_or_default() };
1059        let switching = Rc::new(Cell::new(!first));
1060        let (o, sw, cr, rm) = (out.clone(), switching.clone(), crossing.clone(), reader.moved.clone());
1061        // FRAME-20: the reader's move it saw last (none: this mirror's first
1062        // run, which crosses whole — another collection's rows).
1063        let seen = Cell::new(None::<u64>);
1064        let mirror = self.rt.bind(move || {
1065            let v = sig.get();
1066            let (at, delta) = rm.borrow().clone();
1067            let last = seen.replace(Some(at));
1068            // STUDIO-16: its status read in place (no copy of its rows).
1069            let pending = v.get("status").and_then(Value::as_str) == Some(Status::Pending.as_str());
1070            match pending {
1071                true if sw.get() => moved_to(&o, &cr, Live { rows: old_rows.clone(), status: Status::Resyncing }.to_value(), status_only()),
1072                _ => {
1073                    sw.set(false);
1074                    let delta = match last {
1075                        Some(p) if at == p + 1 => delta,
1076                        _ => Delta::Whole,
1077                    };
1078                    moved_to(&o, &cr, v, delta);
1079                }
1080            }
1081        });
1082        let mut s = st.borrow_mut();
1083        if let Some(old) = s.mirror.replace(mirror) {
1084            self.rt.dispose(old);
1085        }
1086        s.reader = Some(reader);
1087    }
1088}
1089
1090/// FRAME-19: a module's `live` spec — [`LiveSpec::from_value`]'s keys,
1091/// plus what rhx's `live` has: `when` (a boolean, `true` when left out;
1092/// `false` holds it — nothing asked) and `debounce_ms` (how long its params
1093/// must be quiet before it runs again). `when` and `debounce_ms` are not
1094/// part of what is shared: two modules asking the same spec, held or not,
1095/// read one collection once both ask.
1096#[derive(Debug, Clone, PartialEq)]
1097pub struct ModuleSpec {
1098    pub query: LiveQuery,
1099    pub params: Value,
1100    pub changes_params: Value,
1101    pub when: bool,
1102}
1103
1104impl ModuleSpec {
1105    /// From a module's spec as it crosses the bus (JSON): `{ snapshot,
1106    /// params?, changes?, changes_params?, key, on?, when?, debounce_ms? }`;
1107    /// a `when` that is no boolean, a `debounce_ms` that is no count, or a
1108    /// key it does not know is refused, naming it.
1109    pub fn from_value(v: &Value) -> Result<Self, String> {
1110        let o = v.as_object().ok_or("a live spec is { snapshot, params?, changes?, changes_params?, key, on?, when?, debounce_ms? }")?;
1111        let mut shared = o.clone();
1112        let when = match shared.remove("when") {
1113            None | Some(Value::Null) => true,
1114            Some(Value::Bool(b)) => b,
1115            Some(_) => return Err("a live spec's `when` is true or false".into()),
1116        };
1117        let debounce_ms = match shared.remove("debounce_ms") {
1118            None | Some(Value::Null) => None,
1119            Some(n) => Some(n.as_u64().ok_or("a live spec's `debounce_ms` is a count of milliseconds")?),
1120        };
1121        let s = LiveSpec::from_value(&Value::Object(shared)).map_err(|e| e.replace("on? }", "on?, when?, debounce_ms? }"))?;
1122        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();
1123        Ok(Self {
1124            query: LiveQuery { snapshot: s.snapshot, changes: s.changes, key: s.key, on, debounce_ms },
1125            params: s.params,
1126            changes_params: s.changes_params,
1127            when,
1128        })
1129    }
1130
1131    /// This spec with `patch` — `{ params?, changes_params?, when? }` —
1132    /// over it; anything else in the patch refused, naming it.
1133    pub fn patched(&self, patch: &Value) -> Result<Self, String> {
1134        let p = patch.as_object().ok_or("a live's update is { params?, changes_params?, when? }")?;
1135        let mut next = self.clone();
1136        for (k, v) in p {
1137            match (k.as_str(), v) {
1138                ("params" | "changes_params", Value::Null) => *(if k == "params" { &mut next.params } else { &mut next.changes_params }) = json!({}),
1139                ("params", Value::Object(_)) => next.params = v.clone(),
1140                ("changes_params", Value::Object(_)) => next.changes_params = v.clone(),
1141                ("params" | "changes_params", _) => return Err(format!("a live's update: `{k}` is a map")),
1142                ("when", Value::Bool(b)) => next.when = *b,
1143                ("when", _) => return Err("a live's update: `when` is true or false".into()),
1144                _ => return Err(format!("a live's update has no `{k}`: {{ params?, changes_params?, when? }}")),
1145            }
1146        }
1147        Ok(next)
1148    }
1149}
1150
1151/// FRAME-19: a module's collection — [`LiveCache::follow_held`] over the
1152/// spec's params and `when`, which the module moves with
1153/// [`ModuleLive::update`]; the registry owns the timing (`debounce_ms`).
1154pub struct ModuleLive {
1155    follow: Follow,
1156    spec: Rc<RefCell<ModuleSpec>>,
1157    inputs: Signal<Value>,
1158}
1159
1160impl ModuleLive {
1161    /// `patch` — `{ params?, changes_params?, when? }` — over what the
1162    /// collection follows now; the keys left out stay as they are. A patch
1163    /// that changes nothing asks nothing.
1164    pub fn update(&self, patch: &Value) -> Result<(), String> {
1165        let next = self.spec.borrow().patched(patch)?;
1166        let value = json!({ "params": next.params, "changes_params": next.changes_params, "when": next.when });
1167        *self.spec.borrow_mut() = next;
1168        if self.inputs.peek() != value {
1169            self.inputs.set(value);
1170        }
1171        Ok(())
1172    }
1173
1174    /// The spec as it stands, every update applied.
1175    pub fn spec(&self) -> ModuleSpec {
1176        self.spec.borrow().clone()
1177    }
1178
1179    /// The collection as a signal of `{ rows, status }`.
1180    pub fn signal(&self) -> Signal<Value> {
1181        self.follow.signal()
1182    }
1183
1184    /// The collection now, untracked.
1185    pub fn live(&self) -> Live {
1186        self.follow.live()
1187    }
1188}
1189
1190/// FRAME-20: what crosses to a module when its collection moves — the
1191/// fold's own result by key, not the collection.
1192#[derive(Debug, Clone, PartialEq)]
1193pub enum Delta {
1194    /// The whole collection: the first page, a resync's snapshot, a switch
1195    /// to other params — or a subscriber that missed a move.
1196    Whole,
1197    /// The rows the fold inserted or replaced (each one whose value
1198    /// changed: an upsert equal to the row kept moves nothing), and the keys
1199    /// it removed (an upsert that stops matching the params is a remove).
1200    /// Both empty: only the status moved.
1201    Change { upsert: Vec<Value>, remove: Vec<String> },
1202}
1203
1204/// FRAME-20: a move of a module's collection as a subscriber that last saw
1205/// move `seen` receives it — `seq` the move it now stands at.
1206#[derive(Debug, Clone, PartialEq)]
1207pub struct Crossing {
1208    pub seq: u64,
1209    pub delta: Delta,
1210}
1211
1212impl ModuleLive {
1213    /// FRAME-20: how many times the collection has moved (0: never).
1214    pub fn seq(&self) -> u64 {
1215        self.follow.crossing.borrow().0
1216    }
1217
1218    /// FRAME-20: what crosses to a subscriber that last saw move `seen`:
1219    /// the last move's change when it is the only one since, else (several
1220    /// since, or the last one whole) [`Delta::Whole`].
1221    pub fn since(&self, seen: u64) -> Crossing {
1222        let (seq, delta) = self.follow.crossing.borrow().clone();
1223        let delta = if seq == seen {
1224            status_only()
1225        } else if seen != 0 && seq == seen + 1 {
1226            delta
1227        } else {
1228            Delta::Whole
1229        };
1230        Crossing { seq, delta }
1231    }
1232}
1233
1234impl<W: Wire + Clone + 'static, C: Clock + Clone + 'static> LiveCache<W, C> {
1235    /// FRAME-19: a module's collection, held by its `when` and its param
1236    /// changes coalesced by its `debounce_ms` — rhx's [`Self::follow_held`],
1237    /// its inputs a signal [`ModuleLive::update`] sets.
1238    pub fn follow_module(self: &Rc<Self>, spec: ModuleSpec) -> ModuleLive {
1239        let inputs = self.rt.signal(json!({ "params": spec.params, "changes_params": spec.changes_params, "when": spec.when }));
1240        let read = inputs.clone();
1241        let follow = self.follow_held(spec.query.clone(), move || {
1242            let v = read.get();
1243            (v["when"] != false).then(|| (v["params"].clone(), v["changes_params"].clone()))
1244        });
1245        ModuleLive { follow, spec: Rc::new(RefCell::new(spec)), inputs }
1246    }
1247}
1248
1249/// What a [`Follow`] holds: its reader now, the binding mirroring it, the
1250/// params last seen and how many times they changed (a debounced run
1251/// checks it is still the last).
1252struct Following {
1253    reader: Option<Reader>,
1254    mirror: Option<crate::signals::BindingId>,
1255    generation: u64,
1256    last: Option<(Value, Value)>,
1257    stopped: bool,
1258}
1259
1260/// UI-10: a collection that follows its params; dropping it stops that and
1261/// releases its reader.
1262pub struct Follow {
1263    signal: Signal<Value>,
1264    /// FRAME-20: the moves of `signal`.
1265    crossing: Moves,
1266    st: Rc<RefCell<Following>>,
1267    stop: Option<Box<dyn FnOnce()>>,
1268}
1269
1270impl Follow {
1271    /// The collection as a signal of `{ rows, status }` — the same signal
1272    /// whatever the params become.
1273    pub fn signal(&self) -> Signal<Value> {
1274        self.signal.clone()
1275    }
1276
1277    /// The collection now, untracked.
1278    pub fn live(&self) -> Live {
1279        Live::from_value(&self.signal.peek()).expect("a live collection's value")
1280    }
1281
1282    /// FRAME-17: when the collection it reads now first answered with rows.
1283    pub fn answered_at(&self) -> Option<f64> {
1284        self.st.borrow().reader.as_ref().and_then(Reader::answered_at)
1285    }
1286}
1287
1288impl Drop for Follow {
1289    fn drop(&mut self) {
1290        if let Some(stop) = self.stop.take() {
1291            stop();
1292        }
1293    }
1294}
1295
1296/// One reader of a collection; dropping it releases the subscription
1297/// (kept [`KEEP_MS`] more).
1298pub struct Reader {
1299    signal: Signal<Value>,
1300    /// FRAME-20: its collection's moves.
1301    moved: Moves,
1302    answered_at: Rc<Cell<Option<f64>>>,
1303    release: Option<Box<dyn FnOnce()>>,
1304}
1305
1306impl Reader {
1307    /// FRAME-17: when its collection's first answer with rows came (the
1308    /// page's clock), if it has.
1309    pub fn answered_at(&self) -> Option<f64> {
1310        self.answered_at.get()
1311    }
1312
1313    /// The collection as a signal of `{ rows, status }` (what the tree binds).
1314    pub fn signal(&self) -> Signal<Value> {
1315        self.signal.clone()
1316    }
1317
1318    /// The collection now, untracked.
1319    pub fn live(&self) -> Live {
1320        Live::from_value(&self.signal.peek()).expect("a live collection's value")
1321    }
1322}
1323
1324impl Drop for Reader {
1325    fn drop(&mut self) {
1326        if let Some(release) = self.release.take() {
1327            release();
1328        }
1329    }
1330}
1331
1332/// A `live` declaration's params resolved against the props: `{ "expr" }`
1333/// values evaluated (a prop by name, or a Rhai expression over the props).
1334pub fn resolve(params: &BTreeMap<String, Value>, props: &Map<String, Value>) -> Value {
1335    let mut out = Map::new();
1336    for (k, v) in params {
1337        let v = match v.as_object().and_then(|o| o.get("expr")).and_then(Value::as_str) {
1338            Some(e) => match props.get(e) {
1339                Some(p) => p.clone(),
1340                None => {
1341                    let mut scope = rhai::Scope::new();
1342                    for (pk, pv) in props {
1343                        scope.push_constant_dynamic(pk.clone(), crate::tree::expr::to_dynamic(pv));
1344                    }
1345                    crate::tree::expr::engine()
1346                        .eval_expression_with_scope::<rhai::Dynamic>(&mut scope, e)
1347                        .map(|d| crate::tree::expr::to_value(&d))
1348                        .unwrap_or(Value::Null)
1349                }
1350            },
1351            None => v.clone(),
1352        };
1353        out.insert(k.clone(), v);
1354    }
1355    Value::Object(out)
1356}
1357
1358#[cfg(test)]
1359mod tests;