~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
919 lines · 31.9 KB Raw History
//! The repository held whole in memory, rebuilt from its records: what the
//! store's checkpoints were folded from by servers before the tree was
//! changed in place, which a log of that kind is read with once, to fold it
//! into a checkpoint of now (the server's `checkpoint`); and what the tests
//! hold the repository changed in place (`Repo`) to.

use crate::data::*;
use crate::mst::Block;
use crate::{
    Change, EvOp, MAX_EVENT_BLOCKS, Op, OpResult, Record, Refused, Tids, car_file, car_with_roots,
    event_blocks_len, make_record, mst, put_record, put_value,
};
use k256::ecdsa::SigningKey;
use k256::ecdsa::signature::hazmat::PrehashSigner;
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, HashMap, HashSet};

/// Where a block the repository holds is: a record, by its path, or a tree
/// node, with its bytes.
enum At {
    Record(String),
    Node(Vec<u8>),
}

/// A block the repository holds but its commit: the rev of the commit that
/// added it, and where it is.
struct Held {
    rev: String,
    at: At,
}

/// A repository as it was before a commit.
pub struct Undo {
    /// Each record the commit wrote or deleted, as it was.
    records: BTreeMap<String, Option<Record>>,
    rev: String,
    head: Vec<u8>,
    head_bytes: Vec<u8>,
    tree: mst::Node,
    held: HashMap<Vec<u8>, Held>,
    /// What `written` held of each record the commit wrote or deleted.
    written: Vec<(String, Option<String>)>,
}

/// A commit made and not yet put in place.
struct Made {
    rev: String,
    tree: mst::Node,
    held: HashMap<Vec<u8>, Held>,
    head: Vec<u8>,
    head_bytes: Vec<u8>,
    change: Change,
}

pub struct Repo {
    pub did: String,
    key: SigningKey,
    pub records: BTreeMap<String, Record>,
    /// The rev of the commit that last wrote each record it holds, by path.
    pub written: HashMap<String, String>,
    /// Empty until the first commit.
    pub rev: String,
    pub head: Vec<u8>,
    head_bytes: Vec<u8>,
    tree: mst::Node,
    pub tids: Tids,
    pub change: Option<Change>,
    /// Every block the repository holds but its commit, by CID: the index
    /// `blocks_car` reads, and when each was added.
    held: HashMap<Vec<u8>, Held>,
    /// The rev of the commit that added each block, as a log replays it,
    /// until `finish_load` makes `held` of it.
    loaded: HashMap<Vec<u8>, String>,
    /// The repository as it was before its last commit.
    undone: Option<Undo>,
}

impl Repo {
    /// A repository with no commit yet: `init` makes its first, or `load`
    /// and `finish_load` replay its log.
    pub fn new(did: String, key: SigningKey) -> Self {
        Repo {
            did,
            key,
            records: BTreeMap::new(),
            written: HashMap::new(),
            rev: String::new(),
            head: vec![],
            head_bytes: vec![],
            tree: mst::build_tree(&[]),
            tids: Tids::new(),
            change: None,
            held: HashMap::new(),
            loaded: HashMap::new(),
            undone: None,
        }
    }

    /// The first commit of a new repository: the empty tree.
    pub fn init(&mut self) -> Change {
        let made = self.make(vec![]);
        self.install(made, BTreeMap::new())
    }

    /// The public key of the key that signs its commits.
    pub fn verifying_key(&self) -> &k256::ecdsa::VerifyingKey {
        self.key.verifying_key()
    }

    /// The key that signs its commits, which is its account's signing key.
    pub fn signing_key(&self) -> &SigningKey {
        &self.key
    }

    /// Sign `message` with the repository's key, as an `ES256K` JWT is
    /// signed: ECDSA over SHA-256 of it, `r ‖ s`, `s` in the lower half.
    pub fn sign(&self, message: &[u8]) -> [u8; 64] {
        let sig: k256::ecdsa::Signature = self
            .key
            .sign_prehash(&Sha256::digest(message))
            .expect("signing a 32-byte digest");
        sig.normalize_s().to_bytes().into()
    }

