1use 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
34pub const KEEP_MS: u64 = 5_000;
36
37#[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#[derive(Debug, Clone, PartialEq, Eq)]
51pub enum FoldRule {
52 Upsert(String),
54 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#[derive(Debug, Clone, PartialEq)]
71pub struct Live {
72 pub rows: Vec<Value>,
73 pub status: Status,
74}
75
76impl Live {
77 pub fn to_value(&self) -> Value {
79 json!({ "rows": self.rows, "status": self.status })
80 }
81
82 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#[derive(Debug, Clone, PartialEq)]
91pub struct LiveSpec {
92 pub snapshot: String,
93 pub params: Value,
94 pub changes: Option<String>,
96 pub changes_params: Value,
97 pub key: String,
98 pub on: BTreeMap<String, FoldRule>,
99}
100
101impl LiveSpec {
102 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 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 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 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
165pub trait Clock {
168 fn now_ms(&self) -> u64;
169 fn schedule(&self, after_ms: u64, f: Box<dyn FnOnce()>);
171}
172
173type Timer = (u64, u64, Box<dyn FnOnce()>);
175
176#[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 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
225struct 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 buffer: Vec<Value>,
237 during: Vec<Value>,
249 asked: u64,
254 message: Option<String>,
258 erred: Option<String>,
260 answered_at: Rc<Cell<Option<f64>>>,
262 moved: Moves,
264}
265
266type Moves = Rc<RefCell<(u64, Delta)>>;
268
269fn 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
283fn 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
294fn 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 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 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 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 (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
418fn 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
447pub struct LiveCache<W: Wire, C: Clock> {
449 rt: Runtime,
450 wire: W,
451 clock: C,
452 subs: RefCell<BTreeMap<String, Rc<RefCell<Sub>>>>,
453 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 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 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 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 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 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 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 if asked != s.asked {
607 return;
608 }
609 let mut delta = Delta::Whole;
612 match item {
613 WireItem::Data(event) => {
614 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 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 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 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 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 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 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 pub fn kept(&self) -> usize {
772 self.subs.borrow().len()
773 }
774}
775
776#[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 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 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 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 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#[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 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 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
975pub struct ModuleLive {
979 follow: Follow,
980 spec: Rc<RefCell<ModuleSpec>>,
981 inputs: Signal<Value>,
982}
983
984impl ModuleLive {
985 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 pub fn spec(&self) -> ModuleSpec {
1000 self.spec.borrow().clone()
1001 }
1002
1003 pub fn signal(&self) -> Signal<Value> {
1005 self.follow.signal()
1006 }
1007
1008 pub fn live(&self) -> Live {
1010 self.follow.live()
1011 }
1012}
1013
1014#[derive(Debug, Clone, PartialEq)]
1017pub enum Delta {
1018 Whole,
1021 Change { upsert: Vec<Value>, remove: Vec<String> },
1026}
1027
1028#[derive(Debug, Clone, PartialEq)]
1031pub struct Crossing {
1032 pub seq: u64,
1033 pub delta: Delta,
1034}
1035
1036impl ModuleLive {
1037 pub fn seq(&self) -> u64 {
1039 self.follow.crossing.borrow().0
1040 }
1041
1042 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 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
1073struct Following {
1077 reader: Option<Reader>,
1078 mirror: Option<crate::signals::BindingId>,
1079 generation: u64,
1080 last: Option<(Value, Value)>,
1081 stopped: bool,
1082}
1083
1084pub struct Follow {
1087 signal: Signal<Value>,
1088 crossing: Moves,
1090 st: Rc<RefCell<Following>>,
1091 stop: Option<Box<dyn FnOnce()>>,
1092}
1093
1094impl Follow {
1095 pub fn signal(&self) -> Signal<Value> {
1098 self.signal.clone()
1099 }
1100
1101 pub fn live(&self) -> Live {
1103 Live::from_value(&self.signal.peek()).expect("a live collection's value")
1104 }
1105
1106 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
1120pub struct Reader {
1123 signal: Signal<Value>,
1124 moved: Moves,
1126 answered_at: Rc<Cell<Option<f64>>>,
1127 release: Option<Box<dyn FnOnce()>>,
1128}
1129
1130impl Reader {
1131 pub fn answered_at(&self) -> Option<f64> {
1134 self.answered_at.get()
1135 }
1136
1137 pub fn signal(&self) -> Signal<Value> {
1139 self.signal.clone()
1140 }
1141
1142 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
1156pub 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;