Skip to main content

lean_ctx_cloud/
docs.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Docs in Cloud (C0 2.2): the engine adapter of [`lean_ctx_doc`].
3//!
4//! The crate holds the model (pages, sections, notes, anchors, the
5//! lowest-seq fold and the doc state); this module feeds it the replica's
6//! verified events and turns its [`EventSpec`]s into signed class-W events,
7//! queued in the replica like every other write, so offline is fine and the
8//! next push sends them. Every string of every body passes the outbound
9//! screen first; one blocked text refuses the whole batch and nothing is
10//! queued.
11
12use lean_ctx_doc::replica::{DocSpace, LogEvent, assemble};
13use lean_ctx_doc::write::{self as doc_write, EventSpec};
14use serde_json::{Map, Value, json};
15
16use crate::CloudError;
17use crate::capture::GATE_VERSION;
18use crate::events::build::EVENT_SCHEMA;
19use crate::events::hlc::{self, Stamp};
20use crate::events::{ids, sign};
21use crate::knowledge::screening::{SCANNER_VERSION, Screen};
22use crate::replica::Replica;
23use crate::review::maintain::{Target, queue};
24
25fn local(e: impl std::fmt::Display) -> CloudError {
26    CloudError::Local(e.to_string())
27}
28
29/// The replica's verified events in the crate's shape, then this engine's
30/// queued events in HLC order after them: a write right after another one
31/// (an edit, then a confirm) bases its CAS on the queued head, which Cloud
32/// has by then, and reads show the engine's own writes at once.
33pub fn log_events(replica: &Replica) -> Result<Vec<LogEvent>, CloudError> {
34    let mut out: Vec<LogEvent> = replica
35        .fold_events()?
36        .into_iter()
37        .filter(|e| !e.sig_invalid)
38        .map(|e| LogEvent {
39            seq: e.seq,
40            event_id: e.event_id,
41            op: e.op,
42            target: e.target,
43            node_type: e.node_type,
44            body: e.body,
45        })
46        .collect();
47    let mut seq = out.iter().map(|e| e.seq).max().unwrap_or(0);
48    for (event_id, bytes) in replica.pending()? {
49        if out.iter().any(|e| e.event_id == event_id) {
50            continue;
51        }
52        let Ok(event) = serde_json::from_slice::<Value>(&bytes) else {
53            continue;
54        };
55        let text = |k: &str| event.get(k).and_then(Value::as_str).map(str::to_owned);
56        let Some(op) = text("op") else {
57            continue;
58        };
59        seq += 1;
60        out.push(LogEvent {
61            seq,
62            event_id,
63            op,
64            target: text("target"),
65            node_type: text("node_type"),
66            body: event.get("body").cloned(),
67        });
68    }
69    Ok(out)
70}
71
72/// The doc pages of the place as the replica holds them.
73pub fn space(replica: &Replica) -> Result<DocSpace, CloudError> {
74    Ok(assemble(&log_events(replica)?))
75}
76
77/// A fresh id for the crate's writers: `n_…` for nodes, `e_…` for edges.
78pub fn new_id(prefix: &str) -> String {
79    // `new_random_id` only fails when the OS RNG does; fall back to an event
80    // id, which is just as unique.
81    ids::new_random_id(prefix).unwrap_or_else(|_| {
82        let ms = lean_ctx_time::UtcDateTime::now()
83            .timestamp_millis()
84            .unsigned_abs();
85        format!(
86            "{prefix}_{}",
87            ids::new_event_id(ms).unwrap_or_default().to_lowercase()
88        )
89    })
90}
91
92/// Every string in `value`, for the screen.
93fn strings<'a>(value: &'a Value, out: &mut Vec<&'a str>) {
94    match value {
95        Value::String(s) => out.push(s),
96        Value::Array(a) => a.iter().for_each(|v| strings(v, out)),
97        Value::Object(m) => m.values().for_each(|v| strings(v, out)),
98        _ => {}
99    }
100}
101
102/// Screens every body of `specs`; the first blocked text refuses all.
103pub fn screen_all(specs: &[EventSpec], screen: &mut Screen) -> Result<(), CloudError> {
104    for spec in specs {
105        let mut texts = Vec::new();
106        for v in spec.body.values() {
107            strings(v, &mut texts);
108        }
109        for t in texts {
110            screen.check(t).map_err(|why| {
111                CloudError::Refused(format!(
112                    "screened: nothing of this doc write was queued ({why})"
113                ))
114            })?;
115        }
116    }
117    Ok(())
118}
119
120fn reasons_hash(spec: &EventSpec) -> String {
121    let kind = spec
122        .node_type
123        .or_else(|| spec.body.get("field").and_then(Value::as_str))
124        .or_else(|| spec.body.get("kind").and_then(Value::as_str))
125        .unwrap_or("doc");
126    blake3::hash(format!("leanctx.cloud.docs.v1:{}:{kind}", spec.op).as_bytes())
127        .to_hex()
128        .to_string()
129}
130
131/// The signed event of `spec` with `event_id` at `stamp`.
132fn build(
133    target: &Target<'_>,
134    spec: &EventSpec,
135    event_id: &str,
136    stamp: Stamp,
137) -> Result<Value, CloudError> {
138    let place = target.place;
139    let mut body: Map<String, Value> = spec.body.clone();
140    body.insert("body_nonce".into(), Value::String(sign::new_body_nonce()?));
141    let body = Value::Object(body);
142    let body_commit = sign::body_commit(&place.pk_id, &body).map_err(local)?;
143    // An engine's own adds are `own`; edits of a page anyone may have
144    // written are the workspace's, as every curation.
145    let claim = if matches!(spec.op, "node.add" | "edge.add") {
146        "own"
147    } else {
148        "workspace"
149    };
150    let mut event = json!({
151        "schema": EVENT_SCHEMA,
152        "event_id": event_id,
153        "place": {"kind": place.kind, "id": place.id},
154        "op": spec.op,
155        "target": spec.target,
156        "body": body,
157        "body_commit": body_commit,
158        "hlc": {"wall_ms": stamp.wall_ms, "counter": stamp.counter, "node": target.signer.hlc_node},
159        "causal_base": place.causal_base,
160        "actor": {"kind": "worker"},
161        "worker_id": target.signer.worker_id,
162        "provenance_claim": claim,
163        "capture": {
164            "gate_version": GATE_VERSION,
165            "evidence": "observed",
166            "reasons_passed_hash": reasons_hash(spec),
167        },
168        "screening": {
169            "counts": {"forbidden": 0, "local_path": 0, "pii": 0, "redaction": 0, "secret": 0},
170            "scanner_version": SCANNER_VERSION,
171        },
172    });
173    if let Some(t) = spec.node_type {
174        event["node_type"] = Value::from(t);
175    }
176    if let Some(base) = &spec.base_event {
177        event["base_event"] = Value::from(base.as_str());
178    }
179    sign::sign(&mut event, target.signer.key).map_err(local)?;
180    Ok(event)
181}
182
183/// Screens, chains, signs and queues `specs` in order. Returns the queued
184/// event ids; nothing is queued when one body is screened out.
185pub fn queue_specs(
186    target: &Target<'_>,
187    specs: Vec<EventSpec>,
188    screen: &mut Screen,
189    now_ms: u64,
190) -> Result<Vec<String>, CloudError> {
191    queue_specs_at(target, specs, screen, now_ms, Stamp::default()).map(|(ids, _)| ids)
192}
193
194/// [`queue_specs`] continuing the HLC `clock` of events queued before it in
195/// the same run (the sync's re-checks); returns the clock after the last.
196pub fn queue_specs_at(
197    target: &Target<'_>,
198    mut specs: Vec<EventSpec>,
199    screen: &mut Screen,
200    now_ms: u64,
201    clock: Stamp,
202) -> Result<(Vec<String>, Stamp), CloudError> {
203    screen_all(&specs, screen)?;
204    let mut stamp = clock;
205    let mut stamps = Vec::with_capacity(specs.len());
206    let mut event_ids = Vec::with_capacity(specs.len());
207    for _ in &specs {
208        stamp = hlc::send(stamp, now_ms);
209        event_ids.push(ids::new_event_id(stamp.wall_ms)?);
210        stamps.push(stamp);
211    }
212    doc_write::chain(&mut specs, &event_ids);
213    let events = specs
214        .iter()
215        .zip(&event_ids)
216        .zip(&stamps)
217        .map(|((spec, id), stamp)| build(target, spec, id, *stamp).map(|e| (e, *stamp)))
218        .collect::<Result<Vec<_>, _>>()?;
219    for (event, stamp) in events {
220        queue(target, &event, stamp)?;
221    }
222    Ok((event_ids, stamp))
223}
224
225/// The files git tracks in the checkout at `root` (repo-relative, `/`), the
226/// file set every C0 2.2 anchor digest is computed over; `None` outside git.
227pub fn tracked_files(root: &str) -> Option<Vec<String>> {
228    let out = std::process::Command::new("git")
229        .args(["ls-files", "-z"])
230        .current_dir(root)
231        .output()
232        .ok()
233        .filter(|o| o.status.success())?;
234    let mut files: Vec<String> = out
235        .stdout
236        .split(|b| *b == 0)
237        .filter(|p| !p.is_empty())
238        .map(|p| String::from_utf8_lossy(p).into_owned())
239        .collect();
240    files.sort();
241    Some(files)
242}
243
244/// The commit the checkout is at, for an anchor's `commit`.
245pub fn head_commit(root: &str) -> Option<String> {
246    let out = std::process::Command::new("git")
247        .args(["rev-parse", "HEAD"])
248        .current_dir(root)
249        .output()
250        .ok()
251        .filter(|o| o.status.success())?;
252    Some(String::from_utf8_lossy(&out.stdout).trim().to_owned())
253}
254
255/// The digest `anchor` has in the checkout now (C0 2.2
256/// `doc_anchor_digest`); `None` when a `file:` or `dir:` target is gone.
257pub fn digest_now(root: &str, files: &[String], anchor: &lean_ctx_doc::Anchor) -> Option<String> {
258    let dir_exists = std::path::Path::new(root).join(&anchor.path).is_dir();
259    let mut read = |p: &str| {
260        std::fs::read(std::path::Path::new(root).join(p))
261            .ok()
262            .map(|b| lean_ctx_doc::anchor::file_digest(&b))
263    };
264    digest_with(files, anchor, dir_exists, &mut read)
265}
266
267/// The digest of `anchor` over `files`, with `file_digest_of` giving each
268/// file's digest (from the working tree or from a commit).
269fn digest_with(
270    files: &[String],
271    anchor: &lean_ctx_doc::Anchor,
272    dir_exists: bool,
273    file_digest_of: &mut dyn FnMut(&str) -> Option<String>,
274) -> Option<String> {
275    use lean_ctx_doc::anchor::{glob_match, shape_digest, tree_digest};
276    use lean_ctx_doc::{AnchorKind, AnchorMode};
277    let selected: Vec<&String> = match anchor.kind {
278        AnchorKind::File => {
279            return files
280                .contains(&anchor.path)
281                .then(|| file_digest_of(&anchor.path))
282                .flatten();
283        }
284        AnchorKind::Dir => {
285            if !dir_exists {
286                return None;
287            }
288            files
289                .iter()
290                .filter(|f| anchor.matches(f) && **f != anchor.path)
291                .collect()
292        }
293        AnchorKind::Glob => files
294            .iter()
295            .filter(|f| glob_match(&anchor.path, f))
296            .collect(),
297    };
298    // dir: relpaths are relative to the anchor dir, glob: to the repo root.
299    let rel = |f: &str| -> String {
300        if anchor.kind == AnchorKind::Dir && !anchor.path.is_empty() {
301            f[anchor.path.trim_end_matches('/').len() + 1..].to_owned()
302        } else {
303            f.to_owned()
304        }
305    };
306    Some(match anchor.mode {
307        AnchorMode::Shape => shape_digest(&selected.iter().map(|f| rel(f)).collect::<Vec<_>>()),
308        AnchorMode::Content => tree_digest(
309            &selected
310                .iter()
311                .filter_map(|f| file_digest_of(f).map(|d| (rel(f), d)))
312                .collect::<Vec<_>>(),
313        ),
314    })
315}
316
317/// Anchor digests at one commit: the tracked files of its tree, each file's
318/// bytes read once through a single `git cat-file --batch`. The migrator pins
319/// an emspace page at the commit emspace pinned it at, so the first re-check
320/// against `HEAD` reproduces emspace's stale set.
321pub struct GitAt {
322    files: Vec<String>,
323    blobs: std::collections::HashMap<String, String>,
324    cache: std::collections::HashMap<String, Option<String>>,
325    child: std::process::Child,
326}
327
328impl GitAt {
329    /// `None` when `commit` is not in the checkout at `root`.
330    pub fn open(root: &str, commit: &str) -> Option<Self> {
331        use std::process::{Command, Stdio};
332        let tree = Command::new("git")
333            .args(["ls-tree", "-r", "-z", commit])
334            .current_dir(root)
335            .output()
336            .ok()
337            .filter(|o| o.status.success())?;
338        let mut files = Vec::new();
339        let mut blobs = std::collections::HashMap::new();
340        for entry in tree.stdout.split(|b| *b == 0).filter(|e| !e.is_empty()) {
341            // `<mode> blob <sha>\t<path>`
342            let line = String::from_utf8_lossy(entry);
343            let Some((meta, path)) = line.split_once('\t') else {
344                continue;
345            };
346            let mut parts = meta.split(' ');
347            if let (Some(_), Some("blob"), Some(sha)) = (parts.next(), parts.next(), parts.next()) {
348                files.push(path.to_owned());
349                blobs.insert(path.to_owned(), sha.to_owned());
350            }
351        }
352        files.sort();
353        let child = Command::new("git")
354            .args(["cat-file", "--batch"])
355            .current_dir(root)
356            .stdin(Stdio::piped())
357            .stdout(Stdio::piped())
358            .stderr(Stdio::null())
359            .spawn()
360            .ok()?;
361        Some(Self {
362            files,
363            blobs,
364            cache: std::collections::HashMap::new(),
365            child,
366        })
367    }
368
369    fn file_digest(&mut self, path: &str) -> Option<String> {
370        use std::io::{BufRead, Read, Write};
371        if let Some(d) = self.cache.get(path) {
372            return d.clone();
373        }
374        let sha = self.blobs.get(path)?.clone();
375        let digest = (|| {
376            let stdin = self.child.stdin.as_mut()?;
377            writeln!(stdin, "{sha}").ok()?;
378            stdin.flush().ok()?;
379            let stdout = self.child.stdout.as_mut()?;
380            let mut reader = std::io::BufReader::new(stdout.by_ref());
381            let mut header = String::new();
382            reader.read_line(&mut header).ok()?;
383            let size: usize = header.split_whitespace().nth(2)?.parse().ok()?;
384            let mut body = vec![0u8; size + 1];
385            reader.read_exact(&mut body).ok()?;
386            body.truncate(size);
387            Some(lean_ctx_doc::anchor::file_digest(&body))
388        })();
389        self.cache.insert(path.to_owned(), digest.clone());
390        digest
391    }
392
393    /// The digest of `anchor` at this commit; `None` for a gone target.
394    pub fn digest(&mut self, anchor: &lean_ctx_doc::Anchor) -> Option<String> {
395        let prefix = format!("{}/", anchor.path.trim_end_matches('/'));
396        let dir_exists =
397            anchor.path.is_empty() || self.files.iter().any(|f| f.starts_with(&prefix));
398        let files = std::mem::take(&mut self.files);
399        let out = digest_with(&files, anchor, dir_exists, &mut |p| self.file_digest(p));
400        self.files = files;
401        out
402    }
403}
404
405impl Drop for GitAt {
406    fn drop(&mut self) {
407        drop(self.child.stdin.take());
408        let _ = self.child.wait();
409    }
410}
411
412/// Parses `file:…`, `dir:…` or `glob:…` (role `derived`, mode `content`;
413/// `shape:` is a `dir:` in shape mode) and pins it at the checkout's digest.
414pub fn pin(
415    root: &str,
416    files: &[String],
417    reference: &str,
418) -> Result<lean_ctx_doc::Anchor, CloudError> {
419    use lean_ctx_doc::{Anchor, AnchorKind, AnchorMode, AnchorRole};
420    let (scheme, path) = reference.split_once(':').ok_or_else(|| {
421        CloudError::Config(format!(
422            "anchor {reference}: use file:, dir:, glob: or shape:"
423        ))
424    })?;
425    if path.contains("..") || path.starts_with('/') || path.contains(':') {
426        return Err(CloudError::Config(format!(
427            "anchor {reference}: repo-relative paths only"
428        )));
429    }
430    let (kind, mode) = match scheme {
431        "file" => (AnchorKind::File, AnchorMode::Content),
432        "dir" => (AnchorKind::Dir, AnchorMode::Content),
433        "shape" => (AnchorKind::Dir, AnchorMode::Shape),
434        "glob" => (AnchorKind::Glob, AnchorMode::Content),
435        _ => {
436            return Err(CloudError::Config(format!(
437                "anchor {reference}: use file:, dir:, glob: or shape:"
438            )));
439        }
440    };
441    let mut anchor = Anchor {
442        kind,
443        mode,
444        role: AnchorRole::Derived,
445        path: path.trim_end_matches('/').to_owned(),
446        digest: String::new(),
447        commit: head_commit(root),
448    };
449    anchor.digest = digest_now(root, files, &anchor)
450        .ok_or_else(|| CloudError::Config(format!("anchor {reference}: not in the checkout")))?;
451    Ok(anchor)
452}
453
454/// The anchors of a page as stored (`anchors` field), parsed back.
455pub fn page_anchors(page: &lean_ctx_doc::replica::PageView) -> Vec<lean_ctx_doc::Anchor> {
456    page.page
457        .fields
458        .get("anchors")
459        .and_then(Value::as_array)
460        .into_iter()
461        .flatten()
462        .filter_map(lean_ctx_doc::write::anchor_from_value)
463        .collect()
464}
465
466/// The recheck of every page's derived anchors against the checkout: one
467/// `anchor_state` + `drift` pair (CAS-exempt) per page whose verdict changed.
468/// Matching bytes never write `fresh`: only a confirm does.
469pub fn recheck(root: &str, space: &DocSpace) -> Vec<EventSpec> {
470    let Some(files) = tracked_files(root) else {
471        return Vec::new();
472    };
473    let mut out = Vec::new();
474    for page in space.pages.values() {
475        let mut drift: Vec<Value> = Vec::new();
476        let mut gone = false;
477        for a in page_anchors(page)
478            .iter()
479            .filter(|a| a.role == lean_ctx_doc::AnchorRole::Derived)
480        {
481            let now = digest_now(root, &files, a);
482            if now.as_deref() != Some(a.digest.as_str()) {
483                gone |= now.is_none();
484                drift.push(json!({ "ref": a.reference(), "observed": now }));
485            }
486        }
487        if drift.is_empty() {
488            continue;
489        }
490        let state = if gone { "gone" } else { "to_verify" };
491        let same_state = page.page.str("anchor_state") == Some(state);
492        let same_drift = page.page.fields.get("drift") == Some(&Value::Array(drift.clone()));
493        if same_state && same_drift {
494            continue;
495        }
496        for (field, value) in [
497            ("anchor_state", Value::from(state)),
498            ("drift", Value::Array(drift)),
499        ] {
500            let mut body = Map::new();
501            body.insert("field".into(), Value::from(field));
502            body.insert("value".into(), value);
503            out.push(EventSpec {
504                op: "field.set",
505                target: page.page.id.clone(),
506                node_type: None,
507                body,
508                base_event: None,
509            });
510        }
511    }
512    out
513}
514
515/// The linked vault of a checkout, opened for reading and writing docs.
516pub struct Vault<'a> {
517    /// `@ns/name`, for messages.
518    pub label: String,
519    pub target: Target<'a>,
520}
521
522/// Doc writes need a C0 2.2 Cloud (doc node types, `base_event` CAS): a
523/// 2.0 or 2.1 Cloud refuses them. The engine records the answered minor at
524/// start (`relay_v2::protocol_minor`).
525pub fn require_docs_protocol(store: &crate::CloudStore) -> Result<(), CloudError> {
526    if crate::bus::relay_v2::speaks_2_2(store) {
527        return Ok(());
528    }
529    let answered = crate::bus::relay_v2::protocol_minor(store).map_or_else(
530        || "no 2.x version yet".to_owned(),
531        |minor| format!("2.{minor}"),
532    );
533    Err(CloudError::Refused(format!(
534        "doc pages need Cloud-Protocol 2.2 and this LeanCTX Cloud server answered {answered}; the instance records it at start (restart it after a LeanCTX Cloud server upgrade)"
535    )))
536}
537
538/// Opens the vault linked to the checkout at `root` and runs `f` on it.
539/// Local only: nothing here contacts Cloud.
540pub fn with_vault<R>(
541    root: &str,
542    f: impl FnOnce(&Vault<'_>) -> Result<R, CloudError>,
543) -> Result<R, CloudError> {
544    use crate::sync::{place, writer};
545    let store = crate::CloudStore::open()?;
546    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
547    let record = crate::resolution::vault_for_root(store.data_dir(), std::path::Path::new(root))?
548        .ok_or_else(|| {
549            CloudError::Config(
550                "this checkout is not linked to a LeanCTX Cloud vault (`lean-ctx cloud link <workspace>/<vault>`)"
551                    .into(),
552            )
553        })?;
554    let dir = crate::replica::store::place_dir(store.data_dir(), &record.vault_id);
555    if !dir.join("replica.db").exists() {
556        return Err(CloudError::Config(format!(
557            "@{}/{} has no replica here yet: run `lean-ctx cloud sync` first",
558            record.ns, record.name
559        )));
560    }
561    let config = lean_ctx::core::config::Config::load().cloud.clone();
562    let trust = crate::root_cert::trust_root(&store, &config, &instance.url)?;
563    let session = crate::auth::Session::load(store.clone(), trust)?;
564    let (mk, _) = crate::replica::crypt::master_key(store.config_dir(), false)?;
565    let (replica, _) = Replica::open(store.data_dir(), &record.vault_id, &mk)?;
566    let vault_writer = writer::VaultWriter::open(&session, place::CAPTURE_ROLE)?;
567    let vault_place = writer::vault_place(&record, &replica)?;
568    let signer = vault_writer.signer();
569    let vault = Vault {
570        label: format!("@{}/{}", record.ns, record.name),
571        target: Target {
572            replica: &replica,
573            place: &vault_place,
574            signer: &signer,
575        },
576    };
577    f(&vault)
578}
579
580/// Sends the queued events of `root`'s vault (one push). The tool hands this
581/// to [`crate::background`], so a doc write never waits for Cloud.
582pub fn push_queued(root: &str) -> Result<String, CloudError> {
583    use crate::sync::{driver, place, writer};
584    let store = crate::CloudStore::open()?;
585    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
586    let record = crate::resolution::vault_for_root(store.data_dir(), std::path::Path::new(root))?
587        .ok_or_else(|| {
588        CloudError::Config("this checkout is not linked to a LeanCTX Cloud vault".into())
589    })?;
590    let config = lean_ctx::core::config::Config::load().cloud.clone();
591    let trust = crate::root_cert::trust_root(&store, &config, &instance.url)?;
592    let session = crate::auth::Session::load(store.clone(), trust)?;
593    let (mk, _) = crate::replica::crypt::master_key(store.config_dir(), false)?;
594    let (replica, _) = Replica::open(store.data_dir(), &record.vault_id, &mk)?;
595    let api = place::SessionApi(&session);
596    let push = driver::push_pending(&api, &replica, &writer::vault_ref(&record), &[])?;
597    let label = format!("@{}/{}", record.ns, record.name);
598    Ok(if push.failed.is_empty() {
599        format!("docs: sent {} event(s) to {label}", push.logged)
600    } else {
601        let why: Vec<&str> = push.failed.iter().map(|(_, w)| w.as_str()).collect();
602        format!(
603            "docs: {} event(s) refused by {label} ({}); re-read the page and write again",
604            push.failed.len(),
605            why.join(", ")
606        )
607    })
608}
609
610#[cfg(test)]
611#[path = "docs_tests.rs"]
612mod tests;