Skip to main content

logicaffeine_system/
relay.rs

1//! Thin WebSocket relay — the v1 browser↔mesh bridge.
2//!
3//! A browser tab cannot open a raw socket or `listen`; its only outbound P2P
4//! primitive is a WebSocket. So a browser peer reaches the world through a relay:
5//! a plain WS server that a browser dials and that forwards its pub/sub traffic.
6//! This is deliberately *thin* — it carries no libp2p stack into the browser. The
7//! browser speaks the same [`RelayFrame`] wire protocol over `web-sys`/`gloo-net`
8//! WebSocket; this module is the native server + a native client (used for tests
9//! and native-to-native links).
10//!
11//! "Native servers are their own relays": any native node runs `serve_bridged`
12//! beside its mesh, which cross-forwards the relay's topics with the libp2p
13//! gossipsub mesh — so a browser that dials a native node is injected
14//! straight into the real mesh, and mesh traffic flows back out to the browser.
15//! The pure hub ([`serve`]) is the browser↔browser path and is fully testable
16//! without a live mesh; the gossip bridge adds browser↔native.
17
18#![cfg(all(not(target_arch = "wasm32"), feature = "relay"))]
19
20use std::collections::HashMap;
21use std::net::SocketAddr;
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::sync::Arc;
24
25use futures::{SinkExt, StreamExt};
26use tokio::net::{TcpListener, TcpStream};
27use tokio::sync::{mpsc, Mutex};
28use tokio_tungstenite::tungstenite::Message;
29
30pub use crate::relay_proto::RelayFrame;
31
32/// Wrap a frame as a WebSocket binary message / read one back.
33fn encode(frame: &RelayFrame) -> Message {
34    Message::Binary(frame.to_bytes())
35}
36fn decode(bytes: &[u8]) -> Option<RelayFrame> {
37    RelayFrame::from_bytes(bytes)
38}
39
40type ConnId = u64;
41
42/// The relay's routing table: topic → the subscribed connections' outboxes.
43/// `gossip_out`, when present, carries a WS client's publishes outward to the
44/// libp2p mesh (the bridged mode); inbound mesh messages re-enter via
45/// [`Hub::deliver`], which is local-only so there is no echo back to the mesh.
46#[derive(Clone)]
47struct Hub {
48    inner: Arc<Mutex<HashMap<String, Vec<(ConnId, mpsc::UnboundedSender<RelayFrame>)>>>>,
49    gossip_out: Option<mpsc::UnboundedSender<(String, Vec<u8>)>>,
50}
51
52impl Hub {
53    fn new(gossip_out: Option<mpsc::UnboundedSender<(String, Vec<u8>)>>) -> Self {
54        Hub {
55            inner: Arc::new(Mutex::new(HashMap::new())),
56            gossip_out,
57        }
58    }
59
60    async fn subscribe(&self, conn: ConnId, topic: String, tx: mpsc::UnboundedSender<RelayFrame>) {
61        let mut map = self.inner.lock().await;
62        let subs = map.entry(topic).or_default();
63        if !subs.iter().any(|(c, _)| *c == conn) {
64            subs.push((conn, tx));
65        }
66    }
67
68    async fn unsubscribe(&self, conn: ConnId, topic: &str) {
69        let mut map = self.inner.lock().await;
70        if let Some(subs) = map.get_mut(topic) {
71            subs.retain(|(c, _)| *c != conn);
72        }
73    }
74
75    /// Deliver `data` to every connection subscribed to `topic` (LOCAL ONLY),
76    /// optionally skipping the originating connection `except` so a publisher does
77    /// not receive its own message (standard pub/sub, and what keeps a CRDT from
78    /// double-counting its own `Sync`). Dead outboxes are pruned; returns how many
79    /// subscribers received it.
80    async fn deliver_except(&self, topic: &str, data: &[u8], except: Option<ConnId>) -> usize {
81        let mut map = self.inner.lock().await;
82        let Some(subs) = map.get_mut(topic) else {
83            return 0;
84        };
85        let event = RelayFrame::Event {
86            topic: topic.to_string(),
87            data: data.to_vec(),
88        };
89        subs.retain(|(conn, tx)| {
90            if Some(*conn) == except {
91                return true; // keep the subscription, just don't echo to it
92            }
93            tx.send(event.clone()).is_ok()
94        });
95        subs.iter()
96            .filter(|(conn, _)| Some(*conn) != except)
97            .count()
98    }
99
100    /// Deliver to every subscriber (no skip) — the inbound path (a mesh message or
101    /// a server-side `inject`), which must not re-emit to the mesh.
102    async fn deliver(&self, topic: &str, data: &[u8]) -> usize {
103        self.deliver_except(topic, data, None).await
104    }
105
106    /// A WS client's publish: deliver to local subscribers (except the publisher)
107    /// AND, when bridged, forward to the libp2p mesh so native peers receive it.
108    async fn publish(&self, topic: &str, data: &[u8], from: ConnId) -> usize {
109        if let Some(gossip) = &self.gossip_out {
110            let _ = gossip.send((topic.to_string(), data.to_vec()));
111        }
112        self.deliver_except(topic, data, Some(from)).await
113    }
114
115    async fn drop_conn(&self, conn: ConnId) {
116        let mut map = self.inner.lock().await;
117        for subs in map.values_mut() {
118            subs.retain(|(c, _)| *c != conn);
119        }
120    }
121}
122
123/// A running relay server. Dropping the handle aborts the accept loop.
124pub struct RelayServer {
125    addr: SocketAddr,
126    hub: Hub,
127    accept: tokio::task::JoinHandle<()>,
128}
129
130impl RelayServer {
131    /// The bound address (resolve `127.0.0.1:0` to its actual port for clients).
132    pub fn addr(&self) -> SocketAddr {
133        self.addr
134    }
135
136    /// The `ws://…` URL a client dials.
137    pub fn url(&self) -> String {
138        format!("ws://{}", self.addr)
139    }
140
141    /// Inject a message into the relay from the server side — local delivery
142    /// only (no re-emit to the mesh), the hook the gossip bridge uses to forward
143    /// a received mesh message to local WS subscribers.
144    pub async fn inject(&self, topic: &str, data: &[u8]) -> usize {
145        self.hub.deliver(topic, data).await
146    }
147}
148
149impl Drop for RelayServer {
150    fn drop(&mut self) {
151        self.accept.abort();
152    }
153}
154
155/// Start a relay (a pure WebSocket pub/sub hub) on `addr` (e.g. `127.0.0.1:0`).
156/// This is the browser↔browser-via-relay path and needs no mesh.
157pub async fn serve(addr: &str) -> std::io::Result<RelayServer> {
158    serve_inner(addr, Hub::new(None)).await
159}
160
161/// Start a relay that is **bridged to the libp2p gossipsub mesh** — "a native
162/// server being its own relay". A WS client's publish is also gossiped to native
163/// peers, and mesh messages on `topics` are injected to WS subscribers. The
164/// browser dials this node's WS port and is thereby joined to the real mesh.
165///
166/// Requires a running mesh node ([`crate::network::MeshNode`]); without one the
167/// bridge tasks simply see no mesh traffic and it degrades to a local hub.
168///
169/// Only available with the `networking` feature (the gossip mesh it bridges to).
170#[cfg(feature = "networking")]
171pub async fn serve_bridged(addr: &str, topics: Vec<String>) -> std::io::Result<RelayServer> {
172    // Outbound: WS publishes → mesh. A pump task drains the channel and gossips.
173    let (gtx, mut grx) = mpsc::unbounded_channel::<(String, Vec<u8>)>();
174    let server = serve_inner(addr, Hub::new(Some(gtx))).await?;
175    tokio::spawn(async move {
176        while let Some((topic, data)) = grx.recv().await {
177            let _ = crate::network::gossip::publish_raw(&topic, data).await;
178        }
179    });
180    // Inbound: subscribe to each mesh topic; forward received messages to local
181    // WS subscribers via `deliver` (local-only ⇒ no echo back to the mesh).
182    for topic in topics {
183        let hub = server.hub.clone();
184        let mut rx = crate::network::gossip::subscribe(&topic).await;
185        tokio::spawn(async move {
186            while let Some(data) = rx.recv().await {
187                hub.deliver(&topic, &data).await;
188            }
189        });
190    }
191    Ok(server)
192}
193
194async fn serve_inner(addr: &str, hub: Hub) -> std::io::Result<RelayServer> {
195    let listener = TcpListener::bind(addr).await?;
196    let addr = listener.local_addr()?;
197    let hub_for_loop = hub.clone();
198    let next_id = Arc::new(AtomicU64::new(0));
199    let accept = tokio::spawn(async move {
200        while let Ok((stream, _peer)) = listener.accept().await {
201            let hub = hub_for_loop.clone();
202            let id = next_id.fetch_add(1, Ordering::Relaxed);
203            tokio::spawn(async move {
204                let _ = handle_conn(stream, hub, id).await;
205            });
206        }
207    });
208    Ok(RelayServer { addr, hub, accept })
209}
210
211async fn handle_conn(stream: TcpStream, hub: Hub, id: ConnId) -> Result<(), ()> {
212    let ws = tokio_tungstenite::accept_async(stream)
213        .await
214        .map_err(|_| ())?;
215    run_conn(ws, hub, id).await;
216    Ok(())
217}
218
219/// The pub/sub protocol loop, over ANY already-framing-ready WebSocket stream — the one
220/// implementation both [`handle_conn`] (which does its own handshake on a raw TCP connection to
221/// this module's own listener) and [`RelayHub::accept`] (which takes over a stream an EMBEDDING
222/// server already upgraded) run once framing is ready. Subscribe/unsubscribe/publish and the
223/// per-connection outbox writer pump are exactly the same either way — a WebSocket frame carries
224/// no memory of who answered its handshake.
225async fn run_conn<S>(ws: tokio_tungstenite::WebSocketStream<S>, hub: Hub, id: ConnId)
226where
227    S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
228{
229    let (mut write, mut read) = ws.split();
230
231    // Per-connection outbox: the hub pushes Events/SubAcks here; a writer pump
232    // forwards them to the socket.
233    let (out_tx, mut out_rx) = mpsc::unbounded_channel::<RelayFrame>();
234    let writer = tokio::spawn(async move {
235        while let Some(frame) = out_rx.recv().await {
236            if write.send(encode(&frame)).await.is_err() {
237                break;
238            }
239        }
240    });
241
242    while let Some(Ok(msg)) = read.next().await {
243        let bytes = match msg {
244            Message::Binary(b) => b,
245            Message::Text(t) => t.into_bytes(),
246            Message::Close(_) => break,
247            _ => continue,
248        };
249        let Some(frame) = decode(&bytes) else {
250            continue;
251        };
252        match frame {
253            RelayFrame::Subscribe { topic } => {
254                hub.subscribe(id, topic.clone(), out_tx.clone()).await;
255                let _ = out_tx.send(RelayFrame::SubAck { topic });
256            }
257            RelayFrame::Unsubscribe { topic } => hub.unsubscribe(id, &topic).await,
258            RelayFrame::Publish { topic, data } => {
259                hub.publish(&topic, &data, id).await;
260            }
261            // Server→client frames are never received from a client.
262            RelayFrame::SubAck { .. } | RelayFrame::Event { .. } => {}
263        }
264    }
265
266    hub.drop_conn(id).await;
267    writer.abort();
268}
269
270/// A `Hub` with no listener of its own — for embedding inside ANOTHER server's accept loop
271/// (`largo serve`'s `/_relay` upgrade, registered on `logicaffeine_system::http::server`'s
272/// shared loop, or a compiled full-stack binary's own `Serve`). [`serve`] is bind-a-listener plus
273/// exactly this; the pub/sub semantics — subscribe, publish (never echoed to the publisher),
274/// unsubscribe on drop — are the identical `Hub` either way.
275#[derive(Clone)]
276pub struct RelayHub {
277    hub: Hub,
278    next_id: Arc<AtomicU64>,
279}
280
281impl Default for RelayHub {
282    fn default() -> Self {
283        Self::new()
284    }
285}
286
287impl RelayHub {
288    /// A hub with no bridge to the libp2p mesh — the browser↔browser-via-relay path, the same
289    /// pub/sub [`serve`] itself runs.
290    pub fn new() -> Self {
291        RelayHub {
292            hub: Hub::new(None),
293            next_id: Arc::new(AtomicU64::new(0)),
294        }
295    }
296
297    /// Take over an ALREADY-UPGRADED stream: the embedding server has already answered the
298    /// client's `101 Switching Protocols` off a request it parsed itself — `prefix` is whatever
299    /// bytes it had already read past that request (almost always empty; a client waits for the
300    /// `101` before framing its first message). Runs the connection's pub/sub loop until it
301    /// closes. Spawns nothing itself — the caller decides whether to await it inline or spawn it,
302    /// exactly the choice an embedding accept loop already makes for an ordinary connection.
303    pub async fn accept(&self, stream: TcpStream, prefix: Vec<u8>) {
304        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
305        let ws = tokio_tungstenite::WebSocketStream::from_raw_socket(
306            PrefixedStream::new(prefix, stream),
307            tokio_tungstenite::tungstenite::protocol::Role::Server,
308            None,
309        )
310        .await;
311        run_conn(ws, self.hub.clone(), id).await;
312    }
313
314    /// This hub as the upgrade table a server registers: [`RELAY_PATH`], the one path every LOGOS
315    /// page dials for `Publish`, `When a message arrives` and a `shared on` store.
316    #[cfg(feature = "http")]
317    pub fn upgrades(&self) -> Vec<(&'static str, crate::http::server::UpgradeHandler)> {
318        let hub = self.clone();
319        let handler: crate::http::server::UpgradeHandler = Arc::new(move |stream, prefix| {
320            let hub = hub.clone();
321            Box::pin(async move { hub.accept(stream, prefix).await })
322        });
323        vec![(RELAY_PATH, handler)]
324    }
325}
326
327/// The path a page's relay connection dials on the server that served it.
328pub const RELAY_PATH: &str = "/_relay";
329
330/// A stream that reads `prefix` before it reads anything from `inner` — writes always go straight
331/// to `inner`. The wrapper an already-upgraded WebSocket stream needs when a caller handed over a
332/// few bytes read past the HTTP request it parsed, so those bytes are not lost to the framing that
333/// begins right where the HTTP parse left off.
334struct PrefixedStream {
335    prefix: Vec<u8>,
336    at: usize,
337    inner: TcpStream,
338}
339
340impl PrefixedStream {
341    fn new(prefix: Vec<u8>, inner: TcpStream) -> Self {
342        PrefixedStream {
343            prefix,
344            at: 0,
345            inner,
346        }
347    }
348}
349
350impl tokio::io::AsyncRead for PrefixedStream {
351    fn poll_read(
352        self: std::pin::Pin<&mut Self>,
353        cx: &mut std::task::Context<'_>,
354        buf: &mut tokio::io::ReadBuf<'_>,
355    ) -> std::task::Poll<std::io::Result<()>> {
356        let this = self.get_mut();
357        if this.at < this.prefix.len() {
358            let take = (this.prefix.len() - this.at).min(buf.remaining());
359            buf.put_slice(&this.prefix[this.at..this.at + take]);
360            this.at += take;
361            return std::task::Poll::Ready(Ok(()));
362        }
363        std::pin::Pin::new(&mut this.inner).poll_read(cx, buf)
364    }
365}
366
367impl tokio::io::AsyncWrite for PrefixedStream {
368    fn poll_write(
369        self: std::pin::Pin<&mut Self>,
370        cx: &mut std::task::Context<'_>,
371        buf: &[u8],
372    ) -> std::task::Poll<std::io::Result<usize>> {
373        std::pin::Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
374    }
375    fn poll_flush(
376        self: std::pin::Pin<&mut Self>,
377        cx: &mut std::task::Context<'_>,
378    ) -> std::task::Poll<std::io::Result<()>> {
379        std::pin::Pin::new(&mut self.get_mut().inner).poll_flush(cx)
380    }
381    fn poll_shutdown(
382        self: std::pin::Pin<&mut Self>,
383        cx: &mut std::task::Context<'_>,
384    ) -> std::task::Poll<std::io::Result<()>> {
385        std::pin::Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)
386    }
387}
388
389/// A native relay client — and the reference for what the browser does over
390/// `web-sys` WebSocket with the same [`RelayFrame`] protocol.
391pub struct RelayClient {
392    out: mpsc::UnboundedSender<RelayFrame>,
393    events: mpsc::UnboundedReceiver<RelayFrame>,
394    acks: mpsc::UnboundedReceiver<String>,
395    _pump: tokio::task::JoinHandle<()>,
396}
397
398impl RelayClient {
399    /// Dial a relay at `url` (`ws://host:port`).
400    pub async fn connect(url: &str) -> Result<RelayClient, String> {
401        let (ws, _) = tokio_tungstenite::connect_async(url)
402            .await
403            .map_err(|e| format!("relay dial failed: {e}"))?;
404        let (mut write, mut read) = ws.split();
405
406        let (out_tx, mut out_rx) = mpsc::unbounded_channel::<RelayFrame>();
407        let (ev_tx, ev_rx) = mpsc::unbounded_channel::<RelayFrame>();
408        let (ack_tx, ack_rx) = mpsc::unbounded_channel::<String>();
409
410        // One pump task owns the socket: it writes outgoing frames and routes
411        // incoming frames to the events / acks channels.
412        let pump = tokio::spawn(async move {
413            loop {
414                tokio::select! {
415                    out = out_rx.recv() => match out {
416                        Some(frame) => {
417                            if write.send(encode(&frame)).await.is_err() { break; }
418                        }
419                        None => break,
420                    },
421                    inb = read.next() => match inb {
422                        Some(Ok(Message::Binary(b))) => {
423                            if let Some(frame) = decode(&b) {
424                                match frame {
425                                    RelayFrame::SubAck { topic } => { let _ = ack_tx.send(topic); }
426                                    ev @ RelayFrame::Event { .. } => { let _ = ev_tx.send(ev); }
427                                    _ => {}
428                                }
429                            }
430                        }
431                        Some(Ok(Message::Close(_))) | None => break,
432                        Some(Ok(_)) => {}
433                        Some(Err(_)) => break,
434                    },
435                }
436            }
437        });
438
439        Ok(RelayClient {
440            out: out_tx,
441            events: ev_rx,
442            acks: ack_rx,
443            _pump: pump,
444        })
445    }
446
447    /// Subscribe to `topic` and await the relay's acknowledgement, so a
448    /// subsequent publish from anyone cannot race ahead of the registration.
449    pub async fn subscribe(&mut self, topic: &str) -> Result<(), String> {
450        self.out
451            .send(RelayFrame::Subscribe {
452                topic: topic.to_string(),
453            })
454            .map_err(|_| "relay connection closed".to_string())?;
455        loop {
456            match self.acks.recv().await {
457                Some(t) if t == topic => return Ok(()),
458                Some(_) => continue,
459                None => return Err("relay closed before subscribe ack".to_string()),
460            }
461        }
462    }
463
464    /// Publish `data` to `topic`.
465    pub fn publish(&self, topic: &str, data: Vec<u8>) -> Result<(), String> {
466        self.out
467            .send(RelayFrame::Publish {
468                topic: topic.to_string(),
469                data,
470            })
471            .map_err(|_| "relay connection closed".to_string())
472    }
473
474    /// Await the next event delivered for a subscribed topic.
475    pub async fn next_event(&mut self) -> Option<(String, Vec<u8>)> {
476        match self.events.recv().await {
477            Some(RelayFrame::Event { topic, data }) => Some((topic, data)),
478            _ => None,
479        }
480    }
481
482    /// Drain every event delivered so far WITHOUT blocking — the non-blocking
483    /// "drain at a sync point" primitive the interpreter's `Sync` uses.
484    pub fn drain_events(&mut self) -> Vec<(String, Vec<u8>)> {
485        let mut out = Vec::new();
486        while let Ok(RelayFrame::Event { topic, data }) = self.events.try_recv() {
487            out.push((topic, data));
488        }
489        out
490    }
491}
492
493#[cfg(test)]
494#[path = "../../logicaffeine_tests/unit/logicaffeine_system/relay/tests.rs"]
495mod tests;