garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /records/src/log.rs

raw

//! An append-only log: what a task did, kept in the vault, written through
//! a file handle that may only add to the end (`pinnacle_abi::file::APPEND`),
//! so what is written stays as it was (`docs/agent-environment.md`).
//!
//! The file is [`HEADER`] and then entries, each its body's length (u32,
//! little-endian), the body, and the length again: read forwards to list
//! what happened, backwards to undo it, newest first. A write is one file
//! system transaction, so a power cut leaves a whole entry or none; a tail
//! that does not frame (written by something else) ends the reading there.

use alloc::vec::Vec;

/// What a log file starts with: its name and format version.
pub const HEADER: &[u8; 8] = b"PLOG\x01\0\0\0";

/// The largest entry body.
pub const MAX_ENTRY: usize = 1 << 20;

/// An entry's bytes, to add at the end; with the header first for a file
/// that is still empty (`at_start`).
pub fn entry(body: &[u8], at_start: bool) -> Vec<u8> {
    let len = (body.len().min(MAX_ENTRY) as u32).to_le_bytes();
    let mut out = Vec::with_capacity(body.len() + 16);
    if at_start {
        out.extend_from_slice(HEADER);
    }
    out.extend_from_slice(&len);
    out.extend_from_slice(&body[..body.len().min(MAX_ENTRY)]);
    out.extend_from_slice(&len);
    out
}

/// The bodies of a log's entries, oldest first; None for a file that is not
/// a log. Reading stops at the first entry that does not frame.
pub fn entries(file: &[u8]) -> Option<Vec<&[u8]>> {
    if file.is_empty() {
        return Some(Vec::new());
    }
    let mut rest = file.strip_prefix(HEADER.as_slice())?;
    let mut out = Vec::new();
    while rest.len() >= 8 {
        let len = u32::from_le_bytes(rest[..4].try_into().unwrap()) as usize;
        if len > MAX_ENTRY || rest.len() < 8 + len || rest[4 + len..8 + len] != rest[..4] {
            break;
        }
        out.push(&rest[4..4 + len]);
        rest = &rest[8 + len..];
    }
    Some(out)
}

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

    #[test]
    fn written_and_read_back() {
        let mut file = entry(b"first", true);
        file.extend(entry(b"", false));
        file.extend(entry(b"third one", false));
        let read = entries(&file).unwrap();
        assert_eq!(read, vec![&b"first"[..], b"", b"third one"]);
        assert_eq!(entries(&[]).unwrap(), Vec::<&[u8]>::new());
    }

    #[test]
    fn a_torn_or_foreign_tail_ends_it() {
        let mut file = entry(b"kept", true);
        let whole = file.len();
        file.extend(entry(b"torn", false));
        file.truncate(file.len() - 2);
        assert_eq!(entries(&file).unwrap(), vec![&b"kept"[..]]);
        file.truncate(whole);
        file.extend_from_slice(&[0xff; 12]);
        assert_eq!(entries(&file).unwrap(), vec![&b"kept"[..]]);
        assert_eq!(entries(b"not a log"), None);
    }
}