~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
248 lines · 9.9 KB Raw History
//! Spaces state before the mark, which this server does not carry: spaces
//! are an alpha, so an earlier version's is let go; from the mark on it is
//! carried (`spec/STORE.md`, "Upgrades").
//!
//! An account's spaces state is this version's where it is **marked**: in
//! a table that does not say it is unmarked, and in its log from the mark
//! on, `{"t":"spaces","v":1}` (`MARK`), which begins every account's log
//! (`log::new_repo`) and which a store found unmarked appends as it loads
//! (`log::open_repo`). A log with no table, after a table that says it is
//! unmarked, or after a table of the format `before` reads, is
//! unmarked until its mark. There each entry of spaces state (`of_spaces`),
//! whatever it holds, is let go as it is replayed: nothing is made of it,
//! and nothing of it is refused. Only what the space repos' records
//! reference of blobs is counted (`Unmarked`), as those references held
//! blobs then, so that every other entry replays as it was written; at the
//! mark they go, as a drop's do (`Small::mark`): a blob only they held is
//! no longer held. A fold of an unmarked log writes a table that says so,
//! with what it counted, and the log after it goes on from there.

use crate::blobs::{Blobs, cids_in};
use crate::space_repo;
use pds_repo::{Tids, put_record, valid_tid};
use serde_json::{Value as Json, json};
use std::collections::BTreeMap;

/// The kind of the mark's entry.
pub(crate) const MARK: &str = "spaces";
/// The mark's version, the only one this server knows.
pub(crate) const MARK_VERSION: u64 = 1;

/// The mark's entry.
pub(crate) fn mark() -> Json {
    json!({ "t": MARK, "v": MARK_VERSION })
}

/// Whether an entry of the kind `t` is of spaces state: of the space repos,
/// the spaces an account is the authority of or its notifications, or of a
/// kind this server does not know named as theirs are, `space…` or
/// `notify…`. Not the mark.
pub(crate) fn of_spaces(t: &str) -> bool {
    t != MARK
        && (t.starts_with("space")
            || t.starts_with("notify")
            || crate::space_authority::ENTRIES.contains(&t)
            || crate::space_notify::ENTRIES.contains(&t))
}

/// What an unmarked account's space repos hold of blob references: by
/// space, then path, the CIDs each record references, for those that
/// reference any. Its blobs count them (`Blobs::space_counted`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Unmarked {
    records: BTreeMap<String, BTreeMap<String, Vec<String>>>,
}

impl Unmarked {
    /// The record at `path` of the space repo `space` now references `cids`,
    /// none if it is deleted: what that changes is counted in `delta`.
    fn set(
        &mut self,
        space: &str,
        path: &str,
        cids: Vec<String>,
        delta: &mut BTreeMap<String, i64>,
    ) {
        let repo = self.records.entry(space.to_string()).or_default();
        let before = if cids.is_empty() {
            repo.remove(path)
        } else {
            repo.insert(path.to_string(), cids.clone())
        }
        .unwrap_or_default();
        if repo.is_empty() {
            self.records.remove(space);
        }
        for cid in before.iter().filter(|c| !cids.contains(c)) {
            *delta.entry(cid.clone()).or_default() -= 1;
        }
        for cid in cids.iter().filter(|c| !before.contains(c)) {
            *delta.entry(cid.clone()).or_default() += 1;
        }
    }

    /// Every record of the space repo `space` gone: counted in `delta`.
    fn empty(&mut self, space: &str, delta: &mut BTreeMap<String, i64>) {
        for cid in self
            .records
            .remove(space)
            .into_iter()
            .flat_map(|r| r.into_values().flatten())
        {
            *delta.entry(cid).or_default() -= 1;
        }
    }

    /// A record of a space repo a table `before` reads keeps whole, at
    /// `path` of `space`, referencing `cids`: counted in `blobs`.
    pub(super) fn kept(&mut self, space: &str, path: &str, cids: Vec<String>, blobs: &mut Blobs) {
        let mut delta = BTreeMap::new();
        self.set(space, path, cids, &mut delta);
        blobs.space_counted(delta);
    }

