~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
990 lines · 37.0 KB Raw History
//! The firehose's index: which events were made, and whose, kept as they
//! are made, so that a start learns the events in the backfill window
//! without reading any account's files (`spec/STORE.md`, "The firehose
//! after a start").
//!
//! It is a log with generations (`pds_store`) in the data directory,
//! `events.<g>.log` and its checkpoint `events.checkpoint`, one of the pool
//! the accounts' logs are of. Numbering events appends one frame, the
//! entries of the events numbered together, each `[seq, time, account]`:
//! its seq, when it was made, in milliseconds since the epoch, which is the
//! `time` its frame carries, and its account's DID; with a fourth element,
//! `1`, where the event's frame is the service log's
//! (`Firehose::reserve_kept`). The entry is appended before the frame that
//! holds the event is appended to its account's log, or the service log,
//! and whatever is made of that frame, an answer or the event sent, waits
//! for both to be on disk, the entry first (`Landing`). Neither the
//! events' frames nor anything of a deletion is in it: a deleted account's
//! events are dropped by the service log's `deleted` entry, which names
//! their seqs (`lifecycle`), and its entries go as they leave the window.
//!
//! So of an event numbered and not yet answered, a kill leaves its entry,
//! with its frame or without; a power cut, either, both or neither:
//!
//! - **An entry with no frame** is of an event never answered and never
//!   sent. Its seq is not given again, and a replay passes over it: its
//!   account's store holds no frame of that seq (`Firehose::batch`).
//! - **A frame with no entry** is of a write never answered either, found
//!   whole after a power cut. Nothing of it is undone: its event is
//!   **void**, never sent, and the index is given an entry of it with a
//!   fourth element `2`, so that no later start takes it for one to look
//!   into again (`Firehose::voided`). The service log's own events need no
//!   entry to be events: a start reads them all.
//!
//! **The checkpoint** is frames (`pds_store`): a header, `{"t": "events",
//! "version", "generation"}`; the entries in order of seq, up to `FRAME` a
//! frame, each as the log has it but that an account is its DID where the
//! file first names it and from then on how many DIDs the file named before
//! that one; then the void entries; and last `{"t": "end", "events",
//! "gone", "made"}`: how many entries the file holds, the greatest seq of
//! an entry let go, and the greatest seq an entry ever had. The fold
//! (`IndexFold`) reads the checkpoint before and the sealed logs as it
//! writes, an entry at a time, and lets go of those before the first made
//! within the backfill window but the latest few of an account's log, of
//! which it cannot tell whether they had a frame: always a run from the
//! start, so that what the files hold is every entry after `gone`; and of
//! the void ones those of a seq not after `gone`. The log is compacted as
//! the service log is (`store::service_policy`): what a start reads of it
//! follows the events in the window, not every event ever made.
//!
//! **A data directory with no index**, as the version before this left
//! it, has one made of its accounts' files on its first start
//! (`Firehose::adopt`, `write_whole`): a checkpoint of generation 0,
//! written beside its place, made durable and renamed into it. The file
//! that version left of the events at a shutdown, `events.index`, is
//! removed (`forget_legacy`).

use super::UNSURE;
use pds_store::{Files, Fold, Layout, Policy, Wal};
use serde_json::{Value as Json, json};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// What the files are named by.
const STEM: &str = "events";

/// What the checkpoint's header's `t` is, and its last frame's.
const HEADER: &str = "events";
const END: &str = "end";

/// The version of the checkpoint's format written, and the only one read.
const VERSION: u64 = 1;

/// The most entries in a frame of the checkpoint.
const FRAME: usize = 4096;

/// How long past the window an entry is kept by a fold: as an account's
/// log keeps its events (`store::in_window`).
const SLACK: u64 = 1000;

/// The file the version before left of the events as it shut down.
const LEGACY: &str = "events.index";

/// The index's files, in the data directory `dir`.
pub(crate) fn layout(dir: &Path) -> Layout {
    Layout::new(dir, STEM)
}

/// Whether the data directory `dir` holds an index: its checkpoint, or a
/// log of any generation.
pub(crate) fn exists(dir: &Path) -> bool {
    let layout = layout(dir);
    layout.checkpoint().exists() || layout.generations().is_ok_and(|g| !g.is_empty())
}

/// Remove what the version before left of the events as it shut down, and
/// what a shutdown cut short left beside it.
pub(crate) fn forget_legacy(dir: &Path) -> io::Result<()> {
    for name in [LEGACY.to_string(), format!("{LEGACY}.tmp")] {
        match std::fs::remove_file(dir.join(name)) {
            Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
            _ => {}
        }
    }
    Ok(())
}