    pub fn head_string(&self) -> String {
        cid_string(&self.head)
    }

    /// The latest commit's block.
    pub fn head_bytes(&self) -> &[u8] {
        &self.head_bytes
    }

    /// How many distinct blocks the latest commit and its tree are: the
    /// commit, every node of the tree, and every record, each CID once.
    pub fn block_count(&self) -> usize {
        let mut cids: HashSet<&[u8]> = HashSet::new();
        cids.insert(&self.head);
        cids.extend(self.tree.nodes().into_iter().map(|n| n.cid.as_slice()));
        cids.extend(self.records.values().map(|r| r.cid.as_slice()));
        cids.len()
    }

    /// About the bytes it holds in memory.
    pub fn cost(&self) -> u64 {
        let records: usize = self
            .records
            .iter()
            .map(|(p, r)| p.len() * 2 + r.bytes.len() * 3 + 256)
            .sum();
        let nodes: usize = self
            .tree
            .nodes()
            .iter()
            .map(|n| n.bytes.len() * 2 + 128)
            .sum();
        (records + nodes + self.held.len() * 96 + self.head_bytes.len()) as u64
    }

    /// The tree's `(key, record cid)` pairs, in key order.
    fn entries(&self) -> Vec<(Vec<u8>, Vec<u8>)> {
        self.records
            .iter()
            .map(|(k, r)| (k.as_bytes().to_vec(), r.cid.clone()))
            .collect()
    }

    /// Every block of `tree` and of the records, each once, where it is,
    /// with the rev `rev_of` gives it.
    fn index(
        &self,
        tree: &mst::Node,
        mut rev_of: impl FnMut(&[u8]) -> String,
    ) -> HashMap<Vec<u8>, Held> {
        let nodes = tree.nodes();
        let mut held = HashMap::with_capacity(nodes.len() + self.records.len());
        for n in nodes {
            if !held.contains_key(&n.cid) {
                held.insert(
                    n.cid.clone(),
                    Held {
                        rev: rev_of(&n.cid),
                        at: At::Node(n.bytes.clone()),
                    },
                );
            }
        }
        for (path, r) in &self.records {
            if !held.contains_key(&r.cid) {
                held.insert(
                    r.cid.clone(),
                    Held {
                        rev: rev_of(&r.cid),
                        at: At::Record(path.clone()),
                    },
                );
            }
        }
        held
    }

    /// Rebuild the tree and sign a new commit over it, for these ops,
    /// changing nothing but the TIDs given out.
    fn make(&mut self, ops: Vec<EvOp>) -> Made {
        let tree = mst::build_tree(&self.entries());
        let first = self.rev.is_empty();
        let rev = self.tids.next_tid();
        let mut added = Vec::new();
        let held = self.index(&tree, |cid| match self.held.get(cid) {
            Some(h) => h.rev.clone(),
            None => {
                added.push(cid.to_vec());
                rev.clone()
            }
        });
        let before = (!first).then_some(&self.tree);
        let mut blocks: Vec<Block> =
            mst::event_nodes(before, &tree, ops.iter().map(|o| o.path.as_bytes()))
                .into_iter()
                .map(|n| (n.cid.clone(), n.bytes.clone()))
                .collect();
        let mut records: Vec<Block> = ops.iter().filter_map(|o| o.block.clone()).collect();
        records.sort();
        records.dedup_by(|a, b| a.0 == b.0);
        blocks.extend(records);
        let unsigned = |sig: Option<Vec<u8>>| {
            let mut m = vec![
                ("did".to_string(), V::Str(self.did.clone())),
                ("version".to_string(), V::Int(3)),
                ("data".to_string(), V::Link(tree.cid.clone())),
                ("rev".to_string(), V::Str(rev.clone())),
                ("prev".to_string(), V::Null),
            ];
            if let Some(s) = sig {
                m.push(("sig".to_string(), V::Bytes(s)));
            }
            V::Map(m)
        };
        let hash = Sha256::digest(encode(&unsigned(None)));
        let sig: k256::ecdsa::Signature = self
            .key
            .sign_prehash(&hash)
            .expect("signing a 32-byte digest");
        let sig = sig.normalize_s();
        let bytes = encode(&unsigned(Some(sig.to_bytes().to_vec())));
        let change = Change {
            rev: rev.clone(),
            head_bytes: bytes.clone(),
            since: (!first).then(|| self.rev.clone()),
            prev_data: (!first).then(|| self.tree.cid.clone()),
            ops,
            blocks,
            added,
            ..Default::default()
        };
        Made {
            rev,
            tree,
            held,
            head: cid_of(0x71, &bytes),
            head_bytes: bytes,
            change,
        }
    }

