Skip to main content

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