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//! The bug is reported upstream as
23//! <https://github.com/linksplatform/mem-rs/issues/36>.
24//!
25//! [`PersistentFileMapped`] fixes this by forwarding to
26//! `RawMem::grow_filled_exact`, which fills only `uninit[inited..]` and
27//! therefore preserves whatever was already written to the file.
28//!
29//! # Reopening an existing mapping
30//!
31//! Upstream [`FileMapped::new`] starts with a logical capacity of zero even
32//! when its file already contains initialized elements. Use
33//! [`PersistentFileMapped::open_existing`] when the file's bytes are a complete
34//! persisted mapping and its capacity must be visible immediately. The safe
35//! API is available only for [`FileMappedValue`] types, whose representations
36//! this crate can soundly adopt without asking each caller for an `unsafe`
37//! block.
38//!
39//! # Durability
40//!
41//! Writes land in a `MAP_SHARED` mapping, which on Linux *is* the page
42//! cache, and the kernel writes dirty pages back. A checked durability barrier
43//! is available through [`MappedFlush`] handles:
44//! Windows flushes the mapped view before synchronizing the owned file;
45//! Unix synchronizes the file's shared page cache. Drop attempts that barrier
46//! without reporting errors. Explicit flush reports them. These barriers do
47//! not repair torn pages or make a sequence of in-place mutations atomic.
48
49use std::fs::File;
50use std::io;
51use std::mem::{self, MaybeUninit};
52use std::path::Path;
53
54use doublets::data::LinkReference;
55use doublets::mem::{FileMapped, RawMem, Result as MemResult};
56use doublets::unit::LinkPart;
57
58use super::MappedFlush;
59
60#[path = "file_mem_grow.rs"]
61mod grow;
62
63/// A value whose representation can safely be adopted from existing file bytes.
64///
65/// This is the safety boundary used by
66/// [`PersistentFileMapped::open_existing`]. The crate implements it for the
67/// unsigned integer link-address types and for [`LinkPart`] values containing
68/// those addresses.
69///
70/// # Safety
71///
72/// Every initialized byte pattern of `Self` must represent a valid value, it
73/// must be safe to drop any such value, and `Self` must not be zero-sized.
74pub unsafe trait FileMappedValue {}
75
76macro_rules! impl_file_mapped_value_for_unsigned {
77 ($($ty:ty),+ $(,)?) => {
78 $(
79 // SAFETY: every bit pattern is valid for unsigned integers, they
80 // have no drop glue, and none of these types is zero-sized.
81 unsafe impl FileMappedValue for $ty {}
82 )+
83 };
84}
85
86impl_file_mapped_value_for_unsigned!(u8, u16, u32, u64, u128, usize);
87
88// SAFETY: `LinkPart<T>` is `repr(C)` and consists only of eight `T` fields.
89// When every bit pattern is valid for `T`, it is therefore valid for the
90// complete link part as well, and dropping it only drops those fields.
91unsafe impl<T: FileMappedValue + LinkReference> FileMappedValue for LinkPart<T> {}
92
93/// A [`FileMapped`] region that does **not** wipe pre-existing file
94/// contents when `doublets` grows it.
95///
96/// See the module documentation for the upstream behaviour this works
97/// around.
98#[derive(Debug)]
99pub struct PersistentFileMapped<T> {
100 inner: FileMapped<T>,
101 flush: MappedFlush,
102 initialized_bytes: u64,
103}
104
105impl<T> PersistentFileMapped<T> {
106 /// Opens (creating it if needed) the file at `path` and maps it.
107 pub fn from_path<P: AsRef<Path>>(path: P) -> std::io::Result<Self> {
108 File::options()
109 .create(true)
110 .truncate(false)
111 .read(true)
112 .write(true)
113 .open(path)
114 .and_then(Self::new)
115 }
116
117 /// Maps an already-opened file.
118 pub fn new(file: File) -> io::Result<Self> {
119 // Capture before upstream adds minimum-page padding. Failed growth can
120 // also extend a file before mapping fails; neither is initialized data.
121 let initialized_bytes = file.metadata()?.len();
122 Ok(Self {
123 inner: FileMapped::new(file.try_clone()?)?,
124 flush: MappedFlush::new(file),
125 initialized_bytes,
126 })
127 }
128
129 /// Borrows the wrapped [`FileMapped`].
130 pub fn inner(&self) -> &FileMapped<T> {
131 &self.inner
132 }
133
134 /// Returns a checked flush barrier that follows this owner's remaps.
135 ///
136 /// Retain this before adopting the mapping into a generic doublets store,
137 /// then attach it with [`DoubletsStorage::with_mapped_flush`](super::DoubletsStorage::with_mapped_flush).
138 /// Rejected growth of values without drop glue retains the existing view
139 /// and barrier. Failed shrink or destructor growth can leave unsafe upstream
140 /// allocator state and invalidate the barrier. Reopening alone cannot establish
141 /// safe cleanup. Dropping a valid owner closes every retained handle.
142 pub fn flush_handle(&self) -> MappedFlush {
143 self.flush.clone()
144 }
145}
146
147impl<T: FileMappedValue> PersistentFileMapped<T> {
148 /// Maps `file` and adopts the capacity represented by its existing bytes.
149 ///
150 /// Unlike [`Self::new`], which starts with a logical capacity of zero, this
151 /// constructor makes every complete `T` already present in the file
152 /// immediately visible through [`RawMem::allocated`]. Any trailing bytes
153 /// that do not form a complete `T` are left untouched and ignored.
154 ///
155 /// ```no_run
156 /// #![deny(unsafe_code)]
157 /// use std::fs::File;
158 ///
159 /// use link_cli::doublets::unit::LinkPart;
160 /// use link_cli::PersistentFileMapped;
161 ///
162 /// # fn main() -> std::io::Result<()> {
163 /// let file = File::options().read(true).write(true).open("links.data")?;
164 /// let mapped = PersistentFileMapped::<LinkPart<usize>>::open_existing(file)?;
165 /// # let _ = mapped;
166 /// # Ok(())
167 /// # }
168 /// ```
169 pub fn open_existing(file: File) -> io::Result<Self> {
170 // Read this before `FileMapped::new`, which extends sub-page files to
171 // its minimum mapping size. That padding was not part of the persisted
172 // contents and must not become visible as logical items.
173 let byte_len = file.metadata()?.len();
174 let mut mapped = Self::new(file)?;
175 let item_size = mem::size_of::<T>() as u64;
176 debug_assert_ne!(item_size, 0, "FileMappedValue must not be zero-sized");
177 let capacity = usize::try_from(byte_len / item_size).map_err(|_| {
178 io::Error::new(
179 io::ErrorKind::InvalidData,
180 "file capacity does not fit in usize",
181 )
182 })?;
183
184 // SAFETY: `FileMapped::new` guarantees the file contains `byte_len`
185 // initialized bytes, and `FileMappedValue` guarantees every byte
186 // pattern in each complete item is a valid, safely droppable `T`.
187 if capacity != 0 {
188 unsafe { mapped.grow_assumed(capacity) }.map_err(|error| match error {
189 doublets::mem::Error::System(error) => error,
190 error => io::Error::other(error),
191 })?;
192 }
193
194 Ok(mapped)
195 }
196}
197
198impl<T> RawMem for PersistentFileMapped<T> {
199 type Item = T;
200
201 fn allocated(&self) -> &[Self::Item] {
202 self.inner.allocated()
203 }
204
205 fn allocated_mut(&mut self) -> &mut [Self::Item] {
206 self.inner.allocated_mut()
207 }
208
209 unsafe fn grow(
210 &mut self,
211 addition: usize,
212 fill: impl FnOnce(usize, (&mut [Self::Item], &mut [MaybeUninit<Self::Item>])),
213 ) -> MemResult<&mut [Self::Item]> {
214 if !mem::needs_drop::<T>() {
215 // Two views may share plain data, but dropping overlapping owners
216 // of destructor values would drop those values twice.
217 return unsafe { self.grow_retained(addition, fill) };
218 }
219 let previous_len = self.inner.allocated().len();
220 // Empty growth has no new items to initialize and needs no remap. Keep
221 // the live descriptor valid even when this callback unwinds.
222 if addition == 0 {
223 fill(0, (self.inner.allocated_mut(), &mut []));
224 return Ok(&mut self.inner.allocated_mut()[previous_len..]);
225 }
226 // These errors leave the upstream view untouched. Reject them before
227 // invalidating its still-valid descriptor, including for Drop values.
228 let capacity = previous_len
229 .checked_add(addition)
230 .ok_or(doublets::mem::Error::CapacityOverflow)?;
231 let bytes = std::alloc::Layout::array::<T>(capacity)
232 .map_err(|_| doublets::mem::Error::CapacityOverflow)?
233 .size();
234 // Upstream unmaps first and keeps its old pointer if a later step fails,
235 // so run those steps while the current view can still be returned to.
236 self.preflight_view(bytes)?;
237 // Upstream counts its minimum-page padding as initialized data. Only
238 // bytes known before that padding (or from successful growth) contain
239 // application values that the caller may skip when filling the tail.
240 let initialized = (self.initialized_bytes / mem::size_of::<T>() as u64)
241 .saturating_sub(previous_len as u64)
242 .min(addition as u64) as usize;
243 self.flush.invalidate();
244 unsafe {
245 self.inner
246 .grow(addition, |_, slices| fill(initialized, slices))
247 }?;
248 self.initialized_bytes = self
249 .initialized_bytes
250 .max(mem::size_of_val(self.inner.allocated()) as u64);
251 // RawMem::grow returns only the added tail. The barrier must cover
252 // the complete current mapping, including writes to its old prefix.
253 self.flush.publish(self.inner.allocated());
254 Ok(&mut self.inner.allocated_mut()[previous_len..])
255 }
256
257 fn shrink(&mut self, cap: usize) -> MemResult<()> {
258 // Upstream still unmaps and truncates for zero removal. In particular,
259 // a not-yet-adopted owner can have persisted items but zero live items.
260 if cap == 0 {
261 return Ok(());
262 }
263 // Reject before retiring the descriptor of the still-valid live view.
264 let retained = self
265 .inner
266 .allocated()
267 .len()
268 .checked_sub(cap)
269 .expect("Tried to shrink to a larger capacity");
270 self.preflight_view(retained * mem::size_of::<T>())?;
271 self.flush.invalidate();
272 // Upstream retires the tail before lowering its length. A panicking
273 // destructor would leave those values reachable through the safe view
274 // and drop them again with the owner, so it must not unwind past here.
275 struct AbortOnUnwind;
276 impl Drop for AbortOnUnwind {
277 fn drop(&mut self) {
278 std::process::abort();
279 }
280 }
281 let guard = AbortOnUnwind;
282 let result = self.inner.shrink(cap);
283 mem::forget(guard);
284 result?;
285 self.initialized_bytes = mem::size_of_val(self.inner.allocated()) as u64;
286 self.flush.publish(self.inner.allocated());
287 Ok(())
288 }
289
290 /// Fills only the genuinely uninitialised tail of the grown region,
291 /// keeping the bytes that were already persisted in the file.
292 fn grow_filled(&mut self, cap: usize, value: Self::Item) -> MemResult<&mut [Self::Item]>
293 where
294 Self::Item: Clone,
295 {
296 // SAFETY: growth reports only genuinely initialized file items below
297 // `inited`; the closure fills every remaining item. Minimum-page
298 // padding is excluded for both plain and destructor-bearing values.
299 unsafe { self.grow_filled_exact(cap, value) }
300 }
301}
302
303impl<T> Drop for PersistentFileMapped<T> {
304 fn drop(&mut self) {
305 // Close retained handles before the inner owner unmaps its address.
306 self.flush.close();
307 }
308}