/// Where the index is kept, and how its log is opened.
pub(crate) struct At {
    /// The data directory.
    pub dir: PathBuf,
    /// The pool its log is one of: the accounts' logs'.
    pub pool: Arc<Files>,
    pub policy: Policy,
    /// Whether every frame its files hold is on disk (`ops::durable`): its
    /// log is then opened with no sync.
    pub durable: bool,
}

/// What an entry is of.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Kind {
    /// An event whose frame its account's log holds.
    Account,
    /// An event whose frame the service log holds.
    Kept,
    /// An event an account's log holds that no entry was kept of, never sent.
    Void,
}

impl Kind {
    /// The fourth element of its entry, if it has one.
    fn flag(self) -> Option<u64> {
        match self {
            Kind::Account => None,
            Kind::Kept => Some(1),
            Kind::Void => Some(2),
        }
    }

    fn of(flag: Option<u64>) -> Option<Kind> {
        match flag {
            None => Some(Kind::Account),
            Some(1) => Some(Kind::Kept),
            Some(2) => Some(Kind::Void),
            Some(_) => None,
        }
    }
}

/// An event as the index has it.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Entry {
    pub seq: u64,
    /// When it was made, in milliseconds since the epoch.
    pub at: u64,
    pub did: Arc<str>,
    pub kind: Kind,
}

/// The log's entry of an event, `[seq, at, did]` and its kind's flag.
pub(super) fn entry(seq: u64, at: u64, did: &str, kind: Kind) -> Json {
    match kind.flag() {
        Some(flag) => json!([seq, at, did, flag]),
        None => json!([seq, at, did]),
    }
}

/// The log's entries of `n` events of `did` numbered from `seq`, made at
/// `at`, their frames the service log's if `kept`.
pub(super) fn entries(seq: u64, n: usize, at: u64, did: &str, kept: bool) -> Vec<Json> {
    let kind = if kept { Kind::Kept } else { Kind::Account };
    (seq..seq + n as u64)
        .map(|seq| entry(seq, at, did, kind))
        .collect()
}

/// The DIDs read so far, each held once.
#[derive(Default)]
struct Dids(HashSet<Arc<str>>);

impl Dids {
    fn get(&mut self, did: &str) -> Arc<str> {
        if let Some(held) = self.0.get(did) {
            return held.clone();
        }
        let held: Arc<str> = Arc::from(did);
        self.0.insert(held.clone());
        held
    }
}

/// An entry of the log, as read.
fn log_entry(e: &Json, dids: &mut Dids) -> Result<Entry, String> {
    let mut entry = || -> Option<Entry> {
        let fields = e.as_array().filter(|f| f.len() <= 4)?;
        let kind = Kind::of(match fields.get(3) {
            None => None,
            Some(k) => Some(k.as_u64()?),
        })?;
        Some(Entry {
            seq: fields.first()?.as_u64().filter(|seq| *seq > 0)?,
            at: fields.get(1)?.as_u64()?,
            did: dids.get(fields.get(2)?.as_str()?),
            kind,
        })
    };
    entry().ok_or_else(|| format!("an entry that is no event's: {e}"))
}

/// An account as a checkpoint's entry names it: its DID, or how many DIDs
/// the file named before it.
enum Account<'a> {
    First(&'a str),
    Again(u64),
}

impl serde::Serialize for Account<'_> {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self {
            Account::First(did) => s.serialize_str(did),
            Account::Again(n) => s.serialize_u64(*n),
        }
    }
}

/// A checkpoint's entry, as read: its account still as the file names it.
struct Row {
    seq: u64,
    at: u64,
    account: Named,
    flag: Option<u64>,
}

/// An account as a checkpoint's entry names it, read.
enum Named {
    First(String),
    Again(u64),
}

impl<'de> serde::Deserialize<'de> for Named {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Named, D::Error> {
        struct V;
        impl serde::de::Visitor<'_> for V {
            type Value = Named;
            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a DID, or how many were named before it")
            }
            fn visit_str<E: serde::de::Error>(self, did: &str) -> Result<Named, E> {
                Ok(Named::First(did.to_string()))
            }
            fn visit_u64<E: serde::de::Error>(self, n: u64) -> Result<Named, E> {
                Ok(Named::Again(n))
            }
        }
        d.deserialize_any(V)
    }
}