    /// Put a commit made in place; its change keeps what it replaced.
    fn install(&mut self, m: Made, records: BTreeMap<String, Option<Record>>) -> Change {
        let change = m.change;
        self.undone = Some(Undo {
            records,
            rev: std::mem::replace(&mut self.rev, m.rev),
            head: std::mem::replace(&mut self.head, m.head),
            head_bytes: std::mem::replace(&mut self.head_bytes, m.head_bytes),
            tree: std::mem::replace(&mut self.tree, m.tree),
            held: std::mem::replace(&mut self.held, m.held),
            written: Vec::new(),
        });
        change
    }

    /// Put the repository back as it was before its last commit.
    pub fn undo_last(&mut self) {
        if let Some(u) = self.undone.take() {
            self.undo(u);
        }
    }

    /// Put the repository back as it was before the commit `undo` came with.
    fn undo(&mut self, u: Undo) {
        for (k, old) in u.records {
            match old {
                Some(r) => self.records.insert(k, r),
                None => self.records.remove(&k),
            };
        }
        self.rev = u.rev;
        self.head = u.head;
        self.head_bytes = u.head_bytes;
        self.tree = u.tree;
        self.held = u.held;
        for (k, rev) in u.written {
            match rev {
                Some(r) => self.written.insert(k, r),
                None => self.written.remove(&k),
            };
        }
        self.change = None;
    }

    /// Replay a logged change to the records; `finish_load` then rebuilds the tree.
    pub fn load(&mut self, c: &Change) -> Result<(), String> {
        for (path, j) in &c.puts {
            self.records.insert(
                path.clone(),
                put_record(j).map_err(|e| format!("record {path}: {e}"))?,
            );
            self.written.insert(path.clone(), c.rev.clone());
        }
        for path in &c.dels {
            self.records.remove(path);
            self.written.remove(path);
        }
        self.rev = c.rev.clone();
        for cid in &c.added {
            self.loaded.insert(cid.clone(), c.rev.clone());
        }
        self.head_bytes = c.head_bytes.clone();
        Ok(())
    }

    /// Rebuild the tree from the replayed records, and check it is the one the
    /// latest commit signed.
    pub fn finish_load(&mut self) -> Result<(), String> {
        self.tree = mst::build_tree(&self.entries());
        let commit = decode(&self.head_bytes).map_err(|e| format!("the latest commit: {e}"))?;
        let field = |k: &str| match &commit {
            V::Map(m) => m.iter().find(|(n, _)| n == k).map(|(_, v)| v),
            _ => None,
        };
        if field("data") != Some(&V::Link(self.tree.cid.clone())) {
            return Err(format!(
                "the records make the tree {}, which the latest commit does not sign",
                cid_string(&self.tree.cid)
            ));
        }
        if field("rev") != Some(&V::Str(self.rev.clone())) {
            return Err(format!("the latest commit is not rev {}", self.rev));
        }
        let loaded = std::mem::take(&mut self.loaded);
        // A block whose adding no entry names was added before any `since` asks after.
        self.held = self.index(&self.tree, |cid| {
            loaded.get(cid).cloned().unwrap_or_default()
        });
        self.head = cid_of(0x71, &self.head_bytes);
        self.tids.after(&self.rev);
        self.change = None;
        Ok(())
    }

