1use 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
56pub const RESERVED: &str = "plexus.";
58
59pub const DISCONNECTED: &str = "disconnected";
61
62#[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 pub fn to_value(&self) -> Value {
78 json!({ "ok": self.ok, "events": self.events, "message": self.message })
79 }
80}
81
82fn 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
94pub 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 let message = events.iter().find_map(in_band).or(ended);
115 done(Answer { ok: message.is_none(), events, message });
116 })
117}
118
119pub 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
130pub fn is_exact(entry: &str) -> bool {
132 !entry.is_empty() && !entry.contains('*')
133}
134
135pub 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#[derive(Debug, Clone, PartialEq)]
148pub enum StreamEnd {
149 Done,
151 Stopped,
154 Refused { message: String, error: Value },
157 Failed(String),
159 Dropped,
161}
162
163impl StreamEnd {
164 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#[derive(Debug, Clone, PartialEq)]
181pub enum StreamEvent {
182 Data(Value),
183 End(StreamEnd),
184}
185
186impl StreamEvent {
187 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#[derive(Debug, Clone, PartialEq, Eq)]
198pub enum BusRefusal {
199 NotInUses { component: String, method: String },
201 Reserved { component: String, topic: String },
203 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
220pub trait BusHost {
223 fn open(&self, method: &str, params: Value, sink: Sink) -> CallId;
224 fn close(&self, call: CallId);
227 fn live(&self, spec: &LiveSpec) -> Reader;
228 fn follow(&self, spec: ModuleSpec) -> ModuleLive;
231 fn navigate(&self, route: &str);
232 fn live_version(&self) -> String;
234 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 Message { from: u64, topic: String, data: Value, sticky: bool, keep: bool },
251 Run(Box<dyn FnOnce()>),
252}
253
254struct 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 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 keys: crate::keys::Keys,
272}
273
274#[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 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 pub fn keys(&self) -> &crate::keys::Keys {
310 &self.0.keys
311 }
312
313 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 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 pub fn say(&self, topic: &str, data: Value) {
340 self.send(self.next(), topic, data, false);
341 }
342
343 pub fn say_sticky(&self, topic: &str, data: Value) {
346 self.send(self.next(), topic, data, true);
347 }
348
349 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 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 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 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 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
408pub 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 streams: RefCell<std::collections::BTreeMap<u64, Rc<Open>>>,
427}
428
429struct Open {
431 call: Cell<Option<CallId>>,
433 ended: Cell<bool>,
434 on: RefCell<Option<Box<dyn FnMut(StreamEvent)>>>,
436 done: RefCell<Option<Box<dyn FnOnce(StreamEnd)>>>,
438 later: RefCell<Option<StreamEnd>>,
441}
442
443impl Open {
444 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
463pub struct Streaming {
467 member: Weak<MemberInner>,
468 key: u64,
469}
470
471impl Streaming {
472 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#[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
496pub 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 pub fn name(&self) -> &str {
513 &self.0.name
514 }
515
516 pub fn bus(&self) -> &Bus {
518 &self.0.bus
519 }
520
521 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 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 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 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 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 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 pub fn emit(&self, topic: &str, data: Value) -> Result<(), BusRefusal> {
633 self.emit_with(topic, data, false)
634 }
635
636 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 pub fn last(&self, topic: &str) -> Option<Value> {
655 self.0.bus.last(topic)
656 }
657
658 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 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 pub fn navigate(&self, route: &str) {
698 if let Some(host) = self.0.bus.host() {
699 host.navigate(route);
700 }
701 }
702
703 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 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 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 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 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}