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