Skip to main content

link_cli/storage/
doublets_storage.rs

1//! A [`LinksStorage`] backed by a real `doublets` store.
2//!
3//! This is the doublets-backed storage the transactions layer composes
4//! over. Two shapes are supported:
5//!
6//! * [`DoubletsStorage::open`] and friends create a **file-mapped**
7//!   `doublets::unit::Store` — links live in a memory-mapped file and are
8//!   mutated *in place*, so the inode never changes and other processes
9//!   that already mapped the same file keep observing the same data.
10//! * [`DoubletsStorage::wrap`] adopts a store the caller already owns
11//!   (for example a `unit::Store<usize, _>` opened by an embedding
12//!   application), which is what makes the transactions layer reusable
13//!   without giving up ownership of the database.
14//!
15//! # Durability
16//!
17//! Writes go straight into the shared memory mapping, which *is* the
18//! page cache on Linux. [`LinksStorage::flush`] synchronizes that file;
19//! on Windows, owned mappings first flush the mapped view. Both barriers
20//! propagate errors. Drop attempts the same ordering without reporting errors.
21//! This does not repair torn pages or make in-place transactions atomic.
22//!
23//! # Multi-process access
24//!
25//! A `doublets` store has no internal concurrency control, so concurrent
26//! writers to one file will corrupt it. Use [`DoubletsStorage::open_exclusive`]
27//! (single writer), [`DoubletsStorage::open_shared`] (concurrent readers)
28//! or the [`FileLock`] guards returned by [`DoubletsStorage::lock_shared`] /
29//! [`DoubletsStorage::lock_exclusive`] to serialise access, and
30//! [`LinksStorage::has_external_changes`] to find out cheaply whether
31//! somebody else has written since the last local write.
32
33use std::marker::PhantomData;
34use std::path::{Path, PathBuf};
35
36use doublets::data::{Flow, LinkReference};
37use doublets::decorators::{AutomaticUniquenessAndUsagesResolution, DecoratorsExt};
38use doublets::unit::{LinkPart, Store as UnitStore};
39use doublets::{Doublets, DoubletsExt};
40
41use crate::error::LinkError;
42use crate::link::GenericLink;
43use crate::storage::file_mem::PersistentFileMapped;
44use crate::storage::lock::{lock_file_path, FileLock, LockMode};
45use crate::storage::traits::{LinksStorage, StorageRevision};
46use crate::storage::MappedFlush;
47
48/// The file-mapped `doublets` store used by [`DoubletsStorage::open`].
49pub type FileMappedUnitStore<T> = UnitStore<T, PersistentFileMapped<LinkPart<T>>>;
50
51/// The file-mapped store wrapped in the upstream decorator stack that C#
52/// applies by default, produced by
53/// [`DoubletsStorage::with_automatic_uniqueness_and_usages_resolution`].
54///
55/// This is the Rust spelling of the C# type produced by
56/// `ILinksExtensions.DecorateWithAutomaticUniquenessAndUsagesResolution`,
57/// which `Foundation.Data.Doublets.Cli.Library` applies to every
58/// `UnitedMemoryLinks<TLinkAddress>` it opens.
59pub type ResolvedFileMappedUnitStore<T> =
60    AutomaticUniquenessAndUsagesResolution<T, FileMappedUnitStore<T>>;
61
62/// A [`LinksStorage`] over any `doublets` store.
63pub struct DoubletsStorage<T: LinkReference, S: Doublets<T>> {
64    store: S,
65    path: Option<PathBuf>,
66    known_revision: StorageRevision,
67    lock: Option<FileLock>,
68    mapped_flush: Option<MappedFlush>,
69    address: PhantomData<T>,
70}
71
72impl<T: LinkReference> DoubletsStorage<T, FileMappedUnitStore<T>> {
73    /// Opens (or creates) a file-mapped doublets database at `path`
74    /// without taking an advisory lock.
75    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, LinkError> {
76        Self::open_internal(path, None)
77    }
78
79    /// Opens the database and holds a **shared** advisory lock for the
80    /// lifetime of the returned storage, excluding concurrent writers.
81    pub fn open_shared<P: AsRef<Path>>(path: P) -> Result<Self, LinkError> {
82        Self::open_internal(path, Some(LockMode::Shared))
83    }
84
85    /// Opens the database and holds an **exclusive** advisory lock for
86    /// the lifetime of the returned storage, excluding every other
87    /// reader and writer that honours the same protocol.
88    pub fn open_exclusive<P: AsRef<Path>>(path: P) -> Result<Self, LinkError> {
89        Self::open_internal(path, Some(LockMode::Exclusive))
90    }
91
92    /// Like [`Self::open_exclusive`] but returns `Ok(None)` instead of
93    /// blocking when another holder owns a conflicting lock.
94    pub fn try_open_exclusive<P: AsRef<Path>>(path: P) -> Result<Option<Self>, LinkError> {
95        let path = path.as_ref();
96        match FileLock::try_acquire(lock_file_path(path), LockMode::Exclusive)? {
97            Some(lock) => Ok(Some(Self::open_mapped(path, Some(lock))?)),
98            None => Ok(None),
99        }
100    }
101
102    fn open_internal<P: AsRef<Path>>(path: P, mode: Option<LockMode>) -> Result<Self, LinkError> {
103        let path = path.as_ref();
104        let lock = match mode {
105            Some(mode) => Some(FileLock::acquire(lock_file_path(path), mode)?),
106            None => None,
107        };
108        Self::open_mapped(path, lock)
109    }
110
111    fn open_mapped(path: &Path, lock: Option<FileLock>) -> Result<Self, LinkError> {
112        if let Some(parent) = path.parent() {
113            if !parent.as_os_str().is_empty() && !parent.exists() {
114                std::fs::create_dir_all(parent)?;
115            }
116        }
117        let mem = PersistentFileMapped::<LinkPart<T>>::from_path(path)?;
118        let mapped_flush = Some(mem.flush_handle());
119        let store = FileMappedUnitStore::<T>::new(mem)?;
120        Ok(Self {
121            store,
122            path: Some(path.to_path_buf()),
123            known_revision: StorageRevision::of(path)?,
124            lock,
125            mapped_flush,
126            address: PhantomData,
127        })
128    }
129}
130
131impl<T: LinkReference, S: Doublets<T>> DoubletsStorage<T, S> {
132    /// Adopts a doublets store the caller already owns.
133    ///
134    /// Nothing about the store is assumed: no path, no locking and no
135    /// external-change detection. This is the entry point for embedding
136    /// applications that open their own `unit::Store<usize, _>` and only
137    /// want the transactions layer on top of it.
138    pub fn wrap(store: S) -> Self {
139        Self {
140            store,
141            path: None,
142            known_revision: StorageRevision::default(),
143            lock: None,
144            mapped_flush: None,
145            address: PhantomData,
146        }
147    }
148
149    /// Adopts a store the caller already owns while recording the path
150    /// it is backed by, enabling file synchronization,
151    /// [`LinksStorage::has_external_changes`] and the lock helpers.
152    ///
153    /// For an adopted mapping, attach its matching view barrier with
154    /// [`Self::with_mapped_flush`]; a path alone cannot discover that view.
155    pub fn wrap_at<P: AsRef<Path>>(store: S, path: P) -> Result<Self, LinkError> {
156        let path = path.as_ref().to_path_buf();
157        let known_revision = StorageRevision::of(&path)?;
158        Ok(Self {
159            store,
160            path: Some(path),
161            known_revision,
162            lock: None,
163            mapped_flush: None,
164            address: PhantomData,
165        })
166    }
167
168    /// Attaches the flush barrier belonging to this store's mapped owner.
169    ///
170    /// Obtain it from [`PersistentFileMapped::flush_handle`] before moving
171    /// that mapping into the store. The handle must belong to this store's
172    /// backing file. It is preserved through [`Self::map_store`] and works
173    /// even when the adopted store has no recorded path. Arbitrary foreign
174    /// stores must provide their own view synchronization.
175    pub fn with_mapped_flush(mut self, flush: MappedFlush) -> Self {
176        self.mapped_flush = Some(flush);
177        self
178    }
179
180    /// Replaces the underlying store with `map(store)`, keeping the path,
181    /// advisory lock, mapped flush owner and change-detection fingerprint.
182    ///
183    /// This is the extension point for stacking any `doublets` decorator
184    /// (or a custom one) under the transactions and version control
185    /// layers. If the closure replaces the mapped owner instead of retaining
186    /// it, attach that replacement's barrier with [`Self::with_mapped_flush`].
187    /// A retired owner's barrier rejects flush rather than publishing changes.
188    ///
189    /// ```no_run
190    /// use doublets::decorators::DecoratorsExt;
191    /// use link_cli::storage::DoubletsStorage;
192    ///
193    /// # fn main() -> Result<(), link_cli::LinkError> {
194    /// let storage = DoubletsStorage::<u32, _>::open("links.data")?
195    ///     .map_store(|store| store.with_inner_reference_existence_validation());
196    /// # Ok(()) }
197    /// ```
198    pub fn map_store<S2, F>(self, map: F) -> DoubletsStorage<T, S2>
199    where
200        S2: Doublets<T>,
201        F: FnOnce(S) -> S2,
202    {
203        DoubletsStorage {
204            store: map(self.store),
205            path: self.path,
206            known_revision: self.known_revision,
207            lock: self.lock,
208            mapped_flush: self.mapped_flush,
209            address: PhantomData,
210        }
211    }
212
213    /// Wraps the underlying store in the same decorator stack C# applies
214    /// through `ILinksExtensions.DecorateWithAutomaticUniquenessAndUsagesResolution`.
215    ///
216    /// After this call `(source, target)` pairs are unique: creating or
217    /// updating a link into a pair that already exists resolves to the
218    /// existing link, re-points every usage of the redundant link at the
219    /// survivor and deletes the redundant link. Deleting a link cascades
220    /// to its usages and resets its contents first.
221    ///
222    /// ```no_run
223    /// use link_cli::storage::{DoubletsStorage, LinksStorage};
224    ///
225    /// # fn main() -> Result<(), link_cli::LinkError> {
226    /// let mut storage = DoubletsStorage::<u32, _>::open("links.data")?
227    ///     .with_automatic_uniqueness_and_usages_resolution();
228    /// let first = storage.create_link(1, 1)?;
229    /// let second = storage.create_link(1, 1)?;
230    /// assert_eq!(first, second);
231    /// # Ok(()) }
232    /// ```
233    pub fn with_automatic_uniqueness_and_usages_resolution(
234        self,
235    ) -> DoubletsStorage<T, AutomaticUniquenessAndUsagesResolution<T, S>> {
236        self.map_store(DecoratorsExt::with_automatic_uniqueness_and_usages_resolution)
237    }
238
239    /// The database file backing this storage, when known.
240    pub fn path(&self) -> Option<&Path> {
241        self.path.as_deref()
242    }
243
244    /// Borrows the underlying doublets store.
245    pub fn store(&self) -> &S {
246        &self.store
247    }
248
249    /// Mutably borrows the underlying doublets store.
250    pub fn store_mut(&mut self) -> &mut S {
251        &mut self.store
252    }
253
254    /// Returns the underlying doublets store, dropping any held lock.
255    pub fn into_store(self) -> S {
256        self.store
257    }
258
259    /// Acquires a shared advisory lock on this database's sidecar lock file.
260    pub fn lock_shared(&self) -> Result<FileLock, LinkError> {
261        FileLock::acquire(self.require_lock_path()?, LockMode::Shared)
262    }
263
264    /// Acquires an exclusive advisory lock on this database's sidecar lock file.
265    pub fn lock_exclusive(&self) -> Result<FileLock, LinkError> {
266        FileLock::acquire(self.require_lock_path()?, LockMode::Exclusive)
267    }
268
269    /// The advisory lock held for the lifetime of this storage, if any.
270    pub fn held_lock(&self) -> Option<&FileLock> {
271        self.lock.as_ref()
272    }
273
274    fn require_lock_path(&self) -> Result<PathBuf, LinkError> {
275        self.path.as_ref().map(lock_file_path).ok_or_else(|| {
276            LinkError::Lock("this doublets storage is not backed by a known file".to_string())
277        })
278    }
279
280    fn refresh_revision(&mut self) -> Result<(), LinkError> {
281        if let Some(path) = self.path.as_ref() {
282            self.known_revision = StorageRevision::of(path)?;
283        }
284        Ok(())
285    }
286}
287
288impl<T: LinkReference, S: Doublets<T>> LinksStorage<T> for DoubletsStorage<T, S> {
289    fn create_link(&mut self, source: T, target: T) -> Result<T, LinkError> {
290        Ok(Doublets::create_link(&mut self.store, source, target)?)
291    }
292
293    fn create_link_observed(
294        &mut self,
295        source: T,
296        target: T,
297        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
298    ) -> Result<T, LinkError> {
299        let mut index = T::from_byte(0);
300        Doublets::create_link_with(&mut self.store, source, target, |before, after| {
301            index = after.index;
302            observer(before.into(), after.into());
303            Flow::Continue
304        })?;
305        Ok(index)
306    }
307
308    fn ensure_link_created(&mut self, index: T) -> Result<T, LinkError> {
309        if self.link_exists(index) {
310            return Ok(index);
311        }
312        // `unit::Store` hands out the lowest free address, reusing the
313        // slots of deleted links first, so repeatedly creating empty
314        // links walks up to (and reuses) `index`.
315        loop {
316            let created = Doublets::create(&mut self.store)?;
317            match created.cmp(&index) {
318                std::cmp::Ordering::Equal => return Ok(index),
319                std::cmp::Ordering::Less => continue,
320                std::cmp::Ordering::Greater => {
321                    return Err(LinkError::StorageError(format!(
322                    "could not reserve link address {index}: the store allocated {created} instead"
323                )))
324                }
325            }
326        }
327    }
328
329    fn get_link(&self, index: T) -> Option<GenericLink<T>> {
330        Doublets::get_link(&self.store, index).map(GenericLink::from)
331    }
332
333    fn link_exists(&self, index: T) -> bool {
334        Doublets::get_link(&self.store, index).is_some()
335    }
336
337    fn update_link(&mut self, index: T, source: T, target: T) -> Result<GenericLink<T>, LinkError> {
338        let before = self
339            .get_link(index)
340            .ok_or_else(|| LinkError::not_found(index))?;
341        Doublets::update(&mut self.store, index, source, target)?;
342        Ok(before)
343    }
344
345    fn delete_link(&mut self, index: T) -> Result<GenericLink<T>, LinkError> {
346        let before = self
347            .get_link(index)
348            .ok_or_else(|| LinkError::not_found(index))?;
349        Doublets::delete(&mut self.store, index)?;
350        Ok(before)
351    }
352
353    fn update_link_observed(
354        &mut self,
355        index: T,
356        source: T,
357        target: T,
358        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
359    ) -> Result<GenericLink<T>, LinkError> {
360        let before = self
361            .get_link(index)
362            .ok_or_else(|| LinkError::not_found(index))?;
363        Doublets::update_with(&mut self.store, index, source, target, |before, after| {
364            observer(before.into(), after.into());
365            Flow::Continue
366        })?;
367        Ok(before)
368    }
369
370    fn delete_link_observed(
371        &mut self,
372        index: T,
373        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
374    ) -> Result<GenericLink<T>, LinkError> {
375        let before = self
376            .get_link(index)
377            .ok_or_else(|| LinkError::not_found(index))?;
378        Doublets::delete_with(&mut self.store, index, |before, after| {
379            observer(before.into(), after.into());
380            Flow::Continue
381        })?;
382        Ok(before)
383    }
384
385    fn all_links(&self) -> Vec<GenericLink<T>> {
386        DoubletsExt::iter(&self.store)
387            .map(GenericLink::from)
388            .collect()
389    }
390
391    fn query_links(
392        &self,
393        index: Option<T>,
394        source: Option<T>,
395        target: Option<T>,
396    ) -> Vec<GenericLink<T>> {
397        let any = self.store.constants().any;
398        let query = [
399            index.unwrap_or(any),
400            source.unwrap_or(any),
401            target.unwrap_or(any),
402        ];
403        DoubletsExt::each_iter(&self.store, query)
404            .map(GenericLink::from)
405            .collect()
406    }
407
408    fn search_link(&self, source: T, target: T) -> Option<T> {
409        Doublets::search(&self.store, source, target)
410    }
411
412    fn get_or_create_link(&mut self, source: T, target: T) -> Result<T, LinkError> {
413        Ok(Doublets::get_or_create(&mut self.store, source, target)?)
414    }
415
416    fn links_count(&self) -> usize {
417        TryInto::<usize>::try_into(Doublets::count(&self.store)).unwrap_or(usize::MAX)
418    }
419
420    /// Flushes the owned mapped view, synchronizes its file, and publishes
421    /// changes by advancing the known path's modification time. Without an
422    /// attached mapped owner, only the known file is synchronized. A no-op
423    /// for adopted stores with neither a flush owner nor a known path.
424    ///
425    /// Bumping the timestamp is deliberate: the kernel only refreshes
426    /// `mtime` when a *clean* page of a shared mapping is first written
427    /// to, so a long-lived writer that keeps touching already-dirty
428    /// pages would otherwise stay invisible to
429    /// [`LinksStorage::has_external_changes`].
430    fn flush(&mut self) -> Result<(), LinkError> {
431        if let Some(flush) = &self.mapped_flush {
432            flush.flush()?;
433        }
434        if let Some(path) = self.path.clone() {
435            let file = std::fs::File::options().write(true).open(&path)?;
436            if self.mapped_flush.is_none() {
437                file.sync_all()?;
438            }
439            file.set_modified(std::time::SystemTime::now())?;
440            self.refresh_revision()?;
441        }
442        Ok(())
443    }
444
445    /// Compares the database file's size and mtime against the values
446    /// observed when this storage was opened, reloaded or flushed.
447    ///
448    /// The granularity is a **published** write: writers publish by
449    /// calling [`LinksStorage::flush`], which `fsync`s and advances the
450    /// file's modification time. Writes that a peer has made but not yet
451    /// flushed are already visible through the shared mapping, but are
452    /// not reported here — take [`DoubletsStorage::lock_shared`] when an
453    /// exact answer is required.
454    fn has_external_changes(&self) -> Result<bool, LinkError> {
455        match self.path.as_ref() {
456            Some(path) => Ok(StorageRevision::of(path)? != self.known_revision),
457            None => Ok(false),
458        }
459    }
460
461    /// Memory-mapped stores always read through to the mapping, so this
462    /// only refreshes the change-detection fingerprint.
463    fn reload(&mut self) -> Result<(), LinkError> {
464        self.refresh_revision()
465    }
466}