Skip to main content

qualia_client_core/wellfair/api/
sync.rs

1//! Sync-operation protocol + transport
2
3use super::super::journal::JournalEntry;
4use super::super::sync_outbox::{SyncOutbox, SyncOutboxEntry, SyncOutboxState};
5use super::super::sync_protocol::{AdmitOutcome, InboxRecord, SyncInbox, SyncOperation};
6use super::super::sync_transport::SyncTransport;
7use ed25519_dalek::Signer;
8
9use super::*;
10
11impl WebizenHostApi {
12    // --- Phase 5 sync-operation protocol (SyncService, §4.2 / §9.5 / §17) ---
13
14    /// Build a signed outbound sync operation from a committed journal entry.
15    /// Returns `None` for Classified/Sanctuary records — they never enter the ordinary sync
16    /// lane (§5.2). The signature is a real ed25519 signature over the operation's bound payload.
17    pub fn build_outbound_operation(
18        &self,
19        entry: &JournalEntry,
20        lamport: u64,
21    ) -> Option<SyncOperation> {
22        if entry.sensitivity == "Classified" {
23            return None;
24        }
25        let op = SyncOperation::new(
26            uuid::Uuid::new_v4().to_string(),
27            entry.id.clone(),
28            entry.kind.clone(),
29            self.author_did.clone(),
30            entry.sensitivity.clone(),
31            entry.summary.clone().unwrap_or_default(),
32            lamport,
33            entry.committed_unix,
34        );
35        let signature = self.signing_key.sign(&op.signing_payload());
36        Some(op.with_signature(hex::encode(signature.to_bytes())))
37    }
38
39    /// Admit an inbound sync operation into the durable quarantined inbox. Idempotent: a
40    /// replayed operation id is recorded as `Duplicate` and never applied twice.
41    pub fn admit_sync_operation(&self, op: &SyncOperation) -> Result<AdmitOutcome, String> {
42        let inbox = SyncInbox::open(&self.storage_root).map_err(|e| e.to_string())?;
43        inbox
44            .admit(op, Self::now_unix() as u32)
45            .map_err(|e| e.to_string())
46    }
47
48    /// Validated operations currently held in the inbox, in Lamport order.
49    pub fn validated_sync_operations(&self) -> Result<Vec<SyncOperation>, String> {
50        SyncInbox::open(&self.storage_root)
51            .map_err(|e| e.to_string())?
52            .validated_operations()
53            .map_err(|e| e.to_string())
54    }
55
56    /// Lists the sync inbox.
57    pub fn list_sync_inbox(&self, limit: usize) -> Result<Vec<InboxRecord>, String> {
58        SyncInbox::open(&self.storage_root)
59            .map_err(|e| e.to_string())?
60            .list_recent(limit)
61            .map_err(|e| e.to_string())
62    }
63
64    // --- Sync transport orchestration (T3.1: drain outbox → transport → peer inbox) ---
65
66    /// The next Lamport value to stamp on outbound operations: one past the greatest observed among
67    /// the locally-validated inbox operations. Keeps outbound clocks causally ahead of what we've seen.
68    fn next_sync_lamport(&self) -> Result<u64, String> {
69        let max = self
70            .validated_sync_operations()?
71            .iter()
72            .map(|o| o.lamport)
73            .max()
74            .unwrap_or(0);
75        Ok(max + 1)
76    }
77
78    /// **Drain the outbox through a transport.** For each `Queued` outbox entry, build a signed
79    /// [`SyncOperation`] from its committed journal entry and publish it; on success the entry is
80    /// marked `Sent`. Classified/Sanctuary records never enter the ordinary lane — they are marked
81    /// `Rejected` so they stop being retried. Returns the number of operations published.
82    ///
83    /// The transport is a dumb pipe; correctness (dedup, convergence) is enforced by the peer's
84    /// fail-closed inbox on the other side.
85    pub fn sync_push_via<T: SyncTransport>(
86        &self,
87        transport: &T,
88        limit: usize,
89    ) -> Result<usize, String> {
90        let outbox = SyncOutbox::open(&self.storage_root).map_err(|e| e.to_string())?;
91        let queued: Vec<SyncOutboxEntry> = outbox
92            .list_all()
93            .map_err(|e| e.to_string())?
94            .into_iter()
95            .filter(|e| e.state == SyncOutboxState::Queued)
96            .take(limit)
97            .collect();
98        if queued.is_empty() {
99            return Ok(0);
100        }
101        let journal = self.list_health_records(512)?;
102        let mut lamport = self.next_sync_lamport()?;
103        let mut ops = Vec::new();
104        let mut sent_ids = Vec::new();
105        for entry in &queued {
106            let Some(journal_entry) = journal.iter().find(|j| j.id == entry.record_id) else {
107                continue; // the record is outside the recent window; leave it queued for a later drain
108            };
109            match self.build_outbound_operation(journal_entry, lamport) {
110                Some(op) => {
111                    lamport += 1;
112                    ops.push(op);
113                    sent_ids.push(entry.operation_id.clone());
114                }
115                None => {
116                    // Classified/Sanctuary — never syncs; stop retrying it.
117                    let _ = outbox.update_state(&entry.operation_id, SyncOutboxState::Rejected);
118                }
119            }
120        }
121        if ops.is_empty() {
122            return Ok(0);
123        }
124        transport.publish(&ops)?;
125        for id in &sent_ids {
126            let _ = outbox.update_state(id, SyncOutboxState::Sent);
127        }
128        Ok(ops.len())
129    }
130
131    /// **Pull from a transport and admit into the quarantined inbox.** Every op is validated
132    /// fail-closed on admission (bad signature/hash/version/oversize/Classified → `Rejected`;
133    /// replays → `Duplicate`), so a hostile peer can only cause rejections. Returns the admission
134    /// tally.
135    pub fn sync_pull_via<T: SyncTransport>(
136        &self,
137        transport: &T,
138        since: u64,
139    ) -> Result<SyncPullReport, String> {
140        let ops = transport.pull(since)?;
141        let mut report = SyncPullReport {
142            pulled: ops.len(),
143            validated: 0,
144            duplicate: 0,
145            rejected: 0,
146        };
147        for op in &ops {
148            match self.admit_sync_operation(op)? {
149                AdmitOutcome::Validated => report.validated += 1,
150                AdmitOutcome::Duplicate => report.duplicate += 1,
151                AdmitOutcome::Rejected(_) => report.rejected += 1,
152            }
153        }
154        Ok(report)
155    }
156
157    /// One-shot sync against an HTTP relay (the production wire): drain the outbox to the relay,
158    /// then pull + admit from it. Returns `(pushed, pull_report)`. Native-only (`reqwest`).
159    #[cfg(not(target_arch = "wasm32"))]
160    pub fn sync_with_http_relay(
161        &self,
162        base_url: &str,
163        since: u64,
164    ) -> Result<(usize, SyncPullReport), String> {
165        let transport = super::super::sync_transport::HttpRelayTransport::new(base_url);
166        let pushed = self.sync_push_via(&transport, 256)?;
167        let report = self.sync_pull_via(&transport, since)?;
168        Ok((pushed, report))
169    }
170
171    /// One-shot sync against a **libp2p** peer/relay (noise-encrypted request-response — the peer-to-peer
172    /// wire): drain the outbox to the peer, then pull + admit from it. `peer_id` is the base58 peer id,
173    /// `peer_addr` a libp2p multiaddr (e.g. `/ip4/1.2.3.4/tcp/4001`). Returns `(pushed, pull_report)`.
174    /// Native-only (libp2p). Same dumb-pipe contract as [`Self::sync_with_http_relay`]: correctness is
175    /// enforced by the fail-closed inbox, not the transport.
176    #[cfg(not(target_arch = "wasm32"))]
177    pub fn sync_with_libp2p_peer(
178        &self,
179        peer_id: &str,
180        peer_addr: &str,
181        since: u64,
182    ) -> Result<(usize, SyncPullReport), String> {
183        let transport =
184            super::super::sync_transport::Libp2pSyncTransport::connect(peer_id, peer_addr)?;
185        let pushed = self.sync_push_via(&transport, 256)?;
186        let report = self.sync_pull_via(&transport, since)?;
187        Ok((pushed, report))
188    }
189}