Skip to main content

vpf_runner/
journal.rs

1//! The journal of a run: everything it was given from outside it, each under a key that names where in the run it
2//! was given, so that the run can go on from its kept state without asking any of it again.
3
4use std::collections::HashMap;
5
6use jiff::Timestamp;
7use serde::de::DeserializeOwned;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11/// One thing a run was given: an agent's answer, a command's result, a person's reply or a time.
12#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
13pub struct Entry {
14    /// Where in the run it was given.
15    pub key: String,
16    /// When.
17    pub at: Timestamp,
18    /// Who gave it, when they said who they are.
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub by: Option<String>,
21    /// What was given.
22    pub value: Value,
23}
24
25/// 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
26/// should the computer go down in the middle of it.
27///
28/// A run that stopped is rebuilt from the record it last began with and the entries kept after it, joined by
29/// [`Record::add_entries`](crate::Record::add_entries), and goes on with [`Runner::resume`](crate::Runner::resume)
30/// without asking any of them again.
31pub trait Keeper {
32    /// A run begins, or goes on: its record as it stands, with the entries it was given before. Nothing the record
33    /// holds is handed to [`Keeper::kept`] again.
34    fn begin(&mut self, record: &crate::Record) {
35        let _ = record;
36    }
37
38    /// The run was just given this: it is handed out as soon as it is kept, once. A later entry under the same key
39    /// takes the place of the earlier.
40    fn kept(&mut self, entry: &Entry);
41}
42
43impl<F: FnMut(&Entry)> Keeper for F {
44    fn kept(&mut self, entry: &Entry) {
45        self(entry);
46    }
47}
48
49/// The entries of a run, read back in any order by their keys.
50#[derive(Debug, Default)]
51pub(crate) struct Journal {
52    entries: Vec<Entry>,
53    places: HashMap<String, usize>,
54    /// Whether the run has gone past what it was given before, and now reads the clock and asks for itself.
55    pub live: bool,
56    /// While the run goes over what it was given before, the latest time of what it read back: its clock.
57    pub time: Timestamp,
58}
59
60impl Journal {
61    /// A journal with these entries, of a run that started at `started`.
62    pub fn new(entries: Vec<Entry>, started: Timestamp) -> Self {
63        let live = entries.is_empty();
64        let places = entries
65            .iter()
66            .enumerate()
67            .map(|(place, entry)| (entry.key.clone(), place))
68            .collect();
69        Self {
70            entries,
71            places,
72            live,
73            time: started,
74        }
75    }
76
77    /// What was given under `key`, and who gave it, when the run was given it before.
78    pub fn recall<T: DeserializeOwned>(&mut self, key: &str) -> Option<(T, Option<String>)> {
79        let entry = &self.entries[*self.places.get(key)?];
80        let value = serde_json::from_value(entry.value.clone()).ok()?;
81        let by = entry.by.clone();
82        self.time = self.time.max(entry.at);
83        Some((value, by))
84    }
85
86    /// Keeps what was given under `key`.
87    pub fn keep<T: Serialize>(&mut self, key: String, value: &T, at: Timestamp) {
88        let entry = Entry {
89            key: key.clone(),
90            at,
91            by: None,
92            value: serde_json::to_value(value).unwrap_or_default(),
93        };
94        if let Some(&place) = self.places.get(&key) {
95            self.entries[place] = entry;
96        } else {
97            self.places.insert(key, self.entries.len());
98            self.entries.push(entry);
99        }
100    }
101
102    /// Whether the run was given anything under `key` before.
103    pub fn knows(&self, key: &str) -> bool {
104        self.places.contains_key(key)
105    }
106
107    /// The entries, in the order they were given.
108    pub fn entries(&self) -> Vec<Entry> {
109        self.entries.clone()
110    }
111}
112
113/// A short, stable name for a text, to tell its versions apart in keys.
114pub(crate) fn stamp(text: &str) -> String {
115    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
116    for byte in text.bytes() {
117        hash ^= u64::from(byte);
118        hash = hash.wrapping_mul(0x0100_0000_01b3);
119    }
120    format!("{:08x}", hash >> 32)
121}
122
123#[cfg(test)]
124mod tests {
125    use super::{Journal, stamp};
126
127    #[test]
128    fn what_is_kept_is_recalled_by_key() {
129        let started = "2027-03-01T10:00:00Z".parse().expect("a time");
130        let mut journal = Journal::new(Vec::new(), started);
131        assert!(journal.live);
132        journal.keep(
133            "a/0/work".to_owned(),
134            &"done",
135            "2027-03-01T11:00:00Z".parse().expect("a time"),
136        );
137        let mut again = Journal::new(journal.entries(), started);
138        assert!(!again.live);
139        assert_eq!(
140            again.recall::<String>("a/0/work"),
141            Some(("done".to_owned(), None))
142        );
143        assert_eq!(again.time, "2027-03-01T11:00:00Z".parse().expect("a time"));
144        assert_eq!(again.recall::<String>("b/0/work"), None);
145        assert!(again.knows("a/0/work") && !again.knows("a/0"));
146        assert_eq!(stamp("x"), stamp("x"));
147        assert_ne!(stamp("x"), stamp("y"));
148    }
149}