    /// Every node of its tree, each once, children before parents.
    pub fn tree_nodes(&self) -> impl Iterator<Item = (&[u8], &[u8])> {
        self.tree
            .nodes()
            .into_iter()
            .map(|n| (n.cid.as_slice(), n.bytes.as_slice()))
    }

    /// Each block of its tree, MST node or record, each once, with the rev of
    /// the commit that added it: of a repository with a commit, loaded or made.
    pub fn block_revs(&self) -> impl Iterator<Item = (&[u8], &str)> {
        self.held
            .iter()
            .map(|(cid, h)| (cid.as_slice(), h.rev.as_str()))
    }

    /// Begin loading from a checkpoint (`spec/STORE.md`): the latest commit,
    /// the records of its tree by path, the rev of the commit that added each
    /// block of the tree, the rev of the commit that last wrote each record,
    /// and the last TID made. The log's changes after it are then `load`ed,
    /// and `finish_load` rebuilds the tree and checks it against the latest
    /// commit, as for a log replayed from the start.
    pub fn load_checkpoint(
        &mut self,
        head_bytes: Vec<u8>,
        records: Vec<(String, Record)>,
        revs: HashMap<Vec<u8>, String>,
        written: HashMap<String, String>,
        tid: &str,
    ) -> Result<(), String> {
        let rev = match decode(&head_bytes).map_err(|e| format!("the latest commit: {e}"))? {
            V::Map(m) => m.into_iter().find(|(k, _)| k == "rev").map(|(_, v)| v),
            _ => None,
        };
        let Some(V::Str(rev)) = rev else {
            return Err("the latest commit has no rev".into());
        };
        self.records = records.into_iter().collect();
        self.written = written;
        self.rev = rev;
        self.head_bytes = head_bytes;
        self.loaded = revs;
        self.tids.after(tid);
        Ok(())
    }

    pub fn uri(&self, collection: &str, rkey: &str) -> String {
        format!("at://{}/{}/{}", self.did, collection, rkey)
    }

    /// Apply writes as one commit, all or nothing.
    pub fn apply(
        &mut self,
        ops: Vec<Op>,
        swap_commit: Option<&str>,
    ) -> Result<Vec<OpResult>, Refused> {
        self.apply_checked(ops, swap_commit, || Ok(()))
    }

    /// Apply writes as one commit, all or nothing, once `check` passes: it
    /// runs only once the writes are found possible, and its refusal makes no
    /// commit and changes nothing. A commit whose event would carry more than
    /// `MAX_EVENT_BLOCKS` bytes of blocks is refused too.
    pub fn apply_checked<E: From<Refused>>(
        &mut self,
        ops: Vec<Op>,
        swap_commit: Option<&str>,
        check: impl FnOnce() -> Result<(), E>,
    ) -> Result<Vec<OpResult>, E> {
        if swap_commit.is_some_and(|s| s != self.head_string()) {
            return Err(Refused::StaleCommit.into());
        }
        let mut originals: BTreeMap<String, Option<Record>> = BTreeMap::new();
        let mut results = Vec::new();
        let mut evops = Vec::new();
        let mut refused = None;
        for op in ops {
            match self.apply_one(op, &mut originals, &mut evops) {
                Ok(x) => results.push(x),
                Err(e) => {
                    refused = Some(E::from(e));
                    break;
                }
            }
        }
        let mut refused = refused.map_or_else(|| check().err(), Some);
        let made = refused.is_none().then(|| self.make(evops));
        if made.as_ref().is_some_and(|m| {
            event_blocks_len(&m.head, &m.head_bytes, &m.change.blocks) > MAX_EVENT_BLOCKS
        }) {
            refused = Some(Refused::TooBig.into());
        }
        if let Some(e) = refused {
            for (k, old) in originals {
                match old {
                    Some(r) => self.records.insert(k, r),
                    None => self.records.remove(&k),
                };
            }
            return Err(e);
        }
        let puts: Vec<(String, serde_json::Value)> = originals
            .keys()
            .filter_map(|k| self.records.get(k).map(|r| (k.clone(), put_value(r))))
            .collect();
        let dels: Vec<String> = originals
            .keys()
            .filter(|k| !self.records.contains_key(*k))
            .cloned()
            .collect();
        let mut change = self.install(made.expect("a commit made"), originals);
        let rev = change.rev.clone();
        let was = self
            .undone
            .as_mut()
            .map(|u| &mut u.written)
            .expect("an undo installed");
        for (k, _) in &puts {
            was.push((k.clone(), self.written.insert(k.clone(), rev.clone())));
        }
        for k in &dels {
            was.push((k.clone(), self.written.remove(k)));
        }
        change.puts = puts;
        change.dels = dels;
        self.change = Some(change);
        Ok(results)
    }