    /// Replay an entry of spaces state before the mark (`of_spaces`): of a
    /// space repo's commit, import or drop, what it changes of its records'
    /// blob references, counted in `blobs`, and its rev, after which
    /// `tids` makes revs; of any other kind, nothing. Whatever of it does
    /// not read as this version writes it is passed over.
    pub(crate) fn replay(&mut self, e: &Json, blobs: &mut Blobs, tids: &mut Tids) {
        let Some(space) = e["space"].as_str() else {
            return;
        };
        let t = e["t"].as_str().unwrap_or_default();
        if ![space_repo::ENTRY, space_repo::IMPORT, space_repo::DROP].contains(&t) {
            return;
        }
        if let Some(rev) = e["rev"].as_str().filter(|r| valid_tid(r)) {
            tids.after(rev);
        }
        let list = |k: &str| e[k].as_array().map(Vec::as_slice).unwrap_or_default();
        // Each `[path, value]` of a list, and the CIDs its value references.
        let records = |k: &str| {
            list(k)
                .iter()
                .filter_map(|p| match p.as_array().map(Vec::as_slice) {
                    Some([Json::String(path), value]) => Some((
                        path.clone(),
                        put_record(value)
                            .map(|r| cids_in(&r.value))
                            .unwrap_or_default(),
                    )),
                    _ => None,
                })
        };
        let mut delta = BTreeMap::new();
        match t {
            space_repo::ENTRY => {
                // A `clearRecords` that names the prefixes of the records it keeps.
                if let Some(kept) = e["kept"].as_array() {
                    let kept: Vec<&str> = kept.iter().filter_map(Json::as_str).collect();
                    let gone: Vec<String> = self
                        .records
                        .get(space)
                        .into_iter()
                        .flat_map(BTreeMap::keys)
                        .filter(|p| !kept.iter().any(|k| p.starts_with(k)))
                        .cloned()
                        .collect();
                    for path in gone {
                        self.set(space, &path, Vec::new(), &mut delta);
                    }
                }
                for path in list("dels").iter().filter_map(Json::as_str) {
                    self.set(space, path, Vec::new(), &mut delta);
                }
                for (path, cids) in records("puts") {
                    self.set(space, &path, cids, &mut delta);
                }
            }
            space_repo::IMPORT => {
                self.empty(space, &mut delta);
                for (path, cids) in records("records") {
                    self.set(space, &path, cids, &mut delta);
                }
            }
            _ => self.empty(space, &mut delta),
        }
        blobs.space_counted(delta);
    }

    /// As a table's state keeps it: each record that references blobs, its
    /// space, path and CIDs, in order.
    pub(super) fn saved(&self) -> impl Iterator<Item = (&str, &str, &[String])> {
        self.records.iter().flat_map(|(space, repo)| {
            repo.iter()
                .map(move |(path, cids)| (space.as_str(), path.as_str(), cids.as_slice()))
        })
    }

    /// Restore a record `saved` gave, in its order.
    pub(super) fn restore(
        &mut self,
        space: String,
        path: String,
        cids: Vec<String>,
    ) -> Result<(), String> {
        let last = self
            .records
            .last_key_value()
            .and_then(|(s, repo)| Some((s.as_str(), repo.last_key_value()?.0.as_str())));
        if cids.is_empty() || last.is_some_and(|l| l >= (space.as_str(), path.as_str())) {
            return Err("unmarked records out of order, or with no blob refs".into());
        }
        self.records.entry(space).or_default().insert(path, cids);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pds_repo::data::{V, cid_of, cid_string};
    use pds_repo::{make_record, put_value};

    /// A space record whose put holds its block, as `put_value` writes one
    /// whose JSON would read back as another, a blob ref whose `ref` is a
    /// map of the one key `$link`, references its blob when replayed before
    /// the mark, from an import and from a commit alike.
    #[test]
    fn a_put_of_a_block_references_its_blobs() {
        let blob = cid_string(&cid_of(0x55, b"blob"));
        let text = |t: &str| V::Str(t.into());
        let map =
            |kv: &[(&str, V)]| V::Map(kv.iter().map(|(k, v)| (k.to_string(), v.clone())).collect());
        let put = put_value(&make_record(map(&[
            ("$type", text("a.b.c")),
            (
                "img",
                map(&[
                    ("$type", text("blob")),
                    ("ref", map(&[("$link", text(&blob))])),
                    ("mimeType", text("text/plain")),
                    ("size", V::Int(4)),
                ]),
            ),
        ])));
        assert!(put.is_string(), "a put of the record's block");
        let space = "at://did:web:example.com/space/com.example.chat/room";
        let (mut unmarked, mut blobs, mut tids) =
            (Unmarked::default(), Blobs::default(), Tids::new());
        unmarked.replay(
            &json!({ "t": space_repo::IMPORT, "space": space, "rev": "3mzzzzzzzzzz2", "records": [["a.b.c/x", put]] }),
            &mut blobs,
            &mut tids,
        );
        unmarked.replay(
            &json!({ "t": space_repo::ENTRY, "space": space, "rev": "3mzzzzzzzzzz3", "puts": [["a.b.c/y", put]], "dels": [] }),
            &mut blobs,
            &mut tids,
        );
        let saved: Vec<(&str, &str, &[String])> = unmarked.saved().collect();
        let cids = [blob];
        assert_eq!(
            saved,
            [(space, "a.b.c/x", &cids[..]), (space, "a.b.c/y", &cids[..])]
        );
    }
}