Skip to main content

plexus_ui_engine/bus/
mod.rs

1//! FRAME-12: **the bus** — what the host hands every mounted component,
2//! whatever drew it (the rhx runtime, a module written by hand, FRAME-13's
3//! Svelte): one [`Bus`] per page, one [`Member`] per mounted component.
4//!
5//! - `call(method, params)` — through the page's one socket, refused before
6//!   it when the component's `uses` does not name the method; FRAME-37: its
7//!   stream gathered into one [`Answer`] by [`answer_sink`] — what rhx's
8//!   `call(method, params, "fold")` folds and a module's `bus.call` resolves;
9//! - `live(spec)` — the page's live collection for that spec (the whole
10//!   spec: snapshot, params, changes, changes params, key, folds), shared
11//!   with every other reader of it, rhx or not; its methods held to `uses`;
12//!   FRAME-19: a module's ([`Member::follow`]) held by its `when` and its
13//!   param changes coalesced by its `debounce_ms`, as rhx's are;
14//! - `emit(topic, data)` / `on(topic, f)` — page-wide, topics bare strings
15//!   matched whole, `plexus.` the host's own (a component's emit under it is
16//!   refused); a member never hears its own emit;
17//! - FRAME-53: **a sticky topic** — [`Member::emit_sticky`] (and the host's
18//!   [`Bus::say_sticky`], `plexus.booted`) keeps the topic's last event on
19//!   the bus, one per topic; a later emit on it, sticky or not, replaces
20//!   it, and it goes when the member that said it leaves (a remount says
21//!   it again; the host's own are never cleared). [`Member::on_last`] hears
22//!   the kept event at once (in the bus's turn: now, when nothing is under
23//!   way or held), then as [`Member::on`]; [`Bus::last`] answers it — only
24//!   what has been delivered. A topic never emitted sticky is kept for no
25//!   one;
26//! - `navigate(route)`; `slots_set(layout, slot, component, version?)` —
27//!   `ui.slots.set`, a call like any other, held to `uses`; FRAME-29: a
28//!   section a mark binds (`data-component`) is refused `bound` before it.
29//!
30//! **Delivery waits its turn.** Everything the bus hands out — each
31//! listener's event, each deferred callback ([`Bus::defer`], a module's
32//! `subscribe`) — goes through one queue, first in first out, and is run
33//! only when nothing of the host's is under way: an emit made inside a
34//! delivery, or inside an rhx fold ([`Bus::hold`] around it), is heard
35//! after the one under way has reached every listener. Nothing is
36//! re-entered, so no borrow of the host's is ever held across a component.
37//!
38//! FRAME-36: `keys(decls)` — a component's shortcuts into the page's one
39//! registry ([`crate::keys::Keys`]), held until the answer is dropped or
40//! the member leaves.
41//!
42//! A member that [`Member::leave`]s (its component unmounted or swapped
43//! out) hears nothing more and reaches no one.
44
45use crate::live::{LiveSpec, ModuleLive, ModuleSpec, Reader};
46use crate::transport::{CallId, Sink, WireItem};
47use serde_json::{json, Value};
48use std::cell::{Cell, RefCell};
49use std::collections::{BTreeSet, VecDeque};
50use std::rc::{Rc, Weak};
51
52/// The prefix of the host's own topics.
53pub const RESERVED: &str = "plexus.";
54
55/// FRAME-37: what `message` says when the socket dropped before the answer.
56pub const DISCONNECTED: &str = "disconnected";
57
58/// FRAME-37: a call's answer, whole, once its stream ended — `ok` when it
59/// ended with no in-band `error` / `refused` event, no refusal, no failure
60/// and no drop; `events` its data events in order (each a map with `type`);
61/// `message` the error's, refusal's or failure's words (an in-band one's
62/// `message`, else its `reason`), or [`DISCONNECTED`] for a drop, when not
63/// `ok`.
64#[derive(Debug, Clone, PartialEq)]
65pub struct Answer {
66    pub ok: bool,
67    pub events: Vec<Value>,
68    pub message: Option<String>,
69}
70
71impl Answer {
72    /// `{ ok, events, message }` (`message` null when `ok`).
73    pub fn to_value(&self) -> Value {
74        json!({ "ok": self.ok, "events": self.events, "message": self.message })
75    }
76}
77
78/// An in-band refusal's words: an event whose `type` is `error` or
79/// `refused`, its `message`, else its `reason`, else its type.
80fn in_band(event: &Value) -> Option<String> {
81    let kind = event.get("type").and_then(Value::as_str).filter(|t| *t == "error" || *t == "refused")?;
82    let words = ["message", "reason"].iter().find_map(|k| event.get(*k).filter(|v| !v.is_null()));
83    Some(match words {
84        Some(Value::String(s)) => s.clone(),
85        Some(v) => v.to_string(),
86        None => kind.to_string(),
87    })
88}
89
90/// FRAME-37: a sink that gathers a call's stream and hands `done` its
91/// [`Answer`] once, when the stream ends (`Done`, a refusal, or the socket
92/// dropping under it). Nothing here sends anything: a call is sent once.
93pub fn answer_sink(done: impl FnOnce(Answer) + 'static) -> Sink {
94    let mut events = Vec::new();
95    let mut done = Some(done);
96    Box::new(move |item| {
97        let ended = match item {
98            WireItem::Data(v) => {
99                events.push(v);
100                return;
101            }
102            WireItem::Done => None,
103            WireItem::Refused(m) => Some(m),
104            WireItem::Failed(m) => Some(m),
105            WireItem::Dropped => Some(DISCONNECTED.to_string()),
106        };
107        let Some(done) = done.take() else { return };
108        let events = std::mem::take(&mut events);
109        // An in-band refusal says more than how the stream ended.
110        let message = events.iter().find_map(in_band).or(ended);
111        done(Answer { ok: message.is_none(), events, message });
112    })
113}
114
115/// What the bus refuses a member, before anything reaches the socket.
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub enum BusRefusal {
118    /// The component's `uses` does not name the method.
119    NotInUses { component: String, method: String },
120    /// A topic under `plexus.`, the host's.
121    Reserved { component: String, topic: String },
122    /// FRAME-29: `slots_set` on a section its mark binds — early-bound, the
123    /// component its code chose; no assignment reaches it.
124    Bound { layout: String, slot: String, component: String },
125}
126
127impl std::fmt::Display for BusRefusal {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        match self {
130            BusRefusal::NotInUses { component, method } => write!(f, "{component} calls {method}, which its uses does not name"),
131            BusRefusal::Reserved { component, topic } => write!(f, "{component} emits {topic}: topics under {RESERVED} are the host's"),
132            BusRefusal::Bound { layout, slot, component } => {
133                write!(f, "bound: {layout} · {slot} is bound to {component} by its mark (data-component); ui.slots.set does not reach it")
134            }
135        }
136    }
137}
138
139/// What the bus needs of the host: the socket, the live cache, the router
140/// and the live version.
141pub trait BusHost {
142    fn open(&self, method: &str, params: Value, sink: Sink) -> CallId;
143    fn live(&self, spec: &LiveSpec) -> Reader;
144    /// FRAME-19: a module's collection, held by `when`, coalesced by
145    /// `debounce_ms`.
146    fn follow(&self, spec: ModuleSpec) -> ModuleLive;
147    fn navigate(&self, route: &str);
148    /// The live version's hash (`slots_set` with no version names it).
149    fn live_version(&self) -> String;
150    /// FRAME-29: the component a mark binds `layout`'s `slot` to, when one
151    /// does — `slots_set` on it is refused `bound`.
152    fn bound(&self, _layout: &str, _slot: &str) -> Option<String> {
153        None
154    }
155}
156
157struct Listener {
158    id: u64,
159    member: u64,
160    topic: String,
161    f: Rc<dyn Fn(&Value)>,
162}
163
164enum Item {
165    /// `keep`: whether its delivery may keep it (false once its member left).
166    Message { from: u64, topic: String, data: Value, sticky: bool, keep: bool },
167    Run(Box<dyn FnOnce()>),
168}
169
170/// FRAME-53: a sticky topic's last event, and the member that said it.
171struct Kept {
172    from: u64,
173    data: Value,
174}
175
176struct Inner {
177    host: RefCell<Option<Weak<dyn BusHost>>>,
178    rt: crate::signals::Runtime,
179    listeners: RefCell<Vec<Listener>>,
180    /// FRAME-53: each sticky topic's last event, by topic.
181    kept: RefCell<std::collections::BTreeMap<String, Kept>>,
182    queue: RefCell<VecDeque<Item>>,
183    holds: Cell<u32>,
184    draining: Cell<bool>,
185    next: Cell<u64>,
186    /// FRAME-36: the page's keys.
187    keys: crate::keys::Keys,
188}
189
190/// The page's one bus (a handle: clones are the same bus).
191#[derive(Clone)]
192pub struct Bus(Rc<Inner>);
193
194impl std::fmt::Debug for Bus {
195    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196        write!(f, "Bus({} listeners, {} queued)", self.0.listeners.borrow().len(), self.0.queue.borrow().len())
197    }
198}
199
200impl Bus {
201    /// A bus over the signals of `rt`; the host is set by [`Self::set_host`].
202    pub fn new(rt: &crate::signals::Runtime) -> Self {
203        Self(Rc::new(Inner {
204            host: RefCell::new(None),
205            rt: rt.clone(),
206            listeners: RefCell::new(Vec::new()),
207            kept: RefCell::new(std::collections::BTreeMap::new()),
208            queue: RefCell::new(VecDeque::new()),
209            holds: Cell::new(0),
210            draining: Cell::new(false),
211            next: Cell::new(0),
212            keys: crate::keys::Keys::default(),
213        }))
214    }
215
216    pub fn set_host(&self, host: Weak<dyn BusHost>) {
217        *self.0.host.borrow_mut() = Some(host);
218    }
219
220    fn host(&self) -> Option<Rc<dyn BusHost>> {
221        self.0.host.borrow().as_ref().and_then(Weak::upgrade)
222    }
223
224    /// FRAME-36: the page's keys — every mounted component's shortcuts.
225    pub fn keys(&self) -> &crate::keys::Keys {
226        &self.0.keys
227    }
228
229    /// The signals the bus's collections live on.
230    pub fn runtime(&self) -> &crate::signals::Runtime {
231        &self.0.rt
232    }
233
234    fn next(&self) -> u64 {
235        let n = self.0.next.get() + 1;
236        self.0.next.set(n);
237        n
238    }
239
240    /// A member: what the mounted component `name`, whose `uses` is
241    /// `uses`, is handed.
242    pub fn join(&self, name: &str, uses: &[String]) -> Member {
243        Member(Rc::new(MemberInner { bus: self.clone(), id: self.next(), name: name.into(), uses: uses.iter().cloned().collect(), left: Cell::new(false) }))
244    }
245
246    /// FRAME-50: the host's own word — `data` on `topic` (under `plexus.`)
247    /// to every member listening, in the bus's turn.
248    pub fn say(&self, topic: &str, data: Value) {
249        self.send(self.next(), topic, data, false);
250    }
251
252    /// FRAME-53: the host's word, kept as the topic's last event — what a
253    /// late [`Member::on_last`] hears (`plexus.booted`).
254    pub fn say_sticky(&self, topic: &str, data: Value) {
255        self.send(self.next(), topic, data, true);
256    }
257
258    /// FRAME-53: `topic`'s kept event, if it is sticky and was said.
259    pub fn last(&self, topic: &str) -> Option<Value> {
260        self.0.kept.borrow().get(topic).map(|k| k.data.clone())
261    }
262
263    fn send(&self, from: u64, topic: &str, data: Value, sticky: bool) {
264        self.0.queue.borrow_mut().push_back(Item::Message { from, topic: topic.into(), data, sticky, keep: true });
265        self.drain();
266    }
267
268    /// Runs `f` in the bus's turn: now when nothing is under way, else
269    /// after what is.
270    pub fn defer(&self, f: impl FnOnce() + 'static) {
271        self.0.queue.borrow_mut().push_back(Item::Run(Box::new(f)));
272        self.drain();
273    }
274
275    /// Holds every delivery until the guard is dropped (the host holds the
276    /// bus while a fold runs).
277    pub fn hold(&self) -> Hold {
278        self.0.holds.set(self.0.holds.get() + 1);
279        Hold(self.clone())
280    }
281
282    fn drain(&self) {
283        if self.0.holds.get() > 0 || self.0.draining.get() {
284            return;
285        }
286        self.0.draining.set(true);
287        loop {
288            let next = self.0.queue.borrow_mut().pop_front();
289            match next {
290                None => break,
291                Some(Item::Run(f)) => f(),
292                Some(Item::Message { from, topic, data, sticky, keep }) => {
293                    // FRAME-53: kept as it is delivered — a sticky emit, or
294                    // any later emit on a topic once made sticky, replaces
295                    // the topic's last event.
296                    if keep {
297                        let mut kept = self.0.kept.borrow_mut();
298                        if sticky || kept.contains_key(&topic) {
299                            kept.insert(topic.clone(), Kept { from, data: data.clone() });
300                        }
301                    }
302                    let hit: Vec<(u64, Rc<dyn Fn(&Value)>)> =
303                        self.0.listeners.borrow().iter().filter(|l| l.topic == topic && l.member != from).map(|l| (l.id, l.f.clone())).collect();
304                    for (id, f) in hit {
305                        // One that stopped listening meanwhile hears nothing.
306                        if self.0.listeners.borrow().iter().any(|l| l.id == id) {
307                            f(&data);
308                        }
309                    }
310                }
311            }
312        }
313        self.0.draining.set(false);
314    }
315}
316
317/// [`Bus::hold`]'s guard: dropping it lets the queue run.
318pub struct Hold(Bus);
319
320impl Drop for Hold {
321    fn drop(&mut self) {
322        let inner = &self.0 .0;
323        inner.holds.set(inner.holds.get().saturating_sub(1));
324        self.0.drain();
325    }
326}
327
328struct MemberInner {
329    bus: Bus,
330    id: u64,
331    name: String,
332    uses: BTreeSet<String>,
333    left: Cell<bool>,
334}
335
336/// One mounted component's side of the bus (a handle).
337#[derive(Clone)]
338pub struct Member(Rc<MemberInner>);
339
340impl std::fmt::Debug for Member {
341    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
342        write!(f, "Member({} #{})", self.0.name, self.0.id)
343    }
344}
345
346/// A listener held: dropping it stops it.
347pub struct Listening {
348    bus: Weak<Inner>,
349    id: u64,
350}
351
352impl Drop for Listening {
353    fn drop(&mut self) {
354        if let Some(inner) = self.bus.upgrade() {
355            inner.listeners.borrow_mut().retain(|l| l.id != self.id);
356        }
357    }
358}
359
360impl Member {
361    /// The component's name.
362    pub fn name(&self) -> &str {
363        &self.0.name
364    }
365
366    /// The bus it is a member of.
367    pub fn bus(&self) -> &Bus {
368        &self.0.bus
369    }
370
371    /// COMPS-2: **a frame's member** — what a page or component this member
372    /// frames (`bus.frame`) calls through: a member of the same bus named
373    /// `name`, its calls held to `uses`. `within`: a page the framer wrote
374    /// (`{ html }`), whose `uses` the framer declares, so only what the
375    /// framer's own `uses` names is kept — a framer gives no more than it
376    /// holds; not `within`: a stored component (`{ component }`), whose
377    /// `uses` is its own manifest entry's. Either way the call goes over the
378    /// page's one socket as the viewer, so the service's gate holds it to
379    /// the viewer's grants too.
380    pub fn framed(&self, name: &str, uses: &[String], within: bool) -> Member {
381        let kept: Vec<String> = uses.iter().filter(|m| !within || self.0.uses.contains(*m)).cloned().collect();
382        self.0.bus.join(name, &kept)
383    }
384
385    /// COMPS-2: whether `method` is one this member may call.
386    pub fn holds(&self, method: &str) -> bool {
387        self.0.uses.contains(method)
388    }
389
390    fn left(&self) -> bool {
391        self.0.left.get()
392    }
393
394    fn held(&self, method: &str) -> Result<(), BusRefusal> {
395        if self.0.uses.contains(method) {
396            Ok(())
397        } else {
398            Err(BusRefusal::NotInUses { component: self.0.name.clone(), method: method.into() })
399        }
400    }
401
402    /// `method` through the page's socket, its items into `sink`; refused
403    /// before the socket when `uses` does not name it.
404    pub fn call(&self, method: &str, params: Value, sink: Sink) -> Result<CallId, BusRefusal> {
405        self.held(method)?;
406        let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: method.into() })?;
407        Ok(host.open(method, params, sink))
408    }
409
410    /// The page's collection for `spec`, shared; its snapshot and changes
411    /// methods held to `uses`.
412    pub fn live(&self, spec: &LiveSpec) -> Result<Reader, BusRefusal> {
413        self.held(&spec.snapshot)?;
414        if let Some(c) = &spec.changes {
415            self.held(c)?;
416        }
417        let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: spec.snapshot.clone() })?;
418        Ok(host.live(spec))
419    }
420
421    /// `data` on `topic` to every other member listening; `plexus.…`
422    /// refused. A member that left reaches no one.
423    pub fn emit(&self, topic: &str, data: Value) -> Result<(), BusRefusal> {
424        self.emit_with(topic, data, false)
425    }
426
427    /// FRAME-53: [`Self::emit`], the event kept as the topic's last — what a
428    /// member that listens later with [`Self::on_last`] hears at once.
429    pub fn emit_sticky(&self, topic: &str, data: Value) -> Result<(), BusRefusal> {
430        self.emit_with(topic, data, true)
431    }
432
433    fn emit_with(&self, topic: &str, data: Value, sticky: bool) -> Result<(), BusRefusal> {
434        if topic.starts_with(RESERVED) {
435            return Err(BusRefusal::Reserved { component: self.0.name.clone(), topic: topic.into() });
436        }
437        if self.left() {
438            return Ok(());
439        }
440        self.0.bus.send(self.0.id, topic, data, sticky);
441        Ok(())
442    }
443
444    /// FRAME-53: `topic`'s kept event (the page's, whoever said it).
445    pub fn last(&self, topic: &str) -> Option<Value> {
446        self.0.bus.last(topic)
447    }
448
449    /// FRAME-53: [`Self::on`], and first the topic's kept event, if any,
450    /// at once — in the bus's turn: now when nothing is under way, else
451    /// right after what is. Not the member's own, and not when an event of
452    /// the topic reached `f` first (a newer one than the kept).
453    pub fn on_last(&self, topic: &str, f: impl Fn(&Value) + 'static) -> Listening {
454        let heard = Rc::new(Cell::new(false));
455        let f: Rc<dyn Fn(&Value)> = Rc::new(f);
456        let (h, g) = (heard.clone(), f.clone());
457        let listening = self.on(topic, move |data: &Value| {
458            h.set(true);
459            g(data)
460        });
461        if !self.left() {
462            let (bus, me, id, topic) = (Rc::downgrade(&self.0.bus.0), self.0.id, listening.id, topic.to_string());
463            self.0.bus.defer(move || {
464                let Some(inner) = bus.upgrade() else { return };
465                if heard.get() || !inner.listeners.borrow().iter().any(|l| l.id == id) {
466                    return;
467                }
468                let kept = inner.kept.borrow().get(&topic).filter(|k| k.from != me).map(|k| k.data.clone());
469                if let Some(data) = kept {
470                    f(&data);
471                }
472            });
473        }
474        listening
475    }
476
477    /// `f` on every `topic` another member emits, until the [`Listening`] is
478    /// dropped or the member leaves.
479    pub fn on(&self, topic: &str, f: impl Fn(&Value) + 'static) -> Listening {
480        let id = self.0.bus.next();
481        if !self.left() {
482            self.0.bus.0.listeners.borrow_mut().push(Listener { id, member: self.0.id, topic: topic.into(), f: Rc::new(f) });
483        }
484        Listening { bus: Rc::downgrade(&self.0.bus.0), id }
485    }
486
487    /// Moves the page to `route`.
488    pub fn navigate(&self, route: &str) {
489        if let Some(host) = self.0.bus.host() {
490            host.navigate(route);
491        }
492    }
493
494    /// `ui.slots.set { layout, slot, component, version }` (the live
495    /// version when none is named) — a call held to `uses`.
496    pub fn slots_set(&self, layout: &str, slot: &str, component: &str, version: Option<&str>, sink: Sink) -> Result<CallId, BusRefusal> {
497        self.held("ui.slots.set")?;
498        if let Some(component) = self.0.bus.host().and_then(|h| h.bound(layout, slot)) {
499            return Err(BusRefusal::Bound { layout: layout.into(), slot: slot.into(), component });
500        }
501        let version = match version {
502            Some(v) => v.to_string(),
503            None => self.0.bus.host().map(|h| h.live_version()).unwrap_or_default(),
504        };
505        self.call("ui.slots.set", json!({ "layout": layout, "slot": slot, "component": component, "version": version }), sink)
506    }
507
508    /// FRAME-19: a module's collection for `spec` — `when` and
509    /// `debounce_ms` held by the registry as rhx's are, the module moving
510    /// its params with [`ModuleLive::update`]; its methods held to `uses`.
511    pub fn follow(&self, spec: ModuleSpec) -> Result<ModuleLive, BusRefusal> {
512        self.held(&spec.query.snapshot)?;
513        if let Some(c) = &spec.query.changes {
514            self.held(c)?;
515        }
516        let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: spec.query.snapshot.clone() })?;
517        Ok(host.follow(spec))
518    }
519
520    /// FRAME-36: the component's shortcuts, each with what it runs, into
521    /// the page's registry until the answer is dropped or the member leaves
522    /// (one that left binds nothing).
523    pub fn keys(&self, decls: Vec<(crate::keys::KeyDecl, crate::keys::KeyRun)>) -> crate::keys::KeysHeld {
524        let decls = if self.left() { Vec::new() } else { decls };
525        self.0.bus.0.keys.add(self.0.id, &self.0.name, decls)
526    }
527
528    /// Leaves the bus: every listener of it stops, its keys go, and its
529    /// emits reach no one. FRAME-53: what it kept goes too — every sticky
530    /// topic whose last event it said is kept for no one until said again,
531    /// and an emit of its still queued keeps nothing.
532    pub fn leave(&self) {
533        self.0.left.set(true);
534        let me = self.0.id;
535        self.0.bus.0.kept.borrow_mut().retain(|_, k| k.from != me);
536        for item in self.0.bus.0.queue.borrow_mut().iter_mut() {
537            if let Item::Message { from, keep, .. } = item {
538                if *from == me {
539                    *keep = false;
540                }
541            }
542        }
543        self.0.bus.0.keys.remove_member(self.0.id);
544        self.0.bus.0.listeners.borrow_mut().retain(|l| l.member != self.0.id);
545    }
546}