    fn apply_one(
        &mut self,
        op: Op,
        originals: &mut BTreeMap<String, Option<Record>>,
        evops: &mut Vec<EvOp>,
    ) -> Result<OpResult, Refused> {
        let prev_of = |o: &Option<Record>| o.as_ref().map(|r| r.cid.clone());
        match op {
            Op::Create {
                collection,
                rkey,
                value,
            } => {
                let rkey = rkey.unwrap_or_else(|| self.tids.next_tid());
                let path = format!("{collection}/{rkey}");
                if self.records.contains_key(&path) {
                    return Err(Refused::Exists(path));
                }
                let rec = make_record(value);
                let cid = cid_string(&rec.cid);
                let prev = prev_of(originals.entry(path.clone()).or_insert(None));
                evops.push(EvOp {
                    action: "create",
                    path: path.clone(),
                    cid: Some(rec.cid.clone()),
                    prev,
                    block: Some((rec.cid.clone(), rec.bytes.clone())),
                });
                self.records.insert(path, rec);
                Ok(OpResult::Create {
                    uri: self.uri(&collection, &rkey),
                    cid,
                })
            }
            Op::Update {
                collection,
                rkey,
                value,
            } => {
                let path = format!("{collection}/{rkey}");
                if !self.records.contains_key(&path) {
                    return Err(Refused::Missing(path));
                }
                let rec = make_record(value);
                let cid = cid_string(&rec.cid);
                let block = Some((rec.cid.clone(), rec.bytes.clone()));
                let rec_cid = rec.cid.clone();
                let old = self.records.insert(path.clone(), rec);
                let prev = prev_of(originals.entry(path.clone()).or_insert(old));
                evops.push(EvOp {
                    action: "update",
                    path,
                    cid: Some(rec_cid),
                    prev,
                    block,
                });
                Ok(OpResult::Update {
                    uri: self.uri(&collection, &rkey),
                    cid,
                })
            }
            Op::Delete { collection, rkey } => {
                let path = format!("{collection}/{rkey}");
                let Some(old) = self.records.remove(&path) else {
                    return Err(Refused::Missing(path));
                };
                let prev = prev_of(originals.entry(path.clone()).or_insert(Some(old)));
                evops.push(EvOp {
                    action: "delete",
                    path,
                    cid: None,
                    prev,
                    block: None,
                });
                Ok(OpResult::Delete)
            }
        }
    }

    /// The whole repository as a CAR file.
    pub fn car(&self) -> Vec<u8> {
        let mut blocks: Vec<(&[u8], &[u8])> = vec![(&self.head, &self.head_bytes)];
        blocks.extend(
            self.tree
                .nodes()
                .into_iter()
                .map(|n| (n.cid.as_slice(), n.bytes.as_slice())),
        );
        blocks.extend(
            self.records
                .values()
                .map(|r| (r.cid.as_slice(), r.bytes.as_slice())),
        );
        car_file(&self.head, blocks)
    }