impl<'de> serde::Deserialize<'de> for Row {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Row, D::Error> {
        struct V;
        impl<'de> serde::de::Visitor<'de> for V {
            type Value = Row;
            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("an event's seq, time and account")
            }
            fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut a: A) -> Result<Row, A::Error> {
                use serde::de::Error;
                let missing = || A::Error::custom("an entry cut short");
                let row = Row {
                    seq: a.next_element()?.ok_or_else(missing)?,
                    at: a.next_element()?.ok_or_else(missing)?,
                    account: a.next_element()?.ok_or_else(missing)?,
                    flag: a.next_element::<u64>()?,
                };
                match a.next_element::<serde::de::IgnoredAny>()? {
                    None => Ok(row),
                    Some(_) => Err(A::Error::custom("an entry with more than an event's")),
                }
            }
        }
        d.deserialize_seq(V)
    }
}

/// What a checkpoint says of itself, besides its entries.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) struct Summary {
    /// The generation it is the checkpoint of.
    pub generation: u64,
    /// Its size, in bytes.
    pub size: u64,
    /// The greatest seq of an entry let go; 0 if none was.
    pub gone: u64,
    /// The greatest seq an entry ever had; 0 if there was none.
    pub made: u64,
}

/// Writes a checkpoint: its header, the entries given, in order of seq
/// but for the void ones after them, and its end.
struct Writer<'a> {
    out: &'a mut dyn Write,
    /// Each DID named so far, and how many were named before it.
    named: HashMap<Arc<str>, u64>,
    /// The entries of the frame being made.
    frame: Vec<Entry>,
    /// How many entries were given.
    count: u64,
}

