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    Refused(String),
28    /// The call failed under the transport — never sent (the socket not
29    /// open), or a frame it could not read: its words. A reconnect re-opens
30    /// what the engine still wants.
31    Failed(String),
32    /// FRAME-37: the socket dropped under the call (plexus-client's
33    /// `Closed`); a reconnect re-opens what the engine still wants.
34    Dropped,
35}
36
37/// Where a call's items go.
38pub type Sink = Box<dyn FnMut(WireItem)>;
39
40/// The wire: the page's one socket.
41pub trait Wire {
42    /// Calls `method` (`tickets.list`) with `params`, its items into `sink`.
43    fn open(&self, method: &str, params: Value, sink: Sink) -> CallId;
44    /// Stops the call (an unsubscribe); its sink hears nothing more.
45    fn close(&self, call: CallId);
46}
47
48impl<W: Wire + ?Sized> Wire for std::rc::Rc<W> {
49    fn open(&self, method: &str, params: Value, sink: Sink) -> CallId {
50        (**self).open(method, params, sink)
51    }
52    fn close(&self, call: CallId) {
53        (**self).close(call)
54    }
55}
56
57/// One call [`FakeWire`] saw.
58#[derive(Debug, Clone, PartialEq)]
59pub struct Opened {
60    pub id: CallId,
61    pub method: String,
62    pub params: Value,
63}
64
65/// The tests' wire: records each open and close; the test feeds a call's
66/// sink with [`FakeWire::feed`].
67#[derive(Clone, Default)]
68pub struct FakeWire(std::rc::Rc<std::cell::RefCell<Calls>>);
69
70#[derive(Default)]
71struct Calls {
72    opened: Vec<Opened>,
73    closed: Vec<CallId>,
74    sinks: std::collections::BTreeMap<CallId, Sink>,
75}
76
77impl std::fmt::Debug for FakeWire {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        let c = self.0.borrow();
80        write!(f, "FakeWire({} opened, {} closed)", c.opened.len(), c.closed.len())
81    }
82}
83
84impl FakeWire {
85    pub fn new() -> Self {
86        Self::default()
87    }
88
89    /// Every call opened, in order.
90    pub fn opened(&self) -> Vec<Opened> {
91        self.0.borrow().opened.clone()
92    }
93
94    /// The calls of `method` opened, in order.
95    pub fn opened_of(&self, method: &str) -> Vec<Opened> {
96        self.opened().into_iter().filter(|o| o.method == method).collect()
97    }
98
99    /// The latest call of `method`; panics naming it when none was opened.
100    pub fn last_of(&self, method: &str) -> CallId {
101        self.opened_of(method).last().unwrap_or_else(|| panic!("no call of {method} was opened")).id
102    }
103
104    /// Every call closed, in order.
105    pub fn closed(&self) -> Vec<CallId> {
106        self.0.borrow().closed.clone()
107    }
108
109    /// The calls open now.
110    pub fn open_now(&self) -> Vec<Opened> {
111        let closed = self.closed();
112        self.opened().into_iter().filter(|o| !closed.contains(&o.id)).collect()
113    }
114
115    /// Hands `item` to `call`'s sink (nothing, once it is closed). The sink
116    /// runs outside the wire's borrow, so it may open or close calls.
117    pub fn feed(&self, call: CallId, item: WireItem) {
118        let Some(mut sink) = self.0.borrow_mut().sinks.remove(&call) else { return };
119        let ends = matches!(item, WireItem::Done | WireItem::Refused(_) | WireItem::Failed(_) | WireItem::Dropped);
120        sink(item);
121        let mut c = self.0.borrow_mut();
122        if !ends && !c.closed.contains(&call) {
123            c.sinks.insert(call, sink);
124        }
125    }
126
127    /// Hands each data event to `call`'s sink, then `Done`.
128    pub fn answer(&self, call: CallId, events: impl IntoIterator<Item = Value>) {
129        for e in events {
130            self.feed(call, WireItem::Data(e));
131        }
132        self.feed(call, WireItem::Done);
133    }
134
135    /// Drops the socket: every open call hears `Dropped`.
136    pub fn drop_socket(&self) {
137        let open: Vec<CallId> = self.0.borrow().sinks.keys().copied().collect();
138        for id in open {
139            self.feed(id, WireItem::Dropped);
140        }
141    }
142}
143
144impl Wire for FakeWire {
145    fn open(&self, method: &str, params: Value, sink: Sink) -> CallId {
146        let mut c = self.0.borrow_mut();
147        let id = CallId(c.opened.len() as u64 + 1);
148        c.opened.push(Opened { id, method: method.into(), params });
149        c.sinks.insert(id, sink);
150        id
151    }
152    fn close(&self, call: CallId) {
153        let mut c = self.0.borrow_mut();
154        c.sinks.remove(&call);
155        if !c.closed.contains(&call) {
156            c.closed.push(call);
157        }
158    }
159}
160
161#[cfg(all(target_arch = "wasm32", feature = "dom"))]
162pub mod ws;