    /// The repository as a CAR file whose root is the latest commit, holding
    /// only the blocks it holds now that commits after rev `since` added: none
    /// when `since` is the latest rev.
    pub fn car_since(&self, since: &str) -> Vec<u8> {
        let after = |cid: &[u8]| self.held.get(cid).is_some_and(|h| h.rev.as_str() > since);
        let mut blocks: Vec<(&[u8], &[u8])> = Vec::new();
        if self.rev.as_str() > since {
            blocks.push((&self.head, &self.head_bytes));
        }
        blocks.extend(
            self.tree
                .nodes()
                .into_iter()
                .filter(|n| after(&n.cid))
                .map(|n| (n.cid.as_slice(), n.bytes.as_slice())),
        );
        let mut seen = HashSet::new();
        blocks.extend(
            self.records
                .values()
                .filter(|r| after(&r.cid) && seen.insert(r.cid.as_slice()))
                .map(|r| (r.cid.as_slice(), r.bytes.as_slice())),
        );
        car_file(&self.head, blocks)
    }

    /// The blocks with these CIDs, each once, as a CAR file with no roots:
    /// None if the repository does not hold one of them, its latest commit or
    /// a node or record of its current tree. Each CID is looked up in the
    /// index of the blocks it holds, so what this reads is what is asked for,
    /// however large the repository.
    pub fn blocks_car(&self, cids: &[Vec<u8>]) -> Option<Vec<u8>> {
        let mut seen: HashSet<&[u8]> = HashSet::with_capacity(cids.len());
        let mut found: Vec<(&[u8], &[u8])> = Vec::with_capacity(cids.len());
        for cid in cids {
            if !seen.insert(cid.as_slice()) {
                continue;
            }
            if *cid == self.head {
                found.push((&self.head, &self.head_bytes));
                continue;
            }
            let bytes = match &self.held.get(cid)?.at {
                At::Node(bytes) => bytes.as_slice(),
                At::Record(path) => self
                    .records
                    .get(path)
                    .filter(|r| r.cid == *cid)?
                    .bytes
                    .as_slice(),
            };
            found.push((cid, bytes));
        }
        Some(car_with_roots(&[], found))
    }

    /// A CAR file rooted at the latest commit that proves the record at
    /// `path`, or that there is none: the commit, the tree nodes a search for
    /// the key passes through, and the record if the tree holds it.
    pub fn proof_car(&self, path: &str) -> Vec<u8> {
        let mut blocks: Vec<(&[u8], &[u8])> = vec![(&self.head, &self.head_bytes)];
        blocks.extend(
            self.tree
                .path(path.as_bytes())
                .into_iter()
                .map(|n| (n.cid.as_slice(), n.bytes.as_slice())),
        );
        if let Some(r) = self.records.get(path) {
            blocks.push((&r.cid, &r.bytes));
        }
        car_file(&self.head, blocks)
    }
}

#[cfg(test)]
mod tests {
    use super::Repo;
    use super::*;
    use crate::{car_with_roots, mst, read_car, varint};

    fn repo() -> Repo {
        let mut r = Repo::new(
            "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa".into(),
            SigningKey::from_slice(&[7u8; 32]).unwrap(),
        );
        r.init();
        r
    }

    fn create(r: &mut Repo, rkey: &str, value: V) -> Result<Change, Refused> {
        let op = Op::Create {
            collection: "a.b.c".into(),
            rkey: Some(rkey.into()),
            value,
        };
        r.apply(vec![op], None)?;
        Ok(r.change.take().unwrap())
    }

    fn text(n: usize) -> V {
        V::Map(vec![
            ("$type".into(), V::Str("a.b.c".into())),
            ("b".into(), V::Bytes(vec![1; n])),
        ])
    }

