Skip to main content

link_cli/storage/
file_mem.rs

1//! Persistent memory-mapped backing store for `doublets`.
2//!
3//! # Why this wrapper exists
4//!
5//! `doublets` resizes its memory through `RawMem::grow_filled`, whose
6//! default implementation in `platform-mem` fills the **entire** newly
7//! mapped region with `Default::default()` — including the part that is
8//! already backed by bytes on disk:
9//!
10//! ```text
11//! fn grow_filled(&mut self, cap: usize, value: Self::Item) -> Result<&mut [Self::Item]> {
12//!     unsafe { self.grow(cap, |_, (_, uninit)| { uninit::fill(uninit, value); }) }
13//! }
14//! ```
15//!
16//! `FileMapped` computes how many of those elements were already
17//! initialised on disk and passes it as the `inited` argument, but the
18//! default `grow_filled` ignores it. The consequence is that opening an
19//! existing file-mapped `doublets` database zeroes it: every link is
20//! lost. `docs/case-studies/issue-98/evidence/doublets_persistence.rs`
21//! reproduces this against upstream `doublets` directly.
22//!
23//! [`PersistentFileMapped`] fixes this by forwarding to
24//! `RawMem::grow_filled_exact`, which fills only `uninit[inited..]` and
25//! therefore preserves whatever was already written to the file.
26//!
27//! # Reopening an existing mapping
28//!
29//! Upstream [`FileMapped::new`] starts with a logical capacity of zero even
30//! when its file already contains initialized elements. Use
31//! [`PersistentFileMapped::open_existing`] when the file's bytes are a complete
32//! persisted mapping and its capacity must be visible immediately. The safe
33//! API is available only for [`FileMappedValue`] types, whose representations
34//! this crate can soundly adopt without asking each caller for an `unsafe`
35//! block.
36//!
37//! # Durability
38//!
39//! Writes land in a `MAP_SHARED` mapping, which on Linux *is* the page
40//! cache, so they survive a process crash without any explicit action
41//! and are written back by the kernel. `FileMapped` additionally
42//! `sync_all()`s the file when it is dropped, and
43//! [`LinksStorage::flush`](crate::LinksStorage::flush) `fsync`s on
44//! demand for durability across a machine crash.
45
46use std::fs::File;
47use std::io;
48use std::mem::{self, MaybeUninit};
49use std::path::Path;
50
51use doublets::data::LinkReference;
52use doublets::mem::{FileMapped, RawMem, Result as MemResult};
53use doublets::unit::LinkPart;
54
55/// A value whose representation can safely be adopted from existing file bytes.
56///
57/// This is the safety boundary used by
58/// [`PersistentFileMapped::open_existing`]. The crate implements it for the
59/// unsigned integer link-address types and for [`LinkPart`] values containing
60/// those addresses.
61///
62/// # Safety
63///
64/// Every initialized byte pattern of `Self` must represent a valid value, it
65/// must be safe to drop any such value, and `Self` must not be zero-sized.
66pub unsafe trait FileMappedValue {}
67
68macro_rules! impl_file_mapped_value_for_unsigned {
69    ($($ty:ty),+ $(,)?) => {
70        $(
71            // SAFETY: every bit pattern is valid for unsigned integers, they
72            // have no drop glue, and none of these types is zero-sized.
73            unsafe impl FileMappedValue for $ty {}
74        )+
75    };
76}
77
78impl_file_mapped_value_for_unsigned!(u8, u16, u32, u64, u128, usize);
79
80// SAFETY: `LinkPart<T>` is `repr(C)` and consists only of eight `T` fields.
81// When every bit pattern is valid for `T`, it is therefore valid for the
82// complete link part as well, and dropping it only drops those fields.
83unsafe impl<T: FileMappedValue + LinkReference> FileMappedValue for LinkPart<T> {}
84
85/// A [`FileMapped`] region that does **not** wipe pre-existing file
86/// contents when `doublets` grows it.
87///
88/// See the module documentation for the upstream behaviour this works
89/// around.
90#[derive(Debug)]
91pub struct PersistentFileMapped<T>(FileMapped<T>);
92
93impl<T> PersistentFileMapped<T> {
94    /// Opens (creating it if needed) the file at `path` and maps it.
95    pub fn from_path<P: AsRef<Path>>(path: P) -> std::io::Result<Self> {
96        FileMapped::from_path(path).map(Self)
97    }
98
99    /// Maps an already-opened file.
100    pub fn new(file: File) -> io::Result<Self> {
101        FileMapped::new(file).map(Self)
102    }
103
104    /// Borrows the wrapped [`FileMapped`].
105    pub fn inner(&self) -> &FileMapped<T> {
106        &self.0
107    }
108}
109
110impl<T: FileMappedValue> PersistentFileMapped<T> {
111    /// Maps `file` and adopts the capacity represented by its existing bytes.
112    ///
113    /// Unlike [`Self::new`], which starts with a logical capacity of zero, this
114    /// constructor makes every complete `T` already present in the file
115    /// immediately visible through [`RawMem::allocated`]. Any trailing bytes
116    /// that do not form a complete `T` are left untouched and ignored.
117    ///
118    /// ```no_run
119    /// #![deny(unsafe_code)]
120    /// use std::fs::File;
121    ///
122    /// use link_cli::doublets::unit::LinkPart;
123    /// use link_cli::PersistentFileMapped;
124    ///
125    /// # fn main() -> std::io::Result<()> {
126    /// let file = File::options().read(true).write(true).open("links.data")?;
127    /// let mapped = PersistentFileMapped::<LinkPart<usize>>::open_existing(file)?;
128    /// # let _ = mapped;
129    /// # Ok(())
130    /// # }
131    /// ```
132    pub fn open_existing(file: File) -> io::Result<Self> {
133        // Read this before `FileMapped::new`, which extends sub-page files to
134        // its minimum mapping size. That padding was not part of the persisted
135        // contents and must not become visible as logical items.
136        let byte_len = file.metadata()?.len();
137        let mut mapped = FileMapped::new(file)?;
138        let item_size = mem::size_of::<T>() as u64;
139        debug_assert_ne!(item_size, 0, "FileMappedValue must not be zero-sized");
140        let capacity = usize::try_from(byte_len / item_size).map_err(|_| {
141            io::Error::new(
142                io::ErrorKind::InvalidData,
143                "file capacity does not fit in usize",
144            )
145        })?;
146
147        // SAFETY: `FileMapped::new` guarantees the file contains `byte_len`
148        // initialized bytes, and `FileMappedValue` guarantees every byte
149        // pattern in each complete item is a valid, safely droppable `T`.
150        if capacity != 0 {
151            unsafe { mapped.grow_assumed(capacity) }.map_err(|error| match error {
152                doublets::mem::Error::System(error) => error,
153                error => io::Error::other(error),
154            })?;
155        }
156
157        Ok(Self(mapped))
158    }
159}
160
161impl<T> RawMem for PersistentFileMapped<T> {
162    type Item = T;
163
164    fn allocated(&self) -> &[Self::Item] {
165        self.0.allocated()
166    }
167
168    fn allocated_mut(&mut self) -> &mut [Self::Item] {
169        self.0.allocated_mut()
170    }
171
172    unsafe fn grow(
173        &mut self,
174        addition: usize,
175        fill: impl FnOnce(usize, (&mut [Self::Item], &mut [MaybeUninit<Self::Item>])),
176    ) -> MemResult<&mut [Self::Item]> {
177        unsafe { self.0.grow(addition, fill) }
178    }
179
180    fn shrink(&mut self, cap: usize) -> MemResult<()> {
181        self.0.shrink(cap)
182    }
183
184    /// Fills only the genuinely uninitialised tail of the grown region,
185    /// keeping the bytes that were already persisted in the file.
186    fn grow_filled(&mut self, cap: usize, value: Self::Item) -> MemResult<&mut [Self::Item]>
187    where
188        Self::Item: Clone,
189    {
190        // SAFETY: `FileMapped::grow` derives `inited` from the size the
191        // file had before growing, so the elements below it really are
192        // initialised (they were written by a previous session).
193        unsafe { self.0.grow_filled_exact(cap, value) }
194    }
195}