Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 14.7 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! File system helpers: positional I/O, flushes, unique names, and files
5//! published whole through a temporary file and a rename.
6//!
7//! # Flushes
8//!
9//! Every flush goes through [`flush`], which takes a batch of files and
10//! makes everything written to them so far durable, `Full`, or ordered
11//! before anything written after it returns, `Ordered`:
12//!
13//! - **Apple systems.** `fsync` moves a file's data to the drive, but the
14//! drive may keep it in its cache and write it out in any order;
15//! `F_FULLFSYNC` also has the drive write out its whole cache, which can
16//! cost many times what the rest of a transaction does; `F_BARRIERFSYNC`
17//! makes every write issued before it reach the medium before any write
18//! issued after it, without waiting for the cache. A batch moves every
19//! file but the last with `fsync`, then ends with one `F_BARRIERFSYNC`
20//! (`Ordered`) or `F_FULLFSYNC` (`Full`), which covers the writes of the
21//! whole batch, since cache and barrier are the drive's.
22//! - **Elsewhere.** `fdatasync` (`Ordered`) or `fsync` (`Full`), file by
23//! file. Linux has no barrier to ask for: each of them writes out what
24//! the drive holds.
25//!
26//! Directories are flushed the same way on Unix systems, and not at all
27//! elsewhere.
28
29use std::fs::{self, File, OpenOptions, TryLockError};
30use std::io::{self, Write};
31use std::path::{Path, PathBuf};
32use std::time::{Duration, SystemTime};
33
34use crate::Durability;
35use crate::error::{Error, io_error};
36
37/// Names of temporary files start with this. Readers ignore them.
38pub(crate) const TEMP_PREFIX: &str = "tmp-";
39
40/// A temporary file this old whose lock is free belongs to a writer that died.
41const STALE_TEMP: Duration = Duration::from_secs(60);
42
43/// Reads exactly `buf.len()` bytes at `offset`, without moving any cursor.
44#[cfg(unix)]
45pub(crate) fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> io::Result<()> {
46 std::os::unix::fs::FileExt::read_exact_at(file, buf, offset)
47}
48
49/// Writes all of `buf` at `offset`, without moving any cursor.
50#[cfg(unix)]
51pub(crate) fn write_all_at(file: &File, buf: &[u8], offset: u64) -> io::Result<()> {
52 std::os::unix::fs::FileExt::write_all_at(file, buf, offset)
53}
54
55/// Reads exactly `buf.len()` bytes at `offset`.
56#[cfg(windows)]
57pub(crate) fn read_exact_at(file: &File, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
58 use std::os::windows::fs::FileExt;
59 while !buf.is_empty() {
60 match file.seek_read(buf, offset) {
61 Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()),
62 Ok(n) => {
63 buf = &mut buf[n..];
64 offset += n as u64;
65 }
66 Err(err) if err.kind() == io::ErrorKind::Interrupted => {}
67 Err(err) => return Err(err),
68 }
69 }
70 Ok(())
71}
72
73/// Writes all of `buf` at `offset`.
74#[cfg(windows)]
75pub(crate) fn write_all_at(file: &File, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
76 use std::os::windows::fs::FileExt;
77 while !buf.is_empty() {
78 match file.seek_write(buf, offset) {
79 Ok(0) => return Err(io::ErrorKind::WriteZero.into()),
80 Ok(n) => {
81 buf = &buf[n..];
82 offset += n as u64;
83 }
84 Err(err) if err.kind() == io::ErrorKind::Interrupted => {}
85 Err(err) => return Err(err),
86 }
87 }
88 Ok(())
89}
90
91/// Reads `len` bytes at `offset` into a new buffer.
92pub(crate) fn read_range(file: &File, offset: u64, len: u64) -> io::Result<Vec<u8>> {
93 let len = usize::try_from(len).map_err(|_| io::Error::from(io::ErrorKind::OutOfMemory))?;
94 let mut buf = vec![0u8; len];
95 read_exact_at(file, &mut buf, offset)?;
96 Ok(buf)
97}
98
99/// Flushes a batch of files, each with the path errors name: everything
100/// written to them before the call is durable once it returns (`Full`), or
101/// reaches the disk before anything written after it (`Ordered`). See the
102/// module documentation for what that takes on each system.
103pub(crate) fn flush(files: &[(&Path, &File)], durability: Durability) -> Result<(), Error> {
104 let Some(((last_path, last), rest)) = files.split_last() else {
105 return Ok(());
106 };
107 #[cfg(test)]
108 observe::before(files);
109 #[cfg(target_vendor = "apple")]
110 {
111 for (path, file) in rest {
112 apple::push(file).map_err(io_error("sync", path))?;
113 }
114 match durability {
115 Durability::Ordered => apple::barrier(last),
116 Durability::Full => apple::full(last),
117 }
118 .map_err(io_error("sync", last_path))?;
119 }
120 #[cfg(not(target_vendor = "apple"))]
121 {
122 let _ = (rest, last, last_path);
123 for (path, file) in files {
124 match durability {
125 Durability::Ordered => file.sync_data(),
126 Durability::Full => file.sync_all(),
127 }
128 .map_err(io_error("sync", path))?;
129 }
130 }
131 #[cfg(test)]
132 observe::after(files);
133 Ok(())
134}
135
136/// Flushes one file, as [`flush`] does a batch.
137pub(crate) fn flush_file(path: &Path, file: &File, durability: Durability) -> Result<(), Error> {
138 flush(&[(path, file)], durability)
139}
140
141/// A directory opened to flush it, so that files created, renamed or
142/// removed in it stay that way. `None` where directories cannot be opened
143/// as files, and need no flush.
144pub(crate) fn open_dir(path: &Path) -> Result<Option<File>, Error> {
145 #[cfg(unix)]
146 {
147 File::open(path)
148 .map(Some)
149 .map_err(io_error("open directory", path))
150 }
151 #[cfg(not(unix))]
152 {
153 let _ = path;
154 Ok(None)
155 }
156}
157
158/// Flushes a directory, so that files created, renamed or removed in it
159/// stay that way.
160pub(crate) fn sync_dir(path: &Path, durability: Durability) -> Result<(), Error> {
161 match open_dir(path)? {
162 Some(dir) => flush_file(path, &dir, durability),
163 None => Ok(()),
164 }
165}
166
167/// The flushes of Apple systems, through `nix`, which wraps the calls safely.
168#[cfg(target_vendor = "apple")]
169mod apple {
170 use std::fs::File;
171 use std::io;
172
173 use nix::errno::Errno;
174 use nix::fcntl::{FcntlArg, fcntl};
175
176 /// `fsync`: the drive has the data, in its cache, in no particular order.
177 pub fn push(file: &File) -> io::Result<()> {
178 retry(|| nix::unistd::fsync(file))
179 }
180
181 /// `F_BARRIERFSYNC`: `fsync`, then a barrier, so that the writes before
182 /// it reach the medium before any after it. Where the file system does
183 /// not take barriers, a full flush stands in for one.
184 pub fn barrier(file: &File) -> io::Result<()> {
185 match retry(|| fcntl(file, FcntlArg::F_BARRIERFSYNC).map(drop)) {
186 Ok(()) => Ok(()),
187 Err(_) => full(file),
188 }
189 }
190
191 /// `F_FULLFSYNC`: `fsync`, then the drive writes out its whole cache.
192 pub fn full(file: &File) -> io::Result<()> {
193 retry(|| fcntl(file, FcntlArg::F_FULLFSYNC).map(drop))
194 }
195
196 fn retry(mut call: impl FnMut() -> nix::Result<()>) -> io::Result<()> {
197 loop {
198 match call() {
199 Err(Errno::EINTR) => continue,
200 result => return result.map_err(io::Error::from),
201 }
202 }
203 }
204}
205
206/// What tests see of flushes: a hook called before and after every batch,
207/// with the paths of its files, on the thread that flushes.
208#[cfg(test)]
209pub(crate) mod observe {
210 use std::cell::RefCell;
211 use std::fs::File;
212 use std::path::{Path, PathBuf};
213
214 /// When a batch is reported.
215 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
216 pub(crate) enum When {
217 /// About to flush: what was written may or may not be durable.
218 Before,
219 /// Flushed.
220 After,
221 }
222
223 type Hook = Box<dyn FnMut(When, &[PathBuf])>;
224
225 thread_local! {
226 static HOOK: RefCell<Option<Hook>> = const { RefCell::new(None) };
227 }
228
229 /// Calls `hook` for every batch this thread flushes, until the returned
230 /// guard is dropped.
231 pub(crate) fn watch(hook: impl FnMut(When, &[PathBuf]) + 'static) -> Guard {
232 HOOK.with(|slot| *slot.borrow_mut() = Some(Box::new(hook)));
233 Guard
234 }
235
236 /// Stops the hook when dropped.
237 pub(crate) struct Guard;
238
239 impl Drop for Guard {
240 fn drop(&mut self) {
241 HOOK.with(|slot| *slot.borrow_mut() = None);
242 }
243 }
244
245 fn call(when: When, files: &[(&Path, &File)]) {
246 let paths: Vec<PathBuf> = files.iter().map(|(path, _)| path.to_path_buf()).collect();
247 HOOK.with(|slot| {
248 // A hook that flushes itself does not see its own batches.
249 if let Ok(mut hook) = slot.try_borrow_mut()
250 && let Some(hook) = hook.as_mut()
251 {
252 hook(when, &paths);
253 }
254 });
255 }
256
257 pub(super) fn before(files: &[(&Path, &File)]) {
258 call(When::Before, files);
259 }
260
261 pub(super) fn after(files: &[(&Path, &File)]) {
262 call(When::After, files);
263 }
264}
265
266/// 32 random lowercase hex digits, for a file name in `dir`.
267pub(crate) fn random_name(dir: &Path) -> Result<String, Error> {
268 let mut bytes = [0u8; 16];
269 getrandom::fill(&mut bytes).map_err(|err| Error::Io {
270 action: "pick a random file name in",
271 path: dir.to_path_buf(),
272 source: io::Error::other(err),
273 })?;
274 let mut name = String::with_capacity(32);
275 for byte in bytes {
276 name.push(char::from(b"0123456789abcdef"[usize::from(byte >> 4)]));
277 name.push(char::from(b"0123456789abcdef"[usize::from(byte & 0x0f)]));
278 }
279 Ok(name)
280}
281
282/// Whether `name` is 32 lowercase hex digits.
283pub(crate) fn is_random_name(name: &str) -> bool {
284 name.len() == 32 && name.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
285}
286
287/// Writes `bytes` as `dir/name` all at once: into a temporary file, flushed
288/// in one batch with `with`, then renamed over `name`, then the directory
289/// flushed. Readers see the old file or the new one, never a mix, even after
290/// a crash, and the new one never reaches the disk before what `with` holds.
291pub(crate) fn publish_file(
292 dir: &Path,
293 name: &str,
294 bytes: &[u8],
295 durability: Durability,
296 with: &[(&Path, &File)],
297) -> Result<(), Error> {
298 let (temp_path, mut file) = create_temp(dir)?;
299 let target = dir.join(name);
300 let result = file
301 .write_all(bytes)
302 .map_err(io_error("write", &temp_path))
303 .and_then(|()| {
304 let mut batch = with.to_vec();
305 batch.push((&temp_path, &file));
306 flush(&batch, durability)
307 })
308 .and_then(|()| fs::rename(&temp_path, &target).map_err(io_error("rename", &temp_path)))
309 .and_then(|()| sync_dir(dir, durability));
310 if result.is_err() {
311 let _ = fs::remove_file(&temp_path);
312 }
313 result
314}
315
316/// Creates a new temporary file in `dir` and locks it. The lock lives as long
317/// as the file is open, which tells [`remove_stale_temps`] that its writer is
318/// alive.
319fn create_temp(dir: &Path) -> Result<(PathBuf, File), Error> {
320 loop {
321 let path = dir.join(format!("{TEMP_PREFIX}{}", random_name(dir)?));
322 match OpenOptions::new().write(true).create_new(true).open(&path) {
323 Ok(file) => {
324 file.lock().map_err(io_error("lock", &path))?;
325 return Ok((path, file));
326 }
327 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
328 Err(err) => return Err(io_error("create", &path)(err)),
329 }
330 }
331}
332
333/// Removes temporary files that writers which died left behind: old enough,
334/// and with no live process holding their lock. Best effort: anything that
335/// fails is left for next time. Returns how many were removed.
336pub(crate) fn remove_stale_temps(dir: &Path) -> usize {
337 let Ok(entries) = fs::read_dir(dir) else {
338 return 0;
339 };
340 let mut removed = 0;
341 for entry in entries.flatten() {
342 let name = entry.file_name();
343 if !name.to_string_lossy().starts_with(TEMP_PREFIX) {
344 continue;
345 }
346 let path = entry.path();
347 let old = entry
348 .metadata()
349 .and_then(|meta| meta.modified())
350 .ok()
351 .and_then(|modified| SystemTime::now().duration_since(modified).ok())
352 .is_some_and(|age| age >= STALE_TEMP);
353 if !old {
354 continue;
355 }
356 let Ok(file) = File::open(&path) else {
357 continue;
358 };
359 match file.try_lock() {
360 Ok(()) => {
361 if fs::remove_file(&path).is_ok() {
362 removed += 1;
363 }
364 }
365 Err(TryLockError::WouldBlock | TryLockError::Error(_)) => {}
366 }
367 }
368 removed
369}
370
371/// Number of temporary files in `dir`.
372pub(crate) fn count_temps(dir: &Path) -> usize {
373 fs::read_dir(dir)
374 .map(|entries| {
375 entries
376 .flatten()
377 .filter(|entry| entry.file_name().to_string_lossy().starts_with(TEMP_PREFIX))
378 .count()
379 })
380 .unwrap_or(0)
381}
382
383#[cfg(test)]
384mod tests {
385 use super::*;
386
387 #[test]
388 fn random_names_are_hex_and_differ() {
389 let dir = Path::new(".");
390 let a = random_name(dir).unwrap();
391 let b = random_name(dir).unwrap();
392 assert!(is_random_name(&a), "{a}");
393 assert!(is_random_name(&b), "{b}");
394 assert_ne!(a, b);
395 assert!(!is_random_name("0123456789ABCDEF0123456789abcdef"));
396 assert!(!is_random_name("0123"));
397 }
398
399 #[test]
400 fn publish_replaces_whole_files() {
401 let dir = tempfile::tempdir().unwrap();
402 publish_file(dir.path(), "f", b"one", Durability::Ordered, &[]).unwrap();
403 publish_file(dir.path(), "f", b"two", Durability::Full, &[]).unwrap();
404 assert_eq!(fs::read(dir.path().join("f")).unwrap(), b"two");
405 assert_eq!(count_temps(dir.path()), 0);
406 }
407
408 #[test]
409 fn locked_or_young_temps_survive_cleanup() {
410 let dir = tempfile::tempdir().unwrap();
411 let (path, file) = create_temp(dir.path()).unwrap();
412 // Young, and locked: kept either way.
413 assert_eq!(remove_stale_temps(dir.path()), 0);
414 drop(file);
415 // Unlocked but young: still kept.
416 assert_eq!(remove_stale_temps(dir.path()), 0);
417 assert!(path.exists());
418 assert_eq!(count_temps(dir.path()), 1);
419 }
420
421 #[test]
422 fn positional_io() {
423 let dir = tempfile::tempdir().unwrap();
424 let path = dir.path().join("f");
425 let file = OpenOptions::new()
426 .read(true)
427 .write(true)
428 .create(true)
429 .truncate(true)
430 .open(&path)
431 .unwrap();
432 write_all_at(&file, b"world", 6).unwrap();
433 write_all_at(&file, b"hello ", 0).unwrap();
434 assert_eq!(read_range(&file, 0, 11).unwrap(), b"hello world");
435 assert_eq!(read_range(&file, 6, 5).unwrap(), b"world");
436 assert!(read_range(&file, 6, 6).is_err());
437 }
438}