Skip to main content

link_cli/storage/
traits.rs

1//! Storage abstraction shared by every links backend.
2//!
3//! [`LinksStorage`] is the trait the transactions layer is written
4//! against, so any doublets-compatible store — the CLI's own
5//! [`LinkStorage`](crate::LinkStorage), a file-mapped
6//! [`DoubletsStorage`](super::DoubletsStorage), or an externally owned
7//! `doublets::unit::Store` wrapped with
8//! [`DoubletsStorage::wrap`](super::DoubletsStorage::wrap) — can be
9//! composed under [`GenericTransactionsDecorator`](crate::transactions::GenericTransactionsDecorator).
10//!
11//! The trait is generic over the doublets address type `T`, so external
12//! consumers using `usize`-addressed stores are first-class.
13
14use std::fs;
15use std::path::Path;
16
17use doublets::data::LinkReference;
18
19use crate::error::LinkError;
20use crate::link::GenericLink;
21
22/// Cheap fingerprint of a database file, used to answer
23/// "has anyone else written since I last looked?" without reparsing.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub struct StorageRevision {
26    /// Size of the database file in bytes (0 when it does not exist).
27    pub len: u64,
28    /// Last modification time in nanoseconds since the Unix epoch.
29    pub modified_nanos: u128,
30}
31
32impl StorageRevision {
33    /// Reads the current revision of `path`.
34    ///
35    /// A missing file is reported as [`StorageRevision::default`] rather
36    /// than an error, so callers can fingerprint a database before it
37    /// has been created.
38    pub fn of<P: AsRef<Path>>(path: P) -> Result<Self, LinkError> {
39        let metadata = match fs::metadata(path.as_ref()) {
40            Ok(metadata) => metadata,
41            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
42                return Ok(Self::default())
43            }
44            Err(error) => return Err(LinkError::Io(error)),
45        };
46        let modified_nanos = metadata
47            .modified()
48            .ok()
49            .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
50            .map(|duration| duration.as_nanos())
51            .unwrap_or(0);
52        Ok(Self {
53            len: metadata.len(),
54            modified_nanos,
55        })
56    }
57}
58
59/// A store of links addressed by `T`, expressed in terms of owned
60/// [`GenericLink<T>`] values so that both in-memory maps and
61/// memory-mapped doublets stores can implement it.
62pub trait LinksStorage<T: LinkReference> {
63    /// Creates a link and returns its address. A uniqueness resolver may return
64    /// an existing link after removing the temporary allocation.
65    fn create_link(&mut self, source: T, target: T) -> Result<T, LinkError>;
66
67    /// [`Self::create_link`], reporting every change, including partial changes
68    /// before an error. Transactions need these callbacks to distinguish a new
69    /// allocation from a duplicate resolved into an existing link.
70    ///
71    /// The default is for backends that create one row atomically. Backends
72    /// with cascades or partial writes must override it with their callbacks,
73    /// as for [`Self::update_link_observed`].
74    fn create_link_observed(
75        &mut self,
76        source: T,
77        target: T,
78        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
79    ) -> Result<T, LinkError> {
80        let index = self.create_link(source, target)?;
81        let after = self
82            .get_link(index)
83            .unwrap_or_else(|| GenericLink::new(index, source, target));
84        observer(GenericLink::null(), after);
85        Ok(index)
86    }
87
88    /// Ensures a link exists at `index`, creating placeholders as needed.
89    fn ensure_link_created(&mut self, index: T) -> Result<T, LinkError>;
90
91    /// [`Self::ensure_link_created`], reporting every placeholder it creates.
92    ///
93    /// Backends differ in whether intermediate addresses remain allocated.
94    /// This default compares rows before/after the operation, including partial
95    /// changes on error, so a transaction can undo either backend's behavior.
96    /// It costs O(N log N) time and O(N) rows; backends may override it with
97    /// allocation callbacks. The built-in map adapters avoid this copy.
98    fn ensure_link_created_observed(
99        &mut self,
100        index: T,
101        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
102    ) -> Result<T, LinkError> {
103        let before: std::collections::BTreeMap<_, _> = self
104            .all_links()
105            .into_iter()
106            .map(|row| (row.index, row))
107            .collect();
108        let outcome = self.ensure_link_created(index);
109        let mut after: std::collections::BTreeMap<_, _> = self
110            .all_links()
111            .into_iter()
112            .map(|row| (row.index, row))
113            .collect();
114        for (id, previous) in before {
115            let next = after.remove(&id).unwrap_or_else(GenericLink::null);
116            if previous != next {
117                observer(previous, next);
118            }
119        }
120        for (_, row) in after {
121            observer(GenericLink::null(), row);
122        }
123        outcome
124    }
125
126    /// Returns the link stored at `index`, if any.
127    fn get_link(&self, index: T) -> Option<GenericLink<T>>;
128
129    /// Returns `true` when a link exists at `index`.
130    fn link_exists(&self, index: T) -> bool {
131        self.get_link(index).is_some()
132    }
133
134    /// Repoints `index` at `source`/`target`, returning the previous state.
135    fn update_link(&mut self, index: T, source: T, target: T) -> Result<GenericLink<T>, LinkError>;
136
137    /// Writes exactly this row for undo and replay, returning the previous state.
138    ///
139    /// The change was already resolved when it was recorded, and any other
140    /// changes it caused have their own records. A store whose `update_link`
141    /// resolves duplicates must override this, or restoring a recorded duplicate
142    /// merges it away. A layered view keeps this default: it must not skip its
143    /// own checks, so a duplicate below such a view still merges when restored.
144    fn restore_link(
145        &mut self,
146        index: T,
147        source: T,
148        target: T,
149    ) -> Result<GenericLink<T>, LinkError> {
150        self.update_link(index, source, target)
151    }
152
153    /// Deletes `index`, returning the link that was removed.
154    fn delete_link(&mut self, index: T) -> Result<GenericLink<T>, LinkError>;
155
156    /// [`Self::update_link`], reporting every `(before, after)` change it made.
157    ///
158    /// A store that resolves duplicate doublets turns one write into a cascade
159    /// of changes, and the transactions layer has to log each of them or a
160    /// rollback cannot restore what the write actually did. This is the
161    /// equivalent of the `WriteHandler` the C# decorators forward to.
162    ///
163    /// The default implementation reports the single change a store without any
164    /// policy of its own makes, so implementors only override it when they
165    /// really can cascade.
166    fn update_link_observed(
167        &mut self,
168        index: T,
169        source: T,
170        target: T,
171        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
172    ) -> Result<GenericLink<T>, LinkError> {
173        let previous = self.update_link(index, source, target)?;
174        let after = self
175            .get_link(index)
176            .unwrap_or_else(|| GenericLink::new(index, source, target));
177        observer(previous, after);
178        Ok(previous)
179    }
180
181    /// [`Self::delete_link`], reporting every `(before, after)` change it made.
182    ///
183    /// See [`Self::update_link_observed`]; a cascading delete removes every link
184    /// that still referenced `index`.
185    fn delete_link_observed(
186        &mut self,
187        index: T,
188        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
189    ) -> Result<GenericLink<T>, LinkError> {
190        let deleted = self.delete_link(index)?;
191        observer(deleted, GenericLink::null());
192        Ok(deleted)
193    }
194
195    /// Returns every link in the store.
196    fn all_links(&self) -> Vec<GenericLink<T>>;
197
198    /// Returns every link matching the (optional) index/source/target pattern.
199    fn query_links(
200        &self,
201        index: Option<T>,
202        source: Option<T>,
203        target: Option<T>,
204    ) -> Vec<GenericLink<T>> {
205        self.all_links()
206            .into_iter()
207            .filter(|link| {
208                index.is_none_or(|value| value == link.index)
209                    && source.is_none_or(|value| value == link.source)
210                    && target.is_none_or(|value| value == link.target)
211            })
212            .collect()
213    }
214
215    /// Finds the address of a link with the given source and target.
216    fn search_link(&self, source: T, target: T) -> Option<T> {
217        self.all_links()
218            .into_iter()
219            .find(|link| link.source == source && link.target == target)
220            .map(|link| link.index)
221    }
222
223    /// Returns the address of an existing `(source, target)` link,
224    /// creating it when it does not exist yet.
225    fn get_or_create_link(&mut self, source: T, target: T) -> Result<T, LinkError> {
226        match self.search_link(source, target) {
227            Some(index) => Ok(index),
228            None => self.create_link(source, target),
229        }
230    }
231
232    /// Number of links currently stored.
233    fn links_count(&self) -> usize {
234        self.all_links().len()
235    }
236
237    /// Optional logical name snapshot for transactional undo. Unnamed stores
238    /// return None without allocation. Include names of absent/external rows.
239    fn capture_names(
240        &mut self,
241    ) -> Result<Option<std::collections::BTreeMap<T, String>>, LinkError> {
242        Ok(None)
243    }
244
245    /// Changes one logical name without recording. A named adapter must restore
246    /// external-reference names even when their row currently does not exist.
247    fn set_link_name(&mut self, _index: T, _name: Option<&str>) -> Result<T, LinkError> {
248        Err(LinkError::StorageError(
249            "storage does not support names".into(),
250        ))
251    }
252
253    /// Makes every write durable on disk.
254    ///
255    /// Implementations that keep state in memory write it out here;
256    /// memory-mapped implementations `fsync` the backing file. Callers
257    /// that need crash-consistency guarantees must call this — see the
258    /// durability notes on each implementation.
259    fn flush(&mut self) -> Result<(), LinkError>;
260
261    /// Cheap check for "did another process write to this database since
262    /// we last read or wrote it?".
263    ///
264    /// The default implementation reports `false`, which is correct for
265    /// stores that are not shared through the filesystem.
266    fn has_external_changes(&self) -> Result<bool, LinkError> {
267        Ok(false)
268    }
269
270    /// Re-reads the database from disk, discarding cached state.
271    ///
272    /// The default implementation is a no-op for stores that always read
273    /// through to their backing storage.
274    fn reload(&mut self) -> Result<(), LinkError> {
275        Ok(())
276    }
277}
278
279/// Extension implemented by stores that keep links resident in memory and
280/// can therefore lend out references instead of copies.
281///
282/// Memory-mapped stores deliberately do **not** implement this: their
283/// links are decoded from raw memory on read, so there is no stable
284/// `&GenericLink<T>` to borrow.
285pub trait LinksStorageRef<T: LinkReference>: LinksStorage<T> {
286    /// Borrows the link stored at `index`.
287    fn get_link_ref(&self, index: T) -> Option<&GenericLink<T>>;
288
289    /// Borrows every link in the store.
290    fn all_link_refs(&self) -> Vec<&GenericLink<T>>;
291
292    /// Borrows every link matching the (optional) index/source/target pattern.
293    fn query_link_refs(
294        &self,
295        index: Option<T>,
296        source: Option<T>,
297        target: Option<T>,
298    ) -> Vec<&GenericLink<T>> {
299        self.all_link_refs()
300            .into_iter()
301            .filter(|link| {
302                index.is_none_or(|value| value == link.index)
303                    && source.is_none_or(|value| value == link.source)
304                    && target.is_none_or(|value| value == link.target)
305            })
306            .collect()
307    }
308}