Skip to main content

lean_ctx_cloud/sync/
driver.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Driving a place's replica from the server (SPEC-ENGINE §3.4.3–§3.4.4):
3//! clone (signed manifest, then every segment, each verified before import,
4//! refetched once on a mismatch), tail since the cursor, and push of own
5//! events. The server log is the only source of truth: accepted pushes stay
6//! pending until the tail delivers them.
7
8use serde_json::Value;
9
10use super::{push, records};
11use crate::CloudError;
12use crate::replica::Replica;
13use crate::replica::store::{META_PLACE_NAME, META_SNAPSHOT_REV};
14
15/// Largest segment body read (JSON lines).
16const MAX_SEGMENT_BYTES: usize = 256 * 1024 * 1024;
17/// Tail pages fetched per call before yielding.
18const MAX_TAIL_PAGES: usize = 1_000;
19
20/// The routes a replica needs. [`crate::transport::CloudClient`]
21/// implements it; tests use an in-memory server.
22pub trait PlaceApi {
23    fn get(&self, path: &str) -> Result<Value, CloudError>;
24    fn get_bytes(&self, path: &str, max: usize) -> Result<Vec<u8>, CloudError>;
25    fn post(&self, path: &str, body: &Value) -> Result<Value, CloudError>;
26}
27
28impl PlaceApi for crate::transport::CloudClient {
29    fn get(&self, path: &str) -> Result<Value, CloudError> {
30        crate::transport::CloudClient::get(self, path)
31    }
32    fn get_bytes(&self, path: &str, max: usize) -> Result<Vec<u8>, CloudError> {
33        crate::transport::CloudClient::get_bytes(self, path, max)
34    }
35    fn post(&self, path: &str, body: &Value) -> Result<Value, CloudError> {
36        crate::transport::CloudClient::post(self, path, body)
37    }
38}
39
40/// How a place's events are checked on receive: the Cloud snapshot keys and
41/// the signer rules of §3.3.5 (class W worker keys, class A Cloud keys).
42pub struct Verifier<'a> {
43    pub snapshot_keys: &'a [[u8; 32]],
44    pub signature_ok: &'a dyn Fn(&Value) -> bool,
45}
46
47fn protocol(what: impl std::fmt::Display) -> CloudError {
48    CloudError::Protocol(what.to_string())
49}
50
51fn place_path(place: &str) -> String {
52    format!("/places/{place}")
53}
54
55/// The place id key from the replica (`id_salt` after a clone).
56fn pk_id(replica: &Replica) -> Result<[u8; 32], CloudError> {
57    replica
58        .id_salt()?
59        .ok_or_else(|| CloudError::Local("replica has no id_salt: clone it first".into()))
60}
61
62/// The zstd frame magic (E3 is served `Content-Encoding: zstd`).
63const ZSTD_MAGIC: [u8; 4] = [0x28, 0xb5, 0x2f, 0xfd];
64
65/// The JSON lines of a segment, zstd frames decoded (bounded) whether or
66/// not the transport already decoded them.
67fn segment_records(bytes: &[u8]) -> Result<Vec<Value>, CloudError> {
68    use std::io::Read as _;
69    let decoded;
70    let text = if bytes.starts_with(&ZSTD_MAGIC) {
71        let mut out = Vec::new();
72        zstd::stream::read::Decoder::new(bytes)
73            .map_err(protocol)?
74            .take(MAX_SEGMENT_BYTES as u64 + 1)
75            .read_to_end(&mut out)
76            .map_err(protocol)?;
77        if out.len() > MAX_SEGMENT_BYTES {
78            return Err(protocol("segment larger than the limit"));
79        }
80        decoded = out;
81        &decoded[..]
82    } else {
83        bytes
84    };
85    std::str::from_utf8(text)
86        .map_err(protocol)?
87        .lines()
88        .filter(|l| !l.trim().is_empty())
89        .map(|l| serde_json::from_str(l).map_err(protocol))
90        .collect()
91}
92
93/// What a clone or tail did.
94#[derive(Debug, Clone, Default, PartialEq, Eq)]
95pub struct SyncReport {
96    pub cloned: bool,
97    pub stored: usize,
98    pub cursor: Option<u64>,
99    /// A failover reconcile ran (R48).
100    pub reconciled: bool,
101    /// Own events re-pushed from the history by it.
102    pub repushed: usize,
103    /// Local rows it dropped (their `seq` changed or did not come back).
104    pub dropped: usize,
105}
106
107/// Clone `place` into an empty replica: verified manifest, then every
108/// segment. A segment that fails its checks is fetched once more; a second
109/// failure stops the clone (`segment_unavailable`) with nothing of it stored.
110/// A snapshot revision that rotated out meanwhile (`404 not_found`, only the
111/// latest 2 are kept) restarts the clone once from a fresh manifest.
112pub fn clone_place(
113    api: &dyn PlaceApi,
114    replica: &mut Replica,
115    place: &str,
116    verifier: &Verifier<'_>,
117) -> Result<SyncReport, CloudError> {
118    match clone_once(api, replica, place, verifier) {
119        Err(CloudError::NotFound) => clone_once(api, replica, place, verifier),
120        other => other,
121    }
122}
123
124fn clone_once(
125    api: &dyn PlaceApi,
126    replica: &mut Replica,
127    place: &str,
128    verifier: &Verifier<'_>,
129) -> Result<SyncReport, CloudError> {
130    let base = place_path(place);
131    let manifest = api.get(&format!("{base}/snapshot"))?;
132    if manifest.get("place").and_then(Value::as_str) != Some(place) {
133        return Err(protocol("snapshot manifest names another place"));
134    }
135    if !verifier
136        .snapshot_keys
137        .iter()
138        .any(|k| records::manifest_verifies(&manifest, k))
139    {
140        return Err(protocol("snapshot manifest signature does not verify"));
141    }
142    let rev = manifest
143        .get("rev")
144        .and_then(Value::as_u64)
145        .ok_or_else(|| protocol("manifest without rev"))?;
146    // The place carries the server's id_salt.
147    if let Some(salt) = manifest.get("id_salt").and_then(Value::as_str) {
148        let salt: [u8; 32] = hex::decode(salt)
149            .ok()
150            .and_then(|b| b.try_into().ok())
151            .ok_or_else(|| protocol("manifest id_salt"))?;
152        replica.set_id_salt(&salt)?;
153    }
154    if let Some(epoch) = manifest.get("epoch").and_then(Value::as_u64) {
155        replica.set_epoch(epoch)?;
156    }
157    replica.set_meta(META_PLACE_NAME, place.as_bytes())?;
158    let pk = pk_id(replica)?;
159    let mut stored = 0;
160    for meta in records::segments(&manifest).map_err(protocol)? {
161        let path = format!("{base}/snapshot/{rev}/segments/{}", meta.n);
162        let mut attempt = 0;
163        let events = loop {
164            let lines = segment_records(&api.get_bytes(&path, MAX_SEGMENT_BYTES)?)?;
165            match records::import_segment(&meta, &lines, &pk, verifier.signature_ok) {
166                Ok(events) => break events,
167                Err(_) if attempt == 0 => attempt += 1,
168                Err(e) => return Err(protocol(format!("segment_unavailable: {e}"))),
169            }
170        };
171        stored += replica.insert_events(&events)?;
172    }
173    replica.set_meta(META_SNAPSHOT_REV, &rev.to_le_bytes())?;
174    let mut report = tail(api, replica, place, verifier)?;
175    report.cloned = true;
176    report.stored += stored;
177    Ok(report)
178}
179
180/// Fetch the log since the replica's cursor, page by page, store what
181/// verifies (and what does not, marked `sig_invalid`), settle own pending
182/// events the log now holds, and refold.
183pub fn tail(
184    api: &dyn PlaceApi,
185    replica: &mut Replica,
186    place: &str,
187    verifier: &Verifier<'_>,
188) -> Result<SyncReport, CloudError> {
189    let pk = pk_id(replica)?;
190    let now = now_ms();
191    replica.prune_history(now)?;
192    let mut since = replica.cursor()?.unwrap_or(0);
193    let mut stored = 0;
194    let mut lost = Vec::new();
195    for _ in 0..MAX_TAIL_PAGES {
196        let page = api.get(&format!("{}/events?since={since}", place_path(place)))?;
197        let page = records::tail_page(&page, &pk, verifier.signature_ok).map_err(protocol)?;
198        // Failover (R48): a higher epoch, or a log that lost events below
199        // our cursor, is reconciled before anything of this page is kept.
200        let known = replica.epoch()?;
201        let epoch_up = matches!((page.epoch, known), (Some(e), Some(k)) if e > k);
202        let regressed = page.head_seq > 0 && page.head_seq < since;
203        if epoch_up || regressed {
204            let mut report = reconcile(
205                api,
206                replica,
207                place,
208                verifier,
209                page.epoch.or(known),
210                regressed.then_some(page.head_seq),
211            )?;
212            report.stored += stored;
213            return Ok(report);
214        }
215        if known.is_none()
216            && let Some(epoch) = page.epoch
217        {
218            replica.set_epoch(epoch)?;
219        }
220        stored += keep(replica, &page.events, now)?;
221        lost.extend(page.events.iter().filter_map(|e| {
222            (e.event.get("key_lost").and_then(Value::as_bool) == Some(true))
223                .then(|| e.event.get("event_id").and_then(Value::as_str))
224                .flatten()
225                .map(str::to_string)
226        }));
227        let last = page.events.iter().map(|e| e.seq).max();
228        let empty = page.events.is_empty();
229        match page.next_since.or(last) {
230            Some(next) if next > since && !empty => since = next,
231            _ => break,
232        }
233    }
234    replica.refold()?;
235    let repaired = repair_key_lost(api, replica, place, &lost)?;
236    if refetch_lost(api, replica, place, &pk, verifier)? > 0 {
237        replica.refold()?;
238    }
239    Ok(SyncReport {
240        cloned: false,
241        stored,
242        cursor: replica.cursor()?,
243        repushed: repaired,
244        ..SyncReport::default()
245    })
246}
247
248/// `key_lost` bodies fetched per place and tail (inside E6's 600 per instance).
249const MAX_BODY_REFETCH: usize = 100;
250
251/// Fetch the content of `key_lost` rows again (E6); a body that verifies
252/// with the stored envelope (signature and `body_commit`) is stored and the
253/// row folds. Returns how many came back.
254fn refetch_lost(
255    api: &dyn PlaceApi,
256    replica: &Replica,
257    place: &str,
258    pk: &[u8; 32],
259    verifier: &Verifier<'_>,
260) -> Result<usize, CloudError> {
261    let mut restored = 0;
262    for id in replica.key_lost_ids()?.into_iter().take(MAX_BODY_REFETCH) {
263        let answer = api.get(&format!("{}/events/{id}/body", place_path(place)))?;
264        let Some(body) = answer.get("body").filter(|b| !b.is_null()) else {
265            continue;
266        };
267        let Some(mut event) = replica.stored_envelope(&id)? else {
268            continue;
269        };
270        event["body"] = body.clone();
271        if records::event_verifies(&event, pk, verifier.signature_ok) {
272            replica.restore_body(&id, body)?;
273            restored += 1;
274        }
275    }
276    Ok(restored)
277}
278
279/// Re-push own events of `lost` (just served `key_lost`) with the identical
280/// signed envelope kept in the history; the place stores the content again
281/// and clears the flag (SPEC-ENGINE §3.4.4 "Repair").
282// lean-ctx: only from the 24-h history; rebuilding older own events from
283// the replica (`envelope_ct` + `body_ct`) follows with V4.11's re-wrap.
284fn repair_key_lost(
285    api: &dyn PlaceApi,
286    replica: &Replica,
287    place: &str,
288    lost: &[String],
289) -> Result<usize, CloudError> {
290    let mut own = Vec::new();
291    for id in lost {
292        if let Some(bytes) = replica.history_event(id)? {
293            own.push(serde_json::from_slice::<Value>(&bytes).map_err(protocol)?);
294        }
295    }
296    if !own.is_empty() {
297        api.post(
298            &format!("{}/events", place_path(place)),
299            &push::request(&own, None, &[]),
300        )?;
301    }
302    Ok(own.len())
303}
304
305fn now_ms() -> u64 {
306    lean_ctx_time::UtcDateTime::now()
307        .timestamp_millis()
308        .max(0)
309        .unsigned_abs()
310}
311
312/// Deletions while the month's transfer is used up (E2E-FINAL). E4 then
313/// answers only the `purge` tombstones of purges still waiting for acks,
314/// with `next_since` = `since` (deleting is protected capacity). They fold
315/// on top of the replica's graph without being stored, so the cursor never
316/// moves past events not received yet, and the bodies they purge are
317/// shredded at once; the caller denies, removes local text and acks.
318/// `None`: the answer was an ordinary page (it moved on, or held other
319/// events), so the quota is back and a full sync is due.
320pub fn deletions(
321    api: &dyn PlaceApi,
322    replica: &mut Replica,
323    place: &str,
324    verifier: &Verifier<'_>,
325) -> Result<Option<crate::replica::fold::Graph>, CloudError> {
326    use crate::replica::fold::FoldEvent;
327    let Some(since) = replica.cursor()? else {
328        // Never cloned: there is nothing to delete here yet.
329        return Ok(Some(crate::replica::fold::Graph::default()));
330    };
331    let pk = pk_id(replica)?;
332    let page = api.get(&format!("{}/events?since={since}", place_path(place)))?;
333    let page = records::tail_page(&page, &pk, verifier.signature_ok).map_err(protocol)?;
334    let str_of = |e: &Value, k: &str| e.get(k).and_then(Value::as_str).map(str::to_string);
335    let tombstones_only = page
336        .events
337        .iter()
338        .all(|e| e.event.get("op").and_then(Value::as_str) == Some("purge"));
339    if page.next_since.is_some_and(|n| n > since) || !tombstones_only {
340        return Ok(None);
341    }
342    let mut graph = replica.refold()?;
343    let events: Vec<FoldEvent> = page
344        .events
345        .iter()
346        .filter(|e| e.seq > since)
347        .map(|e| FoldEvent {
348            seq: e.seq,
349            event_id: str_of(&e.event, "event_id").unwrap_or_default(),
350            op: "purge".into(),
351            target: None,
352            node_type: None,
353            body: e.event.get("body").filter(|b| !b.is_null()).cloned(),
354            sig_invalid: e.sig_invalid,
355            provenance: str_of(&e.event, "provenance"),
356            review_state: str_of(&e.event, "review_state"),
357        })
358        .collect();
359    graph.fold(&events).map_err(protocol)?;
360    replica.shred_events(&graph.purged_events)?;
361    Ok(Some(graph))
362}
363
364/// Send signed purge acks alone (an ack-only E5 push, never metered).
365pub fn push_acks(api: &dyn PlaceApi, place: &str, acks: &[Value]) -> Result<(), CloudError> {
366    if acks.is_empty() {
367        return Ok(());
368    }
369    api.post(
370        &format!("{}/events", place_path(place)),
371        &push::request(&[], None, acks),
372    )
373    .map(|_| ())
374}
375
376/// Store tailed events: settle own pending ones, note when each arrived.
377fn keep(
378    replica: &mut Replica,
379    events: &[crate::replica::log::StoredEvent],
380    now: u64,
381) -> Result<usize, CloudError> {
382    for e in events {
383        if let Some(id) = e.event.get("event_id").and_then(Value::as_str) {
384            replica.settle_pending(id)?;
385        }
386    }
387    let seqs: Vec<u64> = events.iter().map(|e| e.seq).collect();
388    replica.note_received(&seqs, now)?;
389    replica.insert_events(events)
390}
391
392/// Failover reconcile (SPEC-ENGINE §3.4.4, RESOLUTIONS R48), once per
393/// trigger: re-push the kept own batches unchanged (the place answers
394/// `duplicate` for what it still holds and logs the lost ones again),
395/// re-tail from the lowest `seq` received in the last 24 h (or the place's
396/// `head_seq` after a restore), drop local rows whose `seq` came back with
397/// another event or not at all, refold, then take the new epoch.
398pub fn reconcile(
399    api: &dyn PlaceApi,
400    replica: &mut Replica,
401    place: &str,
402    verifier: &Verifier<'_>,
403    epoch: Option<u64>,
404    head_seq: Option<u64>,
405) -> Result<SyncReport, CloudError> {
406    let pk = pk_id(replica)?;
407    let now = now_ms();
408    let mut report = SyncReport {
409        reconciled: true,
410        ..SyncReport::default()
411    };
412    for batch in replica.history_batches()? {
413        let events: Vec<Value> = batch
414            .iter()
415            .map(|bytes| serde_json::from_slice(bytes).map_err(protocol))
416            .collect::<Result<_, _>>()?;
417        api.post(
418            &format!("{}/events", place_path(place)),
419            &push::request(&events, None, &[]),
420        )?;
421        report.repushed += events.len();
422    }
423    let cursor = replica.cursor()?.unwrap_or(0);
424    let mut from = replica.rewind_seq(now)?.unwrap_or(cursor + 1);
425    if let Some(head) = head_seq {
426        from = from.min(head + 1);
427    }
428    let from = from.max(1);
429    let mut since = from - 1;
430    let mut fetched = Vec::new();
431    for _ in 0..MAX_TAIL_PAGES {
432        let page = api.get(&format!("{}/events?since={since}", place_path(place)))?;
433        let page = records::tail_page(&page, &pk, verifier.signature_ok).map_err(protocol)?;
434        let last = page.events.iter().map(|e| e.seq).max();
435        let empty = page.events.is_empty();
436        fetched.extend(page.events);
437        match page.next_since.or(last) {
438            Some(next) if next > since && !empty => since = next,
439            _ => break,
440        }
441    }
442    let kept: Vec<(u64, String)> = fetched
443        .iter()
444        .filter_map(|e| {
445            let id = e.event.get("event_id").and_then(Value::as_str)?;
446            Some((e.seq, id.to_string()))
447        })
448        .collect();
449    report.dropped = replica.drop_changed_from(from, &kept)?;
450    report.stored = keep(replica, &fetched, now)?;
451    replica.refold()?;
452    if let Some(epoch) = epoch {
453        replica.set_epoch(epoch)?;
454    }
455    report.cursor = replica.cursor()?;
456    Ok(report)
457}
458
459/// What a push did.
460#[derive(Debug, Clone, Default, PartialEq, Eq)]
461pub struct PushReport {
462    pub sent: usize,
463    pub logged: usize,
464    pub held: usize,
465    /// Event ids to stamp again (`hlc_skew`).
466    pub restamp: Vec<String>,
467    /// Event ids to retry later (rate limits, migrations).
468    pub retry: Vec<String>,
469    /// Event ids that move to the failed queue, with the refusal: code,
470    /// reason and failing member (`invalid_event shape /body/statement`).
471    pub failed: Vec<(String, String)>,
472    /// The purge acks went out with an accepted request.
473    pub acked: bool,
474}
475
476/// Push the replica's pending own events in batches of
477/// [`push::MAX_BATCH`], with the signed purge acks riding on the first
478/// request (one is sent even without events). Failed events leave the
479/// pending queue; everything else stays pending until the tail delivers
480/// it. `report.acked` is true when the acks reached the place.
481pub fn push_pending(
482    api: &dyn PlaceApi,
483    replica: &Replica,
484    place: &str,
485    purge_acks: &[Value],
486) -> Result<PushReport, CloudError> {
487    let pending = replica.pending()?;
488    let mut report = PushReport::default();
489    let mut batches: Vec<&[(String, zeroize::Zeroizing<Vec<u8>>)]> =
490        pending.chunks(push::MAX_BATCH).collect();
491    if batches.is_empty() && !purge_acks.is_empty() {
492        batches.push(&[]);
493    }
494    for (i, batch) in batches.into_iter().enumerate() {
495        let events: Vec<Value> = batch
496            .iter()
497            .map(|(_, bytes)| serde_json::from_slice(bytes).map_err(protocol))
498            .collect::<Result<_, _>>()?;
499        let acks = if i == 0 { purge_acks } else { &[] };
500        let response = api.post(
501            &format!("{}/events", place_path(place)),
502            &push::request(&events, None, acks),
503        )?;
504        report.acked |= !acks.is_empty();
505        // The place answered: keep the batch for a failover re-push (R48).
506        let answered: Vec<(&str, &[u8])> = batch
507            .iter()
508            .map(|(id, bytes)| (id.as_str(), bytes.as_slice()))
509            .collect();
510        if !answered.is_empty() {
511            replica.record_history(
512                &crate::events::ids::new_random_id("b")?,
513                now_ms(),
514                &answered,
515            )?;
516        }
517        report.sent += events.len();
518        let (results, _) = push::results(&response).map_err(protocol)?;
519        for (id, outcome) in results {
520            if outcome.logged() {
521                report.logged += 1;
522                continue;
523            }
524            match outcome.next() {
525                None => report.held += 1,
526                Some(push::Next::Restamp) => report.restamp.push(id),
527                Some(push::Next::RetryLater) => report.retry.push(id),
528                Some(push::Next::Fail) => {
529                    let code = match &outcome {
530                        push::Outcome::Refused {
531                            code,
532                            reason,
533                            field,
534                            ..
535                        } => [Some(code.as_str()), reason.as_deref(), field.as_deref()]
536                            .into_iter()
537                            .flatten()
538                            .collect::<Vec<_>>()
539                            .join(" "),
540                        _ => String::new(),
541                    };
542                    replica.settle_pending(&id)?;
543                    report.failed.push((id, code));
544                }
545            }
546        }
547    }
548    Ok(report)
549}
550
551#[cfg(test)]
552#[path = "driver_tests.rs"]
553mod tests;