qualia_client_core/wellfair/
sync_transport.rs1use super::sync_protocol::SyncOperation;
19use std::sync::{Arc, Mutex};
20
21pub trait SyncTransport {
23 fn publish(&self, ops: &[SyncOperation]) -> Result<(), String>;
26
27 fn pull(&self, since: u64) -> Result<Vec<SyncOperation>, String>;
30}
31
32#[derive(Clone, Default)]
35pub struct InMemoryRelay {
36 inner: Arc<Mutex<Vec<SyncOperation>>>,
37}
38
39impl InMemoryRelay {
40 pub fn new() -> Self {
42 Self::default()
43 }
44
45 pub fn len(&self) -> usize {
47 self.inner.lock().map(|v| v.len()).unwrap_or(0)
48 }
49
50 pub fn is_empty(&self) -> bool {
52 self.len() == 0
53 }
54}
55
56impl SyncTransport for InMemoryRelay {
57 fn publish(&self, ops: &[SyncOperation]) -> Result<(), String> {
58 let mut store = self
59 .inner
60 .lock()
61 .map_err(|_| "relay lock poisoned".to_string())?;
62 for op in ops {
63 if !store.iter().any(|e| e.operation_id == op.operation_id) {
64 store.push(op.clone());
65 }
66 }
67 Ok(())
68 }
69
70 fn pull(&self, since: u64) -> Result<Vec<SyncOperation>, String> {
71 let store = self
72 .inner
73 .lock()
74 .map_err(|_| "relay lock poisoned".to_string())?;
75 let start = (since as usize).min(store.len());
76 Ok(store[start..].to_vec())
77 }
78}
79
80#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
82pub struct SyncOpsBody {
83 pub ops: Vec<SyncOperation>,
84}
85
86#[cfg(not(target_arch = "wasm32"))]
89pub struct HttpRelayTransport {
90 base_url: String,
91 timeout: std::time::Duration,
92}
93
94#[cfg(not(target_arch = "wasm32"))]
95impl HttpRelayTransport {
96 pub fn new(base_url: impl Into<String>) -> Self {
98 Self {
99 base_url: base_url.into().trim_end_matches('/').to_string(),
100 timeout: std::time::Duration::from_secs(8),
101 }
102 }
103
104 fn client(&self) -> Result<reqwest::blocking::Client, String> {
105 reqwest::blocking::Client::builder()
106 .timeout(self.timeout)
107 .build()
108 .map_err(|e| e.to_string())
109 }
110}
111
112#[cfg(not(target_arch = "wasm32"))]
113impl SyncTransport for HttpRelayTransport {
114 fn publish(&self, ops: &[SyncOperation]) -> Result<(), String> {
115 let url = format!("{}/sync/publish", self.base_url);
116 let body = SyncOpsBody { ops: ops.to_vec() };
117 let resp = self
118 .client()?
119 .post(&url)
120 .json(&body)
121 .send()
122 .map_err(|e| e.to_string())?;
123 if !resp.status().is_success() {
124 return Err(format!("relay publish failed: HTTP {}", resp.status()));
125 }
126 Ok(())
127 }
128
129 fn pull(&self, since: u64) -> Result<Vec<SyncOperation>, String> {
130 let url = format!("{}/sync/pull?since={since}", self.base_url);
131 let resp = self.client()?.get(&url).send().map_err(|e| e.to_string())?;
132 if !resp.status().is_success() {
133 return Err(format!("relay pull failed: HTTP {}", resp.status()));
134 }
135 let parsed: SyncOpsBody = resp.json().map_err(|e| e.to_string())?;
136 Ok(parsed.ops)
137 }
138}
139
140#[cfg(not(target_arch = "wasm32"))]
148pub struct Libp2pSyncTransport {
149 client: qualia_core_db::p2p::sync_node::BlockingSyncClient,
150}
151
152#[cfg(not(target_arch = "wasm32"))]
153impl Libp2pSyncTransport {
154 pub fn connect(peer_id: &str, peer_addr: &str) -> Result<Self, String> {
157 let client = qualia_core_db::p2p::sync_node::BlockingSyncClient::connect(
158 qualia_core_db::p2p::sync_ops::SyncOpRelay::new(),
159 peer_id,
160 peer_addr,
161 )?;
162 Ok(Self { client })
163 }
164
165 pub fn local_peer_id(&self) -> String {
167 self.client.local_peer_id().to_string()
168 }
169}
170
171#[cfg(not(target_arch = "wasm32"))]
173fn op_to_frame(op: &SyncOperation) -> Result<Vec<u8>, String> {
174 let mut buf = Vec::new();
175 ciborium::into_writer(op, &mut buf).map_err(|e| format!("encode operation: {e}"))?;
176 Ok(buf)
177}
178
179#[cfg(not(target_arch = "wasm32"))]
180impl SyncTransport for Libp2pSyncTransport {
181 fn publish(&self, ops: &[SyncOperation]) -> Result<(), String> {
182 if ops.is_empty() {
183 return Ok(());
184 }
185 let frames = ops.iter().map(op_to_frame).collect::<Result<Vec<_>, _>>()?;
186 self.client.publish_frames(frames)?;
187 Ok(())
188 }
189
190 fn pull(&self, since: u64) -> Result<Vec<SyncOperation>, String> {
191 let (frames, _next_cursor) = self.client.pull_frames(since)?;
192 Ok(frames
195 .iter()
196 .filter_map(|f| ciborium::from_reader::<SyncOperation, _>(&f[..]).ok())
197 .collect())
198 }
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204 use crate::wellfair::sync_protocol::{AdmitOutcome, SyncInbox, SyncOperation};
205
206 fn signed(id: &str, kind: &str, summary: &str, lamport: u64) -> SyncOperation {
207 SyncOperation::new(
208 id,
209 format!("urn:wellfair:{kind}:{id}"),
210 kind,
211 "did:wf:remote",
212 "Restricted",
213 summary,
214 lamport,
215 1_700_000_000,
216 )
217 .with_signature("deadbeef")
218 }
219
220 #[test]
221 fn in_memory_relay_dedups_and_pulls_from_cursor() {
222 let relay = InMemoryRelay::new();
223 relay
224 .publish(&[signed("a", "ledger_entry", "1", 1)])
225 .unwrap();
226 relay
227 .publish(&[signed("b", "ledger_entry", "2", 2)])
228 .unwrap();
229 relay
231 .publish(&[signed("a", "ledger_entry", "1", 1)])
232 .unwrap();
233 assert_eq!(relay.len(), 2);
234
235 assert_eq!(relay.pull(0).unwrap().len(), 2);
237 assert_eq!(relay.pull(2).unwrap().len(), 0);
238 relay
239 .publish(&[signed("c", "ledger_entry", "3", 3)])
240 .unwrap();
241 let fresh = relay.pull(2).unwrap();
242 assert_eq!(fresh.len(), 1);
243 assert_eq!(fresh[0].operation_id, "c");
244 }
245
246 #[test]
247 fn two_nodes_converge_over_one_relay() {
248 let relay = InMemoryRelay::new();
251 let dir_a = tempfile::tempdir().unwrap();
252 let dir_b = tempfile::tempdir().unwrap();
253 let inbox_a = SyncInbox::open(dir_a.path()).unwrap();
254 let inbox_b = SyncInbox::open(dir_b.path()).unwrap();
255
256 let a_op = signed("a1", "contribution", "a", 1);
257 let b_op = signed("b1", "contribution", "b", 2);
258 inbox_a.admit(&a_op, 1).unwrap();
260 relay.publish(&[a_op.clone()]).unwrap();
261 inbox_b.admit(&b_op, 1).unwrap();
262 relay.publish(&[b_op.clone()]).unwrap();
263
264 for op in relay.pull(0).unwrap() {
266 inbox_a.admit(&op, 2).unwrap();
267 inbox_b.admit(&op, 2).unwrap();
268 }
269
270 let set_a = inbox_a.validated_operations().unwrap();
271 let set_b = inbox_b.validated_operations().unwrap();
272 assert_eq!(
273 set_a, set_b,
274 "nodes must converge to the same validated set"
275 );
276 assert_eq!(set_a.len(), 2);
277 }
278
279 #[test]
280 fn hostile_relay_ops_are_rejected_not_admitted() {
281 let relay = InMemoryRelay::new();
284 let dir = tempfile::tempdir().unwrap();
285 let inbox = SyncInbox::open(dir.path()).unwrap();
286
287 let mut unsigned = signed("h1", "ledger_entry", "x", 1);
289 unsigned.signature = None;
290 let mut tampered = signed("h2", "ledger_entry", "orig", 1);
292 tampered.payload_summary = "changed".into();
293 let mut bad_ver = signed("h3", "ledger_entry", "x", 1);
295 bad_ver.protocol_version = 99;
296 let mut classified = signed("h4", "sanctuary_note", "x", 1);
298 classified.sensitivity = "Classified".into();
299
300 relay
301 .publish(&[unsigned, tampered, bad_ver, classified])
302 .unwrap();
303
304 let mut rejected = 0;
305 for op in relay.pull(0).unwrap() {
306 if matches!(inbox.admit(&op, 5).unwrap(), AdmitOutcome::Rejected(_)) {
307 rejected += 1;
308 }
309 }
310 assert_eq!(rejected, 4, "all hostile ops must be rejected");
311 assert!(inbox.validated_operations().unwrap().is_empty());
312 }
313
314 #[test]
315 fn replayed_pull_is_idempotent() {
316 let relay = InMemoryRelay::new();
318 let dir = tempfile::tempdir().unwrap();
319 let inbox = SyncInbox::open(dir.path()).unwrap();
320 relay
321 .publish(&[signed("r1", "ledger_entry", "x", 1)])
322 .unwrap();
323
324 for _ in 0..3 {
325 for op in relay.pull(0).unwrap() {
326 inbox.admit(&op, 9).unwrap();
327 }
328 }
329 assert_eq!(inbox.validated_operations().unwrap().len(), 1);
330 }
331
332 #[test]
333 fn partition_then_rejoin_converges() {
334 let left = InMemoryRelay::new();
337 let right = InMemoryRelay::new();
338 left.publish(&[signed("L", "contribution", "l", 1)])
339 .unwrap();
340 right
341 .publish(&[signed("R", "contribution", "r", 2)])
342 .unwrap();
343
344 let dir_a = tempfile::tempdir().unwrap();
345 let dir_b = tempfile::tempdir().unwrap();
346 let inbox_a = SyncInbox::open(dir_a.path()).unwrap();
347 let inbox_b = SyncInbox::open(dir_b.path()).unwrap();
348
349 let mut all = left.pull(0).unwrap();
351 all.extend(right.pull(0).unwrap());
352 for op in &all {
353 inbox_a.admit(op, 1).unwrap();
354 inbox_b.admit(op, 1).unwrap();
355 }
356 assert_eq!(
357 inbox_a.validated_operations().unwrap(),
358 inbox_b.validated_operations().unwrap()
359 );
360 assert_eq!(inbox_a.validated_operations().unwrap().len(), 2);
361 }
362
363 #[cfg(not(target_arch = "wasm32"))]
368 #[test]
369 fn libp2p_transport_round_trips_real_operations_and_inbox_admits() {
370 use qualia_core_db::p2p::sync_node::Libp2pSyncNode;
371 use qualia_core_db::p2p::sync_ops::SyncOpRelay;
372
373 let rt_a = tokio::runtime::Builder::new_multi_thread()
376 .worker_threads(1)
377 .enable_all()
378 .build()
379 .unwrap();
380 let relay_a = SyncOpRelay::new();
381 let a = {
382 let _guard = rt_a.enter();
383 Libp2pSyncNode::spawn(relay_a.clone())
384 };
385 let a_addr = rt_a
386 .block_on(a.listen("/ip4/127.0.0.1/tcp/0"))
387 .expect("A listen");
388
389 let transport = Libp2pSyncTransport::connect(&a.peer_id.to_string(), &a_addr.to_string())
391 .expect("connect");
392
393 let ops = vec![
395 signed("t1", "contribution", "alpha", 1),
396 signed("t2", "contribution", "beta", 2),
397 ];
398 transport.publish(&ops).expect("publish");
399 assert_eq!(relay_a.len(), 2, "A's relay holds both op frames");
400
401 let pulled = transport.pull(0).expect("pull");
402 assert_eq!(
403 pulled, ops,
404 "operations round-trip losslessly through CBOR + libp2p"
405 );
406
407 let dir = tempfile::tempdir().unwrap();
409 let inbox = SyncInbox::open(dir.path()).unwrap();
410 for op in &pulled {
411 assert_eq!(inbox.admit(op, 1).unwrap(), AdmitOutcome::Validated);
412 }
413 assert_eq!(inbox.validated_operations().unwrap().len(), 2);
414 }
415}