ant_node/storage/file_store.rs
1//! One immutable file per chunk, content-addressed, with the filesystem as the
2//! only authority.
3//!
4//! ```text
5//! {root}/chunks/ store root
6//! {root}/chunks/layout.json versioned layout marker
7//! {root}/chunks/.lock advisory single-process guard
8//! {root}/chunks/<xy>/<64-hex> xy = the LAST two hex characters of the address
9//! {root}/chunks/<xy>/.tmp.<pid>.<n> an in-flight write, in the destination directory
10//! ```
11//!
12//! # Why the *last* two hex characters
13//!
14//! A node holds keys for which it is among the [`CLOSE_GROUP_SIZE`] closest, so its
15//! holdings share roughly `log2(N / CLOSE_GROUP_SIZE)` leading bits with its own node
16//! ID, and that shared prefix grows as the network grows. Sharding on a prefix therefore
17//! does not degrade, it collapses: at ~800 nodes a two-hex prefix already resolves to
18//! about two distinct directories, and past a million nodes even a four-hex prefix
19//! resolves to one. Close-group membership constrains the leading bits and places no
20//! constraint at all on the trailing ones, and the address is a BLAKE3 output, so the
21//! last byte is uniform by construction at every network size.
22//!
23//! 256 shards keeps a 24 GiB node at ~23 files per directory and a 1 TiB node at ~977,
24//! for 1 MiB of directory inodes. The scheme and depth are recorded in `layout.json` at
25//! creation so a future layout can be detected rather than silently misread.
26//!
27//! # Why lowercase hex names
28//!
29//! NTFS and default APFS fold case. Under an encoding with both cases (base64url,
30//! base58) two distinct 32-byte keys can share one case-folded filename, which is a
31//! silent overwrite. Hex has one case-folded form per key, and no hex string can ever
32//! spell a reserved Windows device name (`CON`, `NUL`, `AUX`, `COM1`, ...) because none
33//! of those letters is in `0-9a-f`. The full 64-character key stays in the filename, so
34//! a `find` over the tree recovers the whole store even if the directory layer is lost.
35//!
36//! [`CLOSE_GROUP_SIZE`]: crate::ant_protocol::CLOSE_GROUP_SIZE
37
38use crate::ant_protocol::{XorName, MAX_CHUNK_SIZE, XORNAME_LEN};
39use crate::error::{Error, Result};
40use crate::logging::{debug, info, trace, warn};
41use crate::storage::StorageStats;
42use fs2::FileExt;
43use serde::{Deserialize, Serialize};
44use std::collections::{BTreeSet, HashMap, HashSet};
45use std::fs::{File, OpenOptions};
46use std::io::{ErrorKind, Read, Write};
47use std::path::{Path, PathBuf};
48use std::sync::atomic::{AtomicU64, Ordering};
49use std::sync::Arc;
50use std::time::{Duration, Instant};
51use tokio::task::spawn_blocking;
52use tokio_util::task::TaskTracker;
53
54/// Directory under the node root that holds the chunk files.
55pub const CHUNKS_DIR_NAME: &str = "chunks";
56
57/// Name of the layout marker written once at store creation.
58pub const LAYOUT_FILE_NAME: &str = "layout.json";
59
60/// Name of the advisory single-process lock file.
61const LOCK_FILE_NAME: &str = ".lock";
62
63/// Prefix that marks an in-flight write. Never a valid chunk name (chunk names are
64/// exactly [`CHUNK_NAME_LEN`] lowercase hex characters, and `.` is not hex).
65const TEMP_PREFIX: &str = ".tmp.";
66
67/// Number of shard directories. One level, `00` through `ff`.
68const SHARD_COUNT: usize = 256;
69
70/// Length of a chunk filename: the full address in lowercase hex.
71const CHUNK_NAME_LEN: usize = XORNAME_LEN * 2;
72
73/// How often to re-query available disk space, in seconds.
74///
75/// Matches the LMDB store's cadence so the capacity predicate behaves identically
76/// for callers that only ask "is there room at all".
77const DISK_CHECK_INTERVAL_SECS: u64 = 5;
78
79/// Allocation granularity assumed when charging a pending write against free space.
80///
81/// Every filesystem we support allocates in units of at least 4 KiB, so a write of
82/// `n` bytes consumes at least `ceil(n / 4096) * 4096`. One extra unit covers the
83/// directory entry and inode.
84const ALLOC_UNIT: u64 = 4096;
85
86/// How many times a publish retries a transient Windows sharing violation.
87const RENAME_RETRY_ATTEMPTS: u32 = 5;
88
89/// Base backoff between those retries; the wait grows linearly with the attempt.
90const RENAME_RETRY_BACKOFF: Duration = Duration::from_millis(20);
91
92/// Longest absolute path a chunk file may need, checked once at open.
93///
94/// Windows caps a non-verbatim path at `MAX_PATH` (260) including the terminating NUL.
95/// Rust's standard library transparently switches to the `\\?\` verbatim form for long
96/// absolute paths, so this is a warning rather than a hard failure, but an operator who
97/// buries the node root ten directories deep should hear about it before the first write
98/// fails rather than after.
99#[cfg(windows)]
100const WINDOWS_PATH_WARN_LEN: usize = 240;
101
102/// The on-disk layout marker.
103///
104/// Written once when the store directory is created and read on every subsequent open.
105/// Nothing in this survey of comparable stores (IPFS flatfs, Storj, borgbackup) shipped
106/// an in-place re-sharder, and all three paid for it. Recording the scheme costs one
107/// small file and is the difference between changing the default later and never being
108/// able to.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct StoreLayout {
111 /// Marker schema version. A store written by a newer schema is refused.
112 pub schema: u32,
113 /// How a chunk address maps to a shard directory.
114 pub scheme: String,
115 /// How many hex characters of the address name the shard directory.
116 pub shard_chars: u8,
117 /// How many directory levels of sharding.
118 pub depth: u8,
119 /// How a chunk address maps to a filename.
120 pub name_encoding: String,
121}
122
123/// Marker schema this build writes and understands.
124const LAYOUT_SCHEMA: u32 = 1;
125/// Shard scheme this build implements: the trailing hex characters of the address.
126const LAYOUT_SCHEME_SUFFIX_HEX: &str = "suffix-hex";
127/// Filename encoding this build implements.
128const LAYOUT_NAME_LOWER_HEX: &str = "lower-hex";
129
130impl Default for StoreLayout {
131 fn default() -> Self {
132 Self {
133 schema: LAYOUT_SCHEMA,
134 scheme: LAYOUT_SCHEME_SUFFIX_HEX.to_string(),
135 shard_chars: 2,
136 depth: 1,
137 name_encoding: LAYOUT_NAME_LOWER_HEX.to_string(),
138 }
139 }
140}
141
142impl StoreLayout {
143 /// Return an error unless this build can read a store written with this layout.
144 fn check_supported(&self) -> Result<()> {
145 if self.schema > LAYOUT_SCHEMA {
146 return Err(Error::Storage(format!(
147 "Chunk store layout schema {} is newer than this build understands ({LAYOUT_SCHEMA}). \
148 Refusing to open rather than misread the store.",
149 self.schema
150 )));
151 }
152 if self.scheme != LAYOUT_SCHEME_SUFFIX_HEX {
153 return Err(Error::Storage(format!(
154 "Chunk store uses shard scheme '{}', this build implements '{LAYOUT_SCHEME_SUFFIX_HEX}'",
155 self.scheme
156 )));
157 }
158 if self.shard_chars != 2 || self.depth != 1 {
159 return Err(Error::Storage(format!(
160 "Chunk store uses {} shard characters at depth {}, this build implements 2 at depth 1",
161 self.shard_chars, self.depth
162 )));
163 }
164 if self.name_encoding != LAYOUT_NAME_LOWER_HEX {
165 return Err(Error::Storage(format!(
166 "Chunk store names files with '{}', this build implements '{LAYOUT_NAME_LOWER_HEX}'",
167 self.name_encoding
168 )));
169 }
170 Ok(())
171 }
172}
173
174/// Configuration for [`FileStore`].
175#[derive(Debug, Clone)]
176pub struct FileStoreConfig {
177 /// Node root directory. The store lives at `{root_dir}/chunks/`.
178 pub root_dir: PathBuf,
179 /// Verify `BLAKE3(content) == address` on read.
180 pub verify_on_read: bool,
181 /// Free bytes to keep on the storage partition. Writes are refused below this.
182 pub disk_reserve: u64,
183}
184
185/// Outcome of a single write attempt, used to keep the duplicate accounting honest.
186enum PutOutcome {
187 /// The chunk was newly published.
188 New,
189 /// The chunk was already on disk.
190 Duplicate,
191}
192
193/// Snapshot of free space, plus what has been written since it was taken.
194#[derive(Debug)]
195struct CapacitySnapshot {
196 /// When `available` was measured. `None` means never.
197 measured_at: Option<Instant>,
198 /// Free bytes reported by the filesystem at `measured_at`.
199 available: u64,
200 /// Bytes published since `measured_at`, charged against `available`.
201 ///
202 /// Cleared by a fresh measurement, which already accounts for them.
203 written_since: u64,
204 /// Bytes reserved by writes that have not landed yet.
205 ///
206 /// Deliberately **not** cleared by a measurement: a `statvfs` taken while writes are
207 /// in flight reports space those writes are about to consume, so forgetting their
208 /// reservations at that moment would hand the same bytes out twice. That is precisely
209 /// the over-admission the reservation exists to prevent.
210 in_flight: u64,
211}
212
213/// Size-aware free-space predicate with a short-lived cache.
214///
215/// Free bytes alone stopped being a sufficient answer the moment chunks became files:
216/// a caller wants to know whether *this* write fits, not whether the disk is non-empty.
217/// The cache keeps the common case at one `statvfs` per interval while staying correct
218/// under a burst, because bytes written since the measurement are charged against it.
219#[derive(Debug)]
220struct CapacityGuard {
221 /// Directory whose partition is measured.
222 dir: PathBuf,
223 /// Free bytes to keep unused.
224 reserve: u64,
225 /// The cached measurement.
226 snapshot: parking_lot::Mutex<CapacitySnapshot>,
227}
228
229impl CapacitySnapshot {
230 /// Free bytes, less everything written or promised since the measurement.
231 fn free_estimate(&self) -> u64 {
232 self.available
233 .saturating_sub(self.written_since)
234 .saturating_sub(self.in_flight)
235 }
236}
237
238impl CapacityGuard {
239 /// Create a guard over the partition hosting `dir`.
240 fn new(dir: PathBuf, reserve: u64) -> Self {
241 Self {
242 dir,
243 reserve,
244 snapshot: parking_lot::Mutex::new(CapacitySnapshot {
245 measured_at: None,
246 available: 0,
247 written_since: 0,
248 in_flight: 0,
249 }),
250 }
251 }
252
253 /// Bytes actually consumed on disk by a payload of `len` bytes.
254 fn charge(len: u64) -> u64 {
255 // Round the payload up to the allocation unit, then add one unit for the
256 // directory entry and inode.
257 len.div_ceil(ALLOC_UNIT)
258 .saturating_mul(ALLOC_UNIT)
259 .saturating_add(ALLOC_UNIT)
260 }
261
262 /// Free bytes right now, or `None` if the question could not be answered.
263 ///
264 /// Deliberately separate from [`Self::measure`], which folds a failure into an error
265 /// the caller cannot tell from "below the reserve".
266 fn measure_available(&self) -> Option<u64> {
267 let mut snapshot = self.snapshot.lock();
268 match self.measure(&mut snapshot) {
269 Ok(()) => Some(snapshot.free_estimate()),
270 Err(_) => None,
271 }
272 }
273
274 /// Query the filesystem and refresh the snapshot.
275 fn measure(&self, snapshot: &mut CapacitySnapshot) -> Result<()> {
276 let available = fs2::available_space(&self.dir)
277 .map_err(|e| Error::Storage(format!("Failed to query available disk space: {e}")))?;
278 snapshot.available = available;
279 // Reservations survive: their bytes are not on the platter yet, so the fresh
280 // measurement does not include them.
281 snapshot.written_since = 0;
282 snapshot.measured_at = Some(Instant::now());
283 Ok(())
284 }
285
286 /// Test `needed` against the snapshot, refreshing it if it is stale or short.
287 ///
288 /// Only *passing* results are cached, so a low-space condition is rechecked on every
289 /// call and freed space is noticed promptly.
290 fn admit(&self, snapshot: &mut CapacitySnapshot, needed: u64) -> Result<()> {
291 let want = self.reserve.saturating_add(Self::charge(needed));
292
293 let cache_fresh = snapshot
294 .measured_at
295 .is_some_and(|t| t.elapsed().as_secs() < DISK_CHECK_INTERVAL_SECS);
296 if cache_fresh && snapshot.free_estimate() >= want {
297 return Ok(());
298 }
299
300 self.measure(snapshot)?;
301 if snapshot.free_estimate() < want {
302 // Do not cache a failing result: `measured_at` is left set so the next call
303 // still re-measures, because the branch above only short-circuits a pass.
304 return Err(Error::Storage(format!(
305 "Insufficient disk space: {:.2} GiB available, {:.2} GiB reserve required. \
306 Free disk space or increase the partition to continue storing chunks.",
307 bytes_to_gib(snapshot.free_estimate()),
308 bytes_to_gib(self.reserve),
309 )));
310 }
311 Ok(())
312 }
313
314 /// Drop the cached measurement so the next question hits the filesystem.
315 fn invalidate(&self) {
316 let mut snapshot = self.snapshot.lock();
317 snapshot.measured_at = None;
318 snapshot.written_since = 0;
319 }
320
321 /// Return `Ok(())` if a write of `needed` bytes would fit. Charges nothing.
322 fn check(&self, needed: u64) -> Result<()> {
323 let mut snapshot = self.snapshot.lock();
324 self.admit(&mut snapshot, needed)
325 }
326
327 /// Admit a write of `needed` bytes and charge it in the same critical section.
328 ///
329 /// Checking and charging separately is the bug this exists to prevent: dozens of
330 /// protocol handlers can each pass against the same cached measurement before any of
331 /// them has written a byte, and collectively cross the reserve.
332 ///
333 /// The returned [`Reservation`] settles itself when dropped, so a caller whose future
334 /// is dropped mid-write cannot strand it. Nothing else ever decrements the in-flight
335 /// count, so a stranded reservation would be permanent, and enough of them would make
336 /// an empty disk look full until the process restarted.
337 fn reserve(self: &Arc<Self>, needed: u64) -> Result<Reservation> {
338 {
339 let mut snapshot = self.snapshot.lock();
340 self.admit(&mut snapshot, needed)?;
341 snapshot.in_flight = snapshot.in_flight.saturating_add(Self::charge(needed));
342 }
343 Ok(Reservation {
344 capacity: Arc::clone(self),
345 bytes: needed,
346 settled: false,
347 })
348 }
349
350 /// Give back a reservation whose write did not happen.
351 fn release(&self, needed: u64) {
352 let mut snapshot = self.snapshot.lock();
353 snapshot.in_flight = snapshot.in_flight.saturating_sub(Self::charge(needed));
354 }
355
356 /// Turn a reservation into bytes that are now on disk.
357 fn commit_reservation(&self, needed: u64) {
358 let charge = Self::charge(needed);
359 let mut snapshot = self.snapshot.lock();
360 snapshot.in_flight = snapshot.in_flight.saturating_sub(charge);
361 snapshot.written_since = snapshot.written_since.saturating_add(charge);
362 }
363
364 /// Credit a completed delete back to the cached measurement.
365 fn record_removed(&self, len: u64) {
366 let mut snapshot = self.snapshot.lock();
367 snapshot.written_since = snapshot.written_since.saturating_sub(Self::charge(len));
368 }
369}
370
371/// A charged, unsettled write.
372///
373/// Held by whatever is actually doing the write, so the charge is released even if the
374/// caller's future is dropped and only the blocking closure survives.
375struct Reservation {
376 /// The guard this was taken from.
377 capacity: Arc<CapacityGuard>,
378 /// Payload size, before rounding.
379 bytes: u64,
380 /// Whether it has already been accounted for.
381 settled: bool,
382}
383
384impl Reservation {
385 /// The write landed: move the charge from in-flight to written.
386 fn commit(mut self) {
387 self.capacity.commit_reservation(self.bytes);
388 self.settled = true;
389 }
390}
391
392impl Drop for Reservation {
393 fn drop(&mut self) {
394 if !self.settled {
395 self.capacity.release(self.bytes);
396 }
397 }
398}
399
400/// Environment variable naming a failpoint: stop after the temp file, before the rename.
401#[cfg(any(test, feature = "test-utils"))]
402pub const HALT_BEFORE_PUBLISH: &str = "ANT_HALT_BEFORE_PUBLISH";
403
404/// Environment variable naming a failpoint: stop once the legacy environment is renamed
405/// aside and marked retired, before any of it is deleted.
406///
407/// The most destructive window in the migration. What a start that finds a marked
408/// directory must do is finish the deletion, never reopen it, because the node has already
409/// told the network it holds those chunks from the file store.
410#[cfg(any(test, feature = "test-utils"))]
411pub const HALT_AFTER_RETIRE_MARK: &str = "ANT_HALT_AFTER_RETIRE_MARK";
412
413/// Park forever at a named failpoint, once a marker says the process has reached it.
414///
415/// For crash tests, which need a process to die *inside* an operation rather than at
416/// whatever point a sleep in another process happened to land. The variable holds a path:
417/// this writes it, so the parent knows the child is exactly here, and then waits to be
418/// killed.
419///
420/// Costs one environment read per write when the feature is compiled in, and the feature
421/// is not in a release build.
422#[cfg(any(test, feature = "test-utils"))]
423pub(crate) fn halt_here_if_asked(variable: &str, reached: &Path) {
424 let Ok(marker) = std::env::var(variable) else {
425 return;
426 };
427 // Let the first few through. A test that stops the very first write leaves a store
428 // with nothing successfully in it, and an assertion over what it holds then passes by
429 // iterating nothing. Letting some land first means the crash happens to a store that
430 // has real chunks in it, which is the situation worth checking.
431 let skip: u64 = std::env::var(HALT_AFTER)
432 .ok()
433 .and_then(|raw| raw.parse().ok())
434 .unwrap_or(0);
435 if HALTS_SEEN.fetch_add(1, std::sync::atomic::Ordering::AcqRel) < skip {
436 return;
437 }
438 if let Err(e) = std::fs::write(&marker, reached.as_os_str().as_encoded_bytes()) {
439 // The parent waits for this file. Saying so on the way past is the difference
440 // between a test that fails and one that hangs until the job times out.
441 eprintln!("failpoint could not write its marker {marker}: {e}");
442 return;
443 }
444 loop {
445 std::thread::sleep(Duration::from_secs(3600));
446 }
447}
448
449/// How many writes to let through before the failpoint fires.
450#[cfg(any(test, feature = "test-utils"))]
451pub const HALT_AFTER: &str = "ANT_HALT_AFTER";
452
453/// How many times the failpoint has been reached in this process.
454#[cfg(any(test, feature = "test-utils"))]
455static HALTS_SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
456
457/// Clears a write's registration when the work finishes, however it finishes.
458///
459/// Held by the blocking closure rather than by the caller, so a dropped future cannot
460/// leave an entry behind, and a panic in the work cannot either.
461struct WriteInFlight {
462 writing: Arc<parking_lot::Mutex<HashMap<XorName, usize>>>,
463 finished: Arc<tokio::sync::Notify>,
464 address: XorName,
465}
466
467impl Drop for WriteInFlight {
468 fn drop(&mut self) {
469 let was_last = {
470 let mut writing = self.writing.lock();
471 match writing.get_mut(&self.address) {
472 Some(count) if *count > 1 => {
473 *count -= 1;
474 false
475 }
476 _ => {
477 writing.remove(&self.address);
478 true
479 }
480 }
481 };
482 // Only when this was the last one. Waking a waiter while another write for the
483 // same key is still queued is exactly what the count exists to prevent.
484 if was_last {
485 self.finished.notify_waiters();
486 }
487 }
488}
489
490/// What is behind a chunk's name on disk.
491///
492/// Four answers, not two, because "could not read it" must never be treated as "wrong":
493/// replacing a chunk is destructive, and off Unix it truncates the file in place, so a
494/// transient fault would turn a healthy sole copy into an empty one.
495#[derive(Debug, Clone, Copy, PartialEq, Eq)]
496enum StoredBytes {
497 /// The bytes are there and hash to the name.
498 Good,
499 /// The bytes are there and do not.
500 Wrong,
501 /// There is nothing behind the name.
502 Absent,
503 /// The question could not be answered this time.
504 Unreadable,
505}
506
507/// Convert a byte count to GiB for human-readable log messages.
508#[allow(clippy::cast_precision_loss)] // display only — sub-byte precision is irrelevant
509fn bytes_to_gib(bytes: u64) -> f64 {
510 bytes as f64 / (1024.0 * 1024.0 * 1024.0)
511}
512
513/// Content-addressed store holding one immutable file per chunk.
514///
515/// The filesystem is the sole authority. The in-memory index is a cache of what the
516/// directory tree already contains, rebuilt from directory entries at every open, and
517/// every mutation of it mirrors a filesystem operation that has *already* completed.
518/// Bitcask's issue #114 is the cautionary tale for the opposite order: an index that is
519/// rebuilt at startup and then mutated in anticipation drifts, and the drift is silent.
520#[derive(Debug)]
521pub struct FileStore {
522 /// Store configuration.
523 config: FileStoreConfig,
524 /// `{root_dir}/chunks`.
525 chunks_dir: PathBuf,
526 /// Every address whose file is published, in ascending order.
527 ///
528 /// `BTreeSet` rather than a hash set because `all_keys()` must be sorted (the
529 /// commitment builder truncates with `take(cap)` *before* the Merkle tree sorts, so
530 /// an unstable order would make the node's published commitment depend on iteration
531 /// luck), and because it never spikes memory while growing.
532 index: Arc<parking_lot::RwLock<BTreeSet<XorName>>>,
533 /// One mutex per shard, serialising writers of the same address.
534 ///
535 /// LMDB gave exactly-once `put` semantics for free: the duplicate test happened
536 /// inside the write transaction. Two threads publishing the same address here would
537 /// otherwise both see an absent file, both rename, and both report "newly stored",
538 /// double-counting the chunk. The lane is indexed by the address's LAST byte for the
539 /// same reason the shard is: a node's keys share their leading bytes, so lanes keyed
540 /// on the first byte would all collapse into one.
541 write_lanes: Arc<Vec<parking_lot::Mutex<()>>>,
542 /// Operation counters, same shape as the LMDB store reported.
543 stats: parking_lot::RwLock<StorageStats>,
544 /// Which of the 256 shard directories are known to exist, so a steady-state write
545 /// does not pay a `create_dir_all` syscall.
546 shards_present: Arc<parking_lot::Mutex<[bool; SHARD_COUNT]>>,
547 /// Indexed chunks this store currently cannot read.
548 ///
549 /// Held back from everything the node says it has, while the files themselves are
550 /// left alone. See [`Self::mark_suspect`].
551 suspect: Arc<parking_lot::RwLock<HashSet<XorName>>>,
552 /// Indexed chunks a read has proven do not match their name.
553 ///
554 /// Separate from the above because they clear differently. Not being able to read a
555 /// file is a question a later read answers; bytes that are wrong stay wrong however
556 /// often they are read, and only a repair or a removal settles it. A raw read that
557 /// does not hash anything must not take a chunk out of this set.
558 known_wrong: Arc<parking_lot::RwLock<HashSet<XorName>>>,
559 /// Addresses this store is part-way through writing.
560 ///
561 /// Every mutation registers here before it spawns its blocking work and clears the
562 /// entry *inside* that work, so a caller whose future is dropped cannot skip the
563 /// clearing while the write itself goes on to land. That is the difference that
564 /// matters: the blocking half is not cancelled with the future, so anything the
565 /// future was going to do afterwards is not a record of what happened.
566 ///
567 /// It lets a delete queue behind the exact write it would otherwise race, rather than
568 /// behind every write this store has in flight.
569 ///
570 /// Counted, not a set. Cancellation can release the facade's key lane while the
571 /// blocking half survives, so a second write for the same key can start behind the
572 /// first. With one entry between them, whichever finished first would remove it and a
573 /// waiter would be told the key is free while the other was still queued.
574 writing: Arc<parking_lot::Mutex<HashMap<XorName, usize>>>,
575 /// Woken when [`Self::writing`] loses its last entry for a key.
576 write_finished: Arc<tokio::sync::Notify>,
577 /// Bumped whenever a chunk stops being servable.
578 ///
579 /// The pre-retirement pass reads every chunk, and its result is reused for a while
580 /// rather than re-read on every tick. This is how the caller can tell that the store
581 /// has not changed underneath that result: a proof carries the value it saw, and a
582 /// file that has since gone or stopped being readable makes it stale.
583 health: Arc<std::sync::atomic::AtomicU64>,
584 /// Size-aware free-space predicate.
585 capacity: Arc<CapacityGuard>,
586 /// Monotonic counter that makes temp filenames unique within this store.
587 temp_seq: AtomicU64,
588 /// Random per-instance discriminator for temp filenames.
589 nonce: u32,
590 /// Held for the store's lifetime. Startup fails without it.
591 ///
592 /// Shared rather than owned so the blocking work that depends on it can hold a lease
593 /// of its own: that work outlives the future that spawned it, and a cancelled caller
594 /// releasing the lock would leave it writing into a directory another process had
595 /// just been let into.
596 lock: Arc<File>,
597 /// Tracks every blocking task, so [`FileStore::wait_idle`] can wait for writes that
598 /// outlived their awaiting future.
599 blocking_tracker: TaskTracker,
600 /// Test-only gate read-acquired at the top of the put blocking closure.
601 ///
602 /// Tests hold the write half to park an in-flight write on the blocking pool, which
603 /// is the shape a `select!` losing to a shutdown token leaves behind.
604 #[cfg(any(test, feature = "test-utils"))]
605 test_put_gate: Arc<parking_lot::RwLock<()>>,
606}
607
608impl FileStore {
609 /// Open (or create) the store at `{root_dir}/chunks/`.
610 ///
611 /// Sweeps orphaned temp files, then rebuilds the index from directory entries.
612 /// The scan reads names only: it never `stat`s an entry and never reads a chunk.
613 ///
614 /// # Errors
615 ///
616 /// Returns [`Error::Storage`] if the directory cannot be created, the layout marker
617 /// is unreadable or describes a layout this build does not implement, or the scan
618 /// fails.
619 pub async fn new(config: FileStoreConfig) -> Result<Self> {
620 let chunks_dir = config.root_dir.join(CHUNKS_DIR_NAME);
621 std::fs::create_dir_all(&chunks_dir).map_err(|e| {
622 Error::Storage(format!(
623 "Failed to create chunk store directory {}: {e}",
624 chunks_dir.display()
625 ))
626 })?;
627
628 check_path_budget(&chunks_dir);
629
630 let layout = read_or_write_layout(&chunks_dir)?;
631 layout.check_supported()?;
632
633 // Startup fails without it, so from here this process is the only one using this
634 // directory and an interrupted write can only be its own.
635 let lock = acquire_store_lock(&chunks_dir)?;
636
637 let scan_dir = chunks_dir.clone();
638 // The scan holds the lease itself. It sweeps interrupted writes on the strength of
639 // being alone here, and it runs on a thread that outlives this future: a
640 // cancelled startup that released the lock would leave it sweeping a directory
641 // another process had just been let into.
642 let scan_lease = Arc::clone(&lock);
643 // The node root as well as the chunk tree. The scan sweeps interrupted writes
644 // under `chunks/`, which covers the layout marker's temporary because that lives
645 // there; the migration marker's lives in the root, where nothing looked.
646 let root = config.root_dir.clone();
647 let scan = spawn_blocking(move || {
648 let _lease = scan_lease;
649 sweep_marker_temps(&root);
650 scan_store(&scan_dir)
651 })
652 .await
653 .map_err(|e| Error::Storage(format!("Chunk store scan task failed: {e}")))??;
654
655 let ScanResult {
656 keys,
657 shards_present,
658 swept_temps,
659 skipped,
660 } = scan;
661
662 let key_count = keys.len();
663 // Build from a sorted vector: bulk-building packs every B-tree node to its
664 // capacity, where repeated `insert` converges on ~68% fill for the same keys.
665 let index: BTreeSet<XorName> = keys.into_iter().collect();
666
667 if swept_temps > 0 {
668 info!("Chunk store: removed {swept_temps} orphaned temporary file(s) from interrupted writes");
669 }
670 if skipped > 0 {
671 warn!("Chunk store: ignored {skipped} directory entr(ies) that are not chunk files");
672 }
673 info!(
674 "Chunk store open at {} ({key_count} chunks)",
675 chunks_dir.display()
676 );
677
678 let capacity = Arc::new(CapacityGuard::new(chunks_dir.clone(), config.disk_reserve));
679
680 Ok(Self {
681 config,
682 chunks_dir,
683 index: Arc::new(parking_lot::RwLock::new(index)),
684 write_lanes: Arc::new(
685 std::iter::repeat_with(|| parking_lot::Mutex::new(()))
686 .take(SHARD_COUNT)
687 .collect(),
688 ),
689 stats: parking_lot::RwLock::new(StorageStats::default()),
690 shards_present: Arc::new(parking_lot::Mutex::new(shards_present)),
691 suspect: Arc::new(parking_lot::RwLock::new(HashSet::new())),
692 known_wrong: Arc::new(parking_lot::RwLock::new(HashSet::new())),
693 writing: Arc::new(parking_lot::Mutex::new(HashMap::new())),
694 write_finished: Arc::new(tokio::sync::Notify::new()),
695 health: Arc::new(std::sync::atomic::AtomicU64::new(0)),
696 capacity,
697 temp_seq: AtomicU64::new(0),
698 nonce: rand::random(),
699 lock,
700 blocking_tracker: TaskTracker::new(),
701 #[cfg(any(test, feature = "test-utils"))]
702 test_put_gate: Arc::new(parking_lot::RwLock::new(())),
703 })
704 }
705
706 /// Store a chunk.
707 ///
708 /// On Unix, publishing is a rename within the destination directory, so the final name
709 /// can never appear on partial content: the name *is* the hash, and the content is
710 /// fully written and flushed before the name exists. Off Unix there is no rename, for
711 /// the reason `publish_in_place` gives (it is compiled only on those platforms, so this
712 /// is not a link), and a partial file can wear a real name; that
713 /// is why a duplicate is read and compared rather than trusted.
714 ///
715 /// # Returns
716 ///
717 /// `true` if the chunk was newly stored, `false` if it was already present.
718 ///
719 /// # Errors
720 ///
721 /// Returns [`Error::Storage`] if the content does not hash to `address`, the disk
722 /// is too full, or the write fails.
723 pub async fn put(&self, address: &XorName, content: &[u8]) -> Result<bool> {
724 let computed = crate::client::compute_address(content);
725 if computed != *address {
726 return Err(Error::Storage(format!(
727 "Content address mismatch: expected {}, computed {}",
728 hex::encode(address),
729 hex::encode(computed)
730 )));
731 }
732 // The read path refuses anything over the ceiling, so writing one would create a
733 // file the store could never read back and could never repair.
734 if content.len() > MAX_CHUNK_SIZE {
735 return Err(Error::Storage(format!(
736 "Chunk {} is {} bytes, over the {MAX_CHUNK_SIZE} byte maximum",
737 hex::encode(address),
738 content.len()
739 )));
740 }
741
742 // An indexed name is not proof of the bytes under it. The index is built from
743 // names, by the startup scan and by a completed publish, and a name can outlive
744 // what it points at: off Unix a chunk is created under its final name before its
745 // bytes are written, so a crash leaves a short file wearing a real name, and rot
746 // leaves a full-length one. Answering "already have it" to the copy that would fix
747 // either is how a node discards its own repair and is never offered another.
748 //
749 // So the bytes decide. Checked before the reservation below, so re-storing a chunk
750 // this node already holds stays a no-op on a full disk.
751 if self.index.read().contains(address) {
752 if let Some(answer) = self.settle_indexed_duplicate(address, content).await {
753 return answer;
754 }
755 }
756
757 let len = content.len() as u64;
758 // Reserved after the duplicate test so re-storing an existing chunk stays a
759 // harmless no-op on a full disk, matching the LMDB store's ordering.
760 let reservation = self.capacity.reserve(len)?;
761
762 let shard = self.chunks_dir.join(shard_name(address));
763 let final_path = shard.join(hex::encode(address));
764 let temp_path = shard.join(self.next_temp_name());
765 let payload = content.to_vec();
766 let lanes = Arc::clone(&self.write_lanes);
767 let index = Arc::clone(&self.index);
768 let shards_present = Arc::clone(&self.shards_present);
769 let chunks_dir = self.chunks_dir.clone();
770 let lane = shard_index(address);
771 let key = *address;
772 #[cfg(any(test, feature = "test-utils"))]
773 let test_put_gate = Arc::clone(&self.test_put_gate);
774 // Registered before the work is spawned and cleared by the work itself, so a
775 // caller that goes away cannot leave a delete free to race this publish.
776 let in_flight = self.begin_write(address);
777 // And the lease, for the same reason the scan holds it: this thread writes into a
778 // directory whose exclusivity the lock is what establishes, and it can outlive
779 // the last owner of the store.
780 let lease = Arc::clone(&self.lock);
781 let known_wrong = Arc::clone(&self.known_wrong);
782 let suspect = Arc::clone(&self.suspect);
783
784 let outcome = self
785 .blocking_tracker
786 .spawn_blocking(move || -> Result<PutOutcome> {
787 let _in_flight = in_flight;
788 let _lease = lease;
789 // Test-only: parks here while a test holds the write half.
790 #[cfg(any(test, feature = "test-utils"))]
791 let _test_put_gate = test_put_gate.read();
792 let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
793 // `mkdir` plus a directory flush are syscalls, so they belong here and
794 // not on a runtime worker.
795 ensure_shard_dir(&chunks_dir, &shard, lane, &shards_present)?;
796 let outcome = match publish(&temp_path, &final_path, &payload, &shard) {
797 Ok(outcome) => outcome,
798 Err(PublishFailed { error, left_behind }) => {
799 // A publish that failed can still have left the bytes there: off
800 // Unix the chunk is created under its final name, and if the write
801 // or the flush then fails, the cleanup that removes it can fail
802 // too. Releasing the reservation would hand back a charge for a
803 // file that is on the disk.
804 //
805 // The publish says so rather than this deciding from a later
806 // `is_file`. Asking the filesystem afterwards infers ownership from
807 // a name being occupied, which is true under the store lock and the
808 // shard lane and not true against anything out of band, and this
809 // file spends a lot of its length arguing that a name is not
810 // evidence. A bit set by the code that created the file is.
811 if left_behind {
812 reservation.commit();
813 }
814 return Err(error);
815 }
816 };
817 // Placed, not yet durable. A failure from here on leaves the bytes on the
818 // disk: the chunk is rightly not reported as stored, because a copy that is
819 // not durable must not authorise deleting another, but the space is spent
820 // all the same. Dropping the reservation would hand that charge back and
821 // admit the next write against room that is already gone.
822 //
823 // Only for a chunk this call published. `Duplicate` means the file was
824 // already there and was charged by whoever wrote it, so charging it again
825 // here would count one file twice and shrink the store's idea of its own
826 // disk on every retry.
827 if let Err(e) = flush_publication(&final_path, &shard) {
828 if matches!(outcome, PutOutcome::New) {
829 reservation.commit();
830 }
831 return Err(e);
832 }
833 // Index inside the lane, and only after the rename has returned. A
834 // concurrent delete of the same address therefore cannot interleave
835 // between publishing the file and admitting the key.
836 //
837 // Only for a chunk this call actually published. `Duplicate` says a file
838 // already wears the name, and a name is not evidence about the bytes under
839 // it: the four-way answer that decides whether they are good, wrong, absent
840 // or unreadable runs after the await below, and a caller whose future is
841 // dropped never reaches it. Admitting the key here would leave the node
842 // claiming, advertising and committing to bytes nothing has read, with no
843 // suspect or known-wrong mark to hold it back, and the sharpest case is a
844 // name the startup scan deliberately refused because what wears it is a
845 // fifo, a socket or a directory. The duplicate arm admits the key itself,
846 // once a read has proven the bytes.
847 if matches!(outcome, PutOutcome::New) {
848 index.write().insert(key);
849 // With the marks that would otherwise hold the key back. These bytes
850 // were hashed against their own name on the way in, so an older
851 // instance proven wrong or merely unreadable has just been replaced by
852 // a good one. Cleared here rather than after the await for the same
853 // reason the insert is here: a cancelled caller would leave the key
854 // indexed and suppressed at once, so a chunk this node really does hold
855 // would stay hidden from `exists` and `all_keys` until some later read
856 // happened to settle it.
857 known_wrong.write().remove(&key);
858 suspect.write().remove(&key);
859 // Settled here, inside the work, so a dropped awaiter cannot strand it.
860 reservation.commit();
861 }
862 Ok(outcome)
863 })
864 .await
865 .map_err(|e| Error::Storage(format!("Chunk store put task failed: {e}")))??;
866
867 match outcome {
868 PutOutcome::Duplicate => self.settle_duplicate(address, content).await,
869 PutOutcome::New => {
870 // Freshly published bytes that were checked against their own name on the
871 // way in. The marks were already cleared inside the work, where a dropped
872 // caller cannot skip them; what is left here is only what a caller who is
873 // still waiting should see.
874 let mut stats = self.stats.write();
875 stats.chunks_stored = stats.chunks_stored.saturating_add(1);
876 stats.bytes_stored = stats.bytes_stored.saturating_add(len);
877 drop(stats);
878 debug!("Stored chunk {} ({len} bytes)", hex::encode(address));
879 Ok(true)
880 }
881 }
882 }
883
884 /// Decide what a name that was already taken actually means.
885 ///
886 /// Split out of [`Self::put`] because it is a different question. `put` puts bytes on
887 /// a disk; this reads bytes back to find out whether the ones already there are the
888 /// ones the caller is offering, which is the only thing that makes a duplicate safe to
889 /// report as stored.
890 ///
891 /// # Errors
892 ///
893 /// Returns [`Error::Storage`] when the existing file is absent or could not be read,
894 /// both of which mean this node must not report the chunk as held.
895 async fn settle_duplicate(&self, address: &XorName, content: &[u8]) -> Result<bool> {
896 // The file was already on disk, and its name is not evidence its contents
897 // are right. The startup scan indexes by name without reading anything,
898 // and on Windows a crash mid-write leaves a partial file under a real
899 // chunk name. Trusting the name here would acknowledge a chunk that was
900 // never stored, and then discard the good copy arriving to repair it.
901 // Every answer handled, because three of the four must not report the
902 // chunk as stored. A caller that hears success acts on it: a client drops
903 // its own copy, replication marks the key held, and the copier takes it
904 // out of the legacy-only set.
905 match self.stored_bytes_match(address).await {
906 StoredBytes::Good => {
907 // Admitted here, which is the first moment the bytes behind the
908 // name have been read and shown to hash to it. Idempotent: the
909 // ordinary case is a key the startup scan already indexed.
910 self.index.write().insert(*address);
911 {
912 let mut stats = self.stats.write();
913 stats.duplicates = stats.duplicates.saturating_add(1);
914 }
915 Ok(false)
916 }
917 StoredBytes::Wrong => {
918 warn!(
919 "Chunk {} was already on disk but its contents are wrong; \
920 replacing it with the copy just offered",
921 hex::encode(address)
922 );
923 self.repair(address, content).await.map(|()| true)
924 }
925 // The name was taken a moment ago and is not now, or was never a
926 // readable chunk file. Either way nothing holds these bytes, so say so
927 // rather than reporting a chunk that is not there.
928 StoredBytes::Absent => Err(Error::Storage(format!(
929 "Chunk {} was reported already on disk but nothing is there. Not \
930 reporting it as stored.",
931 hex::encode(address)
932 ))),
933 // Replacing on an unanswered question would destroy a healthy copy,
934 // and reporting success would discard the offered one. The index entry
935 // stays: the file is still there, and dropping the entry would leave
936 // the chunk in neither this store's view nor the legacy one, which is
937 // what retirement destroys. Removing an entry is the quarantine path's
938 // job, and it removes the file with it, after a read that succeeded
939 // and proved the bytes wrong.
940 StoredBytes::Unreadable => Err(Error::Storage(format!(
941 "Chunk {} is on disk but could not be read to check it. Not \
942 replacing it, and not reporting it as stored.",
943 hex::encode(address)
944 ))),
945 }
946 }
947
948 /// Flush every directory a chunk can live in, so the names in them are durable.
949 ///
950 /// Byte integrity is not the whole of what the pre-retirement proof has to establish.
951 /// A chunk whose contents are on the platter but whose *name* is not is still lost to
952 /// a power loss, and a publish whose rename landed and whose directory flush failed
953 /// leaves exactly that: the next attempt sees the name, the next verification reads
954 /// the right bytes, and nothing goes back to retry the flush. So the proof flushes
955 /// them itself rather than trusting that each publish did.
956 ///
957 /// Cheap: at most 257 directory flushes for a store of any size, and nothing off Unix,
958 /// where directories cannot be flushed and the retirement marker covers the same
959 /// ground instead.
960 ///
961 /// # Errors
962 ///
963 /// Returns [`Error::Storage`] on the first directory that cannot be flushed. The
964 /// caller must treat that as a proof it did not get.
965 pub fn flush_namespace(&self) -> Result<()> {
966 fsync_dir(&self.chunks_dir).map_err(|e| {
967 Error::Storage(format!(
968 "Could not flush {}: {e}",
969 self.chunks_dir.display()
970 ))
971 })?;
972 let present = *self.shards_present.lock();
973 for (shard, _) in present.iter().enumerate().filter(|(_, here)| **here) {
974 let dir = self.chunks_dir.join(format!("{shard:02x}"));
975 fsync_dir(&dir)
976 .map_err(|e| Error::Storage(format!("Could not flush {}: {e}", dir.display())))?;
977 }
978 Ok(())
979 }
980
981 /// Decide what to do about a write of a chunk the index already names.
982 ///
983 /// `None` means the index was wrong and there is nothing on disk, so the caller
984 /// publishes it as new. Everything else is the answer.
985 async fn settle_indexed_duplicate(
986 &self,
987 address: &XorName,
988 content: &[u8],
989 ) -> Option<Result<bool>> {
990 match self.stored_bytes_match(address).await {
991 StoredBytes::Good => {
992 trace!("Chunk {} already exists", hex::encode(address));
993 {
994 let mut stats = self.stats.write();
995 stats.duplicates = stats.duplicates.saturating_add(1);
996 }
997 Some(Ok(false))
998 }
999 StoredBytes::Wrong => {
1000 warn!(
1001 "Chunk {} is indexed but its bytes are wrong; replacing it with the \
1002 copy just offered",
1003 hex::encode(address)
1004 );
1005 Some(self.repair(address, content).await.map(|()| true))
1006 }
1007 // Indexed but gone: publish it fresh rather than replacing something that is
1008 // not there.
1009 StoredBytes::Absent => None,
1010 // Unanswerable this time. Do not touch what is there, and do not tell the
1011 // caller the chunk is safely stored either: a client would take that as an
1012 // acknowledgement and drop the only other copy. The index entry stays, for
1013 // the reason given on the same case after publication.
1014 StoredBytes::Unreadable => Some(Err(Error::Storage(format!(
1015 "Chunk {} is indexed but could not be read to check it. Not replacing it, \
1016 and not reporting it as stored.",
1017 hex::encode(address)
1018 )))),
1019 }
1020 }
1021
1022 /// Drop an address from the index without touching the file. Tests only.
1023 ///
1024 /// Stands in for whatever leaves a key indexed nowhere: a quarantine, a publish that
1025 /// failed after the file went, an operator with a shell.
1026 #[cfg(test)]
1027 pub(crate) fn forget_for_test(&self, address: &XorName) {
1028 self.index.write().remove(address);
1029 }
1030
1031 /// The size of the file behind `address`, if there is one.
1032 ///
1033 /// One `metadata` call, no read. Used where an indexed name has to be checked against
1034 /// what a caller is offering before that offer is turned away.
1035 #[must_use]
1036 pub fn stored_len(&self, address: &XorName) -> Option<usize> {
1037 std::fs::metadata(self.chunk_path(address))
1038 .ok()
1039 .filter(std::fs::Metadata::is_file)
1040 .and_then(|m| usize::try_from(m.len()).ok())
1041 }
1042
1043 /// Whether the file already stored under `address` really hashes to it.
1044 async fn stored_bytes_match(&self, address: &XorName) -> StoredBytes {
1045 match self.get_raw(address).await {
1046 Ok(Some(bytes)) if crate::client::compute_address(&bytes) == *address => {
1047 // A read that hashed. It settles both questions.
1048 self.clear_suspect(address);
1049 self.clear_known_wrong(address);
1050 StoredBytes::Good
1051 }
1052 Ok(Some(_)) => {
1053 self.mark_known_wrong(address);
1054 StoredBytes::Wrong
1055 }
1056 Ok(None) => StoredBytes::Absent,
1057 // NOT the same as wrong. A file that could not be read this once may be
1058 // perfectly good, and off Unix replacing it means opening it with `truncate`,
1059 // which would destroy a healthy sole copy on the strength of a transient
1060 // fault. Say so and let the caller leave it alone.
1061 Err(e) => {
1062 debug!("Could not read {} to check it: {e}", hex::encode(address));
1063 self.mark_suspect(address);
1064 StoredBytes::Unreadable
1065 }
1066 }
1067 }
1068
1069 /// Replace the file behind an address with known-good bytes, atomically.
1070 ///
1071 /// Unlike [`Self::put`], this deliberately publishes **over** an existing name. It
1072 /// exists for one caller: repairing a file whose bytes no longer hash to their own
1073 /// name, from a copy held elsewhere, before that copy is destroyed. Doing it as
1074 /// delete-then-put would leave a window where the only remaining copy is the one
1075 /// about to be deleted, and any failure in that window is unrecoverable.
1076 ///
1077 /// # Errors
1078 ///
1079 /// Returns [`Error::Storage`] if `content` does not hash to `address`, or the write
1080 /// fails. The old file is left untouched on every error path.
1081 pub async fn repair(&self, address: &XorName, content: &[u8]) -> Result<()> {
1082 // The same ceiling `put` enforces. Without it a repair can install bytes the read
1083 // path will refuse for ever, which is a chunk that verifies as present and can
1084 // never be served.
1085 if content.len() > MAX_CHUNK_SIZE {
1086 return Err(Error::Storage(format!(
1087 "Refusing to repair {} with {} bytes, over the {MAX_CHUNK_SIZE} byte \
1088 maximum",
1089 hex::encode(address),
1090 content.len()
1091 )));
1092 }
1093 let computed = crate::client::compute_address(content);
1094 if computed != *address {
1095 return Err(Error::Storage(format!(
1096 "Refusing to repair {} with content that hashes to {}",
1097 hex::encode(address),
1098 hex::encode(computed)
1099 )));
1100 }
1101 // The replacement exists alongside the original until the rename, so the room for
1102 // it has to be there first. Reserved rather than merely checked: a plain check
1103 // passes against a cached measurement, so concurrent repairs and PUTs can each be
1104 // admitted against the same headroom and cross the reserve together.
1105 // Moved into the work below, so it is released when the write finishes rather
1106 // than when its caller stops waiting. A caller that goes away otherwise frees
1107 // room that the detached write is still about to consume.
1108 let reservation = self.capacity.reserve(content.len() as u64)?;
1109
1110 let shard = self.chunks_dir.join(shard_name(address));
1111 let final_path = shard.join(hex::encode(address));
1112 let temp_path = shard.join(self.next_temp_name());
1113 let payload = content.to_vec();
1114 let lanes = Arc::clone(&self.write_lanes);
1115 let index = Arc::clone(&self.index);
1116 let shards_present = Arc::clone(&self.shards_present);
1117 let chunks_dir = self.chunks_dir.clone();
1118 let lane = shard_index(address);
1119 let key = *address;
1120 let in_flight = self.begin_write(address);
1121 let lease = Arc::clone(&self.lock);
1122 let capacity = Arc::clone(&self.capacity);
1123 let suspect = Arc::clone(&self.suspect);
1124 let known_wrong = Arc::clone(&self.known_wrong);
1125
1126 self.blocking_tracker
1127 .spawn_blocking(move || -> Result<()> {
1128 let _in_flight = in_flight;
1129 let _lease = lease;
1130 let _reservation = reservation;
1131 let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
1132 ensure_shard_dir(&chunks_dir, &shard, lane, &shards_present)?;
1133 write_and_replace(&temp_path, &final_path, &payload, &shard)?;
1134 index.write().insert(key);
1135 // Settled here rather than after the await. The replacement has landed
1136 // and hashes to its own name, so nothing is wrong with this chunk any
1137 // more; a caller that stopped waiting would otherwise leave a healthy
1138 // file excluded from everything the node claims to hold, and the
1139 // measurement believing the store is a chunk smaller than it is.
1140 suspect.write().remove(&key);
1141 known_wrong.write().remove(&key);
1142 capacity.invalidate();
1143 Ok(())
1144 })
1145 .await
1146 .map_err(|e| Error::Storage(format!("Chunk store repair task failed: {e}")))??;
1147
1148 // Everything the success means was recorded by the work that succeeded: the
1149 // reservation released, the marks cleared, the measurement thrown away. Released
1150 // rather than committed because a repair is not a new chunk, and the measurement
1151 // discarded rather than adjusted because the file it replaced may have been
1152 // shorter, which is exactly the case a repair fixes.
1153 debug!("Repaired chunk {}", hex::encode(address));
1154 Ok(())
1155 }
1156
1157 /// Retrieve a chunk, verifying it against its address when configured to.
1158 ///
1159 /// # Errors
1160 ///
1161 /// Returns [`Error::Storage`] on an I/O failure, or when verification fails. A
1162 /// chunk whose bytes do not hash to its name is removed and dropped from the index
1163 /// before the error is returned, so it leaves `all_keys()` and ordinary replication
1164 /// repairs it.
1165 pub async fn get(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
1166 let Some(content) = self.read_file(address).await? else {
1167 trace!("Chunk {} not found", hex::encode(address));
1168 return Ok(None);
1169 };
1170
1171 if self.config.verify_on_read {
1172 let computed = crate::client::compute_address(&content);
1173 if computed != *address {
1174 {
1175 let mut stats = self.stats.write();
1176 stats.verification_failures = stats.verification_failures.saturating_add(1);
1177 }
1178 warn!(
1179 "Chunk verification failed: expected {}, computed {}",
1180 hex::encode(address),
1181 hex::encode(computed)
1182 );
1183 // Said before it is acted on. Removing the file can fail or be cancelled,
1184 // and a chunk proven wrong that goes on looking healthy is one the node
1185 // keeps committing to and, worse, one a cached pre-retirement pass still
1186 // covers: the legacy copy that would repair it gets deleted.
1187 self.mark_known_wrong(address);
1188 self.quarantine_corrupt(address).await;
1189 return Err(Error::Storage(format!(
1190 "Chunk verification failed for {}",
1191 hex::encode(address)
1192 )));
1193 }
1194 }
1195
1196 if self.config.verify_on_read {
1197 // The bytes hashed to their name. Whatever this store thought was wrong with
1198 // them is not wrong with them, and a mark that outlives the fault it
1199 // describes means the node can serve a chunk it will not claim, commit or
1200 // offer.
1201 self.clear_known_wrong(address);
1202 }
1203
1204 let len = content.len() as u64;
1205 {
1206 let mut stats = self.stats.write();
1207 stats.chunks_retrieved = stats.chunks_retrieved.saturating_add(1);
1208 stats.bytes_retrieved = stats.bytes_retrieved.saturating_add(len);
1209 }
1210 debug!("Retrieved chunk {} ({len} bytes)", hex::encode(address));
1211 Ok(Some(content))
1212 }
1213
1214 /// Retrieve raw chunk bytes without content-address verification.
1215 ///
1216 /// # Errors
1217 ///
1218 /// Returns [`Error::Storage`] on an I/O failure.
1219 pub async fn get_raw(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
1220 self.read_file(address).await
1221 }
1222
1223 /// Check whether a chunk is stored.
1224 ///
1225 /// An in-memory lookup: no syscall, no I/O.
1226 ///
1227 /// # Errors
1228 ///
1229 /// Never fails. The signature keeps the shape the LMDB store had, because callers
1230 /// treat the error as "assume absent".
1231 pub fn exists(&self, address: &XorName) -> Result<bool> {
1232 if self.is_unservable(address) {
1233 return Ok(false);
1234 }
1235 Ok(self.is_indexed(address))
1236 }
1237
1238 /// Is this chunk one the node must not answer for?
1239 #[must_use]
1240 fn is_unservable(&self, address: &XorName) -> bool {
1241 self.suspect.read().contains(address) || self.known_wrong.read().contains(address)
1242 }
1243
1244 /// Is this chunk in the index, whether or not it can currently be read?
1245 ///
1246 /// The physical question, as against [`Self::exists`]'s question about what the node
1247 /// is willing to claim. The migration must ask this one: a suspect chunk is still a
1248 /// file this store has, and treating it as absent would put the key in the legacy-only
1249 /// set, from where the union view advertises it again — a key the node claims through
1250 /// one view and cannot serve through either.
1251 #[must_use]
1252 pub fn is_indexed(&self, address: &XorName) -> bool {
1253 self.index.read().contains(address)
1254 }
1255
1256 /// Delete a chunk, returning whether it was present.
1257 ///
1258 /// `unlink` returns the blocks to the filesystem immediately. That is the whole
1259 /// point of this store: no free list, no compaction, no free space required to
1260 /// reclaim space.
1261 ///
1262 /// # Errors
1263 ///
1264 /// Returns [`Error::Storage`] if the file exists but cannot be removed. The index
1265 /// keeps the key in that case, because the bytes are still on disk.
1266 pub async fn delete(&self, address: &XorName) -> Result<bool> {
1267 let path = self.chunk_path(address);
1268 let lanes = Arc::clone(&self.write_lanes);
1269 let index = Arc::clone(&self.index);
1270 let lane = shard_index(address);
1271 let key = *address;
1272 // Carried into the closure for the reason `put`, `repair` and the startup scan
1273 // carry it: this work outlives the future that started it, so a cancelled caller
1274 // that drops the last `FileStore` would otherwise release the directory to another
1275 // process while an unlink is still queued against it. Deleting is the operation
1276 // where that matters most.
1277 let lease = Arc::clone(&self.lock);
1278
1279 let (existed, freed) = self
1280 .blocking_tracker
1281 .spawn_blocking(move || -> Result<(bool, u64)> {
1282 let _lease = lease;
1283 let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
1284 let len = std::fs::metadata(&path).map_or(0, |m| m.len());
1285 let removed = match std::fs::remove_file(&path) {
1286 Ok(()) => {
1287 // Without this a crash can resurrect the entry on ext4, XFS,
1288 // btrfs and APFS: the unlink is in the page cache, the directory
1289 // is not.
1290 if let Some(shard) = path.parent() {
1291 fsync_dir_best_effort(shard);
1292 }
1293 true
1294 }
1295 // Already gone: the index was stale. Still a successful delete as
1296 // far as the caller is concerned.
1297 Err(e) if e.kind() == ErrorKind::NotFound => false,
1298 Err(e) => {
1299 return Err(Error::Storage(format!(
1300 "Failed to delete chunk file {}: {e}",
1301 path.display()
1302 )))
1303 }
1304 };
1305 // Index only after the filesystem operation has succeeded. On the error
1306 // path above the entry stays, because the bytes are still on disk.
1307 let was_indexed = index.write().remove(&key);
1308 Ok((removed || was_indexed, if removed { len } else { 0 }))
1309 })
1310 .await
1311 .map_err(|e| Error::Storage(format!("Chunk store delete task failed: {e}")))??;
1312
1313 if freed > 0 {
1314 self.capacity.record_removed(freed);
1315 debug!("Deleted chunk {}", hex::encode(address));
1316 }
1317 Ok(existed)
1318 }
1319
1320 /// Return every stored key, in ascending order.
1321 ///
1322 /// The order is a correctness requirement, not a convenience: the commitment
1323 /// builder truncates the responsible subset with `take(cap)` before the Merkle tree
1324 /// sorts it, so an unstable order would make the node's published commitment depend
1325 /// on iteration luck.
1326 ///
1327 /// # Errors
1328 ///
1329 /// Never fails. The signature matches the LMDB store's.
1330 // Async without awaiting anything, deliberately: the whole point of this store is
1331 // that the key set is already in memory. Callers are spread across the replication
1332 // engine and cannot all be de-async'd in this change.
1333 //
1334 // Two lint names because they were renamed between toolchains, and `unknown_lints`
1335 // so whichever one the compiler in use has never heard of stays quiet.
1336 #[allow(unknown_lints)]
1337 #[allow(clippy::unused_async, clippy::unused_async_trait_impl)]
1338 pub async fn all_keys(&self) -> Result<Vec<XorName>> {
1339 // Copied out first so neither lock is held while the other is taken, and so the
1340 // usual case, where nothing is suspect, costs one clone of an empty set.
1341 let mut unservable: HashSet<XorName> = self.suspect.read().clone();
1342 unservable.extend(self.known_wrong.read().iter().copied());
1343 let keys = self.index.read().clone();
1344 if unservable.is_empty() {
1345 return Ok(keys.into_iter().collect());
1346 }
1347 Ok(keys
1348 .into_iter()
1349 .filter(|key| !unservable.contains(key))
1350 .collect())
1351 }
1352
1353 /// Stop answering for a chunk this store could not read.
1354 ///
1355 /// The file stays. It may be perfectly good and unreadable only for the moment, and
1356 /// deleting it, or dropping it from the index, is how a chunk ends up in neither this
1357 /// store's view nor the legacy one, which is what retirement destroys.
1358 ///
1359 /// What does change is what the node says about it. A chunk it cannot read is one it
1360 /// cannot serve, and claiming it anyway puts the key in signed commitments, answers
1361 /// presence probes with a yes, suppresses the replication that would repair it, and
1362 /// earns a penalty at the next commitment-bound audit. Those penalties are not
1363 /// suspended.
1364 fn mark_suspect(&self, address: &XorName) {
1365 if self.suspect.write().insert(*address) {
1366 self.note_health_changed();
1367 warn!(
1368 "Chunk {} is on disk but could not be read; this node stops answering for \
1369 it until a read succeeds",
1370 hex::encode(address)
1371 );
1372 }
1373 }
1374
1375 /// What the store's health looked like at this moment.
1376 ///
1377 /// Compare a value taken before a long-running check with one taken after, or after
1378 /// taking a lock: different means a chunk stopped being servable in between and any
1379 /// conclusion drawn from that check is out of date.
1380 #[must_use]
1381 pub fn health_generation(&self) -> u64 {
1382 self.health.load(std::sync::atomic::Ordering::Acquire)
1383 }
1384
1385 /// Record that a chunk stopped being servable.
1386 fn note_health_changed(&self) {
1387 self.health
1388 .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1389 }
1390
1391 /// Stop answering for a chunk a read has proven wrong.
1392 ///
1393 /// Unlike a chunk that merely could not be read, a later read does not clear this.
1394 /// The bytes are wrong, and reading them again says the same thing; only replacing
1395 /// them or removing them settles it. Bumping health matters as much as the suppression: a chunk that
1396 /// has become unservable since the last pre-retirement pass must invalidate that pass,
1397 /// or a repair that fails leaves the node deleting the copy it would have repaired
1398 /// from.
1399 ///
1400 /// For callers outside this module that have proven it themselves.
1401 pub fn note_known_wrong(&self, address: &XorName) {
1402 self.mark_known_wrong(address);
1403 }
1404
1405 /// Stop answering for a chunk a read has proven wrong.
1406 fn mark_known_wrong(&self, address: &XorName) {
1407 if self.known_wrong.write().insert(*address) {
1408 self.note_health_changed();
1409 warn!(
1410 "Chunk {} does not match its name; this node stops answering for it until \
1411 it is repaired or removed",
1412 hex::encode(address)
1413 );
1414 }
1415 }
1416
1417 /// A caller outside this module has proven the stored bytes are right.
1418 pub fn note_bytes_proven_good(&self, address: &XorName) {
1419 self.clear_known_wrong(address);
1420 self.clear_suspect(address);
1421 }
1422
1423 /// Answer for a chunk again, after it has been replaced or removed.
1424 fn clear_known_wrong(&self, address: &XorName) {
1425 self.known_wrong.write().remove(address);
1426 }
1427
1428 /// Answer for a chunk again, after a read that worked.
1429 fn clear_suspect(&self, address: &XorName) {
1430 if !self.suspect.read().contains(address) {
1431 return;
1432 }
1433 if self.suspect.write().remove(address) {
1434 info!(
1435 "Chunk {} could be read again; this node answers for it once more",
1436 hex::encode(address)
1437 );
1438 }
1439 }
1440
1441 /// Number of chunks currently stored.
1442 ///
1443 /// The physical count: every name in the index, including chunks the node has stopped
1444 /// answering for because a read found them wrong or could not read them at all. It is
1445 /// deliberately not the same number as `all_keys().len()`, which is what the node is
1446 /// willing to claim and so leaves those out.
1447 ///
1448 /// Anything asking "how much is on this disk" wants this one, and that is what its
1449 /// callers ask: the migration's progress, the storage stats, and the size an audit is
1450 /// built for. Anything asking "what will this node answer for" wants `all_keys`.
1451 /// Quietly filtering this one would move all three of those without saying so, which
1452 /// is why the difference is written down here rather than removed.
1453 ///
1454 /// # Errors
1455 ///
1456 /// Never fails. The signature matches the LMDB store's.
1457 pub fn current_chunks(&self) -> Result<u64> {
1458 Ok(self.index.read().len() as u64)
1459 }
1460
1461 /// Operation statistics, with the live chunk count filled in.
1462 #[must_use]
1463 pub fn stats(&self) -> StorageStats {
1464 let mut stats = self.stats.read().clone();
1465 stats.current_chunks = self.index.read().len() as u64;
1466 stats
1467 }
1468
1469 /// The node root directory this store was configured with.
1470 #[must_use]
1471 pub fn root_dir(&self) -> &Path {
1472 &self.config.root_dir
1473 }
1474
1475 /// The directory holding the shard tree.
1476 #[must_use]
1477 pub fn chunks_dir(&self) -> &Path {
1478 &self.chunks_dir
1479 }
1480
1481 /// Reject work early when the disk cannot take another chunk at all.
1482 ///
1483 /// # Errors
1484 ///
1485 /// Returns [`Error::Storage`] when free space is below the configured reserve.
1486 pub fn check_capacity(&self) -> Result<()> {
1487 self.capacity.check(0)
1488 }
1489
1490 /// Three-way answer to "can this store take a write right now".
1491 ///
1492 /// Kept distinct from [`Self::check_capacity`] because a failed free-space query and a
1493 /// genuinely full disk are not the same thing, and the replication verification cycle
1494 /// depends on the difference: a full disk is a standing condition worth minutes of
1495 /// backoff, while a `statvfs` that failed says nothing about available space and may
1496 /// well succeed on the next pass.
1497 #[must_use]
1498 pub fn capacity_verdict(&self) -> crate::storage::CapacityVerdict {
1499 match self.capacity.measure_available() {
1500 Some(available) if available < self.capacity.reserve => {
1501 crate::storage::CapacityVerdict::Full
1502 }
1503 Some(_) => crate::storage::CapacityVerdict::Writable,
1504 None => crate::storage::CapacityVerdict::Unknown,
1505 }
1506 }
1507
1508 /// Reject work early when the disk cannot take `bytes` more.
1509 ///
1510 /// # Errors
1511 ///
1512 /// Returns [`Error::Storage`] when the write would not fit above the reserve.
1513 pub fn check_capacity_for(&self, bytes: u64) -> Result<()> {
1514 self.capacity.check(bytes)
1515 }
1516
1517 /// Force the next capacity question to re-measure the filesystem.
1518 ///
1519 /// Called after the legacy environment is removed, because that is a step change in
1520 /// free space that the short-lived cache would otherwise hide for a few seconds.
1521 pub fn invalidate_capacity_cache(&self) {
1522 self.capacity.invalidate();
1523 }
1524
1525 /// Test-only handle to the put gate.
1526 ///
1527 /// Hold the write half to park the next write inside its blocking closure, for
1528 /// example to prove that shutdown waits for a write whose awaiter was dropped.
1529 #[cfg(any(test, feature = "test-utils"))]
1530 #[must_use]
1531 pub fn test_put_gate(&self) -> Arc<parking_lot::RwLock<()>> {
1532 Arc::clone(&self.test_put_gate)
1533 }
1534
1535 /// Register a write of `address` and hand back the token that clears it.
1536 ///
1537 /// The token must be moved into the blocking closure that does the work, so the entry
1538 /// is cleared by the thread that finishes rather than by a caller that may be gone.
1539 fn begin_write(&self, address: &XorName) -> WriteInFlight {
1540 *self.writing.lock().entry(*address).or_insert(0) += 1;
1541 WriteInFlight {
1542 writing: Arc::clone(&self.writing),
1543 finished: Arc::clone(&self.write_finished),
1544 address: *address,
1545 }
1546 }
1547
1548 /// Wait until nothing is part-way through writing `address`.
1549 ///
1550 /// For callers that must be last: a delete whose key still has a write in flight
1551 /// would be undone by that write landing afterwards.
1552 pub async fn wait_for_write(&self, address: &XorName) {
1553 loop {
1554 // Registered before the check, so a clear between the two is not missed.
1555 let waiting = self.write_finished.notified();
1556 if !self.writing.lock().contains_key(address) {
1557 return;
1558 }
1559 waiting.await;
1560 }
1561 }
1562
1563 /// How many blocking tasks this store currently has in flight. Tests only.
1564 ///
1565 /// Lets a test wait for work to have actually started rather than guessing at a
1566 /// delay, which is the difference between a test that proves something and one that
1567 /// passes because the machine was quick.
1568 #[cfg(test)]
1569 #[must_use]
1570 pub(crate) fn tasks_in_flight(&self) -> usize {
1571 self.blocking_tracker.len()
1572 }
1573
1574 /// Wait until every blocking task this store spawned has finished.
1575 ///
1576 /// Dropping the awaiting future does not cancel a `spawn_blocking` closure, so
1577 /// shutdown has to wait for the closure itself.
1578 pub async fn wait_idle(&self) {
1579 self.blocking_tracker.close();
1580 self.blocking_tracker.wait().await;
1581 self.blocking_tracker.reopen();
1582 }
1583
1584 /// Absolute path of a chunk file.
1585 fn chunk_path(&self, address: &XorName) -> PathBuf {
1586 self.chunks_dir
1587 .join(shard_name(address))
1588 .join(hex::encode(address))
1589 }
1590
1591 /// A temp name unique to this store instance, and distinguishable from a chunk name.
1592 ///
1593 /// The nonce matters: two `FileStore`s on one root in one process share a PID, and a
1594 /// recycled PID collides with an age-gated leftover. Either way `create_new` would
1595 /// fail and surface as a spurious write error.
1596 fn next_temp_name(&self) -> String {
1597 let seq = self.temp_seq.fetch_add(1, Ordering::Relaxed);
1598 format!(
1599 "{TEMP_PREFIX}{}.{:08x}.{seq}",
1600 std::process::id(),
1601 self.nonce
1602 )
1603 }
1604
1605 /// Read a chunk file, dropping the index entry if the file has vanished.
1606 async fn read_file(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
1607 let path = self.chunk_path(address);
1608 let read = self
1609 .blocking_tracker
1610 .spawn_blocking(move || -> Result<Option<Vec<u8>>> {
1611 match open_regular(&path) {
1612 Ok(Some(f)) => read_bounded(f, &path).map(Some),
1613 Ok(None) => Ok(None),
1614 Err(e) => Err(e),
1615 }
1616 })
1617 .await
1618 .map_err(|e| Error::Storage(format!("Chunk store read task failed: {e}")))?;
1619
1620 // Every read decides the question, not only the ones that were checking. A read
1621 // that failed means this chunk cannot be served, whoever asked; a read that
1622 // worked means it can be, whoever asked. Doing this anywhere else leaves a key
1623 // stuck unadvertised after the fault has cleared, or advertised after it has not.
1624 let read = match read {
1625 Ok(read) => {
1626 self.clear_suspect(address);
1627 read
1628 }
1629 Err(e) => {
1630 self.mark_suspect(address);
1631 return Err(e);
1632 }
1633 };
1634
1635 if read.is_none() && self.forget_if_absent(address).await {
1636 // The file went away underneath us. Stop advertising the key so the close
1637 // group notices the shortfall and replication puts it back.
1638 warn!(
1639 "Chunk {} is indexed but its file is missing; dropped from the index so \
1640 replication can repair it",
1641 hex::encode(address)
1642 );
1643 }
1644 Ok(read)
1645 }
1646
1647 /// Drop an index entry whose file is genuinely gone.
1648 ///
1649 /// Re-checks under the address's write lane, so a chunk republished between the
1650 /// failing read and this call keeps its entry.
1651 async fn forget_if_absent(&self, address: &XorName) -> bool {
1652 // Not suspect any more: it is not unreadable, it is not there.
1653 self.clear_suspect(address);
1654 let path = self.chunk_path(address);
1655 let lanes = Arc::clone(&self.write_lanes);
1656 let index = Arc::clone(&self.index);
1657 let lane = shard_index(address);
1658 let key = *address;
1659 // The bump happens inside the closure, with the mutation it describes. The
1660 // closure runs to completion on its own thread whether or not anyone is still
1661 // awaiting it, so bumping after the await is skipped entirely when a shutdown
1662 // drops the caller — and the index change it was meant to announce still lands.
1663 // A cached pre-retirement proof would then stay valid over a store that had
1664 // quietly lost a chunk.
1665 let health = Arc::clone(&self.health);
1666 self.blocking_tracker
1667 .spawn_blocking(move || {
1668 let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
1669 if path.exists() {
1670 return false;
1671 }
1672 let forgotten = index.write().remove(&key);
1673 if forgotten {
1674 health.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1675 }
1676 forgotten
1677 })
1678 .await
1679 .unwrap_or(false)
1680 }
1681
1682 /// Remove a chunk whose bytes do not match its name, and stop advertising it.
1683 ///
1684 /// Re-reads and re-verifies under the address's write lane first. A read that failed
1685 /// verification is rare enough that paying for one extra read is worth never
1686 /// discarding a chunk that a concurrent write had already repaired.
1687 async fn quarantine_corrupt(&self, address: &XorName) {
1688 let path = self.chunk_path(address);
1689 let lanes = Arc::clone(&self.write_lanes);
1690 let index = Arc::clone(&self.index);
1691 let lane = shard_index(address);
1692 let key = *address;
1693 // For the reason given on `forget_if_absent`: this closure outlives its awaiter,
1694 // and the change it makes has to be announced by the same thread that makes it.
1695 let health = Arc::clone(&self.health);
1696 // And the store-lock lease, for the reason `put`, `repair`, `delete` and the
1697 // startup scan carry it: this closure outlives its awaiter, so without it a
1698 // cancelled verification whose caller dropped the last `FileStore` would unlink
1699 // inside a directory a second process had already been handed.
1700 let lease = Arc::clone(&self.lock);
1701 let outcome =
1702 self.blocking_tracker
1703 .spawn_blocking(move || -> std::io::Result<bool> {
1704 let _lease = lease;
1705 let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
1706 // Nothing is thrown away without proof. A re-read that fails says the
1707 // question could not be answered this time, not that the bytes are wrong,
1708 // and a repair may have published a good copy since the read that brought
1709 // us here. Treating either as corruption deletes a chunk this node has.
1710 let buf = match open_regular(&path) {
1711 Ok(Some(f)) => read_bounded(f, &path)
1712 .map_err(|e| std::io::Error::other(e.to_string()))?,
1713 Ok(None) => {
1714 index.write().remove(&key);
1715 health.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1716 return Ok(true);
1717 }
1718 Err(e) => return Err(std::io::Error::other(e.to_string())),
1719 };
1720 if crate::client::compute_address(&buf) == key {
1721 // Repaired between the failing read and now. Leave it alone.
1722 return Ok(false);
1723 }
1724 std::fs::remove_file(&path)?;
1725 // The same flush the ordinary delete does, for the same reason: an
1726 // unlink that has not reached the directory can be undone by a power
1727 // loss, and here the entry that comes back is one this node has proven
1728 // wrong. The startup scan would re-index it by name, and the
1729 // known-wrong mark that would otherwise hold it back lives only in
1730 // memory and does not survive the restart, so the node would go back to
1731 // claiming and committing to a chunk it already knows is bad.
1732 if let Some(shard) = path.parent() {
1733 fsync_dir_best_effort(shard);
1734 }
1735 index.write().remove(&key);
1736 health.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1737 Ok(true)
1738 })
1739 .await;
1740 match outcome {
1741 Ok(Ok(true)) => {
1742 self.clear_known_wrong(address);
1743 self.clear_suspect(address);
1744 warn!(
1745 "Removed corrupt chunk file {}; replication will repair it",
1746 hex::encode(address)
1747 );
1748 }
1749 Ok(Ok(false)) => {
1750 // The re-read hashed and matched: a repair landed between the failing
1751 // read and this one.
1752 self.clear_known_wrong(address);
1753 self.clear_suspect(address);
1754 debug!(
1755 "Chunk {} verified on re-read; leaving it in place",
1756 hex::encode(address)
1757 );
1758 }
1759 // Still indexed, so it must not still be claimed: the read that brought us
1760 // here proved the bytes wrong, and the node would otherwise go on committing
1761 // to a chunk it knows it cannot serve.
1762 Ok(Err(e)) => {
1763 self.mark_suspect(address);
1764 warn!(
1765 "Corrupt chunk {} could not be removed: {e}. It stays on disk, and \
1766 this node stops answering for it.",
1767 hex::encode(address)
1768 );
1769 }
1770 Err(e) => {
1771 self.mark_suspect(address);
1772 warn!("Corrupt-chunk removal task failed: {e}");
1773 }
1774 }
1775 }
1776}
1777
1778// ────────────────────────────────────────────────────────────────────────────
1779// Free functions
1780// ────────────────────────────────────────────────────────────────────────────
1781
1782/// Create the destination shard directory if this store has not seen it yet.
1783///
1784/// A newly created directory entry is only durable once its parent is flushed; without
1785/// that a crash could take the directory and the chunk inside it together.
1786fn ensure_shard_dir(
1787 chunks_dir: &Path,
1788 dir: &Path,
1789 shard: usize,
1790 present: &parking_lot::Mutex<[bool; SHARD_COUNT]>,
1791) -> Result<()> {
1792 if present.lock().get(shard).copied().unwrap_or(false) {
1793 return Ok(());
1794 }
1795 std::fs::create_dir_all(dir).map_err(|e| {
1796 Error::Storage(format!(
1797 "Failed to create shard directory {}: {e}",
1798 dir.display()
1799 ))
1800 })?;
1801 // Load-bearing, like the flush that publishes a chunk into this directory. Until the
1802 // parent is flushed the shard's own entry can be lost, and losing it loses every chunk
1803 // inside it. Reporting the shard present anyway would let the very first chunk written
1804 // into it count as durably stored.
1805 fsync_dir(chunks_dir).map_err(|e| {
1806 Error::Storage(format!(
1807 "Created shard directory {} but could not flush {}: {e}. Not marking the shard \
1808 usable, because a directory that is not durable cannot hold a chunk that is.",
1809 dir.display(),
1810 chunks_dir.display()
1811 ))
1812 })?;
1813 if let Some(slot) = present.lock().get_mut(shard) {
1814 *slot = true;
1815 }
1816 Ok(())
1817}
1818
1819/// Shard directory index for an address: its last byte.
1820fn shard_index(address: &XorName) -> usize {
1821 address.last().copied().unwrap_or(0) as usize
1822}
1823
1824/// Shard directory name for an address: the last two characters of its hex form.
1825fn shard_name(address: &XorName) -> String {
1826 format!("{:02x}", shard_index(address))
1827}
1828
1829/// True for a string of hex digits in either case.
1830fn is_hex_any_case(s: &str) -> bool {
1831 !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit())
1832}
1833
1834/// Move an entry aside under a name that can never be read as a chunk.
1835fn quarantine_entry(path: &Path) {
1836 let aside = path.with_extension("not-a-chunk");
1837 match std::fs::rename(path, &aside) {
1838 Ok(()) => warn!(
1839 "Chunk store: moved {} aside to {}; a name that differs from a chunk name only \
1840 by case collides with it on Windows and macOS",
1841 path.display(),
1842 aside.display()
1843 ),
1844 Err(e) => warn!(
1845 "Chunk store: {} collides with a chunk name by case folding and could not be \
1846 moved aside: {e}. Rename or delete it.",
1847 path.display()
1848 ),
1849 }
1850}
1851
1852/// True for a string of lowercase hex digits only.
1853fn is_lower_hex(s: &str) -> bool {
1854 !s.is_empty() && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
1855}
1856
1857/// Decode a filename back into the address it names, or `None` if it is not one.
1858///
1859/// Rejects uppercase deliberately. On a case-folding filesystem (NTFS, default APFS)
1860/// accepting both cases would let one file answer to two index entries.
1861fn decode_chunk_name(name: &str) -> Option<XorName> {
1862 if name.len() != CHUNK_NAME_LEN || !is_lower_hex(name) {
1863 return None;
1864 }
1865 let bytes = hex::decode(name).ok()?;
1866 XorName::try_from(bytes.as_slice()).ok()
1867}
1868
1869/// Flush a directory and report whether it worked, for callers outside this module.
1870///
1871/// For the one caller whose next step is destructive: retirement moves the legacy
1872/// environment aside and then deletes it under its new name, so if the rename has not
1873/// reached the disk when the delete lands, a power loss brings the environment back under
1874/// its old name with its contents gone.
1875///
1876/// # Errors
1877///
1878/// Returns the underlying I/O error. Off Unix there is no way to flush a directory through
1879/// the standard library, so this reports success without being able to promise anything.
1880pub fn fsync_path(path: &Path) -> std::io::Result<()> {
1881 fsync_dir(path)
1882}
1883
1884/// Flush a directory so a rename or creation inside it survives power loss.
1885///
1886/// Best effort by design. Linux and XFS require it, macOS accepts it with undocumented
1887/// effect, and Windows offers no way to do it at all through the standard library. The
1888/// content is content-addressed and re-replicable, so a lost directory entry costs a
1889/// refetch rather than data. Pretending otherwise in the code would be dishonest.
1890#[cfg(unix)]
1891fn fsync_dir_best_effort(path: &Path) {
1892 if let Err(e) = fsync_dir(path) {
1893 debug!("Directory flush of {} failed: {e}", path.display());
1894 }
1895}
1896
1897/// Flush a directory, reporting whether it worked.
1898///
1899/// Used where the answer is load-bearing: a chunk copied out of the legacy store is only
1900/// durable once its directory entry is, and that copy is what permits the legacy store to
1901/// be deleted.
1902#[cfg(unix)]
1903fn fsync_dir(path: &Path) -> std::io::Result<()> {
1904 File::open(path)?.sync_all()
1905}
1906
1907/// Off Unix there is no way to flush a directory through the standard library, so this
1908/// reports success without being able to promise anything.
1909///
1910/// That is why the publish path off Unix does not use a rename at all: it creates the
1911/// chunk under its final name and flushes the file, which Microsoft documents as flushing
1912/// the creation metadata with it. Directory creation has no equivalent, so the guarantee
1913/// there rests on the pre-retirement pass, which re-reads every chunk before the legacy
1914/// store is deleted, and on the operator gate that keeps retirement off a platform until
1915/// forced power loss has been shown to hold old-or-new on it.
1916///
1917/// Returns a `Result` so the callers that must handle a flush failure on Unix read the
1918/// same on every platform.
1919#[cfg(not(unix))]
1920#[allow(clippy::unnecessary_wraps)]
1921fn fsync_dir(_path: &Path) -> std::io::Result<()> {
1922 Ok(())
1923}
1924
1925/// No-op on platforms with no way to flush a directory handle.
1926#[cfg(not(unix))]
1927fn fsync_dir_best_effort(_path: &Path) {}
1928
1929/// Warn if the deepest chunk path this store can produce is close to `MAX_PATH`.
1930#[cfg(windows)]
1931fn check_path_budget(chunks_dir: &Path) {
1932 // Measured absolute, because that is what the filesystem sees. A relative root is the
1933 // case that still fails hard at MAX_PATH, since the standard library's long-path
1934 // handling only applies to paths it resolves as absolute.
1935 let absolute = if chunks_dir.is_absolute() {
1936 chunks_dir.to_path_buf()
1937 } else {
1938 std::env::current_dir()
1939 .map_or_else(|_| chunks_dir.to_path_buf(), |cwd| cwd.join(chunks_dir))
1940 };
1941 // `{chunks_dir}\{xy}\{64 hex}` — two separators, two shard characters, 64 name
1942 // characters.
1943 let deepest = absolute.as_os_str().len() + 1 + 2 + 1 + CHUNK_NAME_LEN;
1944 if deepest > WINDOWS_PATH_WARN_LEN {
1945 warn!(
1946 "Chunk file paths will be {deepest} characters, close to the {} character \
1947 Windows limit. Move the node root closer to the drive letter if writes start \
1948 failing.",
1949 WINDOWS_PATH_WARN_LEN
1950 );
1951 }
1952}
1953
1954/// No-op where path length is not a practical constraint.
1955#[cfg(not(windows))]
1956fn check_path_budget(_chunks_dir: &Path) {}
1957
1958/// Write `bytes` to `path` durably, for small metadata files outside the shard tree.
1959///
1960/// # Errors
1961///
1962/// Returns [`Error::Storage`] if the file cannot be written or published.
1963pub fn write_file_durably(path: &Path, bytes: &[u8]) -> Result<()> {
1964 write_file_atomic(path, bytes)
1965}
1966
1967/// Write `bytes` to `path` so a reader sees either the old content or the new.
1968/// Is this the exact name [`write_file_atomic`] gives its temporaries?
1969///
1970/// `.tmp.<pid>.<8 hex>.marker`, with both middle parts checked. Matching on the prefix and
1971/// suffix alone would also take `.tmp.operator-notes.marker`, and this runs over a
1972/// directory holding a node's data, so what it removes is not a place to be approximate.
1973fn is_marker_temp_name(name: &str) -> bool {
1974 let Some(rest) = name.strip_prefix(TEMP_PREFIX) else {
1975 return false;
1976 };
1977 let Some(rest) = rest.strip_suffix(".marker") else {
1978 return false;
1979 };
1980 let mut parts = rest.split('.');
1981 let (Some(pid), Some(nonce), None) = (parts.next(), parts.next(), parts.next()) else {
1982 return false;
1983 };
1984 !pid.is_empty()
1985 && pid.bytes().all(|b| b.is_ascii_digit())
1986 && nonce.len() == 8
1987 && nonce.bytes().all(|b| b.is_ascii_hexdigit())
1988}
1989
1990/// Remove marker temporaries a previous run left beside `path`.
1991///
1992/// [`write_file_atomic`] writes its temporary next to its target. For the layout marker
1993/// that is inside `chunks/`, which the startup scan sweeps; for the migration marker it is
1994/// the node root, which nothing sweeps, so a crash between the write and the rename leaves
1995/// one there for the life of the node. Each is a few hundred bytes, so this is inodes
1996/// rather than capacity, but nothing else was ever going to remove them.
1997///
1998/// Only the exact shape this module writes, and only files: a name has to carry the temp
1999/// prefix and the marker suffix. Anything broader would be this function deciding what
2000/// else in a node's root directory is rubbish, which is not its business.
2001///
2002/// Best effort throughout. Failing to tidy up is not a reason to refuse to start, and the
2003/// caller takes the store lock before this runs, so there is no other process whose live
2004/// temporary this could take.
2005pub(crate) fn sweep_marker_temps(dir: &Path) {
2006 let Ok(entries) = std::fs::read_dir(dir) else {
2007 return;
2008 };
2009 for entry in entries.flatten() {
2010 let name = entry.file_name();
2011 let Some(name) = name.to_str() else {
2012 continue;
2013 };
2014 if !is_marker_temp_name(name) {
2015 continue;
2016 }
2017 if !entry.file_type().is_ok_and(|kind| kind.is_file()) {
2018 continue;
2019 }
2020 match std::fs::remove_file(entry.path()) {
2021 Ok(()) => debug!(
2022 "Swept a leftover marker temporary {}",
2023 entry.path().display()
2024 ),
2025 Err(e) => debug!("Could not sweep {}: {e}", entry.path().display()),
2026 }
2027 }
2028}
2029
2030fn write_file_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
2031 let Some(dir) = path.parent() else {
2032 return Err(Error::Storage(format!(
2033 "Refusing to write {} — it has no parent directory",
2034 path.display()
2035 )));
2036 };
2037 let temp = dir.join(format!(
2038 "{TEMP_PREFIX}{}.{:08x}.marker",
2039 std::process::id(),
2040 rand::random::<u32>()
2041 ));
2042 write_temp(&temp, bytes)?;
2043 // Through the retry, because these small files (the layout marker, the migration
2044 // state) are rewritten while the node runs, and on Windows a scanner holding a handle
2045 // for a few milliseconds turns an ordinary rewrite into a hard failure.
2046 rename_with_retry(&temp, path).map_err(|e| {
2047 let _ = std::fs::remove_file(&temp);
2048 Error::Storage(format!("Failed to publish {}: {e}", path.display()))
2049 })?;
2050 fsync_dir_best_effort(dir);
2051 Ok(())
2052}
2053
2054/// Read the layout marker, writing the current one if the store is new.
2055fn read_or_write_layout(chunks_dir: &Path) -> Result<StoreLayout> {
2056 let path = chunks_dir.join(LAYOUT_FILE_NAME);
2057 match read_small_file(&path) {
2058 Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| {
2059 Error::Storage(format!(
2060 "Chunk store layout marker {} is unreadable: {e}. Refusing to open rather \
2061 than guess the layout.",
2062 path.display()
2063 ))
2064 }),
2065 Err(e) if e.kind() == ErrorKind::NotFound => {
2066 if store_has_entries(chunks_dir) {
2067 warn!(
2068 "Chunk store at {} has data but no layout marker. Adopting it under \
2069 the current scheme, which is the only one this build implements. If \
2070 it was written by a build with a different layout its chunks will \
2071 appear to be missing.",
2072 chunks_dir.display()
2073 );
2074 }
2075 let layout = StoreLayout::default();
2076 let bytes = serde_json::to_vec_pretty(&layout)
2077 .map_err(|e| Error::Storage(format!("Failed to encode chunk store layout: {e}")))?;
2078 write_file_atomic(&path, &bytes)?;
2079 debug!("Wrote chunk store layout marker to {}", path.display());
2080 Ok(layout)
2081 }
2082 Err(e) => Err(Error::Storage(format!(
2083 "Failed to read chunk store layout marker {}: {e}",
2084 path.display()
2085 ))),
2086 }
2087}
2088
2089/// Whether the store directory already holds at least one shard.
2090fn store_has_entries(chunks_dir: &Path) -> bool {
2091 let Ok(entries) = std::fs::read_dir(chunks_dir) else {
2092 return false;
2093 };
2094 entries.filter_map(std::result::Result::ok).any(|e| {
2095 e.file_name()
2096 .to_str()
2097 .is_some_and(|n| n.len() == 2 && is_lower_hex(n))
2098 })
2099}
2100
2101/// Largest a metadata marker may be before it is treated as corrupt.
2102const MAX_MARKER_BYTES: u64 = 64 * 1024;
2103
2104/// Read a small metadata file, refusing an implausibly large one.
2105///
2106/// The chunk path is bounded for exactly this reason; the markers live in the same data
2107/// directory and deserve the same ceiling.
2108///
2109/// # Errors
2110///
2111/// Returns an I/O error, including `NotFound`, so callers can distinguish "no marker yet".
2112pub fn read_small_file(path: &Path) -> std::io::Result<Vec<u8>> {
2113 let file = File::open(path)?;
2114 let mut bytes = Vec::new();
2115 let read = file.take(MAX_MARKER_BYTES + 1).read_to_end(&mut bytes)?;
2116 if read as u64 > MAX_MARKER_BYTES {
2117 return Err(std::io::Error::other(format!(
2118 "{} is larger than the {MAX_MARKER_BYTES} byte limit for a marker file",
2119 path.display()
2120 )));
2121 }
2122 Ok(bytes)
2123}
2124
2125/// Take the store lock, or refuse to open the store.
2126///
2127/// Both failures are refusals, deliberately. Unlike LMDB, which was genuinely
2128/// multi-process safe, two of these stores on one directory keep independent in-memory
2129/// indices, independent views of what is in flight, and independent opinions about
2130/// whether the legacy environment may be deleted: both would report the same write as
2131/// new and each would keep serving keys the other had deleted. A node that cannot create
2132/// the lock file has no way to know it is alone, and this is the one migration where
2133/// being wrong about that destroys data.
2134///
2135/// The lock is an [`Arc`] so the work that relies on it can hold a lease. The startup
2136/// scan sweeps interrupted writes on the strength of being alone in the directory, and it
2137/// runs on a thread that outlives the future that started it.
2138///
2139/// # Errors
2140///
2141/// Returns [`Error::Storage`] when another process owns the directory, or when the lock
2142/// file cannot be created.
2143fn acquire_store_lock(chunks_dir: &Path) -> Result<Arc<File>> {
2144 let path = chunks_dir.join(LOCK_FILE_NAME);
2145 let file = match OpenOptions::new()
2146 .write(true)
2147 .create(true)
2148 .truncate(false)
2149 .open(&path)
2150 {
2151 Ok(f) => f,
2152 // Not a warning and carry on. Without this lock two processes can open the same
2153 // directory, each with its own index, its own view of what is in flight, and its
2154 // own opinion about whether the legacy environment may be deleted. A node that
2155 // cannot take it has no way to know it is alone, and this is the one migration
2156 // where being wrong about that destroys data.
2157 Err(e) => {
2158 return Err(Error::Storage(format!(
2159 "Could not create the chunk store lock {}: {e}. Refusing to start: \
2160 without it this node cannot tell whether another is using the same data \
2161 directory. Fix the permissions on that path, or remove a stale lock file \
2162 left by a different user.",
2163 path.display()
2164 )))
2165 }
2166 };
2167 match file.try_lock_exclusive() {
2168 Ok(()) => Ok(Arc::new(file)),
2169 Err(e) => Err(Error::Storage(format!(
2170 "Another process already has the chunk store at {} open ({e}). Two nodes \
2171 cannot share one data directory: each keeps its own index and they would \
2172 disagree about what is stored. Stop the other node first.",
2173 chunks_dir.display()
2174 ))),
2175 }
2176}
2177
2178/// What a startup scan found.
2179struct ScanResult {
2180 /// Every published address, ascending.
2181 keys: Vec<XorName>,
2182 /// Which shard directories already exist.
2183 shards_present: [bool; SHARD_COUNT],
2184 /// Orphaned temp files removed.
2185 swept_temps: usize,
2186 /// Entries that were neither a chunk nor one of ours.
2187 skipped: usize,
2188}
2189
2190/// Rebuild the key set from directory entries.
2191///
2192/// Reads names only. A `stat` per entry costs about ten times the enumeration on Linux
2193/// and macOS and fifty to sixty times on Windows, and buys nothing: the filename is the
2194/// key, and the content is verified on read.
2195fn scan_store(chunks_dir: &Path) -> Result<ScanResult> {
2196 let mut result = ScanResult {
2197 keys: Vec::new(),
2198 shards_present: [false; SHARD_COUNT],
2199 swept_temps: 0,
2200 skipped: 0,
2201 };
2202
2203 let top = std::fs::read_dir(chunks_dir).map_err(|e| {
2204 Error::Storage(format!(
2205 "Failed to enumerate chunk store {}: {e}",
2206 chunks_dir.display()
2207 ))
2208 })?;
2209
2210 for entry in top {
2211 let entry = entry.map_err(|e| {
2212 Error::Storage(format!(
2213 "Failed to read an entry of {}: {e}",
2214 chunks_dir.display()
2215 ))
2216 })?;
2217 let name = entry.file_name();
2218 let Some(name) = name.to_str() else {
2219 result.skipped = result.skipped.saturating_add(1);
2220 continue;
2221 };
2222 if name == LAYOUT_FILE_NAME || name == LOCK_FILE_NAME {
2223 continue;
2224 }
2225 if name.starts_with(TEMP_PREFIX) {
2226 if sweep_temp(&entry.path()) {
2227 result.swept_temps = result.swept_temps.saturating_add(1);
2228 }
2229 continue;
2230 }
2231 if name.len() != 2 || !is_lower_hex(name) {
2232 warn!(
2233 "Chunk store: ignoring unexpected entry {name} in {}",
2234 chunks_dir.display()
2235 );
2236 result.skipped = result.skipped.saturating_add(1);
2237 continue;
2238 }
2239 let Ok(shard) = u8::from_str_radix(name, 16) else {
2240 result.skipped = result.skipped.saturating_add(1);
2241 continue;
2242 };
2243 // `shards_present` is set inside `scan_shard`, on success only. Setting it from
2244 // the name alone would make a stray regular file called `ab` look like a shard
2245 // that already exists, and every write to that shard would then fail with a
2246 // misleading error until the node was restarted.
2247 scan_shard(&entry.path(), shard, &mut result)?;
2248 }
2249
2250 result.keys.sort_unstable();
2251 result.keys.dedup();
2252 Ok(result)
2253}
2254
2255/// Scan one shard directory into `result`.
2256fn scan_shard(dir: &Path, shard: u8, result: &mut ScanResult) -> Result<()> {
2257 let entries = match std::fs::read_dir(dir) {
2258 Ok(e) => e,
2259 // A stray file named like a shard, or a directory removed between the two reads.
2260 // Neither is fatal, and neither marks the shard as present.
2261 Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) => {
2262 warn!(
2263 "Chunk store: {} is not a shard directory ({e}); ignoring it",
2264 dir.display()
2265 );
2266 result.skipped = result.skipped.saturating_add(1);
2267 return Ok(());
2268 }
2269 // Anything else is a real fault: a permission problem, exhausted descriptors, or
2270 // failing hardware. Opening with a shard's worth of keys silently missing would
2271 // make the node under-claim in its published commitment and stop serving chunks
2272 // it still holds and is answerable for, so refuse to open at all.
2273 Err(e) => {
2274 return Err(Error::Storage(format!(
2275 "Failed to enumerate shard {}: {e}. Refusing to open with an incomplete \
2276 key set.",
2277 dir.display()
2278 )))
2279 }
2280 };
2281 if let Some(slot) = result.shards_present.get_mut(shard as usize) {
2282 *slot = true;
2283 }
2284
2285 for entry in entries {
2286 let entry =
2287 entry.map_err(|e| Error::Storage(format!("Failed to read {}: {e}", dir.display())))?;
2288 let name = entry.file_name();
2289 let Some(name) = name.to_str() else {
2290 result.skipped = result.skipped.saturating_add(1);
2291 continue;
2292 };
2293 if name.starts_with(TEMP_PREFIX) {
2294 if sweep_temp(&entry.path()) {
2295 result.swept_temps = result.swept_temps.saturating_add(1);
2296 }
2297 continue;
2298 }
2299 let Some(key) = decode_chunk_name(name) else {
2300 if name.len() == CHUNK_NAME_LEN && is_hex_any_case(name) {
2301 // A case-folded twin of a real chunk name. On NTFS and default APFS the
2302 // existence check in the write path folds onto it, so a paid write would
2303 // be answered "already stored" and its bytes dropped. Move it aside.
2304 quarantine_entry(&entry.path());
2305 } else {
2306 warn!(
2307 "Chunk store: ignoring non-chunk entry {name} in {}",
2308 dir.display()
2309 );
2310 }
2311 result.skipped = result.skipped.saturating_add(1);
2312 continue;
2313 };
2314 // `file_type` comes from the directory entry itself on Linux and macOS and from
2315 // the enumeration on Windows, so this is not the per-entry `stat` the scan
2316 // deliberately avoids. A pipe, socket, device or directory wearing a chunk name
2317 // must never enter the index: nothing downstream can read it, and it would sit in
2318 // the published commitment forever.
2319 match entry.file_type() {
2320 Ok(kind) if kind.is_file() => {}
2321 Ok(_) => {
2322 warn!(
2323 "Chunk store: {name} in {} is not a regular file; ignoring it",
2324 dir.display()
2325 );
2326 result.skipped = result.skipped.saturating_add(1);
2327 continue;
2328 }
2329 // Not the same as knowing it is not a file. Treating an unanswered question
2330 // as a no would drop a real chunk from the index and from the commitment
2331 // while its bytes sit on disk, and the node would not serve it again until
2332 // some later restart happened to succeed. Fail the scan instead: an index
2333 // that is missing keys must never be published as this node's key set.
2334 Err(e) => {
2335 return Err(Error::Storage(format!(
2336 "Could not tell what {name} in {} is: {e}. Refusing to publish an \
2337 index that may be missing chunks.",
2338 dir.display()
2339 )));
2340 }
2341 }
2342 // A file in the wrong shard is unreachable through `chunk_path`, so indexing it
2343 // would make the index claim a key the read path cannot find.
2344 if shard_index(&key) != shard as usize {
2345 warn!(
2346 "Chunk store: {name} is filed under shard {shard:02x} but belongs in {:02x}; \
2347 ignoring it. Move it or delete it.",
2348 shard_index(&key)
2349 );
2350 result.skipped = result.skipped.saturating_add(1);
2351 continue;
2352 }
2353 result.keys.push(key);
2354 }
2355 Ok(())
2356}
2357
2358/// Remove one orphaned temp file. Returns whether it went.
2359///
2360/// Always removed. The scan that calls this runs only after the store lock has been taken,
2361/// so by then any temp file is an interrupted write of a previous run and there is no other
2362/// process that could be writing it. This used to describe a second, gentler mode for the
2363/// unlocked case; there was never any such branch and there is no caller that would need
2364/// one.
2365fn sweep_temp(path: &Path) -> bool {
2366 match std::fs::remove_file(path) {
2367 Ok(()) => {
2368 debug!("Removed orphaned temporary file {}", path.display());
2369 true
2370 }
2371 Err(e) => {
2372 debug!("Could not remove {}: {e}", path.display());
2373 false
2374 }
2375 }
2376}
2377
2378/// Open a chunk file, refusing anything that is not a regular file.
2379///
2380/// `Ok(None)` means the file is not there. A named pipe wearing a valid chunk name would
2381/// otherwise block the opening thread forever: `open` on a FIFO with no writer does not
2382/// return, and enough of them would exhaust the blocking pool and stall every file and
2383/// database operation in the process. `O_NOFOLLOW` refuses a symlink for the same reason,
2384/// and both are checked on the handle rather than the path, so nothing can be swapped
2385/// underneath between the check and the open.
2386fn open_regular(path: &Path) -> Result<Option<File>> {
2387 #[cfg(unix)]
2388 let opened = {
2389 use std::os::unix::fs::OpenOptionsExt;
2390 OpenOptions::new()
2391 .read(true)
2392 .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW)
2393 .open(path)
2394 };
2395 #[cfg(not(unix))]
2396 let opened = OpenOptions::new().read(true).open(path);
2397
2398 let file = match opened {
2399 Ok(f) => f,
2400 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
2401 Err(e) => {
2402 return Err(Error::Storage(format!(
2403 "Failed to open chunk file {}: {e}",
2404 path.display()
2405 )))
2406 }
2407 };
2408 let is_regular = file.metadata().is_ok_and(|m| m.file_type().is_file());
2409 if !is_regular {
2410 return Err(Error::Storage(format!(
2411 "{} is not a regular file; refusing to read it as a chunk",
2412 path.display()
2413 )));
2414 }
2415 Ok(Some(file))
2416}
2417
2418/// Read a chunk file, refusing anything larger than a chunk can legitimately be.
2419///
2420/// A corrupt, sparse, or locally planted file wearing a valid 64-hex name would
2421/// otherwise be read straight into memory, so a single bad entry could exhaust the node
2422/// during an ordinary GET or an audit response.
2423fn read_bounded(file: File, path: &Path) -> Result<Vec<u8>> {
2424 let ceiling = MAX_CHUNK_SIZE as u64;
2425 let mut buf = Vec::new();
2426 let read = file.take(ceiling + 1).read_to_end(&mut buf).map_err(|e| {
2427 Error::Storage(format!("Failed to read chunk file {}: {e}", path.display()))
2428 })?;
2429 if read as u64 > ceiling {
2430 return Err(Error::Storage(format!(
2431 "Chunk file {} is larger than the {ceiling} byte maximum; refusing to read it",
2432 path.display()
2433 )));
2434 }
2435 Ok(buf)
2436}
2437
2438/// Whether a Windows error is one a scanner or indexer holding a handle would produce.
2439///
2440/// `ERROR_ACCESS_DENIED`, `ERROR_SHARING_VIOLATION`, `ERROR_LOCK_VIOLATION`. Every other
2441/// failure is deterministic and retrying it only burns a blocking thread.
2442fn is_windows_sharing_violation(e: &std::io::Error) -> bool {
2443 matches!(e.raw_os_error(), Some(5 | 32 | 33))
2444}
2445
2446/// Publish `temp_path` as `final_path`, retrying a transient sharing violation.
2447///
2448/// On Windows an antivirus scanner or the search indexer can hold a handle to either
2449/// file for a few milliseconds after it is created, and `MoveFileEx` fails outright
2450/// rather than queueing. Retrying a bounded number of times turns that from a failed
2451/// write into a short pause. Every other error returns immediately.
2452fn rename_with_retry(temp_path: &Path, final_path: &Path) -> std::io::Result<()> {
2453 let mut last = match std::fs::rename(temp_path, final_path) {
2454 Ok(()) => return Ok(()),
2455 Err(e) => e,
2456 };
2457 if !cfg!(windows) || !is_windows_sharing_violation(&last) {
2458 return Err(last);
2459 }
2460 for attempt in 1..=RENAME_RETRY_ATTEMPTS {
2461 std::thread::sleep(RENAME_RETRY_BACKOFF * attempt);
2462 match std::fs::rename(temp_path, final_path) {
2463 Ok(()) => return Ok(()),
2464 Err(e) => last = e,
2465 }
2466 }
2467 Err(last)
2468}
2469
2470/// Write `payload` and publish it as `final_path`, replacing whatever is there.
2471///
2472/// Success here means the bytes are durable, not merely written. The repair path this
2473/// serves runs during the pre-retirement pass, where a chunk that fails to match its
2474/// address is rewritten from the legacy store and the legacy store is then deleted. A
2475/// replacement that a power loss can undo would leave that chunk with the wrong bytes and
2476/// no other copy.
2477fn write_and_replace(
2478 temp_path: &Path,
2479 final_path: &Path,
2480 payload: &[u8],
2481 shard: &Path,
2482) -> Result<()> {
2483 // Unix: an intra-directory rename is atomic, so a reader sees the old content or the
2484 // new one and never an absence, and the directory flush is what makes it durable.
2485 #[cfg(unix)]
2486 {
2487 write_temp(temp_path, payload)?;
2488 if let Err(e) = rename_with_retry(temp_path, final_path) {
2489 let _ = std::fs::remove_file(temp_path);
2490 return Err(Error::Storage(format!(
2491 "Failed to replace chunk {}: {e}",
2492 final_path.display()
2493 )));
2494 }
2495 fsync_dir(shard).map_err(|e| {
2496 Error::Storage(format!(
2497 "Replaced {} but could not flush {}: {e}. Not reporting the repair as \
2498 done, because a rewrite that is not durable must not authorise deleting \
2499 the copy it was rewritten from.",
2500 final_path.display(),
2501 shard.display()
2502 ))
2503 })?;
2504 Ok(())
2505 }
2506 // Everywhere else, Windows included: there is no way to flush a directory through the
2507 // standard library, so a rename cannot be shown to be durable at return. Overwriting
2508 // the existing file changes no directory entry at all, and `sync_all` (FlushFileBuffers
2509 // on Windows) is documented to flush the file's data, so a successful return is
2510 // durable under a documented contract.
2511 //
2512 // The cost is that this is not atomic: a crash part-way leaves the file holding a mix
2513 // of old and new bytes. That is safe here and only here, because the only caller that
2514 // matters runs before the legacy store is deleted, and a crash means no report was
2515 // produced and nothing was deleted. The next start re-reads the file, sees it does not
2516 // match its address, and repairs it again from the store that is still there.
2517 #[cfg(not(unix))]
2518 {
2519 let _ = temp_path;
2520 let _ = shard;
2521 let mut file = OpenOptions::new()
2522 .write(true)
2523 .truncate(true)
2524 .open(final_path)
2525 .map_err(|e| {
2526 Error::Storage(format!(
2527 "Failed to open {} for replacement: {e}",
2528 final_path.display()
2529 ))
2530 })?;
2531 file.write_all(payload).map_err(|e| {
2532 Error::Storage(format!("Failed to rewrite {}: {e}", final_path.display()))
2533 })?;
2534 file.sync_all().map_err(|e| {
2535 Error::Storage(format!(
2536 "Rewrote {} but could not flush it: {e}. Not reporting the repair as \
2537 done, because a rewrite that is not durable must not authorise deleting \
2538 the copy it was rewritten from.",
2539 final_path.display()
2540 ))
2541 })?;
2542 Ok(())
2543 }
2544}
2545
2546/// Create `temp_path`, write `payload` into it, and flush it.
2547///
2548/// Flushed before any rename. On ext4 `auto_da_alloc` only orders the data before the
2549/// rename's own commit; it does not make the data durable, and btrfs has been observed
2550/// reordering. A name must never become visible on bytes that are not on the platter.
2551fn write_temp(temp_path: &Path, payload: &[u8]) -> Result<()> {
2552 let mut f = OpenOptions::new()
2553 .write(true)
2554 .create_new(true)
2555 .open(temp_path)
2556 .map_err(|e| {
2557 Error::Storage(format!(
2558 "Failed to create temporary file {}: {e}",
2559 temp_path.display()
2560 ))
2561 })?;
2562 if let Err(e) = f.write_all(payload) {
2563 let _ = std::fs::remove_file(temp_path);
2564 return Err(Error::Storage(format!(
2565 "Failed to write {}: {e}",
2566 temp_path.display()
2567 )));
2568 }
2569 if let Err(e) = f.sync_all() {
2570 let _ = std::fs::remove_file(temp_path);
2571 return Err(Error::Storage(format!(
2572 "Failed to flush {}: {e}",
2573 temp_path.display()
2574 )));
2575 }
2576 Ok(())
2577}
2578
2579/// Write `payload` and publish it under `final_path`.
2580///
2581/// The temp lives in the destination directory, so the publish is an intra-directory
2582/// rename: atomic on every filesystem we support, and needing only that one directory
2583/// Put `payload` on disk as `final_path`, durably.
2584///
2585/// Returns [`PutOutcome::Duplicate`] when the name is already taken. The name is a hash
2586/// of the content, so that is not treated as proof the bytes are right: the caller
2587/// re-reads and verifies them.
2588#[cfg(unix)]
2589fn publish(
2590 temp_path: &Path,
2591 final_path: &Path,
2592 payload: &[u8],
2593 shard: &Path,
2594) -> std::result::Result<PutOutcome, PublishFailed> {
2595 // On Unix nothing is ever created under the final name by a failing path: the bytes go
2596 // to a temporary and only a successful rename gives them the real name. So every
2597 // failure here leaves the name as it found it.
2598 publish_via_rename(temp_path, final_path, payload, shard)
2599 .map_err(PublishFailed::nothing_written)
2600}
2601
2602/// Put `payload` on disk as `final_path`, durably. See [`publish_in_place`] for why this
2603/// takes a different route off Unix.
2604#[cfg(not(unix))]
2605fn publish(
2606 temp_path: &Path,
2607 final_path: &Path,
2608 payload: &[u8],
2609 shard: &Path,
2610) -> std::result::Result<PutOutcome, PublishFailed> {
2611 let _ = temp_path;
2612 let _ = shard;
2613 publish_in_place(final_path, payload)
2614}
2615
2616/// Create the chunk under its final name and flush it. Everywhere but Unix.
2617///
2618/// There is no way to flush a directory through the standard library, and Microsoft does
2619/// not document `MoveFileEx` as durable at return unless it is called with
2620/// `MOVEFILE_WRITE_THROUGH`, which std does not use. So off Unix a rename cannot be
2621/// relied on to have reached the disk before the legacy store is deleted.
2622///
2623/// Creating the file under its final name sidesteps the rename entirely. Microsoft
2624/// documents that creation metadata is cached and that `FlushFileBuffers`, which
2625/// `sync_all` calls on Windows, is the way to flush it. So a successful create, write and
2626/// flush is a durable publication under a documented contract, with no directory flush
2627/// and no rename involved.
2628///
2629/// The cost is that a crash mid-write leaves a partial file wearing a real chunk name.
2630/// That is why a duplicate re-reads and verifies rather than trusting the name, and why
2631/// the pre-retirement pass re-hashes everything before anything is deleted.
2632#[cfg(not(unix))]
2633fn publish_in_place(
2634 final_path: &Path,
2635 payload: &[u8],
2636) -> std::result::Result<PutOutcome, PublishFailed> {
2637 // Test-only, and here rather than after the write so that it means the same thing on
2638 // both platforms: the file half of a dual write has not happened yet. On Unix the
2639 // equivalent point is the temporary file written and the rename not yet made, which is
2640 // also before the chunk's name exists on disk. Stopping after the write instead would
2641 // put the file under its real name already, so a crash there is not between the two
2642 // halves at all, and it could not demonstrate anything about the missing flush either:
2643 // killing a process does not empty the page cache, so the bytes are still there to be
2644 // read. Only losing power loses them, which no test that kills a process can stage.
2645 #[cfg(any(test, feature = "test-utils"))]
2646 halt_here_if_asked(HALT_BEFORE_PUBLISH, final_path);
2647 let mut file = match OpenOptions::new()
2648 .write(true)
2649 .create_new(true)
2650 .open(final_path)
2651 {
2652 Ok(f) => f,
2653 // Someone got there first. Immutable content under a content-addressed name, so
2654 // the caller verifies what is already there rather than assuming it is right.
2655 Err(e) if e.kind() == ErrorKind::AlreadyExists => return Ok(PutOutcome::Duplicate),
2656 Err(e) => {
2657 // Nothing was created, so nothing was spent.
2658 return Err(PublishFailed::nothing_written(Error::Storage(format!(
2659 "Failed to create chunk {}: {e}",
2660 final_path.display()
2661 ))));
2662 }
2663 };
2664 if let Err(e) = file.write_all(payload) {
2665 drop(file);
2666 // Taken back if it can be. Whether it could is what the caller needs: the file
2667 // was created by this call, so if it is still there the space is spent.
2668 let left_behind = std::fs::remove_file(final_path).is_err();
2669 return Err(PublishFailed {
2670 error: Error::Storage(format!("Failed to write {}: {e}", final_path.display())),
2671 left_behind,
2672 });
2673 }
2674 if let Err(e) = file.sync_all() {
2675 drop(file);
2676 // Taken back if it can be. Whether it could is what the caller needs: the file
2677 // was created by this call, so if it is still there the space is spent.
2678 let left_behind = std::fs::remove_file(final_path).is_err();
2679 return Err(PublishFailed {
2680 error: Error::Storage(format!("Failed to flush {}: {e}", final_path.display())),
2681 left_behind,
2682 });
2683 }
2684 Ok(PutOutcome::New)
2685}
2686
2687/// Write a temp beside the target and rename it into place. Unix only.
2688///
2689/// Places the bytes and nothing more. Making the name durable is
2690/// [`flush_publication`]'s job, kept separate so a caller can tell a publish that spent no
2691/// space from one that spent it and could not be reported.
2692#[cfg(unix)]
2693fn publish_via_rename(
2694 temp_path: &Path,
2695 final_path: &Path,
2696 payload: &[u8],
2697 _shard: &Path,
2698) -> Result<PutOutcome> {
2699 // Content is immutable and the name is its hash, so an existing file already holds
2700 // exactly these bytes. Skipping the write is both cheaper and safer than replacing
2701 // it: on Windows a rename over a file another thread has open fails outright.
2702 //
2703 // The caller flushes either way. A name that is already there is not proof it is
2704 // durable:
2705 // the write that put it there may have been this store's own previous attempt, whose
2706 // rename landed and whose directory flush then failed. That attempt returned an
2707 // error, so nothing was retired on the strength of it, but if this call reported a
2708 // durable duplicate without flushing, the retry would silently launder an unflushed
2709 // rename into a copy that authorises deleting the last other one.
2710 let outcome = if final_path.exists() {
2711 PutOutcome::Duplicate
2712 } else {
2713 write_temp(temp_path, payload)?;
2714 // Test-only: the one moment a complete chunk exists on disk under a name nothing
2715 // looks for. A crash test needs to die at a named point rather than wherever a
2716 // sleep in another process happened to land.
2717 #[cfg(any(test, feature = "test-utils"))]
2718 halt_here_if_asked(HALT_BEFORE_PUBLISH, temp_path);
2719 match rename_with_retry(temp_path, final_path) {
2720 Ok(()) => PutOutcome::New,
2721 Err(e) => {
2722 let _ = std::fs::remove_file(temp_path);
2723 // Another writer of the same address won the race, or the destination was
2724 // open. Either way the bytes are already published.
2725 if !final_path.exists() {
2726 return Err(Error::Storage(format!(
2727 "Failed to publish chunk {}: {e}",
2728 final_path.display()
2729 )));
2730 }
2731 PutOutcome::Duplicate
2732 }
2733 }
2734 };
2735
2736 Ok(outcome)
2737}
2738
2739/// A publish that failed, and whether it left its bytes on the disk.
2740///
2741/// The second half is the point. A failure before anything was created has spent nothing;
2742/// one that created the file and then could not remove it again has spent the space, and
2743/// whoever is accounting for free space has to know which happened. Only the code that did
2744/// the creating can say.
2745struct PublishFailed {
2746 error: Error,
2747 left_behind: bool,
2748}
2749
2750impl PublishFailed {
2751 /// A failure that created nothing.
2752 fn nothing_written(error: Error) -> Self {
2753 Self {
2754 error,
2755 left_behind: false,
2756 }
2757 }
2758}
2759
2760/// Make a publication durable by flushing the directory its name lives in.
2761///
2762/// Separate from placing the bytes, because the caller has to tell the two failures apart.
2763/// A publish that fails before the bytes land has spent nothing; one that fails here has
2764/// spent the space and must not be reported as stored, so whoever is accounting for free
2765/// space has to charge it while whoever is accounting for chunks must not count it.
2766///
2767/// NOT best effort. The directory flush is what makes the rename durable, and a copy
2768/// reported successful is what authorises deleting the only other copy. Swallowing the
2769/// failure would let a power loss discard the directory entry after the legacy store had
2770/// already been removed.
2771///
2772/// # Errors
2773///
2774/// Returns [`Error::Storage`] if the directory cannot be flushed.
2775#[cfg(unix)]
2776fn flush_publication(final_path: &Path, shard: &Path) -> Result<()> {
2777 fsync_dir(shard).map_err(|e| {
2778 Error::Storage(format!(
2779 "Published {} but could not flush {}: {e}. Not reporting this chunk as stored, \
2780 because a copy that is not durable must not authorise deleting another.",
2781 final_path.display(),
2782 shard.display()
2783 ))
2784 })
2785}
2786
2787/// Nothing to do off Unix, where the chunk is created under its final name and flushed
2788/// with `sync_all`, which is documented to carry its creation metadata with it, and where
2789/// there is no way to flush a directory at all.
2790#[cfg(not(unix))]
2791fn flush_publication(_final_path: &Path, _shard: &Path) -> Result<()> {
2792 Ok(())
2793}
2794
2795#[cfg(test)]
2796#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
2797mod tests {
2798 use super::*;
2799 use std::collections::HashSet;
2800
2801 /// A directory flush that fails must say so.
2802 ///
2803 /// The quiet version of this function is only used where the answer does not change
2804 /// what happens next. On the publish path it does.
2805 #[cfg(unix)]
2806 #[test]
2807 fn flushing_a_directory_that_is_not_there_reports_the_failure() {
2808 let dir = TempDir::new().expect("temp dir");
2809 assert!(fsync_dir(dir.path()).is_ok());
2810 assert!(fsync_dir(&dir.path().join("no-such-shard")).is_err());
2811 }
2812
2813 /// A chunk whose directory entry was never flushed is not reported as stored.
2814 ///
2815 /// This is the whole safety argument for retirement: the legacy store is deleted
2816 /// because every chunk was copied durably. A published file whose directory flush
2817 /// failed can vanish on power loss, so counting it as copied would lose data. The
2818 /// file staying on disk afterwards is fine, the next pass republishes it.
2819 #[cfg(unix)]
2820 #[test]
2821 fn a_publish_whose_directory_flush_fails_is_not_reported_as_stored() {
2822 let dir = TempDir::new().expect("temp dir");
2823 let temp_path = dir.path().join("chunk.tmp");
2824 let final_path = dir.path().join("chunk");
2825 let unflushable = dir.path().join("shard-that-does-not-exist");
2826
2827 // Asserted in two steps, not chained. Chaining them means a regression in placing
2828 // the bytes also produces an error, and the test passes without the flush ever
2829 // being reached: it would be checking that something went wrong rather than that
2830 // this went wrong.
2831 let placed = publish_via_rename(&temp_path, &final_path, b"payload", &unflushable);
2832 assert!(
2833 placed.is_ok(),
2834 "the bytes must be placed before this can be about the flush: {:?}",
2835 placed.err()
2836 );
2837 let outcome = flush_publication(&final_path, &unflushable);
2838
2839 assert!(
2840 outcome.is_err(),
2841 "an unflushed publication must not be reported as stored"
2842 );
2843 assert!(
2844 !temp_path.exists(),
2845 "the temp file must not be left behind either way"
2846 );
2847 }
2848
2849 use tempfile::TempDir;
2850
2851 /// Open a store on a fresh temp directory with the disk reserve disabled.
2852 async fn test_store() -> (FileStore, TempDir) {
2853 let dir = TempDir::new().expect("temp dir");
2854 let store = FileStore::new(FileStoreConfig {
2855 root_dir: dir.path().to_path_buf(),
2856 verify_on_read: true,
2857 disk_reserve: 0,
2858 })
2859 .await
2860 .expect("open store");
2861 (store, dir)
2862 }
2863
2864 /// Open a store on an existing directory, as a restart would.
2865 async fn reopen(dir: &TempDir) -> FileStore {
2866 FileStore::new(FileStoreConfig {
2867 root_dir: dir.path().to_path_buf(),
2868 verify_on_read: true,
2869 disk_reserve: 0,
2870 })
2871 .await
2872 .expect("reopen store")
2873 }
2874
2875 /// An ordinary read settles whether the node answers for a chunk.
2876 ///
2877 /// Not only the reads that were checking something. A read that failed means the
2878 /// chunk cannot be served, whoever asked; a read that worked means it can be. Deciding
2879 /// this anywhere else leaves a key stuck unadvertised after the fault has cleared, or
2880 /// advertised after it has not.
2881 #[cfg(unix)]
2882 #[tokio::test]
2883 async fn an_ordinary_read_decides_whether_the_node_answers_for_a_chunk() {
2884 use std::os::unix::fs::PermissionsExt;
2885
2886 let (store, dir) = test_store().await;
2887 let (addr, content) = addressed("read-decides");
2888 store.put(&addr, &content).await.expect("put");
2889 let path = store.chunk_path(&addr);
2890
2891 let mut perms = std::fs::metadata(&path).expect("meta").permissions();
2892 perms.set_mode(0o000);
2893 std::fs::set_permissions(&path, perms).expect("chmod");
2894
2895 assert!(store.get(&addr).await.is_err(), "the read must fail");
2896 assert!(
2897 !store.exists(&addr).expect("exists"),
2898 "and a plain read that failed must stop the node answering for it"
2899 );
2900
2901 let mut perms = std::fs::metadata(&path).expect("meta").permissions();
2902 perms.set_mode(0o600);
2903 std::fs::set_permissions(&path, perms).expect("chmod back");
2904
2905 assert_eq!(
2906 store.get(&addr).await.expect("get").expect("present"),
2907 content
2908 );
2909 assert!(
2910 store.exists(&addr).expect("exists"),
2911 "and a plain read that worked must start it answering again"
2912 );
2913 drop(dir);
2914 }
2915
2916 /// Two writes for one key: waiting means waiting for both.
2917 ///
2918 /// Cancellation releases the caller's lane while the blocking half survives, so a
2919 /// second write for the same key can start behind the first. If the registry only
2920 /// recorded that *something* was writing, whichever finished first would clear it and
2921 /// a delete would be told the key was free while the other was still queued, then be
2922 /// undone by it.
2923 #[tokio::test]
2924 async fn waiting_for_a_key_waits_for_every_write_of_it() {
2925 let (store, dir) = test_store().await;
2926 let store = Arc::new(store);
2927 let (addr, content) = addressed("two-writers");
2928
2929 // Two registrations, as two overlapping writes would make.
2930 let first = store.begin_write(&addr);
2931 let second = store.begin_write(&addr);
2932
2933 let waiting = {
2934 let store = Arc::clone(&store);
2935 tokio::spawn(async move { store.wait_for_write(&addr).await })
2936 };
2937 tokio::time::sleep(Duration::from_millis(50)).await;
2938 assert!(!waiting.is_finished());
2939
2940 // One finishes. The other has not, so the wait must continue.
2941 drop(first);
2942 tokio::time::sleep(Duration::from_millis(50)).await;
2943 assert!(
2944 !waiting.is_finished(),
2945 "one write finishing does not mean the key is free"
2946 );
2947
2948 drop(second);
2949 waiting
2950 .await
2951 .expect("the wait ends once both have finished");
2952
2953 // And the store is still usable afterwards.
2954 store.put(&addr, &content).await.expect("put");
2955 assert!(store.exists(&addr).expect("exists"));
2956 drop(dir);
2957 }
2958
2959 /// A chunk this store cannot read is kept but not claimed.
2960 ///
2961 /// Both halves matter. Deleting it, or dropping it from the index, is how a chunk ends
2962 /// up in neither this store's view nor the legacy one, which is what retirement
2963 /// destroys. Claiming it anyway puts the key in signed commitments and answers
2964 /// presence probes with a yes for a chunk the node cannot serve, and the audit that
2965 /// catches that still penalises.
2966 #[cfg(unix)]
2967 #[tokio::test]
2968 async fn a_chunk_that_cannot_be_read_is_kept_but_not_claimed() {
2969 use std::os::unix::fs::PermissionsExt;
2970
2971 let (store, dir) = test_store().await;
2972 let (addr, content) = addressed("unreadable-for-now");
2973 store.put(&addr, &content).await.expect("put");
2974 assert!(store.exists(&addr).expect("exists"));
2975
2976 let path = store.chunk_path(&addr);
2977 let mut perms = std::fs::metadata(&path).expect("meta").permissions();
2978 perms.set_mode(0o000);
2979 std::fs::set_permissions(&path, perms).expect("chmod");
2980
2981 // Offering the same bytes again must not be acknowledged, and must not replace
2982 // what is there on the strength of a read that did not happen.
2983 assert!(
2984 store.put(&addr, &content).await.is_err(),
2985 "an unreadable chunk must not be reported as stored"
2986 );
2987 assert!(path.exists(), "and the file must be left alone");
2988 assert!(
2989 !store.exists(&addr).expect("exists"),
2990 "but the node must stop claiming it"
2991 );
2992 assert!(!store.all_keys().await.expect("keys").contains(&addr));
2993
2994 // Readable again: the node answers for it once more.
2995 let mut perms = std::fs::metadata(&path).expect("meta").permissions();
2996 perms.set_mode(0o600);
2997 std::fs::set_permissions(&path, perms).expect("chmod back");
2998 assert!(!store.put(&addr, &content).await.expect("put again"));
2999 assert!(store.exists(&addr).expect("exists"));
3000 assert!(store.all_keys().await.expect("keys").contains(&addr));
3001 drop(dir);
3002 }
3003
3004 /// Content plus the address it hashes to.
3005 fn addressed(seed: &str) -> (XorName, Vec<u8>) {
3006 let content = format!("chunk-content-{seed}").into_bytes();
3007 (crate::client::compute_address(&content), content)
3008 }
3009
3010 #[tokio::test]
3011 async fn put_then_get_returns_the_same_bytes() {
3012 let (store, _dir) = test_store().await;
3013 let (addr, content) = addressed("a");
3014
3015 assert!(store.put(&addr, &content).await.expect("put"));
3016 let got = store.get(&addr).await.expect("get").expect("present");
3017 assert_eq!(got, content);
3018 }
3019
3020 #[tokio::test]
3021 async fn a_second_put_of_the_same_chunk_reports_not_new() {
3022 let (store, _dir) = test_store().await;
3023 let (addr, content) = addressed("b");
3024
3025 assert!(store.put(&addr, &content).await.expect("first put"));
3026 assert!(!store.put(&addr, &content).await.expect("second put"));
3027 assert_eq!(store.current_chunks().expect("count"), 1);
3028 assert_eq!(store.stats().duplicates, 1);
3029 }
3030
3031 #[tokio::test]
3032 async fn get_of_an_unknown_address_is_none() {
3033 let (store, _dir) = test_store().await;
3034 let (addr, _) = addressed("missing");
3035 assert!(store.get(&addr).await.expect("get").is_none());
3036 }
3037
3038 #[tokio::test]
3039 async fn exists_tracks_the_store() {
3040 let (store, _dir) = test_store().await;
3041 let (addr, content) = addressed("c");
3042
3043 assert!(!store.exists(&addr).expect("exists"));
3044 store.put(&addr, &content).await.expect("put");
3045 assert!(store.exists(&addr).expect("exists"));
3046 store.delete(&addr).await.expect("delete");
3047 assert!(!store.exists(&addr).expect("exists"));
3048 }
3049
3050 #[tokio::test]
3051 async fn delete_unlinks_the_file_and_returns_the_space() {
3052 let (store, _dir) = test_store().await;
3053 let (addr, content) = addressed("d");
3054 store.put(&addr, &content).await.expect("put");
3055
3056 let path = store.chunk_path(&addr);
3057 assert!(path.exists(), "the chunk file should be on disk");
3058
3059 assert!(store.delete(&addr).await.expect("delete"));
3060 assert!(!path.exists(), "delete must actually unlink the file");
3061 assert_eq!(store.current_chunks().expect("count"), 0);
3062
3063 // Deleting again is a no-op that reports nothing was there.
3064 assert!(!store.delete(&addr).await.expect("second delete"));
3065 }
3066
3067 #[tokio::test]
3068 async fn content_that_does_not_hash_to_its_address_is_rejected() {
3069 let (store, _dir) = test_store().await;
3070 let (addr, _) = addressed("e");
3071 let err = store
3072 .put(&addr, b"different content")
3073 .await
3074 .expect_err("must reject");
3075 assert!(
3076 format!("{err}").contains("Content address mismatch"),
3077 "unexpected error: {err}"
3078 );
3079 assert_eq!(store.current_chunks().expect("count"), 0);
3080 }
3081
3082 #[tokio::test]
3083 async fn a_chunk_is_filed_under_the_last_two_hex_characters_of_its_address() {
3084 let (store, dir) = test_store().await;
3085 let (addr, content) = addressed("f");
3086 store.put(&addr, &content).await.expect("put");
3087
3088 let name = hex::encode(addr);
3089 let expected_shard = name
3090 .get(name.len() - 2..)
3091 .expect("64-character name")
3092 .to_string();
3093 let path = dir
3094 .path()
3095 .join(CHUNKS_DIR_NAME)
3096 .join(&expected_shard)
3097 .join(&name);
3098 assert!(path.exists(), "expected the chunk at {}", path.display());
3099 }
3100
3101 #[tokio::test]
3102 async fn the_index_is_rebuilt_from_the_filesystem_on_restart() {
3103 let (store, dir) = test_store().await;
3104 let mut written = Vec::new();
3105 for i in 0..64 {
3106 let (addr, content) = addressed(&format!("restart-{i}"));
3107 store.put(&addr, &content).await.expect("put");
3108 written.push(addr);
3109 }
3110 drop(store);
3111
3112 let reopened = reopen(&dir).await;
3113 assert_eq!(reopened.current_chunks().expect("count"), 64);
3114 for addr in &written {
3115 assert!(reopened.exists(addr).expect("exists"), "lost a key");
3116 }
3117 }
3118
3119 #[tokio::test]
3120 async fn all_keys_is_sorted_ascending() {
3121 let (store, dir) = test_store().await;
3122 for i in 0..128 {
3123 let (addr, content) = addressed(&format!("sorted-{i}"));
3124 store.put(&addr, &content).await.expect("put");
3125 }
3126
3127 let keys = store.all_keys().await.expect("all_keys");
3128 let mut sorted = keys.clone();
3129 sorted.sort_unstable();
3130 assert_eq!(keys, sorted, "all_keys() must be ordered");
3131
3132 // And the order has to survive a restart, because the commitment builder
3133 // truncates the responsible subset before the Merkle tree sorts it.
3134 drop(store);
3135 let reopened = reopen(&dir).await;
3136 assert_eq!(reopened.all_keys().await.expect("all_keys"), keys);
3137 }
3138
3139 #[tokio::test]
3140 async fn get_raw_skips_verification() {
3141 let (store, _dir) = test_store().await;
3142 let (addr, content) = addressed("raw");
3143 store.put(&addr, &content).await.expect("put");
3144
3145 // Corrupt the file behind the store's back.
3146 std::fs::write(store.chunk_path(&addr), b"tampered").expect("tamper");
3147
3148 let raw = store.get_raw(&addr).await.expect("get_raw").expect("bytes");
3149 assert_eq!(raw, b"tampered");
3150 }
3151
3152 /// A put whose caller goes away does not admit a key on bytes nothing has read.
3153 ///
3154 /// The blocking half of a put outlives the future that started it, deliberately, so
3155 /// the work is never left half done. That makes anything it writes to memory a claim
3156 /// the node keeps whether or not the caller is still there to finish checking it.
3157 ///
3158 /// For a chunk this call published the claim is earned: the bytes were hashed against
3159 /// their own name on the way in. For a name that was already taken it is not. The
3160 /// check that decides whether those bytes are good runs after the await, and a dropped
3161 /// future skips it, so admitting the key in the closure claims a chunk nobody read.
3162 ///
3163 /// Staged with a fifo, which is the sharpest case and a real one: the startup scan
3164 /// refuses non-regular entries by design, so this is a key the store has already
3165 /// decided it must not claim, walked in through the back door.
3166 #[cfg(unix)]
3167 #[tokio::test]
3168 // The gate is held across an await deliberately: holding it is what parks the put
3169 // inside its closure, which is the state under test. Dropping it before awaiting would
3170 // let the put finish and there would be nothing to cancel.
3171 #[allow(clippy::await_holding_lock)]
3172 async fn a_cancelled_put_does_not_admit_a_key_whose_bytes_were_never_read() {
3173 let dir = TempDir::new().expect("temp dir");
3174 let store = Arc::new(reopen(&dir).await);
3175
3176 // A name a real chunk would use, wearing something that is not a chunk.
3177 let content = b"the bytes that belong under this name".to_vec();
3178 let addr = crate::client::compute_address(&content);
3179 let shard = dir
3180 .path()
3181 .join(CHUNKS_DIR_NAME)
3182 .join(format!("{:02x}", addr[31]));
3183 std::fs::create_dir_all(&shard).expect("mkdir");
3184 let path = shard.join(hex::encode(addr));
3185 let name = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())
3186 .expect("a path with no interior nul");
3187 // SAFETY: `name` is a valid NUL-terminated C string that outlives the call, and the
3188 // mode is a constant. `mkfifo` reads the pointer and returns; nothing is retained.
3189 #[allow(clippy::undocumented_unsafe_blocks, unsafe_code)]
3190 let made = unsafe { libc::mkfifo(name.as_ptr(), 0o644) };
3191 assert_eq!(made, 0, "could not make the fifo this test needs");
3192
3193 // Hold the gate so the put parks inside the closure, then drop the future while it
3194 // is parked. That is a caller going away mid-put, which is what a cancelled
3195 // request, a client disconnect or a shutdown all look like from in here.
3196 let gate = store.test_put_gate();
3197 let held = gate.write();
3198 let put = {
3199 let store = Arc::clone(&store);
3200 let content = content.clone();
3201 tokio::spawn(async move { store.put(&addr, &content).await })
3202 };
3203 // Waited for rather than slept at. A sleep proves nothing: if the put had not
3204 // reached the gated closure yet, aborting would cancel it before it ever got
3205 // there and the test would pass having staged nothing.
3206 let deadline = std::time::Instant::now() + Duration::from_secs(30);
3207 while store.tasks_in_flight() == 0 {
3208 assert!(
3209 std::time::Instant::now() < deadline,
3210 "the put never reached the closure, so there was nothing to cancel"
3211 );
3212 tokio::time::sleep(Duration::from_millis(5)).await;
3213 }
3214 put.abort();
3215 let _ = put.await;
3216 drop(held);
3217 store.wait_idle().await;
3218
3219 assert!(
3220 !store.is_indexed(&addr),
3221 "a cancelled put admitted {} on bytes nothing read; the fifo under that name \
3222 would then be advertised, committed to, and audited against",
3223 hex::encode(addr)
3224 );
3225 assert!(
3226 !store.exists(&addr).unwrap_or(true),
3227 "and the node must not claim it either"
3228 );
3229 }
3230
3231 /// A marker temporary left in the node root is swept, and nothing else is.
3232 ///
3233 /// The migration marker is written next to itself in the root, which no sweep looked
3234 /// at, so a crash between its write and its rename left one there for the life of the
3235 /// node. Small, but nothing was ever going to remove it.
3236 ///
3237 /// The second half is the point: this runs over a directory holding a node's data, so
3238 /// it has to take only the exact shape this module writes and leave everything else
3239 /// where it is.
3240 #[tokio::test]
3241 async fn a_leftover_marker_temporary_is_swept_and_its_neighbours_are_not() {
3242 let dir = TempDir::new().expect("temp dir");
3243 let root = dir.path();
3244 let leftover = root.join(format!("{TEMP_PREFIX}1234.abcdef01.marker"));
3245 std::fs::write(&leftover, b"an interrupted marker write").expect("plant");
3246
3247 // Things that must survive: the marker itself, a chunk-shaped temp that belongs to
3248 // the chunk tree's own sweep, and anything an operator put there.
3249 let keep = [
3250 root.join("migration-state.json"),
3251 root.join(format!("{TEMP_PREFIX}1234.abcdef01.chunk")),
3252 root.join("notes.txt"),
3253 // Prefix and suffix alone would take these. The pid and the nonce are checked
3254 // because this runs over a directory holding a node's data.
3255 root.join(format!("{TEMP_PREFIX}operator-notes.marker")),
3256 root.join(format!("{TEMP_PREFIX}1234.nothex01.marker")),
3257 root.join(format!("{TEMP_PREFIX}1234.abcdef0.marker")),
3258 root.join(format!("{TEMP_PREFIX}1234.abcdef01.extra.marker")),
3259 ];
3260 for path in &keep {
3261 std::fs::write(path, b"keep me").expect("plant");
3262 }
3263
3264 let store = reopen(&dir).await;
3265 drop(store);
3266
3267 assert!(
3268 !leftover.exists(),
3269 "the leftover marker temporary is still in the node root"
3270 );
3271 for path in &keep {
3272 assert!(
3273 path.exists(),
3274 "{} was swept and should not have been",
3275 path.display()
3276 );
3277 }
3278 }
3279
3280 #[tokio::test]
3281 async fn a_corrupt_chunk_is_removed_so_replication_can_repair_it() {
3282 let (store, _dir) = test_store().await;
3283 let (addr, content) = addressed("corrupt");
3284 store.put(&addr, &content).await.expect("put");
3285 std::fs::write(store.chunk_path(&addr), b"tampered").expect("tamper");
3286
3287 let err = store.get(&addr).await.expect_err("verification must fail");
3288 assert!(format!("{err}").contains("verification failed"), "{err}");
3289
3290 assert!(!store.chunk_path(&addr).exists(), "corrupt file must go");
3291 assert!(!store.exists(&addr).expect("exists"));
3292 assert!(
3293 !store.all_keys().await.expect("all_keys").contains(&addr),
3294 "a corrupt chunk must stop being advertised"
3295 );
3296 assert_eq!(store.stats().verification_failures, 1);
3297 }
3298
3299 #[tokio::test]
3300 async fn a_file_removed_underneath_the_store_drops_out_of_the_index() {
3301 let (store, _dir) = test_store().await;
3302 let (addr, content) = addressed("vanished");
3303 store.put(&addr, &content).await.expect("put");
3304
3305 std::fs::remove_file(store.chunk_path(&addr)).expect("remove behind our back");
3306
3307 assert!(store.get(&addr).await.expect("get").is_none());
3308 assert!(!store.exists(&addr).expect("exists"));
3309 assert_eq!(store.current_chunks().expect("count"), 0);
3310 }
3311
3312 #[tokio::test]
3313 async fn interrupted_writes_are_swept_at_startup() {
3314 let (store, dir) = test_store().await;
3315 let (addr, content) = addressed("sweep");
3316 store.put(&addr, &content).await.expect("put");
3317 let shard = store
3318 .chunk_path(&addr)
3319 .parent()
3320 .expect("shard")
3321 .to_path_buf();
3322 drop(store);
3323
3324 let orphan = shard.join(format!("{TEMP_PREFIX}999.7"));
3325 std::fs::write(&orphan, b"half a chunk").expect("write orphan");
3326 let stray_root = dir
3327 .path()
3328 .join(CHUNKS_DIR_NAME)
3329 .join(format!("{TEMP_PREFIX}999.8"));
3330 std::fs::write(&stray_root, b"half a marker").expect("write stray");
3331
3332 let reopened = reopen(&dir).await;
3333 assert!(!orphan.exists(), "an interrupted write must not survive");
3334 assert!(!stray_root.exists(), "nor one at the store root");
3335 assert_eq!(reopened.current_chunks().expect("count"), 1);
3336 }
3337
3338 #[tokio::test]
3339 async fn concurrent_writers_of_one_address_store_it_exactly_once() {
3340 let (store, _dir) = test_store().await;
3341 let store = Arc::new(store);
3342 let (addr, content) = addressed("racing");
3343
3344 let mut tasks = Vec::new();
3345 for _ in 0..16 {
3346 let store = Arc::clone(&store);
3347 let content = content.clone();
3348 tasks.push(tokio::spawn(
3349 async move { store.put(&addr, &content).await },
3350 ));
3351 }
3352
3353 let mut new_count = 0;
3354 for task in tasks {
3355 if task.await.expect("join").expect("put") {
3356 new_count += 1;
3357 }
3358 }
3359 assert_eq!(new_count, 1, "exactly one writer may report a new chunk");
3360 assert_eq!(store.current_chunks().expect("count"), 1);
3361 assert_eq!(
3362 store.get(&addr).await.expect("get").expect("present"),
3363 content
3364 );
3365 }
3366
3367 #[tokio::test]
3368 async fn names_that_are_not_lowercase_hex_are_ignored_by_the_scan() {
3369 let (store, dir) = test_store().await;
3370 let (addr, content) = addressed("scan");
3371 store.put(&addr, &content).await.expect("put");
3372 let shard = store
3373 .chunk_path(&addr)
3374 .parent()
3375 .expect("shard")
3376 .to_path_buf();
3377 drop(store);
3378
3379 // Uppercase is deliberately rejected: on a case-folding filesystem accepting it
3380 // would let one file answer to two index entries.
3381 let upper = shard.join(hex::encode_upper(addressed("upper").0));
3382 std::fs::write(&upper, b"x").expect("write upper");
3383 std::fs::write(shard.join("not-a-chunk"), b"x").expect("write junk");
3384 std::fs::write(shard.join("deadbeef"), b"x").expect("write short");
3385
3386 let reopened = reopen(&dir).await;
3387 assert_eq!(reopened.current_chunks().expect("count"), 1);
3388 }
3389
3390 #[tokio::test]
3391 async fn a_chunk_filed_in_the_wrong_shard_is_not_indexed() {
3392 let (store, dir) = test_store().await;
3393 let (addr, content) = addressed("misfiled");
3394 store.put(&addr, &content).await.expect("put");
3395 drop(store);
3396
3397 // Move it one shard over: the read path would never find it there, so indexing
3398 // it would make the store advertise a key it cannot serve.
3399 let correct = dir
3400 .path()
3401 .join(CHUNKS_DIR_NAME)
3402 .join(shard_name(&addr))
3403 .join(hex::encode(addr));
3404 let wrong_shard_index = (shard_index(&addr) + 1) % SHARD_COUNT;
3405 let wrong_dir = dir
3406 .path()
3407 .join(CHUNKS_DIR_NAME)
3408 .join(format!("{wrong_shard_index:02x}"));
3409 std::fs::create_dir_all(&wrong_dir).expect("mkdir");
3410 std::fs::rename(&correct, wrong_dir.join(hex::encode(addr))).expect("misfile");
3411
3412 let reopened = reopen(&dir).await;
3413 assert_eq!(reopened.current_chunks().expect("count"), 0);
3414 assert!(!reopened.exists(&addr).expect("exists"));
3415 }
3416
3417 #[tokio::test]
3418 async fn the_layout_marker_is_written_once_and_checked_on_reopen() {
3419 let (store, dir) = test_store().await;
3420 drop(store);
3421
3422 let marker = dir.path().join(CHUNKS_DIR_NAME).join(LAYOUT_FILE_NAME);
3423 let layout: StoreLayout =
3424 serde_json::from_slice(&std::fs::read(&marker).expect("read marker"))
3425 .expect("parse marker");
3426 assert_eq!(layout, StoreLayout::default());
3427
3428 // A store written by a future build must be refused, not misread.
3429 let future = StoreLayout {
3430 schema: LAYOUT_SCHEMA + 1,
3431 ..StoreLayout::default()
3432 };
3433 std::fs::write(&marker, serde_json::to_vec(&future).expect("encode")).expect("write");
3434 let err = FileStore::new(FileStoreConfig {
3435 root_dir: dir.path().to_path_buf(),
3436 verify_on_read: true,
3437 disk_reserve: 0,
3438 })
3439 .await
3440 .expect_err("must refuse a newer layout");
3441 assert!(format!("{err}").contains("newer than this build"), "{err}");
3442 }
3443
3444 #[tokio::test]
3445 async fn an_unknown_shard_scheme_is_refused() {
3446 let (store, dir) = test_store().await;
3447 drop(store);
3448 let marker = dir.path().join(CHUNKS_DIR_NAME).join(LAYOUT_FILE_NAME);
3449 let other = StoreLayout {
3450 scheme: "prefix-hex".to_string(),
3451 ..StoreLayout::default()
3452 };
3453 std::fs::write(&marker, serde_json::to_vec(&other).expect("encode")).expect("write");
3454 let err = FileStore::new(FileStoreConfig {
3455 root_dir: dir.path().to_path_buf(),
3456 verify_on_read: true,
3457 disk_reserve: 0,
3458 })
3459 .await
3460 .expect_err("must refuse an unknown scheme");
3461 assert!(format!("{err}").contains("shard scheme"), "{err}");
3462 }
3463
3464 #[tokio::test]
3465 async fn writes_are_refused_when_the_disk_reserve_cannot_be_met() {
3466 let dir = TempDir::new().expect("temp dir");
3467 let store = FileStore::new(FileStoreConfig {
3468 root_dir: dir.path().to_path_buf(),
3469 verify_on_read: true,
3470 disk_reserve: u64::MAX / 2,
3471 })
3472 .await
3473 .expect("open store");
3474
3475 let (addr, content) = addressed("full");
3476 let err = store.put(&addr, &content).await.expect_err("must refuse");
3477 assert!(
3478 format!("{err}").contains("Insufficient disk space"),
3479 "{err}"
3480 );
3481 assert!(store.check_capacity().is_err());
3482 }
3483
3484 #[tokio::test]
3485 async fn capacity_is_size_aware() {
3486 // Wide enough that a test running alongside this one cannot move the answer.
3487 const MARGIN: u64 = 512 * 1024 * 1024;
3488
3489 let dir = TempDir::new().expect("temp dir");
3490 let available = fs2::available_space(dir.path()).expect("free space");
3491 // A reserve that leaves room for a small write but not a huge one. This is the
3492 // whole reason the predicate takes a size: free bytes alone stopped being a
3493 // sufficient answer once chunks became files.
3494 let store = FileStore::new(FileStoreConfig {
3495 root_dir: dir.path().to_path_buf(),
3496 verify_on_read: true,
3497 disk_reserve: available.saturating_sub(MARGIN),
3498 })
3499 .await
3500 .expect("open store");
3501
3502 assert!(store.check_capacity_for(1024).is_ok());
3503 assert!(store.check_capacity_for(4 * MARGIN).is_err());
3504 }
3505
3506 #[test]
3507 fn suffix_shards_stay_uniform_for_a_close_group_of_keys() {
3508 // The real distribution: a node holds keys it is closest to, so they share a
3509 // long leading prefix with its own ID. Sharding on that prefix collapses to one
3510 // directory. The trailing byte is untouched by close-group membership.
3511 let mut prefix_dirs = HashSet::new();
3512 let mut suffix_dirs = HashSet::new();
3513 for i in 0u32..4096 {
3514 let mut key = [0u8; XORNAME_LEN];
3515 // 20 shared leading bits, as a ~1M-node network would impose.
3516 let tail = crate::client::compute_address(&i.to_le_bytes());
3517 key.copy_from_slice(&tail);
3518 if let Some(b) = key.first_mut() {
3519 *b = 0xab;
3520 }
3521 if let Some(b) = key.get_mut(1) {
3522 *b = 0xcd;
3523 }
3524 if let Some(b) = key.get_mut(2) {
3525 *b &= 0x0f;
3526 }
3527 prefix_dirs.insert(key.first().copied().unwrap_or(0));
3528 suffix_dirs.insert(shard_index(&key));
3529 }
3530 assert_eq!(
3531 prefix_dirs.len(),
3532 1,
3533 "prefix sharding collapses for a node's own holdings"
3534 );
3535 assert!(
3536 suffix_dirs.len() > 250,
3537 "suffix sharding must stay uniform, got {} of 256 directories",
3538 suffix_dirs.len()
3539 );
3540 }
3541
3542 #[test]
3543 fn no_chunk_filename_can_spell_a_reserved_windows_device_name() {
3544 // Hex has no `n`, `u`, `x`, `p`, `r`, `l`, `t`, `o` or `s`, so `CON`, `NUL`,
3545 // `AUX`, `PRN`, `COM1` and `LPT1` are all unspellable at any length. This is why
3546 // the encoding is hex and not base32 or base64url.
3547 for reserved in ["con", "prn", "aux", "nul", "com1", "com9", "lpt1", "lpt9"] {
3548 assert!(
3549 !is_lower_hex(reserved),
3550 "{reserved} must not be a valid chunk or shard name"
3551 );
3552 }
3553 }
3554
3555 #[test]
3556 fn only_full_length_lowercase_hex_decodes_to_an_address() {
3557 // 0xab so the hex form actually contains letters, which is where case matters.
3558 assert!(decode_chunk_name(&hex::encode([0xabu8; XORNAME_LEN])).is_some());
3559 assert!(decode_chunk_name(&hex::encode_upper([0xabu8; XORNAME_LEN])).is_none());
3560 assert!(decode_chunk_name("deadbeef").is_none());
3561 assert!(decode_chunk_name("").is_none());
3562 assert!(decode_chunk_name(&"g".repeat(CHUNK_NAME_LEN)).is_none());
3563 }
3564
3565 #[tokio::test]
3566 async fn repair_replaces_bad_bytes_without_the_file_ever_being_absent() {
3567 let (store, _dir) = test_store().await;
3568 let (addr, content) = addressed("repairable");
3569 store.put(&addr, &content).await.expect("put");
3570 let path = store.chunk_path(&addr);
3571
3572 std::fs::write(&path, b"rotted").expect("corrupt");
3573 store.repair(&addr, &content).await.expect("repair");
3574
3575 assert_eq!(
3576 store.get(&addr).await.expect("get").expect("present"),
3577 content
3578 );
3579 assert!(store.exists(&addr).expect("exists"));
3580 }
3581
3582 #[tokio::test]
3583 async fn a_repair_with_the_wrong_bytes_is_refused_and_changes_nothing() {
3584 let (store, _dir) = test_store().await;
3585 let (addr, content) = addressed("guarded");
3586 store.put(&addr, &content).await.expect("put");
3587 let path = store.chunk_path(&addr);
3588
3589 // The whole point of repairing in place is that a failure must leave the old file
3590 // where it was. Deleting first and writing after would open a window whose only
3591 // surviving copy is the one the caller is about to destroy.
3592 let err = store
3593 .repair(&addr, b"not this chunk")
3594 .await
3595 .expect_err("must refuse");
3596 assert!(format!("{err}").contains("Refusing to repair"), "{err}");
3597 assert!(
3598 path.exists(),
3599 "the existing file must survive a refused repair"
3600 );
3601 assert_eq!(
3602 store.get(&addr).await.expect("get").expect("present"),
3603 content
3604 );
3605 }
3606
3607 #[tokio::test]
3608 async fn a_chunk_can_be_deleted_and_stored_again() {
3609 let (store, _dir) = test_store().await;
3610 let (addr, content) = addressed("cycle");
3611
3612 assert!(store.put(&addr, &content).await.expect("put"));
3613 assert!(store.delete(&addr).await.expect("delete"));
3614 assert!(
3615 store.put(&addr, &content).await.expect("re-put"),
3616 "a re-stored chunk is new again"
3617 );
3618 assert_eq!(
3619 store.get(&addr).await.expect("get").expect("present"),
3620 content
3621 );
3622 }
3623
3624 /// Write a chunk file straight into its shard, the way an existing store already
3625 /// contains thousands of them. Bypasses the write path deliberately: this exercises
3626 /// the startup scan, not `put`.
3627 fn plant(chunks_dir: &Path, key: &XorName) {
3628 let dir = chunks_dir.join(shard_name(key));
3629 std::fs::create_dir_all(&dir).expect("mkdir");
3630 std::fs::write(dir.join(hex::encode(key)), key).expect("plant");
3631 }
3632
3633 #[tokio::test]
3634 async fn a_populated_and_churned_store_scans_correctly_at_scale() {
3635 // Every shard populated, then aged the way a long-lived node ages: some keys
3636 // deleted, others added in their place, so the directories carry holes rather
3637 // than being freshly written. APFS enumeration is known to degrade with churn
3638 // rather than with size, so a fresh corpus is not a realistic one.
3639 const PLANTED: u32 = 20_000;
3640 const CHURN: u32 = 1_000;
3641
3642 let dir = TempDir::new().expect("temp dir");
3643 let chunks_dir = dir.path().join(CHUNKS_DIR_NAME);
3644 std::fs::create_dir_all(&chunks_dir).expect("mkdir");
3645
3646 let mut expected: Vec<XorName> = Vec::new();
3647 for i in 0..PLANTED {
3648 let key = crate::client::compute_address(&i.to_le_bytes());
3649 plant(&chunks_dir, &key);
3650 expected.push(key);
3651 }
3652 for i in 0..CHURN {
3653 let key = crate::client::compute_address(&i.to_le_bytes());
3654 std::fs::remove_file(chunks_dir.join(shard_name(&key)).join(hex::encode(key)))
3655 .expect("churn out");
3656 let replacement = crate::client::compute_address(&(PLANTED + i).to_le_bytes());
3657 plant(&chunks_dir, &replacement);
3658 }
3659 expected.retain(|k| chunks_dir.join(shard_name(k)).join(hex::encode(k)).exists());
3660 for i in 0..CHURN {
3661 expected.push(crate::client::compute_address(&(PLANTED + i).to_le_bytes()));
3662 }
3663 expected.sort_unstable();
3664 expected.dedup();
3665
3666 let started = std::time::Instant::now();
3667 let store = reopen(&dir).await;
3668 let scan = started.elapsed();
3669
3670 assert_eq!(
3671 store.current_chunks().expect("count"),
3672 expected.len() as u64
3673 );
3674 assert_eq!(store.all_keys().await.expect("all_keys"), expected);
3675
3676 // Every shard should be in use at this size: 20,000 keys over 256 directories is
3677 // about 78 each, and the last byte of a BLAKE3 output is uniform.
3678 let occupied = std::fs::read_dir(&chunks_dir)
3679 .expect("read store root")
3680 .filter_map(std::result::Result::ok)
3681 .filter(|e| e.file_name().to_str().is_some_and(|n| n.len() == 2))
3682 .count();
3683 assert_eq!(occupied, SHARD_COUNT, "the suffix must reach every shard");
3684
3685 println!(
3686 "scan of {} keys across {SHARD_COUNT} shards took {scan:?}",
3687 expected.len()
3688 );
3689 }
3690
3691 #[tokio::test]
3692 async fn wait_idle_returns_once_writes_have_drained() {
3693 let (store, _dir) = test_store().await;
3694 let store = Arc::new(store);
3695 for i in 0..32 {
3696 let store = Arc::clone(&store);
3697 let (addr, content) = addressed(&format!("drain-{i}"));
3698 tokio::spawn(async move { store.put(&addr, &content).await });
3699 }
3700 // Not a synchronisation point for tasks that have not been spawned yet, but it
3701 // must not hang and it must leave the store usable.
3702 store.wait_idle().await;
3703 let (addr, content) = addressed("after-drain");
3704 assert!(store.put(&addr, &content).await.expect("put after drain"));
3705 }
3706}