Skip to main content

qualia_client_core/wellfair/
sync_relay_server.rs

1//! A minimal HTTP relay for the sync transport (T3.1) — the server counterpart to
2//! [`HttpRelayTransport`](super::sync_transport::HttpRelayTransport).
3//!
4//! A **dumb op bus**: it stores published operations (append-only, dedup by operation id) and serves
5//! pulls from a cursor. It does **no validation** — trust is the receiving node's inbox
6//! ([`validate_operation`](super::sync_protocol::validate_operation)), so a compromised relay can
7//! only ever cause rejections, never admission of bad data. Peers rendezvous through it.
8//!
9//! Endpoints:
10//! - `POST /sync/publish` — body `{"ops":[...]}`; stores new ops, returns `{"ops":[]}`.
11//! - `GET  /sync/pull?since={n}` — returns `{"ops":[...]}` for ops at index `>= n` (relay order).
12//!
13//! Native-only (`tiny_http`). Runs a background accept loop with graceful shutdown on drop.
14#![cfg(not(target_arch = "wasm32"))]
15
16use std::net::SocketAddr;
17use std::sync::atomic::{AtomicBool, Ordering};
18use std::sync::{Arc, Mutex};
19use std::thread::JoinHandle;
20use std::time::Duration;
21
22use tiny_http::{Header, Method, Request, Response, Server};
23
24use super::sync_protocol::SyncOperation;
25use super::sync_transport::SyncOpsBody;
26
27type OpStore = Arc<Mutex<Vec<SyncOperation>>>;
28
29/// A running relay. Stop it explicitly with [`SyncRelayServer::stop`] or let `Drop` do it.
30pub struct SyncRelayServer {
31    addr: SocketAddr,
32    shutdown: Arc<AtomicBool>,
33    handle: Option<JoinHandle<()>>,
34    store: OpStore,
35}
36
37impl SyncRelayServer {
38    /// Bind and start the relay. Use `"127.0.0.1:0"` for an OS-assigned port; read the bound
39    /// address back via [`SyncRelayServer::addr`] / [`SyncRelayServer::base_url`].
40    pub fn start(bind: &str) -> Result<Self, String> {
41        let server = Server::http(bind).map_err(|e| e.to_string())?;
42        let addr = server
43            .server_addr()
44            .to_ip()
45            .ok_or_else(|| "relay bound to a non-IP address".to_string())?;
46        let shutdown = Arc::new(AtomicBool::new(false));
47        let store: OpStore = Arc::new(Mutex::new(Vec::new()));
48        let server = Arc::new(server);
49
50        let handle = {
51            let shutdown = shutdown.clone();
52            let store = store.clone();
53            let server = server.clone();
54            std::thread::spawn(move || loop {
55                if shutdown.load(Ordering::Relaxed) {
56                    break;
57                }
58                match server.recv_timeout(Duration::from_millis(100)) {
59                    Ok(Some(req)) => handle_request(req, &store),
60                    Ok(None) => continue, // timeout — re-check the shutdown flag
61                    Err(_) => break,
62                }
63            })
64        };
65
66        Ok(Self {
67            addr,
68            shutdown,
69            handle: Some(handle),
70            store,
71        })
72    }
73
74    /// Address.
75    pub fn addr(&self) -> SocketAddr {
76        self.addr
77    }
78
79    /// `base` URL.
80    pub fn base_url(&self) -> String {
81        format!("http://{}", self.addr)
82    }
83
84    /// Number of operations the relay currently holds.
85    pub fn op_count(&self) -> usize {
86        self.store.lock().map(|v| v.len()).unwrap_or(0)
87    }
88
89    /// Signal shutdown and join the accept thread.
90    pub fn stop(&mut self) {
91        self.shutdown.store(true, Ordering::Relaxed);
92        if let Some(h) = self.handle.take() {
93            let _ = h.join();
94        }
95    }
96}
97
98impl Drop for SyncRelayServer {
99    fn drop(&mut self) {
100        self.stop();
101    }
102}
103
104fn json_response(code: u16, body: &SyncOpsBody) -> Response<std::io::Cursor<Vec<u8>>> {
105    let json = serde_json::to_string(body).unwrap_or_else(|_| "{\"ops\":[]}".to_string());
106    let header = Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..])
107        .expect("static header is valid");
108    Response::from_string(json)
109        .with_status_code(code)
110        .with_header(header)
111}
112
113fn text_response(code: u16, msg: &str) -> Response<std::io::Cursor<Vec<u8>>> {
114    Response::from_string(msg).with_status_code(code)
115}
116
117fn parse_since(query: &str) -> u64 {
118    query
119        .split('&')
120        .find_map(|kv| kv.strip_prefix("since="))
121        .and_then(|v| v.parse().ok())
122        .unwrap_or(0)
123}
124
125fn handle_request(mut req: Request, store: &OpStore) {
126    let method = req.method().clone();
127    let url = req.url().to_string();
128    let (path, query) = url.split_once('?').unwrap_or((url.as_str(), ""));
129
130    // Read the body up front (for POST) so the mutable borrow is released before responding.
131    let mut body = String::new();
132    if method == Method::Post {
133        let _ = req.as_reader().read_to_string(&mut body);
134    }
135
136    let response = match (&method, path) {
137        (Method::Post, "/sync/publish") => match serde_json::from_str::<SyncOpsBody>(&body) {
138            Ok(parsed) => {
139                if let Ok(mut s) = store.lock() {
140                    for op in parsed.ops {
141                        if !s.iter().any(|e| e.operation_id == op.operation_id) {
142                            s.push(op);
143                        }
144                    }
145                }
146                json_response(200, &SyncOpsBody { ops: Vec::new() })
147            }
148            Err(e) => text_response(400, &format!("bad json: {e}")),
149        },
150        (Method::Get, "/sync/pull") => {
151            let since = parse_since(query);
152            let ops = store
153                .lock()
154                .map(|s| {
155                    let start = (since as usize).min(s.len());
156                    s[start..].to_vec()
157                })
158                .unwrap_or_default();
159            json_response(200, &SyncOpsBody { ops })
160        }
161        _ => text_response(404, "not found"),
162    };
163
164    let _ = req.respond(response);
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use crate::wellfair::sync_protocol::SyncOperation;
171    use crate::wellfair::sync_transport::{HttpRelayTransport, SyncTransport};
172
173    fn signed(id: &str, summary: &str, lamport: u64) -> SyncOperation {
174        SyncOperation::new(
175            id,
176            format!("urn:wellfair:ledger_entry:{id}"),
177            "ledger_entry",
178            "did:wf:remote",
179            "Restricted",
180            summary,
181            lamport,
182            1_700_000_000,
183        )
184        .with_signature("deadbeef")
185    }
186
187    #[test]
188    fn http_transport_round_trips_through_the_relay() {
189        let server = SyncRelayServer::start("127.0.0.1:0").expect("relay starts");
190        let base = server.base_url();
191
192        let node_a = HttpRelayTransport::new(&base);
193        let node_b = HttpRelayTransport::new(&base);
194
195        node_a
196            .publish(&[signed("x", "1", 1), signed("y", "2", 2)])
197            .expect("publish");
198        // A second node pulls what A published, over real HTTP.
199        let pulled = node_b.pull(0).expect("pull");
200        assert_eq!(pulled.len(), 2);
201        assert_eq!(pulled[0].operation_id, "x");
202        assert_eq!(server.op_count(), 2);
203
204        // Cursor works: nothing new after index 2.
205        assert!(node_b.pull(2).expect("pull cursor").is_empty());
206
207        // Dedup at the relay: re-publishing 'x' does not grow the store.
208        node_a.publish(&[signed("x", "1", 1)]).expect("republish");
209        assert_eq!(server.op_count(), 2);
210    }
211}