impl<'a> Writer<'a> {
    fn new(out: &'a mut dyn Write, generation: u64) -> Result<Writer<'a>, String> {
        let header = json!({ "t": HEADER, "version": VERSION, "generation": generation });
        out.write_all(&pds_store::frame(&[header]))
            .map_err(|e| e.to_string())?;
        Ok(Writer {
            out,
            named: HashMap::new(),
            frame: Vec::with_capacity(FRAME),
            count: 0,
        })
    }

    fn put(&mut self, e: Entry) -> Result<(), String> {
        self.frame.push(e);
        self.count += 1;
        if self.frame.len() == FRAME {
            self.flush()?;
        }
        Ok(())
    }

    fn flush(&mut self) -> Result<(), String> {
        use serde::ser::{SerializeSeq, Serializer};
        if self.frame.is_empty() {
            return Ok(());
        }
        let (entries, named) = (&self.frame, &mut self.named);
        let frame = pds_store::frame_of(entries.len() * 32, |out| {
            let mut s = serde_json::Serializer::new(out);
            let mut rows = s
                .serialize_seq(Some(entries.len()))
                .expect("a frame serializes");
            for e in entries {
                let before = named.len() as u64;
                let account = match named.get(&e.did) {
                    Some(n) => Account::Again(*n),
                    None => {
                        named.insert(e.did.clone(), before);
                        Account::First(&e.did)
                    }
                };
                match e.kind.flag() {
                    Some(flag) => rows.serialize_element(&(e.seq, e.at, account, flag)),
                    None => rows.serialize_element(&(e.seq, e.at, account)),
                }
                .expect("an entry serializes");
            }
            rows.end().expect("a frame serializes");
        });
        self.frame.clear();
        self.out.write_all(&frame).map_err(|e| e.to_string())
    }

    fn end(mut self, gone: u64, made: u64) -> Result<(), String> {
        self.flush()?;
        let end = json!({ "t": END, "events": self.count, "gone": gone, "made": made });
        self.out
            .write_all(&pds_store::frame(&[end]))
            .map_err(|e| e.to_string())
    }
}

/// The next frame's payload of a checkpoint being read, none at its end:
/// an error if what is there is no whole frame.
fn next_payload(r: &mut impl Read, read: &mut u64) -> Result<Option<Vec<u8>>, String> {
    let mut frame = vec![0u8; pds_store::HEADER];
    match r.read(&mut frame[..1]) {
        Ok(0) => return Ok(None),
        Ok(_) => {}
        Err(e) => return Err(e.to_string()),
    }
    let cut = |_| "a frame cut short".to_string();
    r.read_exact(&mut frame[1..]).map_err(cut)?;
    let len = u32::from_le_bytes(frame[..4].try_into().expect("four bytes")) as usize;
    frame.resize(pds_store::HEADER + len, 0);
    r.read_exact(&mut frame[pds_store::HEADER..]).map_err(cut)?;
    *read += frame.len() as u64;
    pds_store::payload(frame)
        .map(Some)
        .ok_or_else(|| "a frame that fails its check".to_string())
}

/// The one entry of a frame that is the header's or the end's, if it is `t`'s.
fn marker(payload: &[u8], t: &str) -> Option<Json> {
    match serde_json::from_slice::<Vec<Json>>(payload)
        .ok()?
        .as_slice()
    {
        [m] if m["t"] == t => Some(m.clone()),
        _ => None,
    }
}

/// Read the checkpoint at `path`, giving `f` each entry in order: what it
/// says of itself, none if there is no checkpoint; an error if it is not
/// whole, of another version, or its entries are not as it says: those
/// not void in order of seq, then the void ones, none past the last made.
fn read_checkpoint(
    path: &Path,
    dids: &mut Dids,
    mut f: impl FnMut(Entry) -> Result<(), String>,
) -> Result<Option<Summary>, String> {
    let file = match std::fs::File::open(path) {
        Ok(file) => file,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(e.to_string()),
    };
    let mut r = io::BufReader::with_capacity(1 << 16, file);
    let mut size = 0;
    let header = next_payload(&mut r, &mut size)?
        .and_then(|p| marker(&p, HEADER))
        .ok_or("no header")?;
    if header["version"].as_u64() != Some(VERSION) {
        return Err(format!("of version {}, not {VERSION}", header["version"]));
    }
    let generation = header["generation"]
        .as_u64()
        .ok_or("a header with no generation")?;
    // The DIDs the file has named, in the order it named them.
    let mut named: Vec<Arc<str>> = Vec::new();
    // How many entries; the last seq of one not void, the greatest of any;
    // whether the void ones have begun.
    let (mut count, mut last, mut greatest, mut voids) = (0u64, 0u64, 0u64, false);
    loop {
        let payload = next_payload(&mut r, &mut size)?.ok_or("no end")?;
        if payload.starts_with(b"[{") {
            let end = marker(&payload, END).ok_or("a frame that is no entries'")?;
            let n = |k: &str| end[k].as_u64().ok_or_else(|| format!("an end with no {k}"));
            if n("events")? != count {
                return Err(format!(
                    "{count} entries, not the {} it says",
                    end["events"]
                ));
            }
            if next_payload(&mut r, &mut size)?.is_some() {
                return Err("a frame after its end".into());
            }
            let (gone, made) = (n("gone")?, n("made")?);
            if made < greatest.max(gone) {
                return Err(format!("an entry after {made}, the last it says was made"));
            }
            return Ok(Some(Summary {
                generation,
                size,
                gone,
                made,
            }));
        }
        let rows: Vec<Row> =
            serde_json::from_slice(&payload).map_err(|e| format!("an entry: {e}"))?;
        for row in rows {
            let did = match row.account {
                Named::First(did) => {
                    named.push(dids.get(&did));
                    named.last().expect("just named").clone()
                }
                Named::Again(n) => usize::try_from(n)
                    .ok()
                    .and_then(|n| named.get(n))
                    .ok_or_else(|| format!("an entry of account {n}, not yet named"))?
                    .clone(),
            };
            let kind = Kind::of(row.flag).ok_or("an entry of no known kind")?;
            match kind {
                Kind::Void => voids = true,
                _ if voids => return Err(format!("entry {} after the void ones", row.seq)),
                _ if row.seq <= last => {
                    return Err(format!("entry {} after entry {last}", row.seq));
                }
                _ => last = row.seq,
            }
            if row.seq == 0 {
                return Err("an entry of seq 0".into());
            }
            (count, greatest) = (count + 1, greatest.max(row.seq));
            f(Entry {
                seq: row.seq,
                at: row.at,
                did,
                kind,
            })?;
        }
    }
}

/// The index as a start reads it.
pub(super) struct Opened {
    /// Its log, to append to.
    pub wal: Wal,
    /// Every entry it holds but the void ones, in order of seq.
    pub entries: Vec<Entry>,
    /// The seqs of the void ones.
    pub voids: Vec<u64>,
    /// The greatest seq of an entry let go.
    pub gone: u64,
    /// The greatest seq an entry ever had.
    pub made: u64,
}

/// Read the index `at` names: its checkpoint, if it has one, then its log
/// after, replayed, or begun. An error if it holds what cannot be
/// recovered: a checkpoint that is not whole, an entry that is no event's,
/// or entries not void out of order.
pub(super) fn open(at: &At) -> Result<Opened, String> {
    let layout = layout(&at.dir);
    let checkpoint = layout.checkpoint();
    let mut dids = Dids::default();
    let (mut entries, mut voids): (Vec<Entry>, Vec<u64>) = (Vec::new(), Vec::new());
    let summary = read_checkpoint(&checkpoint, &mut dids, |e| {
        match e.kind {
            Kind::Void => voids.push(e.seq),
            _ => entries.push(e),
        }
        Ok(())
    })
    .map_err(|why| format!("{}: {why}", checkpoint.display()))?
    .unwrap_or_default();
    let folded = (entries.len(), voids.len());
    let wal = crate::log::retrying(|| {
        entries.truncate(folded.0);
        voids.truncate(folded.1);
        Wal::open_log_with(
            &layout,
            summary.generation,
            summary.size,
            Some(at.pool.clone()),
            at.policy,
            at.durable,
            &mut |_, frame| {
                for e in &frame {
                    let e = log_entry(e, &mut dids)?;
                    match e.kind {
                        Kind::Void => voids.push(e.seq),
                        _ => entries.push(e),
                    }
                }
                Ok(())
            },
        )
    })
    .map_err(|e| format!("{}: {e}", layout.dir.join(STEM).display()))?;
    if let Some(w) = entries.windows(2).find(|w| w[0].seq >= w[1].seq) {
        return Err(format!(
            "{}: entry {} after entry {}",
            layout.dir.join(STEM).display(),
            w[1].seq,
            w[0].seq
        ));
    }
    let made = entries
        .last()
        .map(|e| e.seq)
        .into_iter()
        .chain(voids.iter().copied())
        .fold(summary.made, u64::max);
    Ok(Opened {
        wal,
        entries,
        voids,
        gone: summary.gone,
        made,
    })
}

/// The index's fold: the checkpoint of a generation, of the one before and
/// the sealed logs after it, without the entries before the first made
/// within the backfill window, nor the void ones of a seq not after them;
/// but for the latest `UNSURE` of those of an account's log, after the
/// last of the service log's: whether an entry had a frame the index
/// cannot tell, and one that had none was no event, so that a start lets
/// them go as the firehose does an entry it holds (`Seq::let_go`), to be
/// found to have none, and `gone` is the greatest seq of the others.
pub(super) struct IndexFold {
    /// The backfill window, in milliseconds.
    pub window: u64,
}

impl Fold for IndexFold {
    fn fold_files(
        &self,
        checkpoint: Option<&Path>,
        logs: &[PathBuf],
        generation: u64,
        out: &mut dyn Write,
    ) -> Result<(), String> {
        let since = super::now_ms().saturating_sub(self.window + SLACK);
        let mut dids = Dids::default();
        let mut w = Writer::new(out, generation)?;
        // The greatest seq let go and the greatest there was; whether an
        // entry is kept yet: every one after the first kept is. Those out
        // of the window kept as unsure, written before the first kept. The
        // void ones, written after the rest.
        let (mut gone, mut made, mut keeping) = (0u64, 0u64, false);
        let mut unsure: std::collections::VecDeque<Entry> = std::collections::VecDeque::new();
        let mut voids: BTreeMap<u64, Entry> = BTreeMap::new();
        let mut put = |e: Entry, w: &mut Writer| {
            made = made.max(e.seq);
            if e.kind == Kind::Void {
                voids.insert(e.seq, e);
                return Ok(());
            }
            if !keeping && e.at < since {
                if e.kind == Kind::Kept {
                    gone = gone.max(e.seq);
                    unsure.clear();
                    return Ok(());
                }
                unsure.push_back(e);
                if unsure.len() > UNSURE
                    && let Some(old) = unsure.pop_front()
                {
                    gone = gone.max(old.seq);
                }
                return Ok(());
            }
            if !keeping {
                keeping = true;
                for u in unsure.drain(..) {
                    w.put(u)?;
                }
            }
            w.put(e)
        };
        let before = match checkpoint {
            Some(path) => read_checkpoint(path, &mut dids, |e| put(e, &mut w))
                .map_err(|why| format!("{}: {why}", path.display()))?,
            None => None,
        };
        for path in logs {
            pds_store::read_sealed(path, |_, _, frame| {
                frame
                    .iter()
                    .try_for_each(|e| put(log_entry(e, &mut dids)?, &mut w))
                    .map_err(|why| format!("{}: {why}", path.display()))
            })?;
        }
        for u in unsure.drain(..) {
            w.put(u)?;
        }
        let before = before.unwrap_or_default();
        let gone = gone.max(before.gone);
        for (_, e) in voids.split_off(&(gone + 1)) {
            w.put(e)?;
        }
        w.end(gone, made.max(before.made))
    }
}

/// Leave in `dir`, which holds no index, the checkpoint of one holding
/// `events`, each one's seq, account and time, in order of seq, with `gone`
/// the greatest seq of an event let go and `made` the greatest any had:
/// written beside its place, made durable, and renamed into it.
pub(super) fn write_whole(
    dir: &Path,
    events: &[(u64, Arc<str>, u64)],
    gone: u64,
    made: u64,
) -> io::Result<()> {
    let layout = layout(dir);
    let tmp = layout.tmp();
    let file = pds_store::open_private(
        &tmp,
        std::fs::OpenOptions::new()
            .create(true)
            .truncate(true)
            .write(true),
    )?;
    let mut out = io::BufWriter::new(&file);
    let written = (|| {
        let mut w = Writer::new(&mut out, 0)?;
        for (seq, did, at) in events {
            w.put(Entry {
                seq: *seq,
                at: *at,
                did: did.clone(),
                kind: Kind::Account,
            })?;
        }
        w.end(gone, made)
    })();
    written.map_err(io::Error::other)?;
    out.flush()?;
    drop(out);
    pds_store::sync_file(&file)?;
    std::fs::rename(&tmp, layout.checkpoint())?;
    pds_store::sync_dir(dir)
}

/// The seqs of the entries of the checkpoint in `dir`, in its order.
#[cfg(test)]
pub(super) fn checkpoint_seqs(dir: &Path) -> Vec<u64> {
    let mut seqs = Vec::new();
    read_checkpoint(&layout(dir).checkpoint(), &mut Dids::default(), |e| {
        seqs.push(e.seq);
        Ok(())
    })
    .unwrap();
    seqs
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entry_of(n: u64) -> Entry {
        Entry {
            seq: 2 * n + 4,
            at: 1_700_000_000_000 + n,
            did: Arc::from(format!("did:plc:{}", (n * n) % 7).as_str()),
            kind: if n % 5 == 3 {
                Kind::Kept
            } else {
                Kind::Account
            },
        }
    }

    /// A checkpoint of `entries`, of generation 3.
    fn checkpoint(entries: &[Entry], gone: u64, made: u64) -> Vec<u8> {
        let mut out = Vec::new();
        let mut w = Writer::new(&mut out, 3).unwrap();
        for e in entries {
            w.put(e.clone()).unwrap();
        }
        w.end(gone, made).unwrap();
        out
    }

    fn read(path: &Path) -> Result<Option<(Summary, Vec<Entry>)>, String> {
        let mut entries = Vec::new();
        let summary = read_checkpoint(path, &mut Dids::default(), |e| {
            entries.push(e);
            Ok(())
        })?;
        Ok(summary.map(|s| (s, entries)))
    }

    /// A checkpoint is read as it was written, however many frames it
    /// takes, its void entries after the rest, an account's entries
    /// sharing its DID; and none is none.
    #[test]
    fn a_checkpoint_is_read_as_written() {
        let dir = crate::testing::scratch("events-checkpoint");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("events.checkpoint");
        assert_eq!(read(&path), Ok(None));
        for n in [0, 3, FRAME as u64, 2 * FRAME as u64 + 1] {
            let mut entries: Vec<Entry> = (0..n).map(entry_of).collect();
            entries.extend((0..n.min(3)).map(|n| Entry {
                seq: 2 * n + 5,
                kind: Kind::Void,
                ..entry_of(n)
            }));
            let made = entries.iter().map(|e| e.seq + 1).max().unwrap_or(9);
            let bytes = checkpoint(&entries, 3, made);
            std::fs::write(&path, &bytes).unwrap();
            let summary = Summary {
                generation: 3,
                size: bytes.len() as u64,
                gone: 3,
                made,
            };
            assert_eq!(read(&path), Ok(Some((summary, entries))));
        }
        let (_, entries) = read(&path).unwrap().unwrap();
        assert!(Arc::ptr_eq(&entries[0].did, &entries[7].did));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A checkpoint cut short at any byte, with a byte changed, with more
    /// after it, of another version, or whose entries are not those it
    /// counts, in order, is an error: never part of one.
    #[test]
    fn a_checkpoint_is_checked_as_read() {
        let dir = crate::testing::scratch("events-checkpoint-cut");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("events.checkpoint");
        let entries: Vec<Entry> = (0..FRAME as u64 + 9).map(entry_of).collect();
        let made = entries.last().unwrap().seq;
        let whole = checkpoint(&entries, 3, made);
        let put = |bytes: &[u8]| std::fs::write(&path, bytes).unwrap();
        let cuts = (0..400).chain((400..whole.len()).step_by(127));
        for cut in cuts.chain(whole.len() - 60..whole.len()) {
            put(&whole[..cut]);
            assert!(read(&path).is_err(), "cut at {cut}");
        }
        for at in (0..whole.len()).step_by(997) {
            let mut bytes = whole.clone();
            bytes[at] ^= 1;
            put(&bytes);
            assert!(read(&path).is_err(), "changed at {at}");
        }
        put(&[&whole[..], b"more"].concat());
        assert!(read(&path).is_err());
        // Whole frames, but not the entries the end counts, not in order,
        // past the last it says was made, or of another version.
        let frames = pds_store::scan(&whole).unwrap().0;
        assert_eq!(frames.len(), 4);
        let bytes = |frames: &[&Vec<Json>]| -> Vec<u8> {
            frames.iter().flat_map(|f| pds_store::frame(f)).collect()
        };
        put(&bytes(&[&frames[0], &frames[1], &frames[3]]));
        assert!(read(&path).is_err());
        put(&bytes(&[&frames[0], &frames[1], &frames[2]]));
        assert!(read(&path).is_err());
        let mut swapped = frames[2].clone();
        swapped.swap(3, 4);
        put(&bytes(&[&frames[0], &frames[1], &swapped, &frames[3]]));
        assert!(read(&path).is_err());
        let mut early = frames[3].clone();
        early[0]["made"] = json!(made - 1);
        put(&bytes(&[&frames[0], &frames[1], &frames[2], &early]));
        assert!(read(&path).is_err());
        let mut versioned = frames[0].clone();
        versioned[0]["version"] = json!(VERSION + 1);
        put(&bytes(&[&versioned, &frames[1], &frames[2], &frames[3]]));
        assert!(read(&path).is_err());
        // An entry not void after the void ones.
        let mut late = frames[2].clone();
        let row = late[0].as_array_mut().unwrap();
        row.truncate(3);
        row.push(json!(2));
        put(&bytes(&[&frames[0], &frames[1], &late, &frames[3]]));
        assert!(read(&path).is_err());
        put(&whole);
        assert_eq!(read(&path).unwrap().unwrap().1, entries);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The log's entries of events numbered together are read as written,
    /// the service log's and the void ones marked; what is no event's
    /// entry is an error.
    #[test]
    fn a_logs_entries_are_read_as_written() {
        let mut dids = Dids::default();
        let read = |e: &Json, dids: &mut Dids| log_entry(e, dids);
        let written = entries(7, 3, 1_700_000_000_123, "did:plc:a", false);
        let got: Vec<Entry> = written
            .iter()
            .map(|e| read(e, &mut dids).unwrap())
            .collect();
        assert_eq!(got.iter().map(|e| e.seq).collect::<Vec<_>>(), [7, 8, 9]);
        assert!(got.iter().all(|e| e.at == 1_700_000_000_123
            && &*e.did == "did:plc:a"
            && e.kind == Kind::Account));
        assert!(Arc::ptr_eq(&got[0].did, &got[2].did));
        let kept = entries(10, 1, 5, "did:plc:b", true);
        assert_eq!(read(&kept[0], &mut dids).unwrap().kind, Kind::Kept);
        let void = entry(4, 5, "did:plc:b", Kind::Void);
        assert_eq!(read(&void, &mut dids).unwrap().kind, Kind::Void);
        for bad in [
            json!([0, 5, "did:plc:a"]),
            json!([1, 5]),
            json!([1, "5", "did:plc:a"]),
            json!([1, 5, 6]),
            json!([1, 5, "did:plc:a", "x"]),
            json!([1, 5, "did:plc:a", 3]),
            json!([1, 5, "did:plc:a", 1, 1]),
            json!({ "t": "event" }),
        ] {
            assert!(read(&bad, &mut dids).is_err(), "{bad}");
        }
    }

    /// A fold keeps every entry from the first made within the window on,
    /// those of the checkpoint before and of the sealed logs in order, and
    /// the void ones after the entries let go; of those before the window,
    /// the latest `UNSURE` of an account's log after the last of the
    /// service log's, which may have had no frame; and says which it let go
    /// and the last there was, whatever it keeps.
    #[test]
    fn a_fold_lets_go_of_what_is_before_the_window() {
        let dir = crate::testing::scratch("events-fold");
        std::fs::create_dir_all(&dir).unwrap();
        let now = crate::events::now_ms();
        let window = 60_000;
        let at = |seq: u64, age: u64, did: &str, kind: Kind| Entry {
            seq,
            at: now - age,
            did: Arc::from(did),
            kind,
        };
        // In the checkpoint: two out of the window, then one within it, then
        // one made before that one and numbered after it, which is kept; and
        // two void ones, one before what is let go.
        let before = [
            at(3, 90_000, "did:plc:a", Kind::Account),
            at(4, 80_000, "did:plc:b", Kind::Account),
            at(6, 30_000, "did:plc:a", Kind::Account),
            at(7, 70_000, "did:plc:b", Kind::Account),
            at(2, 95_000, "did:plc:c", Kind::Void),
            at(5, 85_000, "did:plc:c", Kind::Void),
        ];
        let checkpoint_path = dir.join("events.checkpoint");
        std::fs::write(&checkpoint_path, checkpoint(&before, 2, 7)).unwrap();
        let log = dir.join("events.3.log");
        let mut frames = Vec::new();
        for (seq, did) in [(9, "did:plc:c"), (10, "did:plc:a")] {
            frames.extend(pds_store::frame(&entries(seq, 1, now - 5, did, seq == 10)));
        }
        frames.extend(pds_store::frame(&[entry(8, now, "did:plc:d", Kind::Void)]));
        frames.extend(pds_store::frame(&[json!({ "t": "seal" })]));
        std::fs::write(&log, &frames).unwrap();
        let fold = IndexFold { window };
        let mut out = Vec::new();
        fold.fold_files(
            Some(&checkpoint_path),
            std::slice::from_ref(&log),
            4,
            &mut out,
        )
        .unwrap();
        let folded = dir.join("folded");
        std::fs::write(&folded, &out).unwrap();
        let (summary, kept) = read(&folded).unwrap().unwrap();
        assert_eq!((summary.generation, summary.gone, summary.made), (4, 2, 10));
        assert_eq!(
            kept.iter().map(|e| (e.seq, e.kind)).collect::<Vec<_>>(),
            [
                (3, Kind::Account),
                (4, Kind::Account),
                (6, Kind::Account),
                (7, Kind::Account),
                (9, Kind::Account),
                (10, Kind::Kept),
                (5, Kind::Void),
                (8, Kind::Void)
            ]
        );
        // With every entry out of the window, none is kept before the
        // service log's last, and the last made is still told.
        let fold = IndexFold { window: 0 };
        let mut out = Vec::new();
        std::thread::sleep(std::time::Duration::from_millis(SLACK + 20));
        fold.fold_files(Some(&folded), &[], 5, &mut out).unwrap();
        std::fs::write(&folded, &out).unwrap();
        let (summary, kept) = read(&folded).unwrap().unwrap();
        assert_eq!((summary.gone, summary.made, kept.len()), (10, 10, 0));
        // Of more of an account's log's out of the window, the latest
        // `UNSURE` are kept, in order, and those before them let go.
        let log = dir.join("events.6.log");
        let last = 12 + UNSURE as u64;
        let mut frames = Vec::new();
        for seq in 11..=last {
            frames.extend(pds_store::frame(&entries(
                seq,
                1,
                now - 5,
                "did:plc:a",
                false,
            )));
        }
        frames.extend(pds_store::frame(&[json!({ "t": "seal" })]));
        std::fs::write(&log, &frames).unwrap();
        let mut out = Vec::new();
        fold.fold_files(Some(&folded), std::slice::from_ref(&log), 6, &mut out)
            .unwrap();
        std::fs::write(&folded, &out).unwrap();
        let (summary, kept) = read(&folded).unwrap().unwrap();
        assert_eq!((summary.gone, summary.made), (last - UNSURE as u64, last));
        assert_eq!(
            kept.iter().map(|e| e.seq).collect::<Vec<_>>(),
            (last + 1 - UNSURE as u64..=last).collect::<Vec<_>>()
        );
        // Folded again, they are kept as they were.
        let mut out = Vec::new();
        fold.fold_files(Some(&folded), &[], 7, &mut out).unwrap();
        let (again, kept_again) = {
            let refolded = dir.join("refolded");
            std::fs::write(&refolded, &out).unwrap();
            read(&refolded).unwrap().unwrap()
        };
        assert_eq!((again.gone, again.made), (summary.gone, summary.made));
        assert_eq!(kept_again, kept);
        let _ = std::fs::remove_dir_all(&dir);
    }
}