Skip to main content

brep_plm/
journal.rs

1//! [`Journaled`]: an in-memory list of keyed records that remembers what a
2//! change touched, so the store writes and audits only those.
3//!
4//! [`crate::db::Db::mutate`] serializes and diffs the state's other fields on
5//! every change — every write on the server, a sign-in's `last_seen` stamp
6//! included — so a list kept there costs every write O(its length). Parts
7//! have their own journal ([`crate::table::Parts`]); this is the same idea,
8//! keyed by a string rather than a creation position, for the lists that
9//! grow with use: workspace entries ([`crate::workspace::Workspace`]) and
10//! browser sessions.
11//!
12//! The list is private and there is no `DerefMut`: every mutable touch goes
13//! through [`Journaled::get_mut`], [`Journaled::iter_mut`],
14//! [`Journaled::push`], [`Journaled::remove`] or [`Journaled::retain`], which
15//! record the record's before-copy while a change is open.
16
17use std::collections::{BTreeMap, BTreeSet, HashMap};
18
19/// A record with a key that is unique in its list and never changes.
20pub trait Keyed {
21    fn key(&self) -> &str;
22}
23
24#[derive(Debug, Clone)]
25pub struct Journaled<T> {
26    items: Vec<T>,
27    /// Key → position in `items`.
28    index: HashMap<String, usize>,
29    journal: Option<BTreeMap<String, Option<T>>>,
30}
31
32impl<T> Default for Journaled<T> {
33    fn default() -> Self {
34        Journaled { items: Vec::new(), index: HashMap::new(), journal: None }
35    }
36}
37
38/// A record a change touched: its key and what it was before (`None`: it
39/// was created). What it is after is read from the list (absent: removed).
40#[derive(Debug, Clone)]
41pub struct Touched<T> {
42    pub key: String,
43    pub before: Option<T>,
44}
45
46impl<T: Keyed + Clone> Journaled<T> {
47    pub fn from_vec(items: Vec<T>) -> Self {
48        let mut list = Journaled { items, index: HashMap::new(), journal: None };
49        list.reindex();
50        list
51    }
52
53    fn reindex(&mut self) {
54        self.index = self.items.iter().enumerate().map(|(i, e)| (e.key().to_string(), i)).collect();
55    }
56
57    pub fn get(&self, key: &str) -> Option<&T> {
58        self.index.get(key).map(|&i| &self.items[i])
59    }
60
61    fn note(&mut self, key: &str) {
62        if self.journal.as_ref().is_none_or(|j| j.contains_key(key)) {
63            return;
64        }
65        let before = self.get(key).cloned();
66        if let Some(journal) = self.journal.as_mut() {
67            journal.insert(key.to_string(), before);
68        }
69    }
70
71    pub fn get_mut(&mut self, key: &str) -> Option<&mut T> {
72        let position = *self.index.get(key)?;
73        self.note(key);
74        Some(&mut self.items[position])
75    }
76
77    /// Every record, mutably — each is recorded as touched. For a sweep
78    /// that may change any of them; [`Journaled::get_mut`] for one.
79    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
80        if let Some(journal) = self.journal.as_mut() {
81            for item in &self.items {
82                journal.entry(item.key().to_string()).or_insert_with(|| Some(item.clone()));
83            }
84        }
85        self.items.iter_mut()
86    }
87
88    /// Add a record. Its key must be new.
89    pub fn push(&mut self, item: T) {
90        debug_assert!(!self.index.contains_key(item.key()), "a key is never reused");
91        let key = item.key().to_string();
92        self.note(&key);
93        self.index.insert(key, self.items.len());
94        self.items.push(item);
95    }
96
97    /// Remove every record whose key is in `keys`.
98    pub fn remove(&mut self, keys: &BTreeSet<String>) {
99        self.retain(|item| !keys.contains(item.key()));
100    }
101
102    /// Keep the records `keep` accepts; the rest are removed (and recorded).
103    pub fn retain(&mut self, mut keep: impl FnMut(&T) -> bool) {
104        let gone: Vec<String> = self.items.iter().filter(|i| !keep(i)).map(|i| i.key().to_string()).collect();
105        if gone.is_empty() {
106            return;
107        }
108        for key in &gone {
109            self.note(key);
110        }
111        let gone: BTreeSet<String> = gone.into_iter().collect();
112        self.items.retain(|i| !gone.contains(i.key()));
113        self.reindex();
114    }
115
116    /// Open a change: from here each first touch of a record is recorded.
117    pub fn begin(&mut self) {
118        self.journal = Some(BTreeMap::new());
119    }
120
121    /// Close the change, keeping its edits; what it touched.
122    ///
123    /// In list order (removed records last), so new records are stored in
124    /// the order they were made: a reopened store lists them as this one does.
125    pub fn commit(&mut self) -> Vec<Touched<T>> {
126        let mut touched: Vec<Touched<T>> =
127            self.journal.take().unwrap_or_default().into_iter().map(|(key, before)| Touched { key, before }).collect();
128        touched.sort_by_key(|t| self.index.get(&t.key).copied().unwrap_or(usize::MAX));
129        touched
130    }
131
132    /// Close the change, putting every touched record back as it was.
133    pub fn rollback(&mut self) {
134        let Some(journal) = self.journal.take() else { return };
135        let created: BTreeSet<&String> = journal.iter().filter(|(_, b)| b.is_none()).map(|(k, _)| k).collect();
136        self.items.retain(|e| !created.contains(&e.key().to_string()));
137        self.reindex();
138        for (_, before) in journal {
139            let Some(item) = before else { continue };
140            match self.index.get(item.key()) {
141                Some(&i) => self.items[i] = item,
142                None => {
143                    self.index.insert(item.key().to_string(), self.items.len());
144                    self.items.push(item);
145                }
146            }
147        }
148    }
149
150    /// Put back a change that was committed in memory but failed to reach
151    /// the disk.
152    pub fn undo(&mut self, touched: Vec<Touched<T>>) {
153        self.journal = Some(touched.into_iter().map(|t| (t.key, t.before)).collect());
154        self.rollback();
155    }
156
157    /// The touched records that actually changed, each with what it is now
158    /// (`None`: removed) — what a change writes and audits.
159    pub fn changed<'a>(&'a self, touched: &'a [Touched<T>]) -> Vec<(&'a Touched<T>, Option<&'a T>)>
160    where
161        T: PartialEq,
162    {
163        touched
164            .iter()
165            .map(|t| (t, self.get(&t.key)))
166            .filter(|(t, now)| t.before.as_ref() != *now)
167            .collect()
168    }
169}
170
171impl<T> std::ops::Deref for Journaled<T> {
172    type Target = [T];
173    fn deref(&self) -> &[T] {
174        &self.items
175    }
176}
177
178impl<T: serde::Serialize> serde::Serialize for Journaled<T> {
179    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
180        self.items.serialize(serializer)
181    }
182}
183
184impl<'de, T: serde::Deserialize<'de> + Keyed + Clone> serde::Deserialize<'de> for Journaled<T> {
185    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
186        Ok(Journaled::from_vec(Vec::deserialize(deserializer)?))
187    }
188}
189
190impl Keyed for crate::jobs::Job {
191    fn key(&self) -> &str {
192        &self.id
193    }
194}
195
196impl Keyed for crate::model::Session {
197    fn key(&self) -> &str {
198        &self.token
199    }
200}
201