1#![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
32fn 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#[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 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; }
93 tx.send(event.clone()).is_ok()
94 });
95 subs.iter()
96 .filter(|(conn, _)| Some(*conn) != except)
97 .count()
98 }
99
100 async fn deliver(&self, topic: &str, data: &[u8]) -> usize {
103 self.deliver_except(topic, data, None).await
104 }
105
106 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
123pub struct RelayServer {
125 addr: SocketAddr,
126 hub: Hub,
127 accept: tokio::task::JoinHandle<()>,
128}
129
130impl RelayServer {
131 pub fn addr(&self) -> SocketAddr {
133 self.addr
134 }
135
136 pub fn url(&self) -> String {
138 format!("ws://{}", self.addr)
139 }
140
141 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
155pub async fn serve(addr: &str) -> std::io::Result<RelayServer> {
158 serve_inner(addr, Hub::new(None)).await
159}
160
161#[cfg(feature = "networking")]
171pub async fn serve_bridged(addr: &str, topics: Vec<String>) -> std::io::Result<RelayServer> {
172 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 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
219async 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 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 RelayFrame::SubAck { .. } | RelayFrame::Event { .. } => {}
263 }
264 }
265
266 hub.drop_conn(id).await;
267 writer.abort();
268}
269
270#[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 pub fn new() -> Self {
291 RelayHub {
292 hub: Hub::new(None),
293 next_id: Arc::new(AtomicU64::new(0)),
294 }
295 }
296
297 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 #[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
327pub const RELAY_PATH: &str = "/_relay";
329
330struct 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
389pub 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 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 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 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 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 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 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;