    /// A commit whose event would carry more than `MAX_EVENT_BLOCKS` bytes is
    /// refused and changes nothing; one of exactly as many is made, and its
    /// event's blocks are that long.
    #[test]
    fn commits_too_big_are_refused() {
        let mut r = repo();
        let (head, rev) = (r.head.clone(), r.rev.clone());
        assert_eq!(
            create(&mut r, "big", text(MAX_EVENT_BLOCKS)).err(),
            Some(Refused::TooBig)
        );
        assert_eq!((&r.head, &r.rev, r.records.len()), (&head, &rev, 0));
        // The largest record that fits, found by halving.
        let (mut lo, mut hi) = (MAX_EVENT_BLOCKS / 2, MAX_EVENT_BLOCKS);
        while hi - lo > 1 {
            let mid = (lo + hi) / 2;
            let mut trial = repo();
            if create(&mut trial, "big", text(mid)).is_ok() {
                lo = mid
            } else {
                hi = mid
            }
        }
        let c = create(&mut r, "big", text(lo)).unwrap();
        let len = event_blocks_len(&r.head, &r.head_bytes, &c.blocks);
        let mut blocks: Vec<(&[u8], &[u8])> = vec![(&r.head, &r.head_bytes)];
        blocks.extend(c.blocks.iter().map(|(k, d)| (k.as_slice(), d.as_slice())));
        assert_eq!(car_file(&r.head, blocks).len(), len);
        assert!(
            len <= MAX_EVENT_BLOCKS && len > MAX_EVENT_BLOCKS - 8,
            "{len}"
        );
        assert_eq!(
            create(&mut r, "big2", text(lo + 1)).err(),
            Some(Refused::TooBig)
        );
    }

    /// A commit undone leaves the repository as it was, and the next commit
    /// goes on from there.
    #[test]
    fn undo_puts_it_back() {
        let mut r = repo();
        create(&mut r, "one", text(1)).unwrap();
        let before = (r.head.clone(), r.rev.clone(), r.car());
        create(&mut r, "two", text(2)).unwrap();
        r.undo_last();
        assert_eq!((r.head.clone(), r.rev.clone(), r.car()), before);
        assert!(r.blocks_car(&[make_record(text(2)).cid]).is_none());
        let c = create(&mut r, "two", text(2)).unwrap();
        assert_eq!(c.since.as_deref(), Some(before.1.as_str()));
        assert!(r.blocks_car(&[make_record(text(2)).cid]).is_some());
    }

    /// `getBlocks` reads what it asks for: no walk of the tree, in a large
    /// repository or a small one, whether the blocks are held or not.
    #[test]
    fn blocks_by_index() {
        for size in [3usize, 3000] {
            let mut r = repo();
            let ops = (0..size)
                .map(|i| Op::Create {
                    collection: "a.b.c".into(),
                    rkey: Some(format!("k{i}")),
                    value: text(i % 7 + 1),
                })
                .collect();
            r.apply(ops, None).unwrap();
            r.change = None;
            let some_record = r.records.values().next().unwrap().cid.clone();
            let root = r.tree.cid.clone();
            mst::VISITS.with(|v| v.set(0));
            let missing = cid_of(0x71, b"not held");
            assert_eq!(r.blocks_car(&[some_record.clone(), missing]), None);
            let car = r
                .blocks_car(&[
                    root.clone(),
                    some_record.clone(),
                    r.head.clone(),
                    root.clone(),
                ])
                .unwrap();
            assert_eq!(mst::VISITS.with(|v| v.get()), 0, "{size} records");
            let want: Vec<(&[u8], &[u8])> = vec![
                (&root, &r.tree.bytes),
                (&some_record, &r.records.values().next().unwrap().bytes),
                (&r.head, &r.head_bytes),
            ];
            assert_eq!(car, car_with_roots(&[], want));
        }
    }

