vpf-runner 0.4.1

The reference runner of the Verifiable Plan Format (VPF): runs a plan step by step and proves each step.
Documentation
//! The journal of a run: everything it was given from outside it, each under a key that names where in the run it
//! was given, so that the run can go on from its kept state without asking any of it again.

use std::collections::HashMap;

use jiff::Timestamp;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// One thing a run was given: an agent's answer, a command's result, a person's reply or a time.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Entry {
    /// Where in the run it was given.
    pub key: String,
    /// When.
    pub at: Timestamp,
    /// Who gave it, when they said who they are.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub by: Option<String>,
    /// What was given.
    pub value: Value,
}

/// Who keeps a run's entries as they come, in a store of its own: a host that must not lose what a run was given
/// should the computer go down in the middle of it.
///
/// A run that stopped is rebuilt from the record it last began with and the entries kept after it, joined by
/// [`Record::add_entries`](crate::Record::add_entries), and goes on with [`Runner::resume`](crate::Runner::resume)
/// without asking any of them again.
pub trait Keeper {
    /// A run begins, or goes on: its record as it stands, with the entries it was given before. Nothing the record
    /// holds is handed to [`Keeper::kept`] again.
    fn begin(&mut self, record: &crate::Record) {
        let _ = record;
    }

    /// The run was just given this: it is handed out as soon as it is kept, once. A later entry under the same key
    /// takes the place of the earlier.
    fn kept(&mut self, entry: &Entry);
}

impl<F: FnMut(&Entry)> Keeper for F {
    fn kept(&mut self, entry: &Entry) {
        self(entry);
    }
}

/// The entries of a run, read back in any order by their keys.
#[derive(Debug, Default)]
pub(crate) struct Journal {
    entries: Vec<Entry>,
    places: HashMap<String, usize>,
    /// Whether the run has gone past what it was given before, and now reads the clock and asks for itself.
    pub live: bool,
    /// While the run goes over what it was given before, the latest time of what it read back: its clock.
    pub time: Timestamp,
}

impl Journal {
    /// A journal with these entries, of a run that started at `started`.
    pub fn new(entries: Vec<Entry>, started: Timestamp) -> Self {
        let live = entries.is_empty();
        let places = entries
            .iter()
            .enumerate()
            .map(|(place, entry)| (entry.key.clone(), place))
            .collect();
        Self {
            entries,
            places,
            live,
            time: started,
        }
    }

    /// What was given under `key`, and who gave it, when the run was given it before.
    pub fn recall<T: DeserializeOwned>(&mut self, key: &str) -> Option<(T, Option<String>)> {
        let entry = &self.entries[*self.places.get(key)?];
        let value = serde_json::from_value(entry.value.clone()).ok()?;
        let by = entry.by.clone();
        self.time = self.time.max(entry.at);
        Some((value, by))
    }

    /// Keeps what was given under `key`.
    pub fn keep<T: Serialize>(&mut self, key: String, value: &T, at: Timestamp) {
        let entry = Entry {
            key: key.clone(),
            at,
            by: None,
            value: serde_json::to_value(value).unwrap_or_default(),
        };
        if let Some(&place) = self.places.get(&key) {
            self.entries[place] = entry;
        } else {
            self.places.insert(key, self.entries.len());
            self.entries.push(entry);
        }
    }

    /// Whether the run was given anything under `key` before.
    pub fn knows(&self, key: &str) -> bool {
        self.places.contains_key(key)
    }

    /// The entries, in the order they were given.
    pub fn entries(&self) -> Vec<Entry> {
        self.entries.clone()
    }
}

/// A short, stable name for a text, to tell its versions apart in keys.
pub(crate) fn stamp(text: &str) -> String {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for byte in text.bytes() {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x0100_0000_01b3);
    }
    format!("{:08x}", hash >> 32)
}

#[cfg(test)]
mod tests {
    use super::{Journal, stamp};

    #[test]
    fn what_is_kept_is_recalled_by_key() {
        let started = "2027-03-01T10:00:00Z".parse().expect("a time");
        let mut journal = Journal::new(Vec::new(), started);
        assert!(journal.live);
        journal.keep(
            "a/0/work".to_owned(),
            &"done",
            "2027-03-01T11:00:00Z".parse().expect("a time"),
        );
        let mut again = Journal::new(journal.entries(), started);
        assert!(!again.live);
        assert_eq!(
            again.recall::<String>("a/0/work"),
            Some(("done".to_owned(), None))
        );
        assert_eq!(again.time, "2027-03-01T11:00:00Z".parse().expect("a time"));
        assert_eq!(again.recall::<String>("b/0/work"), None);
        assert!(again.knows("a/0/work") && !again.knows("a/0"));
        assert_eq!(stamp("x"), stamp("x"));
        assert_ne!(stamp("x"), stamp("y"));
    }
}