Skip to main content

brep_plm/
table.rs

1//! [`Parts`]: the in-memory part list, which remembers what a change touched.
2//!
3//! The store keeps every part in memory for reads, and writes each change to
4//! SQLite ([`crate::sql`]). Before SQLite, [`crate::db::Db::mutate`] copied
5//! the WHOLE state before every change so that it could roll one back, and
6//! rewrote the whole metadata file after it. Both were O(catalog) per write.
7//!
8//! This type makes a change O(what it touched). Every way to get a part
9//! mutably goes through here, and while a change is open ([`Parts::begin`])
10//! the first mutable touch of a part copies that part aside. At the end the
11//! change either keeps its edits ([`Parts::commit`], which hands back each
12//! touched part's before-copy so the store can write and audit exactly those)
13//! or restores the copies ([`Parts::rollback`]).
14//!
15//! The field is private and there is no `DerefMut`, so the compiler finds any
16//! write that tries to go around the journal.
17
18use std::collections::{BTreeMap, HashMap};
19use std::ops::Deref;
20
21use serde::{Deserialize, Deserializer, Serialize, Serializer};
22
23use crate::model::Part;
24
25/// Every part, in the order they were created, with an id index.
26#[derive(Debug, Default, Clone)]
27pub struct Parts {
28    items: Vec<Part>,
29    index: HashMap<String, usize>,
30    /// While a change is open: each touched position, and the part as it was
31    /// before the change (`None`: the change created it).
32    journal: Option<BTreeMap<usize, Option<Part>>>,
33}
34
35/// What one committed change did to one part.
36#[derive(Debug)]
37pub struct Touched {
38    /// Where the part sits in creation order; the store's `ord`.
39    pub position: usize,
40    /// The part before the change, or `None` when the change created it.
41    pub before: Option<Part>,
42}
43
44impl Parts {
45    pub fn from_vec(items: Vec<Part>) -> Self {
46        let index = items.iter().enumerate().map(|(i, p)| (p.id.clone(), i)).collect();
47        Parts { items, index, journal: None }
48    }
49
50    /// The part with this id.
51    pub fn get(&self, id: &str) -> Option<&Part> {
52        self.index.get(id).map(|&i| &self.items[i])
53    }
54
55    /// Where the part with this id sits in creation order.
56    pub fn position(&self, id: &str) -> Option<usize> {
57        self.index.get(id).copied()
58    }
59
60    /// The part with this id, for changing. Journaled.
61    pub fn get_mut(&mut self, id: &str) -> Option<&mut Part> {
62        let position = self.position(id)?;
63        Some(self.at_mut(position))
64    }
65
66    /// The part at `position`, for changing. Journaled.
67    pub fn at_mut(&mut self, position: usize) -> &mut Part {
68        if let Some(journal) = self.journal.as_mut() {
69            journal.entry(position).or_insert_with(|| Some(self.items[position].clone()));
70        }
71        &mut self.items[position]
72    }
73
74    /// The newest part, for changing. Journaled.
75    pub fn last_mut(&mut self) -> Option<&mut Part> {
76        let last = self.items.len().checked_sub(1)?;
77        Some(self.at_mut(last))
78    }
79
80    /// Every part, for changing. Journals EVERY part — O(catalog) — so it is
81    /// for rare whole-store edits (a test, a data repair), never a request.
82    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Part> {
83        if let Some(journal) = self.journal.as_mut() {
84            for (position, part) in self.items.iter().enumerate() {
85                journal.entry(position).or_insert_with(|| Some(part.clone()));
86            }
87        }
88        self.items.iter_mut()
89    }
90
91    /// Add a part. Journaled. The caller has already refused a duplicate id.
92    pub fn push(&mut self, part: Part) {
93        let position = self.items.len();
94        self.index.insert(part.id.clone(), position);
95        self.items.push(part);
96        if let Some(journal) = self.journal.as_mut() {
97            journal.insert(position, None);
98        }
99    }
100
101    /// Open a change. Nested changes are not a thing: the store holds one
102    /// write lock.
103    pub fn begin(&mut self) {
104        debug_assert!(self.journal.is_none(), "a change is already open");
105        self.journal = Some(BTreeMap::new());
106    }
107
108    /// Close the change keeping its edits, and say what it touched.
109    pub fn commit(&mut self) -> Vec<Touched> {
110        self.journal
111            .take()
112            .unwrap_or_default()
113            .into_iter()
114            .map(|(position, before)| Touched { position, before })
115            .collect()
116    }
117
118    /// Close the change, putting every touched part back as it was and
119    /// dropping any part the change created.
120    pub fn rollback(&mut self) {
121        let Some(journal) = self.journal.take() else { return };
122        // Newest first, so created parts come off the end in reverse order.
123        for (position, before) in journal.into_iter().rev() {
124            match before {
125                Some(part) => self.items[position] = part,
126                None => {
127                    let removed = self.items.remove(position);
128                    self.index.remove(&removed.id);
129                }
130            }
131        }
132    }
133
134    /// Put back the edits of a change that was committed in memory but whose
135    /// write to disk then failed: `touched` is what [`Parts::commit`] said.
136    pub fn undo(&mut self, touched: Vec<Touched>) {
137        self.journal = Some(touched.into_iter().map(|t| (t.position, t.before)).collect());
138        self.rollback();
139    }
140}
141
142impl Deref for Parts {
143    type Target = [Part];
144    fn deref(&self) -> &[Part] {
145        &self.items
146    }
147}
148
149impl<'a> IntoIterator for &'a Parts {
150    type Item = &'a Part;
151    type IntoIter = std::slice::Iter<'a, Part>;
152    fn into_iter(self) -> Self::IntoIter {
153        self.items.iter()
154    }
155}
156
157impl Serialize for Parts {
158    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
159        self.items.serialize(serializer)
160    }
161}
162
163impl<'de> Deserialize<'de> for Parts {
164    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
165        Ok(Parts::from_vec(Vec::deserialize(deserializer)?))
166    }
167}
168