Skip to main content

logicaffeine_system/
net.rs

1//! `Net` — the cross-target relay-backed network handle the interpreter holds.
2//!
3//! One API, two transports selected at compile time: native dials with the async
4//! [`crate::relay::RelayClient`]; the browser dials with the callback-based
5//! `crate::relay_browser::RelayBrowserClient`. Both speak the same `RelayFrame`
6//! protocol to the same relay, so the interpreter's `Sync`/`Connect` lowering is
7//! written once and runs on both targets. This is the platform-capability seam
8//! for networking, the analogue of `get_platform_vfs()` for files.
9//!
10//! Events are drained, not awaited: the interpreter's `Sync` is a *sync point*
11//! (publish local state, then merge whatever has arrived) — [`Net::drain`] returns
12//! the pending messages without blocking, which keeps the tree-walker's linear
13//! execution model intact (no background task mutating the environment).
14
15#![cfg(any(
16    all(not(target_arch = "wasm32"), feature = "relay"),
17    target_arch = "wasm32"
18))]
19
20#[cfg(all(not(target_arch = "wasm32"), feature = "relay"))]
21mod imp {
22    use crate::relay::RelayClient;
23
24    /// Native relay handle (async `tokio-tungstenite` client).
25    pub struct Net {
26        client: RelayClient,
27    }
28
29    impl Net {
30        pub async fn connect(url: &str) -> Result<Net, String> {
31            Ok(Net {
32                client: RelayClient::connect(url).await?,
33            })
34        }
35
36        pub async fn subscribe(&mut self, topic: &str) -> Result<(), String> {
37            self.client.subscribe(topic).await
38        }
39
40        pub fn publish(&self, topic: &str, data: Vec<u8>) -> Result<(), String> {
41            self.client.publish(topic, data)
42        }
43
44        /// Non-blocking: every message delivered since the last drain.
45        pub fn drain(&mut self) -> Vec<(String, Vec<u8>)> {
46            self.client.drain_events()
47        }
48    }
49}
50
51#[cfg(target_arch = "wasm32")]
52mod imp {
53    use std::cell::RefCell;
54    use std::collections::VecDeque;
55    use std::rc::Rc;
56
57    use crate::relay_browser::RelayBrowserClient;
58
59    /// Browser relay handle (`web-sys` WebSocket). Received events are pushed onto
60    /// a queue by the socket callback; `drain` empties it.
61    pub struct Net {
62        client: RelayBrowserClient,
63        events: Rc<RefCell<VecDeque<(String, Vec<u8>)>>>,
64    }
65
66    impl Net {
67        pub async fn connect(url: &str) -> Result<Net, String> {
68            let (open_tx, open_rx) = futures::channel::oneshot::channel::<()>();
69            let open_tx = Rc::new(RefCell::new(Some(open_tx)));
70            let events = Rc::new(RefCell::new(VecDeque::new()));
71
72            let opener = open_tx.clone();
73            let queue = events.clone();
74            let client = RelayBrowserClient::connect(
75                url,
76                move || {
77                    if let Some(tx) = opener.borrow_mut().take() {
78                        let _ = tx.send(());
79                    }
80                },
81                move |topic, data| queue.borrow_mut().push_back((topic, data)),
82            )
83            .map_err(|e| format!("relay connect failed: {e:?}"))?;
84
85            open_rx
86                .await
87                .map_err(|_| "socket closed before it opened".to_string())?;
88            Ok(Net { client, events })
89        }
90
91        pub async fn subscribe(&mut self, topic: &str) -> Result<(), String> {
92            // The browser socket is ordered, so a following publish cannot race
93            // the subscribe; no SubAck round-trip is needed.
94            self.client
95                .subscribe(topic)
96                .map_err(|e| format!("subscribe failed: {e:?}"))
97        }
98
99        pub fn publish(&self, topic: &str, data: Vec<u8>) -> Result<(), String> {
100            self.client
101                .publish(topic, data)
102                .map_err(|e| format!("publish failed: {e:?}"))
103        }
104
105        pub fn drain(&mut self) -> Vec<(String, Vec<u8>)> {
106            self.events.borrow_mut().drain(..).collect()
107        }
108    }
109}
110
111pub use imp::Net;