use crate::live::{LiveSpec, ModuleLive, ModuleSpec, Reader};
use crate::transport::{CallId, Sink, WireItem};
use serde_json::{json, Value};
use std::cell::{Cell, RefCell};
use std::collections::{BTreeSet, VecDeque};
use std::rc::{Rc, Weak};
pub const RESERVED: &str = "plexus.";
pub const DISCONNECTED: &str = "disconnected";
#[derive(Debug, Clone, PartialEq)]
pub struct Answer {
pub ok: bool,
pub events: Vec<Value>,
pub message: Option<String>,
}
impl Answer {
pub fn to_value(&self) -> Value {
json!({ "ok": self.ok, "events": self.events, "message": self.message })
}
}
fn in_band(event: &Value) -> Option<String> {
let kind = event.get("type").and_then(Value::as_str).filter(|t| *t == "error" || *t == "refused")?;
let words = ["message", "reason"].iter().find_map(|k| event.get(*k).filter(|v| !v.is_null()));
Some(match words {
Some(Value::String(s)) => s.clone(),
Some(v) => v.to_string(),
None => kind.to_string(),
})
}
pub fn answer_sink(done: impl FnOnce(Answer) + 'static) -> Sink {
let mut events = Vec::new();
let mut done = Some(done);
Box::new(move |item| {
let ended = match item {
WireItem::Data(v) => {
events.push(v);
return;
}
WireItem::Done => None,
WireItem::Refused(m, _) => Some(m),
WireItem::Failed(m) => Some(m),
WireItem::Dropped => Some(DISCONNECTED.to_string()),
};
let Some(done) = done.take() else { return };
let events = std::mem::take(&mut events);
let message = events.iter().find_map(in_band).or(ended);
done(Answer { ok: message.is_none(), events, message });
})
}
pub fn open_prefix(entry: &str) -> Option<&str> {
let prefix = entry.strip_suffix(".*")?;
let plain = !prefix.is_empty() && prefix.split('.').all(|seg| !seg.is_empty() && !seg.contains('*'));
plain.then_some(prefix)
}
pub fn is_exact(entry: &str) -> bool {
!entry.is_empty() && !entry.contains('*')
}
pub fn covers<'a>(uses: impl IntoIterator<Item = &'a str>, method: &str) -> bool {
uses.into_iter().any(|u| match open_prefix(u) {
Some(prefix) => method.strip_prefix(prefix).and_then(|rest| rest.strip_prefix('.')).is_some_and(|rest| !rest.is_empty()),
None => is_exact(u) && u == method,
})
}
#[derive(Debug, Clone, PartialEq)]
pub enum StreamEnd {
Done,
Stopped,
Refused { message: String, error: Value },
Failed(String),
Dropped,
}
impl StreamEnd {
pub fn to_value(&self) -> Value {
match self {
StreamEnd::Done => json!({ "type": "done" }),
StreamEnd::Stopped => json!({ "type": "stopped" }),
StreamEnd::Refused { message, error } => json!({ "type": "refused", "message": message, "error": error }),
StreamEnd::Failed(m) => json!({ "type": "failed", "message": m }),
StreamEnd::Dropped => json!({ "type": "dropped", "message": DISCONNECTED }),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum StreamEvent {
Data(Value),
End(StreamEnd),
}
impl StreamEvent {
pub fn to_value(&self) -> Value {
match self {
StreamEvent::Data(content) => json!({ "type": "data", "content": content }),
StreamEvent::End(end) => end.to_value(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BusRefusal {
NotInUses { component: String, method: String },
Reserved { component: String, topic: String },
Bound { layout: String, slot: String, component: String },
}
impl std::fmt::Display for BusRefusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BusRefusal::NotInUses { component, method } => write!(f, "{component} calls {method}, which its uses does not name"),
BusRefusal::Reserved { component, topic } => write!(f, "{component} emits {topic}: topics under {RESERVED} are the host's"),
BusRefusal::Bound { layout, slot, component } => {
write!(f, "bound: {layout} · {slot} is bound to {component} by its mark (data-component); ui.slots.set does not reach it")
}
}
}
}
pub trait BusHost {
fn open(&self, method: &str, params: Value, sink: Sink) -> CallId;
fn close(&self, call: CallId);
fn live(&self, spec: &LiveSpec) -> Reader;
fn follow(&self, spec: ModuleSpec) -> ModuleLive;
fn navigate(&self, route: &str);
fn live_version(&self) -> String;
fn bound(&self, _layout: &str, _slot: &str) -> Option<String> {
None
}
}
struct Listener {
id: u64,
member: u64,
topic: String,
f: Rc<dyn Fn(&Value)>,
}
enum Item {
Message { from: u64, topic: String, data: Value, sticky: bool, keep: bool },
Run(Box<dyn FnOnce()>),
}
struct Kept {
from: u64,
data: Value,
}
struct Inner {
host: RefCell<Option<Weak<dyn BusHost>>>,
rt: crate::signals::Runtime,
listeners: RefCell<Vec<Listener>>,
kept: RefCell<std::collections::BTreeMap<String, Kept>>,
queue: RefCell<VecDeque<Item>>,
holds: Cell<u32>,
draining: Cell<bool>,
next: Cell<u64>,
keys: crate::keys::Keys,
}
#[derive(Clone)]
pub struct Bus(Rc<Inner>);
impl std::fmt::Debug for Bus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Bus({} listeners, {} queued)", self.0.listeners.borrow().len(), self.0.queue.borrow().len())
}
}
impl Bus {
pub fn new(rt: &crate::signals::Runtime) -> Self {
Self(Rc::new(Inner {
host: RefCell::new(None),
rt: rt.clone(),
listeners: RefCell::new(Vec::new()),
kept: RefCell::new(std::collections::BTreeMap::new()),
queue: RefCell::new(VecDeque::new()),
holds: Cell::new(0),
draining: Cell::new(false),
next: Cell::new(0),
keys: crate::keys::Keys::default(),
}))
}
pub fn set_host(&self, host: Weak<dyn BusHost>) {
*self.0.host.borrow_mut() = Some(host);
}
fn host(&self) -> Option<Rc<dyn BusHost>> {
self.0.host.borrow().as_ref().and_then(Weak::upgrade)
}
pub fn keys(&self) -> &crate::keys::Keys {
&self.0.keys
}
pub fn runtime(&self) -> &crate::signals::Runtime {
&self.0.rt
}
fn next(&self) -> u64 {
let n = self.0.next.get() + 1;
self.0.next.set(n);
n
}
pub fn join(&self, name: &str, uses: &[String]) -> Member {
Member(Rc::new(MemberInner {
bus: self.clone(),
id: self.next(),
name: name.into(),
uses: uses.iter().cloned().collect(),
left: Cell::new(false),
streams: RefCell::new(std::collections::BTreeMap::new()),
}))
}
pub fn say(&self, topic: &str, data: Value) {
self.send(self.next(), topic, data, false);
}
pub fn say_sticky(&self, topic: &str, data: Value) {
self.send(self.next(), topic, data, true);
}
pub fn last(&self, topic: &str) -> Option<Value> {
self.0.kept.borrow().get(topic).map(|k| k.data.clone())
}
fn send(&self, from: u64, topic: &str, data: Value, sticky: bool) {
self.0.queue.borrow_mut().push_back(Item::Message { from, topic: topic.into(), data, sticky, keep: true });
self.drain();
}
pub fn defer(&self, f: impl FnOnce() + 'static) {
self.0.queue.borrow_mut().push_back(Item::Run(Box::new(f)));
self.drain();
}
pub fn hold(&self) -> Hold {
self.0.holds.set(self.0.holds.get() + 1);
Hold(self.clone())
}
fn drain(&self) {
if self.0.holds.get() > 0 || self.0.draining.get() {
return;
}
self.0.draining.set(true);
loop {
let next = self.0.queue.borrow_mut().pop_front();
match next {
None => break,
Some(Item::Run(f)) => f(),
Some(Item::Message { from, topic, data, sticky, keep }) => {
if keep {
let mut kept = self.0.kept.borrow_mut();
if sticky || kept.contains_key(&topic) {
kept.insert(topic.clone(), Kept { from, data: data.clone() });
}
}
let hit: Vec<(u64, Rc<dyn Fn(&Value)>)> =
self.0.listeners.borrow().iter().filter(|l| l.topic == topic && l.member != from).map(|l| (l.id, l.f.clone())).collect();
for (id, f) in hit {
if self.0.listeners.borrow().iter().any(|l| l.id == id) {
f(&data);
}
}
}
}
}
self.0.draining.set(false);
}
}
pub struct Hold(Bus);
impl Drop for Hold {
fn drop(&mut self) {
let inner = &self.0 .0;
inner.holds.set(inner.holds.get().saturating_sub(1));
self.0.drain();
}
}
struct MemberInner {
bus: Bus,
id: u64,
name: String,
uses: BTreeSet<String>,
left: Cell<bool>,
streams: RefCell<std::collections::BTreeMap<u64, Rc<Open>>>,
}
struct Open {
call: Cell<Option<CallId>>,
ended: Cell<bool>,
on: RefCell<Option<Box<dyn FnMut(StreamEvent)>>>,
done: RefCell<Option<Box<dyn FnOnce(StreamEnd)>>>,
later: RefCell<Option<StreamEnd>>,
}
impl Open {
fn end(&self, end: StreamEnd, quiet: bool) {
if self.ended.replace(true) {
return;
}
let on = self.on.borrow_mut().take();
match (on, quiet) {
(Some(mut on), false) => on(StreamEvent::End(end.clone())),
(None, false) => *self.later.borrow_mut() = Some(end.clone()),
_ => {}
}
let done = self.done.borrow_mut().take();
if let Some(done) = done {
done(end);
}
}
}
pub struct Streaming {
member: Weak<MemberInner>,
key: u64,
}
impl Streaming {
pub fn stop(&self) {
let Some(m) = self.member.upgrade() else { return };
let open = m.streams.borrow_mut().remove(&self.key);
let Some(open) = open else { return };
if let (Some(call), Some(host)) = (open.call.get(), m.bus.host()) {
host.close(call);
}
open.end(StreamEnd::Stopped, false);
}
}
#[derive(Clone)]
pub struct Member(Rc<MemberInner>);
impl std::fmt::Debug for Member {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Member({} #{})", self.0.name, self.0.id)
}
}
pub struct Listening {
bus: Weak<Inner>,
id: u64,
}
impl Drop for Listening {
fn drop(&mut self) {
if let Some(inner) = self.bus.upgrade() {
inner.listeners.borrow_mut().retain(|l| l.id != self.id);
}
}
}
impl Member {
pub fn name(&self) -> &str {
&self.0.name
}
pub fn bus(&self) -> &Bus {
&self.0.bus
}
pub fn framed(&self, name: &str, uses: &[String], within: bool) -> Member {
let kept: Vec<String> = uses.iter().filter(|m| is_exact(m) && (!within || self.0.uses.contains(*m))).cloned().collect();
self.0.bus.join(name, &kept)
}
pub fn holds(&self, method: &str) -> bool {
covers(self.0.uses.iter().map(String::as_str), method)
}
fn left(&self) -> bool {
self.0.left.get()
}
fn held(&self, method: &str) -> Result<(), BusRefusal> {
if self.holds(method) {
Ok(())
} else {
Err(BusRefusal::NotInUses { component: self.0.name.clone(), method: method.into() })
}
}
pub fn call(&self, method: &str, params: Value, sink: Sink) -> Result<CallId, BusRefusal> {
self.held(method)?;
let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: method.into() })?;
Ok(host.open(method, params, sink))
}
pub fn stream(&self, method: &str, params: Value, on: impl FnMut(StreamEvent) + 'static, done: impl FnOnce(StreamEnd) + 'static) -> Result<Streaming, BusRefusal> {
self.held(method)?;
let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: method.into() })?;
let key = self.0.bus.next();
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) });
let streaming = Streaming { member: Rc::downgrade(&self.0), key };
if self.left() {
open.end(StreamEnd::Stopped, true);
return Ok(streaming);
}
self.0.streams.borrow_mut().insert(key, open.clone());
let (o, me) = (Rc::downgrade(&open), Rc::downgrade(&self.0));
let sink: Sink = Box::new(move |item| {
let Some(open) = o.upgrade() else { return };
if open.ended.get() {
return;
}
let end = match item {
WireItem::Data(v) => {
let on = open.on.borrow_mut().take();
if let Some(mut on) = on {
on(StreamEvent::Data(v));
if !open.ended.get() {
*open.on.borrow_mut() = Some(on);
} else if let Some(end) = open.later.borrow_mut().take() {
on(StreamEvent::End(end));
}
}
return;
}
WireItem::Done => StreamEnd::Done,
WireItem::Refused(message, error) => StreamEnd::Refused { message, error },
WireItem::Failed(m) => StreamEnd::Failed(m),
WireItem::Dropped => StreamEnd::Dropped,
};
if let Some(m) = me.upgrade() {
m.streams.borrow_mut().remove(&key);
}
open.end(end, false);
});
let call = host.open(method, params, sink);
open.call.set(Some(call));
Ok(streaming)
}
pub fn live(&self, spec: &LiveSpec) -> Result<Reader, BusRefusal> {
self.held(&spec.snapshot)?;
if let Some(c) = &spec.changes {
self.held(c)?;
}
let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: spec.snapshot.clone() })?;
Ok(host.live(spec))
}
pub fn emit(&self, topic: &str, data: Value) -> Result<(), BusRefusal> {
self.emit_with(topic, data, false)
}
pub fn emit_sticky(&self, topic: &str, data: Value) -> Result<(), BusRefusal> {
self.emit_with(topic, data, true)
}
fn emit_with(&self, topic: &str, data: Value, sticky: bool) -> Result<(), BusRefusal> {
if topic.starts_with(RESERVED) {
return Err(BusRefusal::Reserved { component: self.0.name.clone(), topic: topic.into() });
}
if self.left() {
return Ok(());
}
self.0.bus.send(self.0.id, topic, data, sticky);
Ok(())
}
pub fn last(&self, topic: &str) -> Option<Value> {
self.0.bus.last(topic)
}
pub fn on_last(&self, topic: &str, f: impl Fn(&Value) + 'static) -> Listening {
let heard = Rc::new(Cell::new(false));
let f: Rc<dyn Fn(&Value)> = Rc::new(f);
let (h, g) = (heard.clone(), f.clone());
let listening = self.on(topic, move |data: &Value| {
h.set(true);
g(data)
});
if !self.left() {
let (bus, me, id, topic) = (Rc::downgrade(&self.0.bus.0), self.0.id, listening.id, topic.to_string());
self.0.bus.defer(move || {
let Some(inner) = bus.upgrade() else { return };
if heard.get() || !inner.listeners.borrow().iter().any(|l| l.id == id) {
return;
}
let kept = inner.kept.borrow().get(&topic).filter(|k| k.from != me).map(|k| k.data.clone());
if let Some(data) = kept {
f(&data);
}
});
}
listening
}
pub fn on(&self, topic: &str, f: impl Fn(&Value) + 'static) -> Listening {
let id = self.0.bus.next();
if !self.left() {
self.0.bus.0.listeners.borrow_mut().push(Listener { id, member: self.0.id, topic: topic.into(), f: Rc::new(f) });
}
Listening { bus: Rc::downgrade(&self.0.bus.0), id }
}
pub fn navigate(&self, route: &str) {
if let Some(host) = self.0.bus.host() {
host.navigate(route);
}
}
pub fn slots_set(&self, layout: &str, slot: &str, component: &str, version: Option<&str>, sink: Sink) -> Result<CallId, BusRefusal> {
self.held("ui.slots.set")?;
if let Some(component) = self.0.bus.host().and_then(|h| h.bound(layout, slot)) {
return Err(BusRefusal::Bound { layout: layout.into(), slot: slot.into(), component });
}
let version = match version {
Some(v) => v.to_string(),
None => self.0.bus.host().map(|h| h.live_version()).unwrap_or_default(),
};
self.call("ui.slots.set", json!({ "layout": layout, "slot": slot, "component": component, "version": version }), sink)
}
pub fn follow(&self, spec: ModuleSpec) -> Result<ModuleLive, BusRefusal> {
self.held(&spec.query.snapshot)?;
if let Some(c) = &spec.query.changes {
self.held(c)?;
}
let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: spec.query.snapshot.clone() })?;
Ok(host.follow(spec))
}
pub fn keys(&self, decls: Vec<(crate::keys::KeyDecl, crate::keys::KeyRun)>) -> crate::keys::KeysHeld {
let decls = if self.left() { Vec::new() } else { decls };
self.0.bus.0.keys.add(self.0.id, &self.0.name, decls)
}
pub fn leave(&self) {
self.0.left.set(true);
let me = self.0.id;
self.0.bus.0.kept.borrow_mut().retain(|_, k| k.from != me);
for item in self.0.bus.0.queue.borrow_mut().iter_mut() {
if let Item::Message { from, keep, .. } = item {
if *from == me {
*keep = false;
}
}
}
self.0.bus.0.keys.remove_member(self.0.id);
self.0.bus.0.listeners.borrow_mut().retain(|l| l.member != self.0.id);
let streams = std::mem::take(&mut *self.0.streams.borrow_mut());
let host = self.0.bus.host();
for open in streams.into_values() {
if let (Some(call), Some(host)) = (open.call.get(), &host) {
host.close(call);
}
open.end(StreamEnd::Stopped, true);
}
}
}