    /// A CAR file reads back as written; one cut short, with bytes after
    /// it, or with a header of another shape, does not.
    #[test]
    fn cars_read_back() {
        let mut r = repo();
        create(&mut r, "one", text(3)).unwrap();
        let car = r.car();
        let (roots, blocks) = read_car(&car).unwrap();
        assert_eq!(roots, vec![r.head.clone()]);
        let refs: Vec<(&[u8], &[u8])> = blocks
            .iter()
            .map(|(c, d)| (c.as_slice(), d.as_slice()))
            .collect();
        assert_eq!(car_file(&r.head, refs), car);
        // Cut short, it is refused, or else cut at a section's end.
        for cut in 1..car.len() {
            assert!(
                read_car(&car[..cut]).map_or(true, |(_, b)| b.len() < blocks.len()
                    && b[..] == blocks[..b.len()]),
                "{cut}"
            );
        }
        assert!(read_car(&[car.clone(), vec![0]].concat()).is_err());
        let header = |v: V| {
            let h = encode(&v);
            let mut out = Vec::new();
            varint(&mut out, h.len());
            out.extend(h);
            out
        };
        let roots = || ("roots".to_string(), V::Arr(vec![V::Link(r.head.clone())]));
        assert!(
            read_car(&header(V::Map(vec![
                roots(),
                ("version".into(), V::Int(2))
            ])))
            .is_err()
        );
        assert!(read_car(&header(V::Map(vec![roots()]))).is_err());
        assert!(
            read_car(&header(V::Map(vec![
                roots(),
                ("version".into(), V::Int(1)),
                ("x".into(), V::Null)
            ])))
            .is_err()
        );
        assert_eq!(
            read_car(&header(V::Map(vec![
                roots(),
                ("version".into(), V::Int(1))
            ])))
            .unwrap(),
            (vec![r.head.clone()], vec![])
        );
    }

    /// A repository loaded from what a checkpoint keeps of it, then the
    /// changes after it, is the repository replayed whole.
    #[test]
    fn loads_from_a_checkpoint() {
        let mut r = repo();
        let mut revs = vec![r.rev.clone()];
        for i in 0..30 {
            create(&mut r, &format!("k{i}"), text(i % 4 + 1)).unwrap();
            revs.push(r.rev.clone());
        }
        let del = Op::Delete {
            collection: "a.b.c".into(),
            rkey: "k3".into(),
        };
        r.apply(vec![del], None).unwrap();
        r.change = None;
        let up = Op::Update {
            collection: "a.b.c".into(),
            rkey: "k4".into(),
            value: text(9),
        };
        r.apply(vec![up], None).unwrap();
        r.change = None;
        revs.push(r.rev.clone());
        let mut c = Repo::new(r.did.clone(), r.key.clone());
        let records = r
            .records
            .iter()
            .map(|(p, x)| {
                (
                    p.clone(),
                    Record {
                        cid: x.cid.clone(),
                        bytes: x.bytes.clone(),
                        value: x.value.clone(),
                    },
                )
            })
            .collect();
        let block_revs = r
            .block_revs()
            .map(|(c, v)| (c.to_vec(), v.to_string()))
            .collect();
        c.load_checkpoint(
            r.head_bytes.clone(),
            records,
            block_revs,
            r.written.clone(),
            &r.tids.last(),
        )
        .unwrap();
        // The changes after it, as the log replays them.
        let mut later = Vec::new();
        for i in 0..3 {
            later.push(create(&mut r, &format!("n{i}"), text(i + 1)).unwrap());
            revs.push(r.rev.clone());
        }
        for ch in &later {
            c.load(ch).unwrap();
        }
        c.finish_load().unwrap();
        assert_eq!(c.car(), r.car());
        assert_eq!((&c.head, &c.rev, &c.written), (&r.head, &r.rev, &r.written));
        for since in &revs {
            assert_eq!(c.car_since(since), r.car_since(since), "since {since}");
        }
        assert!(c.tids.last() >= r.rev);
        // A tree that is not the commit's is refused.
        let mut bad = Repo::new(r.did.clone(), r.key.clone());
        bad.load_checkpoint(
            r.head_bytes.clone(),
            vec![],
            HashMap::new(),
            HashMap::new(),
            "2222222222222",
        )
        .unwrap();
        assert!(bad.finish_load().is_err());
    }
}