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//! - GAMMA-6: `stream(method, params, on, done)` — a call whose items reach
27//!   the member one by one as they arrive, then its end ([`StreamEnd`]);
28//!   held to `uses` as `call` is; [`Streaming::stop`] closes it on the wire,
29//!   and a member that leaves closes every stream it holds;
30//! - `navigate(route)`; `slots_set(layout, slot, component, version?)` —
31//!   `ui.slots.set`, a call like any other, held to `uses`; FRAME-29: a
32//!   section a mark binds (`data-component`) is refused `bound` before it.
33//!
34//! **Delivery waits its turn.** Everything the bus hands out — each
35//! listener's event, each deferred callback ([`Bus::defer`], a module's
36//! `subscribe`) — goes through one queue, first in first out, and is run
37//! only when nothing of the host's is under way: an emit made inside a
38//! delivery, or inside an rhx fold ([`Bus::hold`] around it), is heard
39//! after the one under way has reached every listener. Nothing is
40//! re-entered, so no borrow of the host's is ever held across a component.
41//!
42//! FRAME-36: `keys(decls)` — a component's shortcuts into the page's one
43//! registry ([`crate::keys::Keys`]), held until the answer is dropped or
44//! the member leaves.
45//!
46//! A member that [`Member::leave`]s (its component unmounted or swapped
47//! out) hears nothing more and reaches no one.
48
49use crate::live::{LiveSpec, ModuleLive, ModuleSpec, Reader};
50use crate::transport::{CallId, Sink, WireItem};
51use serde_json::{json, Value};
52use std::cell::{Cell, RefCell};
53use std::collections::{BTreeSet, VecDeque};
54use std::rc::{Rc, Weak};
55
56/// The prefix of the host's own topics.
57pub const RESERVED: &str = "plexus.";
58
59/// FRAME-37: what `message` says when the socket dropped before the answer.
60pub const DISCONNECTED: &str = "disconnected";
61
62/// FRAME-37: a call's answer, whole, once its stream ended — `ok` when it
63/// ended with no in-band `error` / `refused` event, no refusal, no failure
64/// and no drop; `events` its data events in order (each a map with `type`);
65/// `message` the error's, refusal's or failure's words (an in-band one's
66/// `message`, else its `reason`), or [`DISCONNECTED`] for a drop, when not
67/// `ok`.
68#[derive(Debug, Clone, PartialEq)]
69pub struct Answer {
70    pub ok: bool,
71    pub events: Vec<Value>,
72    pub message: Option<String>,
73}
74
75impl Answer {
76    /// `{ ok, events, message }` (`message` null when `ok`).
77    pub fn to_value(&self) -> Value {
78        json!({ "ok": self.ok, "events": self.events, "message": self.message })
79    }
80}
81
82/// An in-band refusal's words: an event whose `type` is `error` or
83/// `refused`, its `message`, else its `reason`, else its type.
84fn in_band(event: &Value) -> Option<String> {
85    let kind = event.get("type").and_then(Value::as_str).filter(|t| *t == "error" || *t == "refused")?;
86    let words = ["message", "reason"].iter().find_map(|k| event.get(*k).filter(|v| !v.is_null()));
87    Some(match words {
88        Some(Value::String(s)) => s.clone(),
89        Some(v) => v.to_string(),
90        None => kind.to_string(),
91    })
92}
93
94/// FRAME-37: a sink that gathers a call's stream and hands `done` its
95/// [`Answer`] once, when the stream ends (`Done`, a refusal, or the socket
96/// dropping under it). Nothing here sends anything: a call is sent once.
97pub fn answer_sink(done: impl FnOnce(Answer) + 'static) -> Sink {
98    let mut events = Vec::new();
99    let mut done = Some(done);
100    Box::new(move |item| {
101        let ended = match item {
102            WireItem::Data(v) => {
103                events.push(v);
104                return;
105            }
106            WireItem::Done => None,
107            WireItem::Refused(m, _) => Some(m),
108            WireItem::Failed(m) => Some(m),
109            WireItem::Dropped => Some(DISCONNECTED.to_string()),
110        };
111        let Some(done) = done.take() else { return };
112        let events = std::mem::take(&mut events);
113        // An in-band refusal says more than how the stream ended.
114        let message = events.iter().find_map(in_band).or(ended);
115        done(Answer { ok: message.is_none(), events, message });
116    })
117}
118
119/// GAMMA-5: the prefix of an **open** `uses` entry — `things.*` → `things`,
120/// `dyn.peer.*` → `dyn.peer` — a component calling, at run time, any method
121/// whose name begins with that prefix's whole segments. `None` for an exact
122/// method, and for anything else holding a `*`: bare `*` (never an entry),
123/// `things*`, `things.*.list`, an empty segment.
124pub fn open_prefix(entry: &str) -> Option<&str> {
125    let prefix = entry.strip_suffix(".*")?;
126    let plain = !prefix.is_empty() && prefix.split('.').all(|seg| !seg.is_empty() && !seg.contains('*'));
127    plain.then_some(prefix)
128}
129
130/// GAMMA-5: whether `entry` names one method exactly — no `*` in it.
131pub fn is_exact(entry: &str) -> bool {
132    !entry.is_empty() && !entry.contains('*')
133}
134
135/// GAMMA-5: whether `uses` holds `method` — named exactly, or under an
136/// open entry's prefix by whole segments (`things.*` holds `things.list`
137/// and `things.bins.count`, never `things` itself or `thingsx.list`). An
138/// entry that is neither (bare `*`, `things*`) holds nothing.
139pub fn covers<'a>(uses: impl IntoIterator<Item = &'a str>, method: &str) -> bool {
140    uses.into_iter().any(|u| match open_prefix(u) {
141        Some(prefix) => method.strip_prefix(prefix).and_then(|rest| rest.strip_prefix('.')).is_some_and(|rest| !rest.is_empty()),
142        None => is_exact(u) && u == method,
143    })
144}
145
146/// GAMMA-6: how a stream ([`Member::stream`]) ended — once, last.
147#[derive(Debug, Clone, PartialEq)]
148pub enum StreamEnd {
149    /// The service ended it (`done`).
150    Done,
151    /// The member stopped it ([`Streaming::stop`]), or left the bus: the
152    /// call closed on the wire, its unsubscribe sent.
153    Stopped,
154    /// The service refused the call: its words, and the refusal typed as it
155    /// sent it ([`WireItem::Refused`]'s value; null when the wire has none).
156    Refused { message: String, error: Value },
157    /// The call failed under the transport: its words.
158    Failed(String),
159    /// The socket dropped under it ([`DISCONNECTED`]); never sent again.
160    Dropped,
161}
162
163impl StreamEnd {
164    /// What a module is handed: `{ type: "done" | "stopped" | "refused" |
165    /// "failed" | "dropped" }`, with `message` but for `done` and
166    /// `stopped`, and a refusal's `error` (the typed refusal).
167    pub fn to_value(&self) -> Value {
168        match self {
169            StreamEnd::Done => json!({ "type": "done" }),
170            StreamEnd::Stopped => json!({ "type": "stopped" }),
171            StreamEnd::Refused { message, error } => json!({ "type": "refused", "message": message, "error": error }),
172            StreamEnd::Failed(m) => json!({ "type": "failed", "message": m }),
173            StreamEnd::Dropped => json!({ "type": "dropped", "message": DISCONNECTED }),
174        }
175    }
176}
177
178/// GAMMA-6: one item of a stream as a member hears it — each data event's
179/// content, then its end.
180#[derive(Debug, Clone, PartialEq)]
181pub enum StreamEvent {
182    Data(Value),
183    End(StreamEnd),
184}
185
186impl StreamEvent {
187    /// `{ type: "data", content }`, or the end's [`StreamEnd::to_value`].
188    pub fn to_value(&self) -> Value {
189        match self {
190            StreamEvent::Data(content) => json!({ "type": "data", "content": content }),
191            StreamEvent::End(end) => end.to_value(),
192        }
193    }
194}
195
196/// What the bus refuses a member, before anything reaches the socket.
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub enum BusRefusal {
199    /// The component's `uses` does not name the method.
200    NotInUses { component: String, method: String },
201    /// A topic under `plexus.`, the host's.
202    Reserved { component: String, topic: String },
203    /// FRAME-29: `slots_set` on a section its mark binds — early-bound, the
204    /// component its code chose; no assignment reaches it.
205    Bound { layout: String, slot: String, component: String },
206}
207
208impl std::fmt::Display for BusRefusal {
209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210        match self {
211            BusRefusal::NotInUses { component, method } => write!(f, "{component} calls {method}, which its uses does not name"),
212            BusRefusal::Reserved { component, topic } => write!(f, "{component} emits {topic}: topics under {RESERVED} are the host's"),
213            BusRefusal::Bound { layout, slot, component } => {
214                write!(f, "bound: {layout} · {slot} is bound to {component} by its mark (data-component); ui.slots.set does not reach it")
215            }
216        }
217    }
218}
219
220/// What the bus needs of the host: the socket, the live cache, the router
221/// and the live version.
222pub trait BusHost {
223    fn open(&self, method: &str, params: Value, sink: Sink) -> CallId;
224    /// GAMMA-6: stops a call on the wire (an unsubscribe); its sink hears
225    /// nothing more.
226    fn close(&self, call: CallId);
227    fn live(&self, spec: &LiveSpec) -> Reader;
228    /// FRAME-19: a module's collection, held by `when`, coalesced by
229    /// `debounce_ms`.
230    fn follow(&self, spec: ModuleSpec) -> ModuleLive;
231    fn navigate(&self, route: &str);
232    /// The live version's hash (`slots_set` with no version names it).
233    fn live_version(&self) -> String;
234    /// FRAME-29: the component a mark binds `layout`'s `slot` to, when one
235    /// does — `slots_set` on it is refused `bound`.
236    fn bound(&self, _layout: &str, _slot: &str) -> Option<String> {
237        None
238    }
239}
240
241struct Listener {
242    id: u64,
243    member: u64,
244    topic: String,
245    f: Rc<dyn Fn(&Value)>,
246}
247
248enum Item {
249    /// `keep`: whether its delivery may keep it (false once its member left).
250    Message { from: u64, topic: String, data: Value, sticky: bool, keep: bool },
251    Run(Box<dyn FnOnce()>),
252}
253
254/// FRAME-53: a sticky topic's last event, and the member that said it.
255struct Kept {
256    from: u64,
257    data: Value,
258}
259
260struct Inner {
261    host: RefCell<Option<Weak<dyn BusHost>>>,
262    rt: crate::signals::Runtime,
263    listeners: RefCell<Vec<Listener>>,
264    /// FRAME-53: each sticky topic's last event, by topic.
265    kept: RefCell<std::collections::BTreeMap<String, Kept>>,
266    queue: RefCell<VecDeque<Item>>,
267    holds: Cell<u32>,
268    draining: Cell<bool>,
269    next: Cell<u64>,
270    /// FRAME-36: the page's keys.
271    keys: crate::keys::Keys,
272}
273
274/// The page's one bus (a handle: clones are the same bus).
275#[derive(Clone)]
276pub struct Bus(Rc<Inner>);
277
278impl std::fmt::Debug for Bus {
279    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
280        write!(f, "Bus({} listeners, {} queued)", self.0.listeners.borrow().len(), self.0.queue.borrow().len())
281    }
282}
283
284impl Bus {
285    /// A bus over the signals of `rt`; the host is set by [`Self::set_host`].
286    pub fn new(rt: &crate::signals::Runtime) -> Self {
287        Self(Rc::new(Inner {
288            host: RefCell::new(None),
289            rt: rt.clone(),
290            listeners: RefCell::new(Vec::new()),
291            kept: RefCell::new(std::collections::BTreeMap::new()),
292            queue: RefCell::new(VecDeque::new()),
293            holds: Cell::new(0),
294            draining: Cell::new(false),
295            next: Cell::new(0),
296            keys: crate::keys::Keys::default(),
297        }))
298    }
299
300    pub fn set_host(&self, host: Weak<dyn BusHost>) {
301        *self.0.host.borrow_mut() = Some(host);
302    }
303
304    fn host(&self) -> Option<Rc<dyn BusHost>> {
305        self.0.host.borrow().as_ref().and_then(Weak::upgrade)
306    }
307
308    /// FRAME-36: the page's keys — every mounted component's shortcuts.
309    pub fn keys(&self) -> &crate::keys::Keys {
310        &self.0.keys
311    }
312
313    /// The signals the bus's collections live on.
314    pub fn runtime(&self) -> &crate::signals::Runtime {
315        &self.0.rt
316    }
317
318    fn next(&self) -> u64 {
319        let n = self.0.next.get() + 1;
320        self.0.next.set(n);
321        n
322    }
323
324    /// A member: what the mounted component `name`, whose `uses` is
325    /// `uses`, is handed.
326    pub fn join(&self, name: &str, uses: &[String]) -> Member {
327        Member(Rc::new(MemberInner {
328            bus: self.clone(),
329            id: self.next(),
330            name: name.into(),
331            uses: uses.iter().cloned().collect(),
332            left: Cell::new(false),
333            streams: RefCell::new(std::collections::BTreeMap::new()),
334        }))
335    }
336
337    /// FRAME-50: the host's own word — `data` on `topic` (under `plexus.`)
338    /// to every member listening, in the bus's turn.
339    pub fn say(&self, topic: &str, data: Value) {
340        self.send(self.next(), topic, data, false);
341    }
342
343    /// FRAME-53: the host's word, kept as the topic's last event — what a
344    /// late [`Member::on_last`] hears (`plexus.booted`).
345    pub fn say_sticky(&self, topic: &str, data: Value) {
346        self.send(self.next(), topic, data, true);
347    }
348
349    /// FRAME-53: `topic`'s kept event, if it is sticky and was said.
350    pub fn last(&self, topic: &str) -> Option<Value> {
351        self.0.kept.borrow().get(topic).map(|k| k.data.clone())
352    }
353
354    fn send(&self, from: u64, topic: &str, data: Value, sticky: bool) {
355        self.0.queue.borrow_mut().push_back(Item::Message { from, topic: topic.into(), data, sticky, keep: true });
356        self.drain();
357    }
358
359    /// Runs `f` in the bus's turn: now when nothing is under way, else
360    /// after what is.
361    pub fn defer(&self, f: impl FnOnce() + 'static) {
362        self.0.queue.borrow_mut().push_back(Item::Run(Box::new(f)));
363        self.drain();
364    }
365
366    /// Holds every delivery until the guard is dropped (the host holds the
367    /// bus while a fold runs).
368    pub fn hold(&self) -> Hold {
369        self.0.holds.set(self.0.holds.get() + 1);
370        Hold(self.clone())
371    }
372
373    fn drain(&self) {
374        if self.0.holds.get() > 0 || self.0.draining.get() {
375            return;
376        }
377        self.0.draining.set(true);
378        loop {
379            let next = self.0.queue.borrow_mut().pop_front();
380            match next {
381                None => break,
382                Some(Item::Run(f)) => f(),
383                Some(Item::Message { from, topic, data, sticky, keep }) => {
384                    // FRAME-53: kept as it is delivered — a sticky emit, or
385                    // any later emit on a topic once made sticky, replaces
386                    // the topic's last event.
387                    if keep {
388                        let mut kept = self.0.kept.borrow_mut();
389                        if sticky || kept.contains_key(&topic) {
390                            kept.insert(topic.clone(), Kept { from, data: data.clone() });
391                        }
392                    }
393                    let hit: Vec<(u64, Rc<dyn Fn(&Value)>)> =
394                        self.0.listeners.borrow().iter().filter(|l| l.topic == topic && l.member != from).map(|l| (l.id, l.f.clone())).collect();
395                    for (id, f) in hit {
396                        // One that stopped listening meanwhile hears nothing.
397                        if self.0.listeners.borrow().iter().any(|l| l.id == id) {
398                            f(&data);
399                        }
400                    }
401                }
402            }
403        }
404        self.0.draining.set(false);
405    }
406}
407
408/// [`Bus::hold`]'s guard: dropping it lets the queue run.
409pub struct Hold(Bus);
410
411impl Drop for Hold {
412    fn drop(&mut self) {
413        let inner = &self.0 .0;
414        inner.holds.set(inner.holds.get().saturating_sub(1));
415        self.0.drain();
416    }
417}
418
419struct MemberInner {
420    bus: Bus,
421    id: u64,
422    name: String,
423    uses: BTreeSet<String>,
424    left: Cell<bool>,
425    /// GAMMA-6: its streams still open, by key — closed when it leaves.
426    streams: RefCell<std::collections::BTreeMap<u64, Rc<Open>>>,
427}
428
429/// GAMMA-6: one stream a member holds open.
430struct Open {
431    /// Its call on the wire, once opened.
432    call: Cell<Option<CallId>>,
433    ended: Cell<bool>,
434    /// What hears each item and the end ([`StreamEvent`]).
435    on: RefCell<Option<Box<dyn FnMut(StreamEvent)>>>,
436    /// What hears the end alone — called even when the member left.
437    done: RefCell<Option<Box<dyn FnOnce(StreamEnd)>>>,
438    /// The end, while `on` is out hearing an item (a stop from inside its
439    /// own listener): heard once that item's call returns.
440    later: RefCell<Option<StreamEnd>>,
441}
442
443impl Open {
444    /// Ends it once: `on` hears the end (unless `quiet`: the member left),
445    /// then `done`.
446    fn end(&self, end: StreamEnd, quiet: bool) {
447        if self.ended.replace(true) {
448            return;
449        }
450        let on = self.on.borrow_mut().take();
451        match (on, quiet) {
452            (Some(mut on), false) => on(StreamEvent::End(end.clone())),
453            (None, false) => *self.later.borrow_mut() = Some(end.clone()),
454            _ => {}
455        }
456        let done = self.done.borrow_mut().take();
457        if let Some(done) = done {
458            done(end);
459        }
460    }
461}
462
463/// GAMMA-6: a stream a member opened ([`Member::stream`]); `stop` ends it.
464/// Dropping it stops nothing: the stream lives until it ends, it is
465/// stopped, or its member leaves.
466pub struct Streaming {
467    member: Weak<MemberInner>,
468    key: u64,
469}
470
471impl Streaming {
472    /// Ends the stream: its call closed on the wire (the unsubscribe the
473    /// service sees), its listener told `stopped`, nothing heard after.
474    /// Once ended, nothing.
475    pub fn stop(&self) {
476        let Some(m) = self.member.upgrade() else { return };
477        let open = m.streams.borrow_mut().remove(&self.key);
478        let Some(open) = open else { return };
479        if let (Some(call), Some(host)) = (open.call.get(), m.bus.host()) {
480            host.close(call);
481        }
482        open.end(StreamEnd::Stopped, false);
483    }
484}
485
486/// One mounted component's side of the bus (a handle).
487#[derive(Clone)]
488pub struct Member(Rc<MemberInner>);
489
490impl std::fmt::Debug for Member {
491    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
492        write!(f, "Member({} #{})", self.0.name, self.0.id)
493    }
494}
495
496/// A listener held: dropping it stops it.
497pub struct Listening {
498    bus: Weak<Inner>,
499    id: u64,
500}
501
502impl Drop for Listening {
503    fn drop(&mut self) {
504        if let Some(inner) = self.bus.upgrade() {
505            inner.listeners.borrow_mut().retain(|l| l.id != self.id);
506        }
507    }
508}
509
510impl Member {
511    /// The component's name.
512    pub fn name(&self) -> &str {
513        &self.0.name
514    }
515
516    /// The bus it is a member of.
517    pub fn bus(&self) -> &Bus {
518        &self.0.bus
519    }
520
521    /// COMPS-2: **a frame's member** — what a page or component this member
522    /// frames (`bus.frame`) calls through: a member of the same bus named
523    /// `name`, its calls held to `uses`. `within`: a page the framer wrote
524    /// (`{ html }`), whose `uses` the framer declares, so only what the
525    /// framer's own `uses` names is kept — a framer gives no more than it
526    /// holds; not `within`: a stored component (`{ component }`), whose
527    /// `uses` is its own manifest entry's. Either way the call goes over the
528    /// page's one socket as the viewer, so the service's gate holds it to
529    /// the viewer's grants too.
530    ///
531    /// GAMMA-5: **a frame never holds an open entry** (`things.*`): its own
532    /// are dropped, and a page keeps a method only where the framer names
533    /// it exactly — a framer's open entry gives a framed page nothing.
534    pub fn framed(&self, name: &str, uses: &[String], within: bool) -> Member {
535        let kept: Vec<String> = uses.iter().filter(|m| is_exact(m) && (!within || self.0.uses.contains(*m))).cloned().collect();
536        self.0.bus.join(name, &kept)
537    }
538
539    /// COMPS-2: whether `method` is one this member may call — named in its
540    /// `uses`, or GAMMA-5: under one of its open entries.
541    pub fn holds(&self, method: &str) -> bool {
542        covers(self.0.uses.iter().map(String::as_str), method)
543    }
544
545    fn left(&self) -> bool {
546        self.0.left.get()
547    }
548
549    fn held(&self, method: &str) -> Result<(), BusRefusal> {
550        if self.holds(method) {
551            Ok(())
552        } else {
553            Err(BusRefusal::NotInUses { component: self.0.name.clone(), method: method.into() })
554        }
555    }
556
557    /// `method` through the page's socket, its items into `sink`; refused
558    /// before the socket when `uses` does not name it.
559    pub fn call(&self, method: &str, params: Value, sink: Sink) -> Result<CallId, BusRefusal> {
560        self.held(method)?;
561        let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: method.into() })?;
562        Ok(host.open(method, params, sink))
563    }
564
565    /// GAMMA-6: `method` through the page's socket as a stream — `on` hears
566    /// each data event's content as it arrives, then how it ended
567    /// ([`StreamEnd`]), once; `done` hears the end alone. Held to `uses` as
568    /// [`Self::call`] is (refused before the socket). [`Streaming::stop`]
569    /// closes the call on the wire; a member that leaves closes every stream
570    /// it holds, `done` told `stopped` and `on` nothing more. Never sent
571    /// again: a drop under it is its end (`dropped`).
572    pub fn stream(&self, method: &str, params: Value, on: impl FnMut(StreamEvent) + 'static, done: impl FnOnce(StreamEnd) + 'static) -> Result<Streaming, BusRefusal> {
573        self.held(method)?;
574        let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: method.into() })?;
575        let key = self.0.bus.next();
576        let open = Rc::new(Open { call: Cell::new(None), ended: Cell::new(false), on: RefCell::new(Some(Box::new(on))), done: RefCell::new(Some(Box::new(done))), later: RefCell::new(None) });
577        let streaming = Streaming { member: Rc::downgrade(&self.0), key };
578        if self.left() {
579            open.end(StreamEnd::Stopped, true);
580            return Ok(streaming);
581        }
582        self.0.streams.borrow_mut().insert(key, open.clone());
583        let (o, me) = (Rc::downgrade(&open), Rc::downgrade(&self.0));
584        let sink: Sink = Box::new(move |item| {
585            let Some(open) = o.upgrade() else { return };
586            if open.ended.get() {
587                return;
588            }
589            let end = match item {
590                WireItem::Data(v) => {
591                    // Taken out while it runs: what it does (a stop, an
592                    // emit) never meets its own borrow.
593                    let on = open.on.borrow_mut().take();
594                    if let Some(mut on) = on {
595                        on(StreamEvent::Data(v));
596                        if !open.ended.get() {
597                            *open.on.borrow_mut() = Some(on);
598                        } else if let Some(end) = open.later.borrow_mut().take() {
599                            on(StreamEvent::End(end));
600                        }
601                    }
602                    return;
603                }
604                WireItem::Done => StreamEnd::Done,
605                WireItem::Refused(message, error) => StreamEnd::Refused { message, error },
606                WireItem::Failed(m) => StreamEnd::Failed(m),
607                WireItem::Dropped => StreamEnd::Dropped,
608            };
609            if let Some(m) = me.upgrade() {
610                m.streams.borrow_mut().remove(&key);
611            }
612            open.end(end, false);
613        });
614        let call = host.open(method, params, sink);
615        open.call.set(Some(call));
616        Ok(streaming)
617    }
618
619    /// The page's collection for `spec`, shared; its snapshot and changes
620    /// methods held to `uses`.
621    pub fn live(&self, spec: &LiveSpec) -> Result<Reader, BusRefusal> {
622        self.held(&spec.snapshot)?;
623        if let Some(c) = &spec.changes {
624            self.held(c)?;
625        }
626        let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: spec.snapshot.clone() })?;
627        Ok(host.live(spec))
628    }
629
630    /// `data` on `topic` to every other member listening; `plexus.…`
631    /// refused. A member that left reaches no one.
632    pub fn emit(&self, topic: &str, data: Value) -> Result<(), BusRefusal> {
633        self.emit_with(topic, data, false)
634    }
635
636    /// FRAME-53: [`Self::emit`], the event kept as the topic's last — what a
637    /// member that listens later with [`Self::on_last`] hears at once.
638    pub fn emit_sticky(&self, topic: &str, data: Value) -> Result<(), BusRefusal> {
639        self.emit_with(topic, data, true)
640    }
641
642    fn emit_with(&self, topic: &str, data: Value, sticky: bool) -> Result<(), BusRefusal> {
643        if topic.starts_with(RESERVED) {
644            return Err(BusRefusal::Reserved { component: self.0.name.clone(), topic: topic.into() });
645        }
646        if self.left() {
647            return Ok(());
648        }
649        self.0.bus.send(self.0.id, topic, data, sticky);
650        Ok(())
651    }
652
653    /// FRAME-53: `topic`'s kept event (the page's, whoever said it).
654    pub fn last(&self, topic: &str) -> Option<Value> {
655        self.0.bus.last(topic)
656    }
657
658    /// FRAME-53: [`Self::on`], and first the topic's kept event, if any,
659    /// at once — in the bus's turn: now when nothing is under way, else
660    /// right after what is. Not the member's own, and not when an event of
661    /// the topic reached `f` first (a newer one than the kept).
662    pub fn on_last(&self, topic: &str, f: impl Fn(&Value) + 'static) -> Listening {
663        let heard = Rc::new(Cell::new(false));
664        let f: Rc<dyn Fn(&Value)> = Rc::new(f);
665        let (h, g) = (heard.clone(), f.clone());
666        let listening = self.on(topic, move |data: &Value| {
667            h.set(true);
668            g(data)
669        });
670        if !self.left() {
671            let (bus, me, id, topic) = (Rc::downgrade(&self.0.bus.0), self.0.id, listening.id, topic.to_string());
672            self.0.bus.defer(move || {
673                let Some(inner) = bus.upgrade() else { return };
674                if heard.get() || !inner.listeners.borrow().iter().any(|l| l.id == id) {
675                    return;
676                }
677                let kept = inner.kept.borrow().get(&topic).filter(|k| k.from != me).map(|k| k.data.clone());
678                if let Some(data) = kept {
679                    f(&data);
680                }
681            });
682        }
683        listening
684    }
685
686    /// `f` on every `topic` another member emits, until the [`Listening`] is
687    /// dropped or the member leaves.
688    pub fn on(&self, topic: &str, f: impl Fn(&Value) + 'static) -> Listening {
689        let id = self.0.bus.next();
690        if !self.left() {
691            self.0.bus.0.listeners.borrow_mut().push(Listener { id, member: self.0.id, topic: topic.into(), f: Rc::new(f) });
692        }
693        Listening { bus: Rc::downgrade(&self.0.bus.0), id }
694    }
695
696    /// Moves the page to `route`.
697    pub fn navigate(&self, route: &str) {
698        if let Some(host) = self.0.bus.host() {
699            host.navigate(route);
700        }
701    }
702
703    /// `ui.slots.set { layout, slot, component, version }` (the live
704    /// version when none is named) — a call held to `uses`.
705    pub fn slots_set(&self, layout: &str, slot: &str, component: &str, version: Option<&str>, sink: Sink) -> Result<CallId, BusRefusal> {
706        self.held("ui.slots.set")?;
707        if let Some(component) = self.0.bus.host().and_then(|h| h.bound(layout, slot)) {
708            return Err(BusRefusal::Bound { layout: layout.into(), slot: slot.into(), component });
709        }
710        let version = match version {
711            Some(v) => v.to_string(),
712            None => self.0.bus.host().map(|h| h.live_version()).unwrap_or_default(),
713        };
714        self.call("ui.slots.set", json!({ "layout": layout, "slot": slot, "component": component, "version": version }), sink)
715    }
716
717    /// FRAME-19: a module's collection for `spec` — `when` and
718    /// `debounce_ms` held by the registry as rhx's are, the module moving
719    /// its params with [`ModuleLive::update`]; its methods held to `uses`.
720    pub fn follow(&self, spec: ModuleSpec) -> Result<ModuleLive, BusRefusal> {
721        self.held(&spec.query.snapshot)?;
722        if let Some(c) = &spec.query.changes {
723            self.held(c)?;
724        }
725        let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: spec.query.snapshot.clone() })?;
726        Ok(host.follow(spec))
727    }
728
729    /// FRAME-36: the component's shortcuts, each with what it runs, into
730    /// the page's registry until the answer is dropped or the member leaves
731    /// (one that left binds nothing).
732    pub fn keys(&self, decls: Vec<(crate::keys::KeyDecl, crate::keys::KeyRun)>) -> crate::keys::KeysHeld {
733        let decls = if self.left() { Vec::new() } else { decls };
734        self.0.bus.0.keys.add(self.0.id, &self.0.name, decls)
735    }
736
737    /// Leaves the bus: every listener of it stops, its keys go, and its
738    /// emits reach no one. FRAME-53: what it kept goes too — every sticky
739    /// topic whose last event it said is kept for no one until said again,
740    /// and an emit of its still queued keeps nothing.
741    pub fn leave(&self) {
742        self.0.left.set(true);
743        let me = self.0.id;
744        self.0.bus.0.kept.borrow_mut().retain(|_, k| k.from != me);
745        for item in self.0.bus.0.queue.borrow_mut().iter_mut() {
746            if let Item::Message { from, keep, .. } = item {
747                if *from == me {
748                    *keep = false;
749                }
750            }
751        }
752        self.0.bus.0.keys.remove_member(self.0.id);
753        self.0.bus.0.listeners.borrow_mut().retain(|l| l.member != self.0.id);
754        // GAMMA-6: every stream it holds closed on the wire; each `done`
755        // told `stopped`, nothing more heard.
756        let streams = std::mem::take(&mut *self.0.streams.borrow_mut());
757        let host = self.0.bus.host();
758        for open in streams.into_values() {
759            if let (Some(call), Some(host)) = (open.call.get(), &host) {
760                host.close(call);
761            }
762            open.end(StreamEnd::Stopped, true);
763        }
764    }
765}