Skip to main content

plexus_ui_engine/transport/
mod.rs

1//! UI-6: **the wire seam** — every Plexus call the engine makes goes
2//! through one [`Wire`]: on wasm32 the page's one WebSocket ([`ws`],
3//! v1's `WsTransport` over plexus-client's `ws-web`, with its 1 s reconnect
4//! loop); in the native tests [`FakeWire`], which records what was opened
5//! and lets the test feed each stream.
6//!
7//! Push-based: [`Wire::open`] hands a sink every item of the call's stream
8//! in order, ending with [`WireItem::Done`], [`WireItem::Refused`],
9//! [`WireItem::Failed`] or [`WireItem::Dropped`];
10//! [`Wire::close`] unsubscribes. A component never holds a `Wire` — the
11//! engine does.
12
13use serde_json::Value;
14
15/// A call's handle on the wire.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
17pub struct CallId(pub u64);
18
19/// One item of a call's stream.
20#[derive(Debug, Clone, PartialEq)]
21pub enum WireItem {
22    /// A data event's content (`{"type": "summary", …}`).
23    Data(Value),
24    /// The stream ended normally.
25    Done,
26    /// The server refused the call (the gate's `forbidden`, …): its words,
27    /// and GAMMA-6: the refusal typed as the service sent it — its
28    /// `error_kind`, `error`, `code` and the fields beside them (`grant`,
29    /// `scope`, `roles`, `held_on`, …); null when the wire has none.
30    Refused(String, Value),
31    /// The call failed under the transport — never sent (the socket not
32    /// open), or a frame it could not read: its words. A reconnect re-opens
33    /// what the engine still wants.
34    Failed(String),
35    /// FRAME-37: the socket dropped under the call (plexus-client's
36    /// `Closed`); a reconnect re-opens what the engine still wants.
37    Dropped,
38}
39
40/// Where a call's items go.
41pub type Sink = Box<dyn FnMut(WireItem)>;
42
43/// The wire: the page's one socket.
44pub trait Wire {
45    /// Calls `method` (`tickets.list`) with `params`, its items into `sink`.
46    fn open(&self, method: &str, params: Value, sink: Sink) -> CallId;
47    /// Stops the call (an unsubscribe); its sink hears nothing more.
48    fn close(&self, call: CallId);
49}
50
51impl<W: Wire + ?Sized> Wire for std::rc::Rc<W> {
52    fn open(&self, method: &str, params: Value, sink: Sink) -> CallId {
53        (**self).open(method, params, sink)
54    }
55    fn close(&self, call: CallId) {
56        (**self).close(call)
57    }
58}
59
60/// One call [`FakeWire`] saw.
61#[derive(Debug, Clone, PartialEq)]
62pub struct Opened {
63    pub id: CallId,
64    pub method: String,
65    pub params: Value,
66}
67
68/// The tests' wire: records each open and close; the test feeds a call's
69/// sink with [`FakeWire::feed`].
70#[derive(Clone, Default)]
71pub struct FakeWire(std::rc::Rc<std::cell::RefCell<Calls>>);
72
73#[derive(Default)]
74struct Calls {
75    opened: Vec<Opened>,
76    closed: Vec<CallId>,
77    sinks: std::collections::BTreeMap<CallId, Sink>,
78}
79
80impl std::fmt::Debug for FakeWire {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        let c = self.0.borrow();
83        write!(f, "FakeWire({} opened, {} closed)", c.opened.len(), c.closed.len())
84    }
85}
86
87impl FakeWire {
88    pub fn new() -> Self {
89        Self::default()
90    }
91
92    /// Every call opened, in order.
93    pub fn opened(&self) -> Vec<Opened> {
94        self.0.borrow().opened.clone()
95    }
96
97    /// The calls of `method` opened, in order.
98    pub fn opened_of(&self, method: &str) -> Vec<Opened> {
99        self.opened().into_iter().filter(|o| o.method == method).collect()
100    }
101
102    /// The latest call of `method`; panics naming it when none was opened.
103    pub fn last_of(&self, method: &str) -> CallId {
104        self.opened_of(method).last().unwrap_or_else(|| panic!("no call of {method} was opened")).id
105    }
106
107    /// Every call closed, in order.
108    pub fn closed(&self) -> Vec<CallId> {
109        self.0.borrow().closed.clone()
110    }
111
112    /// The calls open now.
113    pub fn open_now(&self) -> Vec<Opened> {
114        let closed = self.closed();
115        self.opened().into_iter().filter(|o| !closed.contains(&o.id)).collect()
116    }
117
118    /// Hands `item` to `call`'s sink (nothing, once it is closed). The sink
119    /// runs outside the wire's borrow, so it may open or close calls.
120    pub fn feed(&self, call: CallId, item: WireItem) {
121        let Some(mut sink) = self.0.borrow_mut().sinks.remove(&call) else { return };
122        let ends = matches!(item, WireItem::Done | WireItem::Refused(..) | WireItem::Failed(_) | WireItem::Dropped);
123        sink(item);
124        let mut c = self.0.borrow_mut();
125        if !ends && !c.closed.contains(&call) {
126            c.sinks.insert(call, sink);
127        }
128    }
129
130    /// Hands each data event to `call`'s sink, then `Done`.
131    pub fn answer(&self, call: CallId, events: impl IntoIterator<Item = Value>) {
132        for e in events {
133            self.feed(call, WireItem::Data(e));
134        }
135        self.feed(call, WireItem::Done);
136    }
137
138    /// Drops the socket: every open call hears `Dropped`.
139    pub fn drop_socket(&self) {
140        let open: Vec<CallId> = self.0.borrow().sinks.keys().copied().collect();
141        for id in open {
142            self.feed(id, WireItem::Dropped);
143        }
144    }
145}
146
147impl Wire for FakeWire {
148    fn open(&self, method: &str, params: Value, sink: Sink) -> CallId {
149        let mut c = self.0.borrow_mut();
150        let id = CallId(c.opened.len() as u64 + 1);
151        c.opened.push(Opened { id, method: method.into(), params });
152        c.sinks.insert(id, sink);
153        id
154    }
155    fn close(&self, call: CallId) {
156        let mut c = self.0.borrow_mut();
157        c.sinks.remove(&call);
158        if !c.closed.contains(&call) {
159            c.closed.push(call);
160        }
161    }
162}
163
164#[cfg(all(target_arch = "wasm32", feature = "dom"))]
165pub mod ws;