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