use crate::ant_protocol::{XorName, MAX_CHUNK_SIZE, XORNAME_LEN};
use crate::error::{Error, Result};
use crate::logging::{debug, info, trace, warn};
use crate::storage::StorageStats;
use fs2::FileExt;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fs::{File, OpenOptions};
use std::io::{ErrorKind, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::task::spawn_blocking;
use tokio_util::task::TaskTracker;
pub const CHUNKS_DIR_NAME: &str = "chunks";
pub const LAYOUT_FILE_NAME: &str = "layout.json";
const LOCK_FILE_NAME: &str = ".lock";
const TEMP_PREFIX: &str = ".tmp.";
const SHARD_COUNT: usize = 256;
const CHUNK_NAME_LEN: usize = XORNAME_LEN * 2;
const DISK_CHECK_INTERVAL_SECS: u64 = 5;
const ALLOC_UNIT: u64 = 4096;
const RENAME_RETRY_ATTEMPTS: u32 = 5;
const RENAME_RETRY_BACKOFF: Duration = Duration::from_millis(20);
#[cfg(windows)]
const WINDOWS_PATH_WARN_LEN: usize = 240;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StoreLayout {
pub schema: u32,
pub scheme: String,
pub shard_chars: u8,
pub depth: u8,
pub name_encoding: String,
}
const LAYOUT_SCHEMA: u32 = 1;
const LAYOUT_SCHEME_SUFFIX_HEX: &str = "suffix-hex";
const LAYOUT_NAME_LOWER_HEX: &str = "lower-hex";
impl Default for StoreLayout {
fn default() -> Self {
Self {
schema: LAYOUT_SCHEMA,
scheme: LAYOUT_SCHEME_SUFFIX_HEX.to_string(),
shard_chars: 2,
depth: 1,
name_encoding: LAYOUT_NAME_LOWER_HEX.to_string(),
}
}
}
impl StoreLayout {
fn check_supported(&self) -> Result<()> {
if self.schema > LAYOUT_SCHEMA {
return Err(Error::Storage(format!(
"Chunk store layout schema {} is newer than this build understands ({LAYOUT_SCHEMA}). \
Refusing to open rather than misread the store.",
self.schema
)));
}
if self.scheme != LAYOUT_SCHEME_SUFFIX_HEX {
return Err(Error::Storage(format!(
"Chunk store uses shard scheme '{}', this build implements '{LAYOUT_SCHEME_SUFFIX_HEX}'",
self.scheme
)));
}
if self.shard_chars != 2 || self.depth != 1 {
return Err(Error::Storage(format!(
"Chunk store uses {} shard characters at depth {}, this build implements 2 at depth 1",
self.shard_chars, self.depth
)));
}
if self.name_encoding != LAYOUT_NAME_LOWER_HEX {
return Err(Error::Storage(format!(
"Chunk store names files with '{}', this build implements '{LAYOUT_NAME_LOWER_HEX}'",
self.name_encoding
)));
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct FileStoreConfig {
pub root_dir: PathBuf,
pub verify_on_read: bool,
pub disk_reserve: u64,
}
enum PutOutcome {
New,
Duplicate,
}
#[derive(Debug)]
struct CapacitySnapshot {
measured_at: Option<Instant>,
available: u64,
written_since: u64,
in_flight: u64,
}
#[derive(Debug)]
struct CapacityGuard {
dir: PathBuf,
reserve: u64,
snapshot: parking_lot::Mutex<CapacitySnapshot>,
}
impl CapacitySnapshot {
fn free_estimate(&self) -> u64 {
self.available
.saturating_sub(self.written_since)
.saturating_sub(self.in_flight)
}
}
impl CapacityGuard {
fn new(dir: PathBuf, reserve: u64) -> Self {
Self {
dir,
reserve,
snapshot: parking_lot::Mutex::new(CapacitySnapshot {
measured_at: None,
available: 0,
written_since: 0,
in_flight: 0,
}),
}
}
fn charge(len: u64) -> u64 {
len.div_ceil(ALLOC_UNIT)
.saturating_mul(ALLOC_UNIT)
.saturating_add(ALLOC_UNIT)
}
fn measure_available(&self) -> Option<u64> {
let mut snapshot = self.snapshot.lock();
match self.measure(&mut snapshot) {
Ok(()) => Some(snapshot.free_estimate()),
Err(_) => None,
}
}
fn measure(&self, snapshot: &mut CapacitySnapshot) -> Result<()> {
let available = fs2::available_space(&self.dir)
.map_err(|e| Error::Storage(format!("Failed to query available disk space: {e}")))?;
snapshot.available = available;
snapshot.written_since = 0;
snapshot.measured_at = Some(Instant::now());
Ok(())
}
fn admit(&self, snapshot: &mut CapacitySnapshot, needed: u64) -> Result<()> {
let want = self.reserve.saturating_add(Self::charge(needed));
let cache_fresh = snapshot
.measured_at
.is_some_and(|t| t.elapsed().as_secs() < DISK_CHECK_INTERVAL_SECS);
if cache_fresh && snapshot.free_estimate() >= want {
return Ok(());
}
self.measure(snapshot)?;
if snapshot.free_estimate() < want {
return Err(Error::Storage(format!(
"Insufficient disk space: {:.2} GiB available, {:.2} GiB reserve required. \
Free disk space or increase the partition to continue storing chunks.",
bytes_to_gib(snapshot.free_estimate()),
bytes_to_gib(self.reserve),
)));
}
Ok(())
}
fn invalidate(&self) {
let mut snapshot = self.snapshot.lock();
snapshot.measured_at = None;
snapshot.written_since = 0;
}
fn check(&self, needed: u64) -> Result<()> {
let mut snapshot = self.snapshot.lock();
self.admit(&mut snapshot, needed)
}
fn reserve(self: &Arc<Self>, needed: u64) -> Result<Reservation> {
{
let mut snapshot = self.snapshot.lock();
self.admit(&mut snapshot, needed)?;
snapshot.in_flight = snapshot.in_flight.saturating_add(Self::charge(needed));
}
Ok(Reservation {
capacity: Arc::clone(self),
bytes: needed,
settled: false,
})
}
#[cfg(test)]
fn counters(&self) -> (u64, u64) {
let snapshot = self.snapshot.lock();
(snapshot.written_since, snapshot.in_flight)
}
fn release(&self, needed: u64) {
let mut snapshot = self.snapshot.lock();
snapshot.in_flight = snapshot.in_flight.saturating_sub(Self::charge(needed));
}
fn commit_reservation(&self, needed: u64) {
let charge = Self::charge(needed);
let mut snapshot = self.snapshot.lock();
snapshot.in_flight = snapshot.in_flight.saturating_sub(charge);
snapshot.written_since = snapshot.written_since.saturating_add(charge);
}
fn record_removed(&self, len: u64) {
let mut snapshot = self.snapshot.lock();
snapshot.written_since = snapshot.written_since.saturating_sub(Self::charge(len));
}
}
pub(crate) struct Reservation {
capacity: Arc<CapacityGuard>,
bytes: u64,
settled: bool,
}
impl Reservation {
pub(crate) fn commit(mut self) {
self.capacity.commit_reservation(self.bytes);
self.settled = true;
}
}
impl Drop for Reservation {
fn drop(&mut self) {
if !self.settled {
self.capacity.release(self.bytes);
}
}
}
#[cfg(any(test, feature = "test-utils"))]
pub const HALT_BEFORE_PUBLISH: &str = "ANT_HALT_BEFORE_PUBLISH";
#[cfg(any(test, feature = "test-utils"))]
pub const HALT_AFTER_RETIRE_MARK: &str = "ANT_HALT_AFTER_RETIRE_MARK";
#[cfg(any(test, feature = "test-utils"))]
pub(crate) fn halt_here_if_asked(variable: &str, reached: &Path) {
let Ok(marker) = std::env::var(variable) else {
return;
};
let skip: u64 = std::env::var(HALT_AFTER)
.ok()
.and_then(|raw| raw.parse().ok())
.unwrap_or(0);
if HALTS_SEEN.fetch_add(1, std::sync::atomic::Ordering::AcqRel) < skip {
return;
}
if let Err(e) = std::fs::write(&marker, reached.as_os_str().as_encoded_bytes()) {
eprintln!("failpoint could not write its marker {marker}: {e}");
return;
}
loop {
std::thread::sleep(Duration::from_hours(1));
}
}
#[cfg(any(test, feature = "test-utils"))]
pub const HALT_AFTER: &str = "ANT_HALT_AFTER";
#[cfg(any(test, feature = "test-utils"))]
static HALTS_SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
struct WriteInFlight {
writing: Arc<parking_lot::Mutex<HashMap<XorName, usize>>>,
finished: Arc<tokio::sync::Notify>,
address: XorName,
}
impl Drop for WriteInFlight {
fn drop(&mut self) {
let was_last = {
let mut writing = self.writing.lock();
match writing.get_mut(&self.address) {
Some(count) if *count > 1 => {
*count -= 1;
false
}
_ => {
writing.remove(&self.address);
true
}
}
};
if was_last {
self.finished.notify_waiters();
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StoredBytes {
Good,
Wrong,
Absent,
Unreadable,
}
#[allow(clippy::cast_precision_loss)] fn bytes_to_gib(bytes: u64) -> f64 {
bytes as f64 / (1024.0 * 1024.0 * 1024.0)
}
#[derive(Debug)]
pub struct FileStore {
config: FileStoreConfig,
chunks_dir: PathBuf,
index: Arc<parking_lot::RwLock<BTreeSet<XorName>>>,
write_lanes: Arc<Vec<parking_lot::Mutex<()>>>,
stats: parking_lot::RwLock<StorageStats>,
shards_present: Arc<parking_lot::Mutex<[bool; SHARD_COUNT]>>,
suspect: Arc<parking_lot::RwLock<HashSet<XorName>>>,
known_wrong: Arc<parking_lot::RwLock<HashSet<XorName>>>,
writing: Arc<parking_lot::Mutex<HashMap<XorName, usize>>>,
write_finished: Arc<tokio::sync::Notify>,
health: Arc<std::sync::atomic::AtomicU64>,
capacity: Arc<CapacityGuard>,
temp_seq: AtomicU64,
nonce: u32,
lock: Arc<File>,
blocking_tracker: TaskTracker,
#[cfg(any(test, feature = "test-utils"))]
test_put_gate: Arc<parking_lot::RwLock<()>>,
}
impl FileStore {
pub async fn new(config: FileStoreConfig) -> Result<Self> {
let chunks_dir = config.root_dir.join(CHUNKS_DIR_NAME);
std::fs::create_dir_all(&chunks_dir).map_err(|e| {
Error::Storage(format!(
"Failed to create chunk store directory {}: {e}",
chunks_dir.display()
))
})?;
check_path_budget(&chunks_dir);
let layout = read_or_write_layout(&chunks_dir)?;
layout.check_supported()?;
let lock = acquire_store_lock(&chunks_dir)?;
let scan_dir = chunks_dir.clone();
let scan_lease = Arc::clone(&lock);
let root = config.root_dir.clone();
let scan = spawn_blocking(move || {
let _lease = scan_lease;
sweep_marker_temps(&root);
scan_store(&scan_dir)
})
.await
.map_err(|e| Error::Storage(format!("Chunk store scan task failed: {e}")))??;
let ScanResult {
keys,
shards_present,
swept_temps,
skipped,
} = scan;
let key_count = keys.len();
let index: BTreeSet<XorName> = keys.into_iter().collect();
if swept_temps > 0 {
info!("Chunk store: removed {swept_temps} orphaned temporary file(s) from interrupted writes");
}
if skipped > 0 {
warn!("Chunk store: ignored {skipped} directory entr(ies) that are not chunk files");
}
info!(
"Chunk store open at {} ({key_count} chunks)",
chunks_dir.display()
);
let capacity = Arc::new(CapacityGuard::new(chunks_dir.clone(), config.disk_reserve));
Ok(Self {
config,
chunks_dir,
index: Arc::new(parking_lot::RwLock::new(index)),
write_lanes: Arc::new(
std::iter::repeat_with(|| parking_lot::Mutex::new(()))
.take(SHARD_COUNT)
.collect(),
),
stats: parking_lot::RwLock::new(StorageStats::default()),
shards_present: Arc::new(parking_lot::Mutex::new(shards_present)),
suspect: Arc::new(parking_lot::RwLock::new(HashSet::new())),
known_wrong: Arc::new(parking_lot::RwLock::new(HashSet::new())),
writing: Arc::new(parking_lot::Mutex::new(HashMap::new())),
write_finished: Arc::new(tokio::sync::Notify::new()),
health: Arc::new(std::sync::atomic::AtomicU64::new(0)),
capacity,
temp_seq: AtomicU64::new(0),
nonce: rand::random(),
lock,
blocking_tracker: TaskTracker::new(),
#[cfg(any(test, feature = "test-utils"))]
test_put_gate: Arc::new(parking_lot::RwLock::new(())),
})
}
pub async fn put(&self, address: &XorName, content: &[u8]) -> Result<bool> {
let computed = crate::client::compute_address(content);
if computed != *address {
return Err(Error::Storage(format!(
"Content address mismatch: expected {}, computed {}",
hex::encode(address),
hex::encode(computed)
)));
}
if content.len() > MAX_CHUNK_SIZE {
return Err(Error::Storage(format!(
"Chunk {} is {} bytes, over the {MAX_CHUNK_SIZE} byte maximum",
hex::encode(address),
content.len()
)));
}
if self.index.read().contains(address) {
if let Some(answer) = self.settle_indexed_duplicate(address, content).await {
return answer;
}
}
let len = content.len() as u64;
let reservation = self.capacity.reserve(len)?;
let shard = self.chunks_dir.join(shard_name(address));
let final_path = shard.join(hex::encode(address));
let temp_path = shard.join(self.next_temp_name());
let payload = content.to_vec();
let lanes = Arc::clone(&self.write_lanes);
let index = Arc::clone(&self.index);
let shards_present = Arc::clone(&self.shards_present);
let chunks_dir = self.chunks_dir.clone();
let lane = shard_index(address);
let key = *address;
#[cfg(any(test, feature = "test-utils"))]
let test_put_gate = Arc::clone(&self.test_put_gate);
let in_flight = self.begin_write(address);
let lease = Arc::clone(&self.lock);
let known_wrong = Arc::clone(&self.known_wrong);
let suspect = Arc::clone(&self.suspect);
let outcome = self
.blocking_tracker
.spawn_blocking(move || -> Result<PutOutcome> {
let _in_flight = in_flight;
let _lease = lease;
#[cfg(any(test, feature = "test-utils"))]
let _test_put_gate = test_put_gate.read();
let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
ensure_shard_dir(&chunks_dir, &shard, lane, &shards_present)?;
let outcome = match publish(&temp_path, &final_path, &payload, &shard) {
Ok(outcome) => outcome,
Err(PublishFailed { error, left_behind }) => {
if left_behind {
reservation.commit();
}
return Err(error);
}
};
if let Err(e) = flush_publication(&final_path, &shard) {
if matches!(outcome, PutOutcome::New) {
reservation.commit();
}
return Err(e);
}
if matches!(outcome, PutOutcome::New) {
index.write().insert(key);
known_wrong.write().remove(&key);
suspect.write().remove(&key);
reservation.commit();
}
Ok(outcome)
})
.await
.map_err(|e| Error::Storage(format!("Chunk store put task failed: {e}")))??;
match outcome {
PutOutcome::Duplicate => self.settle_duplicate(address, content).await,
PutOutcome::New => {
let mut stats = self.stats.write();
stats.chunks_stored = stats.chunks_stored.saturating_add(1);
stats.bytes_stored = stats.bytes_stored.saturating_add(len);
drop(stats);
debug!("Stored chunk {} ({len} bytes)", hex::encode(address));
Ok(true)
}
}
}
async fn settle_duplicate(&self, address: &XorName, content: &[u8]) -> Result<bool> {
match self.stored_bytes_match(address).await {
StoredBytes::Good => {
self.index.write().insert(*address);
{
let mut stats = self.stats.write();
stats.duplicates = stats.duplicates.saturating_add(1);
}
Ok(false)
}
StoredBytes::Wrong => {
warn!(
"Chunk {} was already on disk but its contents are wrong; \
replacing it with the copy just offered",
hex::encode(address)
);
self.repair(address, content).await.map(|()| true)
}
StoredBytes::Absent => Err(Error::Storage(format!(
"Chunk {} was reported already on disk but nothing is there. Not \
reporting it as stored.",
hex::encode(address)
))),
StoredBytes::Unreadable => Err(Error::Storage(format!(
"Chunk {} is on disk but could not be read to check it. Not \
replacing it, and not reporting it as stored.",
hex::encode(address)
))),
}
}
pub fn flush_namespace(&self) -> Result<()> {
fsync_dir(&self.chunks_dir).map_err(|e| {
Error::Storage(format!(
"Could not flush {}: {e}",
self.chunks_dir.display()
))
})?;
let present = *self.shards_present.lock();
for (shard, _) in present.iter().enumerate().filter(|(_, here)| **here) {
let dir = self.chunks_dir.join(format!("{shard:02x}"));
fsync_dir(&dir)
.map_err(|e| Error::Storage(format!("Could not flush {}: {e}", dir.display())))?;
}
Ok(())
}
async fn settle_indexed_duplicate(
&self,
address: &XorName,
content: &[u8],
) -> Option<Result<bool>> {
match self.stored_bytes_match(address).await {
StoredBytes::Good => {
trace!("Chunk {} already exists", hex::encode(address));
{
let mut stats = self.stats.write();
stats.duplicates = stats.duplicates.saturating_add(1);
}
Some(Ok(false))
}
StoredBytes::Wrong => {
warn!(
"Chunk {} is indexed but its bytes are wrong; replacing it with the \
copy just offered",
hex::encode(address)
);
Some(self.repair(address, content).await.map(|()| true))
}
StoredBytes::Absent => None,
StoredBytes::Unreadable => Some(Err(Error::Storage(format!(
"Chunk {} is indexed but could not be read to check it. Not replacing it, \
and not reporting it as stored.",
hex::encode(address)
)))),
}
}
#[cfg(test)]
pub(crate) fn forget_for_test(&self, address: &XorName) {
self.index.write().remove(address);
}
#[must_use]
pub fn stored_len(&self, address: &XorName) -> Option<usize> {
std::fs::metadata(self.chunk_path(address))
.ok()
.filter(std::fs::Metadata::is_file)
.and_then(|m| usize::try_from(m.len()).ok())
}
async fn stored_bytes_match(&self, address: &XorName) -> StoredBytes {
match self.get_raw(address).await {
Ok(Some(bytes)) if crate::client::compute_address(&bytes) == *address => {
self.clear_suspect(address);
self.clear_known_wrong(address);
StoredBytes::Good
}
Ok(Some(_)) => {
self.mark_known_wrong(address);
StoredBytes::Wrong
}
Ok(None) => StoredBytes::Absent,
Err(e) => {
debug!("Could not read {} to check it: {e}", hex::encode(address));
self.mark_suspect(address);
StoredBytes::Unreadable
}
}
}
pub async fn repair(&self, address: &XorName, content: &[u8]) -> Result<()> {
if content.len() > MAX_CHUNK_SIZE {
return Err(Error::Storage(format!(
"Refusing to repair {} with {} bytes, over the {MAX_CHUNK_SIZE} byte \
maximum",
hex::encode(address),
content.len()
)));
}
let computed = crate::client::compute_address(content);
if computed != *address {
return Err(Error::Storage(format!(
"Refusing to repair {} with content that hashes to {}",
hex::encode(address),
hex::encode(computed)
)));
}
let reservation = self.capacity.reserve(content.len() as u64)?;
let shard = self.chunks_dir.join(shard_name(address));
let final_path = shard.join(hex::encode(address));
let temp_path = shard.join(self.next_temp_name());
let payload = content.to_vec();
let lanes = Arc::clone(&self.write_lanes);
let index = Arc::clone(&self.index);
let shards_present = Arc::clone(&self.shards_present);
let chunks_dir = self.chunks_dir.clone();
let lane = shard_index(address);
let key = *address;
let in_flight = self.begin_write(address);
let lease = Arc::clone(&self.lock);
let capacity = Arc::clone(&self.capacity);
let suspect = Arc::clone(&self.suspect);
let known_wrong = Arc::clone(&self.known_wrong);
self.blocking_tracker
.spawn_blocking(move || -> Result<()> {
let _in_flight = in_flight;
let _lease = lease;
let _reservation = reservation;
let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
ensure_shard_dir(&chunks_dir, &shard, lane, &shards_present)?;
write_and_replace(&temp_path, &final_path, &payload, &shard)?;
index.write().insert(key);
suspect.write().remove(&key);
known_wrong.write().remove(&key);
capacity.invalidate();
Ok(())
})
.await
.map_err(|e| Error::Storage(format!("Chunk store repair task failed: {e}")))??;
debug!("Repaired chunk {}", hex::encode(address));
Ok(())
}
pub async fn get(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
let Some(content) = self.read_file(address).await? else {
trace!("Chunk {} not found", hex::encode(address));
return Ok(None);
};
if self.config.verify_on_read {
let computed = crate::client::compute_address(&content);
if computed != *address {
{
let mut stats = self.stats.write();
stats.verification_failures = stats.verification_failures.saturating_add(1);
}
warn!(
"Chunk verification failed: expected {}, computed {}",
hex::encode(address),
hex::encode(computed)
);
self.mark_known_wrong(address);
self.quarantine_corrupt(address).await;
return Err(Error::Storage(format!(
"Chunk verification failed for {}",
hex::encode(address)
)));
}
}
if self.config.verify_on_read {
self.clear_known_wrong(address);
}
let len = content.len() as u64;
{
let mut stats = self.stats.write();
stats.chunks_retrieved = stats.chunks_retrieved.saturating_add(1);
stats.bytes_retrieved = stats.bytes_retrieved.saturating_add(len);
}
debug!("Retrieved chunk {} ({len} bytes)", hex::encode(address));
Ok(Some(content))
}
pub async fn get_raw(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
self.read_file(address).await
}
pub fn exists(&self, address: &XorName) -> Result<bool> {
if self.is_unservable(address) {
return Ok(false);
}
Ok(self.is_indexed(address))
}
#[must_use]
fn is_unservable(&self, address: &XorName) -> bool {
self.suspect.read().contains(address) || self.known_wrong.read().contains(address)
}
#[must_use]
pub fn is_indexed(&self, address: &XorName) -> bool {
self.index.read().contains(address)
}
pub async fn delete(&self, address: &XorName) -> Result<bool> {
let path = self.chunk_path(address);
let lanes = Arc::clone(&self.write_lanes);
let index = Arc::clone(&self.index);
let lane = shard_index(address);
let key = *address;
let lease = Arc::clone(&self.lock);
let (existed, freed) = self
.blocking_tracker
.spawn_blocking(move || -> Result<(bool, u64)> {
let _lease = lease;
let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
let len = std::fs::metadata(&path).map_or(0, |m| m.len());
let removed = match std::fs::remove_file(&path) {
Ok(()) => {
if let Some(shard) = path.parent() {
fsync_dir_best_effort(shard);
}
true
}
Err(e) if e.kind() == ErrorKind::NotFound => false,
Err(e) => {
return Err(Error::Storage(format!(
"Failed to delete chunk file {}: {e}",
path.display()
)))
}
};
let was_indexed = index.write().remove(&key);
Ok((removed || was_indexed, if removed { len } else { 0 }))
})
.await
.map_err(|e| Error::Storage(format!("Chunk store delete task failed: {e}")))??;
if freed > 0 {
self.capacity.record_removed(freed);
debug!("Deleted chunk {}", hex::encode(address));
}
Ok(existed)
}
#[allow(unknown_lints)]
#[allow(clippy::unused_async, clippy::unused_async_trait_impl)]
pub async fn all_keys(&self) -> Result<Vec<XorName>> {
let mut unservable: HashSet<XorName> = self.suspect.read().clone();
unservable.extend(self.known_wrong.read().iter().copied());
let keys = self.index.read().clone();
if unservable.is_empty() {
return Ok(keys.into_iter().collect());
}
Ok(keys
.into_iter()
.filter(|key| !unservable.contains(key))
.collect())
}
fn mark_suspect(&self, address: &XorName) {
if self.suspect.write().insert(*address) {
self.note_health_changed();
warn!(
"Chunk {} is on disk but could not be read; this node stops answering for \
it until a read succeeds",
hex::encode(address)
);
}
}
#[must_use]
pub fn health_generation(&self) -> u64 {
self.health.load(std::sync::atomic::Ordering::Acquire)
}
fn note_health_changed(&self) {
self.health
.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
}
pub fn note_known_wrong(&self, address: &XorName) {
self.mark_known_wrong(address);
}
fn mark_known_wrong(&self, address: &XorName) {
if self.known_wrong.write().insert(*address) {
self.note_health_changed();
warn!(
"Chunk {} does not match its name; this node stops answering for it until \
it is repaired or removed",
hex::encode(address)
);
}
}
pub fn note_bytes_proven_good(&self, address: &XorName) {
self.clear_known_wrong(address);
self.clear_suspect(address);
}
fn clear_known_wrong(&self, address: &XorName) {
self.known_wrong.write().remove(address);
}
fn clear_suspect(&self, address: &XorName) {
if !self.suspect.read().contains(address) {
return;
}
if self.suspect.write().remove(address) {
info!(
"Chunk {} could be read again; this node answers for it once more",
hex::encode(address)
);
}
}
pub fn current_chunks(&self) -> Result<u64> {
Ok(self.index.read().len() as u64)
}
#[must_use]
pub fn stats(&self) -> StorageStats {
let mut stats = self.stats.read().clone();
stats.current_chunks = self.index.read().len() as u64;
stats
}
#[must_use]
pub fn root_dir(&self) -> &Path {
&self.config.root_dir
}
#[must_use]
pub fn chunks_dir(&self) -> &Path {
&self.chunks_dir
}
pub fn check_capacity(&self) -> Result<()> {
self.capacity.check(0)
}
#[must_use]
pub fn capacity_verdict(&self) -> crate::storage::CapacityVerdict {
match self.capacity.measure_available() {
Some(available) if available < self.capacity.reserve => {
crate::storage::CapacityVerdict::Full
}
Some(_) => crate::storage::CapacityVerdict::Writable,
None => crate::storage::CapacityVerdict::Unknown,
}
}
pub(crate) fn release_bytes(&self, len: u64) {
self.capacity.record_removed(len);
}
pub fn check_capacity_for(&self, bytes: u64) -> Result<()> {
self.capacity.check(bytes)
}
pub(crate) fn reserve_bytes(&self, bytes: u64) -> Result<Reservation> {
self.capacity.reserve(bytes)
}
#[cfg(test)]
pub(crate) fn capacity_counters(&self) -> (u64, u64) {
self.capacity.counters()
}
#[cfg(test)]
pub(crate) fn capacity_charge_for(bytes: u64) -> u64 {
CapacityGuard::charge(bytes)
}
pub fn invalidate_capacity_cache(&self) {
self.capacity.invalidate();
}
#[cfg(any(test, feature = "test-utils"))]
#[must_use]
pub fn test_put_gate(&self) -> Arc<parking_lot::RwLock<()>> {
Arc::clone(&self.test_put_gate)
}
#[cfg(test)]
pub(crate) fn test_write_lane(
&self,
address: &XorName,
) -> (Arc<Vec<parking_lot::Mutex<()>>>, usize) {
(Arc::clone(&self.write_lanes), shard_index(address))
}
fn begin_write(&self, address: &XorName) -> WriteInFlight {
*self.writing.lock().entry(*address).or_insert(0) += 1;
WriteInFlight {
writing: Arc::clone(&self.writing),
finished: Arc::clone(&self.write_finished),
address: *address,
}
}
pub async fn wait_for_write(&self, address: &XorName) {
loop {
let waiting = self.write_finished.notified();
if !self.writing.lock().contains_key(address) {
return;
}
waiting.await;
}
}
#[cfg(any(test, feature = "test-utils"))]
#[must_use]
pub(crate) fn tasks_in_flight(&self) -> usize {
self.blocking_tracker.len()
}
pub async fn wait_idle(&self) {
self.blocking_tracker.close();
self.blocking_tracker.wait().await;
self.blocking_tracker.reopen();
}
pub(crate) fn chunk_path(&self, address: &XorName) -> PathBuf {
self.chunks_dir
.join(shard_name(address))
.join(hex::encode(address))
}
fn next_temp_name(&self) -> String {
let seq = self.temp_seq.fetch_add(1, Ordering::Relaxed);
format!(
"{TEMP_PREFIX}{}.{:08x}.{seq}",
std::process::id(),
self.nonce
)
}
async fn read_file(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
let path = self.chunk_path(address);
let read = self
.blocking_tracker
.spawn_blocking(move || -> Result<Option<Vec<u8>>> {
match open_regular(&path) {
Ok(Some(f)) => read_bounded(f, &path).map(Some),
Ok(None) => Ok(None),
Err(e) => Err(e),
}
})
.await
.map_err(|e| Error::Storage(format!("Chunk store read task failed: {e}")))?;
let read = match read {
Ok(read) => {
self.clear_suspect(address);
read
}
Err(e) => {
self.mark_suspect(address);
return Err(e);
}
};
if read.is_none() && self.forget_if_absent(address).await {
warn!(
"Chunk {} is indexed but its file is missing; dropped from the index so \
replication can repair it",
hex::encode(address)
);
}
Ok(read)
}
async fn forget_if_absent(&self, address: &XorName) -> bool {
self.clear_suspect(address);
let path = self.chunk_path(address);
let lanes = Arc::clone(&self.write_lanes);
let index = Arc::clone(&self.index);
let lane = shard_index(address);
let key = *address;
let health = Arc::clone(&self.health);
self.blocking_tracker
.spawn_blocking(move || {
let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
if path.exists() {
return false;
}
let forgotten = index.write().remove(&key);
if forgotten {
health.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
}
forgotten
})
.await
.unwrap_or(false)
}
async fn quarantine_corrupt(&self, address: &XorName) {
let path = self.chunk_path(address);
let lanes = Arc::clone(&self.write_lanes);
let index = Arc::clone(&self.index);
let lane = shard_index(address);
let key = *address;
let health = Arc::clone(&self.health);
let lease = Arc::clone(&self.lock);
let outcome =
self.blocking_tracker
.spawn_blocking(move || -> std::io::Result<bool> {
let _lease = lease;
let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
let buf = match open_regular(&path) {
Ok(Some(f)) => read_bounded(f, &path)
.map_err(|e| std::io::Error::other(e.to_string()))?,
Ok(None) => {
index.write().remove(&key);
health.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
return Ok(true);
}
Err(e) => return Err(std::io::Error::other(e.to_string())),
};
if crate::client::compute_address(&buf) == key {
return Ok(false);
}
std::fs::remove_file(&path)?;
if let Some(shard) = path.parent() {
fsync_dir_best_effort(shard);
}
index.write().remove(&key);
health.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
Ok(true)
})
.await;
match outcome {
Ok(Ok(true)) => {
self.clear_known_wrong(address);
self.clear_suspect(address);
warn!(
"Removed corrupt chunk file {}; replication will repair it",
hex::encode(address)
);
}
Ok(Ok(false)) => {
self.clear_known_wrong(address);
self.clear_suspect(address);
debug!(
"Chunk {} verified on re-read; leaving it in place",
hex::encode(address)
);
}
Ok(Err(e)) => {
self.mark_suspect(address);
warn!(
"Corrupt chunk {} could not be removed: {e}. It stays on disk, and \
this node stops answering for it.",
hex::encode(address)
);
}
Err(e) => {
self.mark_suspect(address);
warn!("Corrupt-chunk removal task failed: {e}");
}
}
}
}
fn ensure_shard_dir(
chunks_dir: &Path,
dir: &Path,
shard: usize,
present: &parking_lot::Mutex<[bool; SHARD_COUNT]>,
) -> Result<()> {
if present.lock().get(shard).copied().unwrap_or(false) {
return Ok(());
}
std::fs::create_dir_all(dir).map_err(|e| {
Error::Storage(format!(
"Failed to create shard directory {}: {e}",
dir.display()
))
})?;
fsync_dir(chunks_dir).map_err(|e| {
Error::Storage(format!(
"Created shard directory {} but could not flush {}: {e}. Not marking the shard \
usable, because a directory that is not durable cannot hold a chunk that is.",
dir.display(),
chunks_dir.display()
))
})?;
if let Some(slot) = present.lock().get_mut(shard) {
*slot = true;
}
Ok(())
}
fn shard_index(address: &XorName) -> usize {
address.last().copied().unwrap_or(0) as usize
}
fn shard_name(address: &XorName) -> String {
format!("{:02x}", shard_index(address))
}
fn is_hex_any_case(s: &str) -> bool {
!s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit())
}
fn quarantine_entry(path: &Path) {
let aside = path.with_extension("not-a-chunk");
match std::fs::rename(path, &aside) {
Ok(()) => warn!(
"Chunk store: moved {} aside to {}; a name that differs from a chunk name only \
by case collides with it on Windows and macOS",
path.display(),
aside.display()
),
Err(e) => warn!(
"Chunk store: {} collides with a chunk name by case folding and could not be \
moved aside: {e}. Rename or delete it.",
path.display()
),
}
}
fn is_lower_hex(s: &str) -> bool {
!s.is_empty() && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
fn decode_chunk_name(name: &str) -> Option<XorName> {
if name.len() != CHUNK_NAME_LEN || !is_lower_hex(name) {
return None;
}
let bytes = hex::decode(name).ok()?;
XorName::try_from(bytes.as_slice()).ok()
}
pub fn fsync_path(path: &Path) -> std::io::Result<()> {
fsync_dir(path)
}
#[cfg(unix)]
fn fsync_dir_best_effort(path: &Path) {
if let Err(e) = fsync_dir(path) {
debug!("Directory flush of {} failed: {e}", path.display());
}
}
#[cfg(unix)]
fn fsync_dir(path: &Path) -> std::io::Result<()> {
File::open(path)?.sync_all()
}
#[cfg(not(unix))]
#[allow(clippy::unnecessary_wraps)]
fn fsync_dir(_path: &Path) -> std::io::Result<()> {
Ok(())
}
#[cfg(not(unix))]
fn fsync_dir_best_effort(_path: &Path) {}
#[cfg(windows)]
fn check_path_budget(chunks_dir: &Path) {
let absolute = if chunks_dir.is_absolute() {
chunks_dir.to_path_buf()
} else {
std::env::current_dir()
.map_or_else(|_| chunks_dir.to_path_buf(), |cwd| cwd.join(chunks_dir))
};
let deepest = absolute.as_os_str().len() + 1 + 2 + 1 + CHUNK_NAME_LEN;
if deepest > WINDOWS_PATH_WARN_LEN {
warn!(
"Chunk file paths will be {deepest} characters, close to the {} character \
Windows limit. Move the node root closer to the drive letter if writes start \
failing.",
WINDOWS_PATH_WARN_LEN
);
}
}
#[cfg(not(windows))]
fn check_path_budget(_chunks_dir: &Path) {}
pub fn write_file_durably(path: &Path, bytes: &[u8]) -> Result<()> {
write_file_atomic(path, bytes)
}
fn is_marker_temp_name(name: &str) -> bool {
let Some(rest) = name.strip_prefix(TEMP_PREFIX) else {
return false;
};
let Some(rest) = rest.strip_suffix(".marker") else {
return false;
};
let mut parts = rest.split('.');
let (Some(pid), Some(nonce), None) = (parts.next(), parts.next(), parts.next()) else {
return false;
};
!pid.is_empty()
&& pid.bytes().all(|b| b.is_ascii_digit())
&& nonce.len() == 8
&& nonce.bytes().all(|b| b.is_ascii_hexdigit())
}
pub(crate) fn sweep_marker_temps(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name) = name.to_str() else {
continue;
};
if !is_marker_temp_name(name) {
continue;
}
if !entry.file_type().is_ok_and(|kind| kind.is_file()) {
continue;
}
match std::fs::remove_file(entry.path()) {
Ok(()) => debug!(
"Swept a leftover marker temporary {}",
entry.path().display()
),
Err(e) => debug!("Could not sweep {}: {e}", entry.path().display()),
}
}
}
fn write_file_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
let Some(dir) = path.parent() else {
return Err(Error::Storage(format!(
"Refusing to write {} — it has no parent directory",
path.display()
)));
};
let temp = dir.join(format!(
"{TEMP_PREFIX}{}.{:08x}.marker",
std::process::id(),
rand::random::<u32>()
));
write_temp(&temp, bytes)?;
rename_with_retry(&temp, path).map_err(|e| {
let _ = std::fs::remove_file(&temp);
Error::Storage(format!("Failed to publish {}: {e}", path.display()))
})?;
fsync_dir_best_effort(dir);
Ok(())
}
fn read_or_write_layout(chunks_dir: &Path) -> Result<StoreLayout> {
let path = chunks_dir.join(LAYOUT_FILE_NAME);
match read_small_file(&path) {
Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| {
Error::Storage(format!(
"Chunk store layout marker {} is unreadable: {e}. Refusing to open rather \
than guess the layout.",
path.display()
))
}),
Err(e) if e.kind() == ErrorKind::NotFound => {
if store_has_entries(chunks_dir) {
warn!(
"Chunk store at {} has data but no layout marker. Adopting it under \
the current scheme, which is the only one this build implements. If \
it was written by a build with a different layout its chunks will \
appear to be missing.",
chunks_dir.display()
);
}
let layout = StoreLayout::default();
let bytes = serde_json::to_vec_pretty(&layout)
.map_err(|e| Error::Storage(format!("Failed to encode chunk store layout: {e}")))?;
write_file_atomic(&path, &bytes)?;
debug!("Wrote chunk store layout marker to {}", path.display());
Ok(layout)
}
Err(e) => Err(Error::Storage(format!(
"Failed to read chunk store layout marker {}: {e}",
path.display()
))),
}
}
fn store_has_entries(chunks_dir: &Path) -> bool {
let Ok(entries) = std::fs::read_dir(chunks_dir) else {
return false;
};
entries.filter_map(std::result::Result::ok).any(|e| {
e.file_name()
.to_str()
.is_some_and(|n| n.len() == 2 && is_lower_hex(n))
})
}
const MAX_MARKER_BYTES: u64 = 64 * 1024;
pub fn read_small_file(path: &Path) -> std::io::Result<Vec<u8>> {
let file = File::open(path)?;
let mut bytes = Vec::new();
let read = file.take(MAX_MARKER_BYTES + 1).read_to_end(&mut bytes)?;
if read as u64 > MAX_MARKER_BYTES {
return Err(std::io::Error::other(format!(
"{} is larger than the {MAX_MARKER_BYTES} byte limit for a marker file",
path.display()
)));
}
Ok(bytes)
}
fn acquire_store_lock(chunks_dir: &Path) -> Result<Arc<File>> {
let path = chunks_dir.join(LOCK_FILE_NAME);
let file = match OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(&path)
{
Ok(f) => f,
Err(e) => {
return Err(Error::Storage(format!(
"Could not create the chunk store lock {}: {e}. Refusing to start: \
without it this node cannot tell whether another is using the same data \
directory. Fix the permissions on that path, or remove a stale lock file \
left by a different user.",
path.display()
)))
}
};
match file.try_lock_exclusive() {
Ok(()) => Ok(Arc::new(file)),
Err(e) => Err(Error::Storage(format!(
"Another process already has the chunk store at {} open ({e}). Two nodes \
cannot share one data directory: each keeps its own index and they would \
disagree about what is stored. Stop the other node first.",
chunks_dir.display()
))),
}
}
struct ScanResult {
keys: Vec<XorName>,
shards_present: [bool; SHARD_COUNT],
swept_temps: usize,
skipped: usize,
}
fn scan_store(chunks_dir: &Path) -> Result<ScanResult> {
let mut result = ScanResult {
keys: Vec::new(),
shards_present: [false; SHARD_COUNT],
swept_temps: 0,
skipped: 0,
};
let top = std::fs::read_dir(chunks_dir).map_err(|e| {
Error::Storage(format!(
"Failed to enumerate chunk store {}: {e}",
chunks_dir.display()
))
})?;
for entry in top {
let entry = entry.map_err(|e| {
Error::Storage(format!(
"Failed to read an entry of {}: {e}",
chunks_dir.display()
))
})?;
let name = entry.file_name();
let Some(name) = name.to_str() else {
result.skipped = result.skipped.saturating_add(1);
continue;
};
if name == LAYOUT_FILE_NAME || name == LOCK_FILE_NAME {
continue;
}
if name.starts_with(TEMP_PREFIX) {
if sweep_temp(&entry.path()) {
result.swept_temps = result.swept_temps.saturating_add(1);
}
continue;
}
if name.len() != 2 || !is_lower_hex(name) {
warn!(
"Chunk store: ignoring unexpected entry {name} in {}",
chunks_dir.display()
);
result.skipped = result.skipped.saturating_add(1);
continue;
}
let Ok(shard) = u8::from_str_radix(name, 16) else {
result.skipped = result.skipped.saturating_add(1);
continue;
};
scan_shard(&entry.path(), shard, &mut result)?;
}
result.keys.sort_unstable();
result.keys.dedup();
Ok(result)
}
fn scan_shard(dir: &Path, shard: u8, result: &mut ScanResult) -> Result<()> {
let entries = match std::fs::read_dir(dir) {
Ok(e) => e,
Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) => {
warn!(
"Chunk store: {} is not a shard directory ({e}); ignoring it",
dir.display()
);
result.skipped = result.skipped.saturating_add(1);
return Ok(());
}
Err(e) => {
return Err(Error::Storage(format!(
"Failed to enumerate shard {}: {e}. Refusing to open with an incomplete \
key set.",
dir.display()
)))
}
};
if let Some(slot) = result.shards_present.get_mut(shard as usize) {
*slot = true;
}
for entry in entries {
let entry =
entry.map_err(|e| Error::Storage(format!("Failed to read {}: {e}", dir.display())))?;
let name = entry.file_name();
let Some(name) = name.to_str() else {
result.skipped = result.skipped.saturating_add(1);
continue;
};
if name.starts_with(TEMP_PREFIX) {
if sweep_temp(&entry.path()) {
result.swept_temps = result.swept_temps.saturating_add(1);
}
continue;
}
let Some(key) = decode_chunk_name(name) else {
if name.len() == CHUNK_NAME_LEN && is_hex_any_case(name) {
quarantine_entry(&entry.path());
} else {
warn!(
"Chunk store: ignoring non-chunk entry {name} in {}",
dir.display()
);
}
result.skipped = result.skipped.saturating_add(1);
continue;
};
match entry.file_type() {
Ok(kind) if kind.is_file() => {}
Ok(_) => {
warn!(
"Chunk store: {name} in {} is not a regular file; ignoring it",
dir.display()
);
result.skipped = result.skipped.saturating_add(1);
continue;
}
Err(e) => {
return Err(Error::Storage(format!(
"Could not tell what {name} in {} is: {e}. Refusing to publish an \
index that may be missing chunks.",
dir.display()
)));
}
}
if shard_index(&key) != shard as usize {
warn!(
"Chunk store: {name} is filed under shard {shard:02x} but belongs in {:02x}; \
ignoring it. Move it or delete it.",
shard_index(&key)
);
result.skipped = result.skipped.saturating_add(1);
continue;
}
result.keys.push(key);
}
Ok(())
}
fn sweep_temp(path: &Path) -> bool {
match std::fs::remove_file(path) {
Ok(()) => {
debug!("Removed orphaned temporary file {}", path.display());
true
}
Err(e) => {
debug!("Could not remove {}: {e}", path.display());
false
}
}
}
fn open_regular(path: &Path) -> Result<Option<File>> {
#[cfg(unix)]
let opened = {
use std::os::unix::fs::OpenOptionsExt;
OpenOptions::new()
.read(true)
.custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW)
.open(path)
};
#[cfg(not(unix))]
let opened = OpenOptions::new().read(true).open(path);
let file = match opened {
Ok(f) => f,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
Err(e) => {
return Err(Error::Storage(format!(
"Failed to open chunk file {}: {e}",
path.display()
)))
}
};
let is_regular = file.metadata().is_ok_and(|m| m.file_type().is_file());
if !is_regular {
return Err(Error::Storage(format!(
"{} is not a regular file; refusing to read it as a chunk",
path.display()
)));
}
Ok(Some(file))
}
fn read_bounded(file: File, path: &Path) -> Result<Vec<u8>> {
let ceiling = MAX_CHUNK_SIZE as u64;
let expected = file.metadata().map_or(0, |m| m.len()).min(ceiling);
let mut buf = Vec::with_capacity(usize::try_from(expected).unwrap_or(0));
let read = file.take(ceiling + 1).read_to_end(&mut buf).map_err(|e| {
Error::Storage(format!("Failed to read chunk file {}: {e}", path.display()))
})?;
if read as u64 > ceiling {
return Err(Error::Storage(format!(
"Chunk file {} is larger than the {ceiling} byte maximum; refusing to read it",
path.display()
)));
}
Ok(buf)
}
fn is_windows_sharing_violation(e: &std::io::Error) -> bool {
matches!(e.raw_os_error(), Some(5 | 32 | 33))
}
pub(crate) fn rename_with_retry(temp_path: &Path, final_path: &Path) -> std::io::Result<()> {
let mut last = match std::fs::rename(temp_path, final_path) {
Ok(()) => return Ok(()),
Err(e) => e,
};
if !cfg!(windows) || !is_windows_sharing_violation(&last) {
return Err(last);
}
for attempt in 1..=RENAME_RETRY_ATTEMPTS {
std::thread::sleep(RENAME_RETRY_BACKOFF * attempt);
match std::fs::rename(temp_path, final_path) {
Ok(()) => return Ok(()),
Err(e) => last = e,
}
}
Err(last)
}
fn write_and_replace(
temp_path: &Path,
final_path: &Path,
payload: &[u8],
shard: &Path,
) -> Result<()> {
#[cfg(unix)]
{
write_temp(temp_path, payload)?;
if let Err(e) = rename_with_retry(temp_path, final_path) {
let _ = std::fs::remove_file(temp_path);
return Err(Error::Storage(format!(
"Failed to replace chunk {}: {e}",
final_path.display()
)));
}
fsync_dir(shard).map_err(|e| {
Error::Storage(format!(
"Replaced {} but could not flush {}: {e}. Not reporting the repair as \
done, because a rewrite that is not durable must not authorise deleting \
the copy it was rewritten from.",
final_path.display(),
shard.display()
))
})?;
Ok(())
}
#[cfg(not(unix))]
{
let _ = temp_path;
let _ = shard;
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.open(final_path)
.map_err(|e| {
Error::Storage(format!(
"Failed to open {} for replacement: {e}",
final_path.display()
))
})?;
file.write_all(payload).map_err(|e| {
Error::Storage(format!("Failed to rewrite {}: {e}", final_path.display()))
})?;
file.sync_all().map_err(|e| {
Error::Storage(format!(
"Rewrote {} but could not flush it: {e}. Not reporting the repair as \
done, because a rewrite that is not durable must not authorise deleting \
the copy it was rewritten from.",
final_path.display()
))
})?;
Ok(())
}
}
fn write_temp(temp_path: &Path, payload: &[u8]) -> Result<()> {
let mut f = OpenOptions::new()
.write(true)
.create_new(true)
.open(temp_path)
.map_err(|e| {
Error::Storage(format!(
"Failed to create temporary file {}: {e}",
temp_path.display()
))
})?;
if let Err(e) = f.write_all(payload) {
let _ = std::fs::remove_file(temp_path);
return Err(Error::Storage(format!(
"Failed to write {}: {e}",
temp_path.display()
)));
}
if let Err(e) = f.sync_all() {
let _ = std::fs::remove_file(temp_path);
return Err(Error::Storage(format!(
"Failed to flush {}: {e}",
temp_path.display()
)));
}
Ok(())
}
#[cfg(unix)]
fn publish(
temp_path: &Path,
final_path: &Path,
payload: &[u8],
shard: &Path,
) -> std::result::Result<PutOutcome, PublishFailed> {
publish_via_rename(temp_path, final_path, payload, shard)
.map_err(PublishFailed::nothing_written)
}
#[cfg(not(unix))]
fn publish(
temp_path: &Path,
final_path: &Path,
payload: &[u8],
shard: &Path,
) -> std::result::Result<PutOutcome, PublishFailed> {
let _ = temp_path;
let _ = shard;
publish_in_place(final_path, payload)
}
#[cfg(not(unix))]
fn publish_in_place(
final_path: &Path,
payload: &[u8],
) -> std::result::Result<PutOutcome, PublishFailed> {
#[cfg(any(test, feature = "test-utils"))]
halt_here_if_asked(HALT_BEFORE_PUBLISH, final_path);
let mut file = match OpenOptions::new()
.write(true)
.create_new(true)
.open(final_path)
{
Ok(f) => f,
Err(e) if e.kind() == ErrorKind::AlreadyExists => return Ok(PutOutcome::Duplicate),
Err(e) => {
return Err(PublishFailed::nothing_written(Error::Storage(format!(
"Failed to create chunk {}: {e}",
final_path.display()
))));
}
};
if let Err(e) = file.write_all(payload) {
drop(file);
let left_behind = std::fs::remove_file(final_path).is_err();
return Err(PublishFailed {
error: Error::Storage(format!("Failed to write {}: {e}", final_path.display())),
left_behind,
});
}
if let Err(e) = file.sync_all() {
drop(file);
let left_behind = std::fs::remove_file(final_path).is_err();
return Err(PublishFailed {
error: Error::Storage(format!("Failed to flush {}: {e}", final_path.display())),
left_behind,
});
}
Ok(PutOutcome::New)
}
#[cfg(unix)]
fn publish_via_rename(
temp_path: &Path,
final_path: &Path,
payload: &[u8],
_shard: &Path,
) -> Result<PutOutcome> {
let outcome = if final_path.exists() {
PutOutcome::Duplicate
} else {
write_temp(temp_path, payload)?;
#[cfg(any(test, feature = "test-utils"))]
halt_here_if_asked(HALT_BEFORE_PUBLISH, temp_path);
match rename_with_retry(temp_path, final_path) {
Ok(()) => PutOutcome::New,
Err(e) => {
let _ = std::fs::remove_file(temp_path);
if !final_path.exists() {
return Err(Error::Storage(format!(
"Failed to publish chunk {}: {e}",
final_path.display()
)));
}
PutOutcome::Duplicate
}
}
};
Ok(outcome)
}
struct PublishFailed {
error: Error,
left_behind: bool,
}
impl PublishFailed {
fn nothing_written(error: Error) -> Self {
Self {
error,
left_behind: false,
}
}
}
#[cfg(unix)]
fn flush_publication(final_path: &Path, shard: &Path) -> Result<()> {
fsync_dir(shard).map_err(|e| {
Error::Storage(format!(
"Published {} but could not flush {}: {e}. Not reporting this chunk as stored, \
because a copy that is not durable must not authorise deleting another.",
final_path.display(),
shard.display()
))
})
}
#[cfg(not(unix))]
fn flush_publication(_final_path: &Path, _shard: &Path) -> Result<()> {
Ok(())
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
use std::collections::HashSet;
#[cfg(unix)]
#[test]
fn flushing_a_directory_that_is_not_there_reports_the_failure() {
let dir = TempDir::new().expect("temp dir");
assert!(fsync_dir(dir.path()).is_ok());
assert!(fsync_dir(&dir.path().join("no-such-shard")).is_err());
}
#[cfg(unix)]
#[test]
fn a_publish_whose_directory_flush_fails_is_not_reported_as_stored() {
let dir = TempDir::new().expect("temp dir");
let temp_path = dir.path().join("chunk.tmp");
let final_path = dir.path().join("chunk");
let unflushable = dir.path().join("shard-that-does-not-exist");
let placed = publish_via_rename(&temp_path, &final_path, b"payload", &unflushable);
assert!(
placed.is_ok(),
"the bytes must be placed before this can be about the flush: {:?}",
placed.err()
);
let outcome = flush_publication(&final_path, &unflushable);
assert!(
outcome.is_err(),
"an unflushed publication must not be reported as stored"
);
assert!(
!temp_path.exists(),
"the temp file must not be left behind either way"
);
}
use tempfile::TempDir;
async fn test_store() -> (FileStore, TempDir) {
let dir = TempDir::new().expect("temp dir");
let store = FileStore::new(FileStoreConfig {
root_dir: dir.path().to_path_buf(),
verify_on_read: true,
disk_reserve: 0,
})
.await
.expect("open store");
(store, dir)
}
async fn reopen(dir: &TempDir) -> FileStore {
FileStore::new(FileStoreConfig {
root_dir: dir.path().to_path_buf(),
verify_on_read: true,
disk_reserve: 0,
})
.await
.expect("reopen store")
}
#[cfg(unix)]
#[tokio::test]
async fn an_ordinary_read_decides_whether_the_node_answers_for_a_chunk() {
use std::os::unix::fs::PermissionsExt;
let (store, dir) = test_store().await;
let (addr, content) = addressed("read-decides");
store.put(&addr, &content).await.expect("put");
let path = store.chunk_path(&addr);
let mut perms = std::fs::metadata(&path).expect("meta").permissions();
perms.set_mode(0o000);
std::fs::set_permissions(&path, perms).expect("chmod");
assert!(store.get(&addr).await.is_err(), "the read must fail");
assert!(
!store.exists(&addr).expect("exists"),
"and a plain read that failed must stop the node answering for it"
);
let mut perms = std::fs::metadata(&path).expect("meta").permissions();
perms.set_mode(0o600);
std::fs::set_permissions(&path, perms).expect("chmod back");
assert_eq!(
store.get(&addr).await.expect("get").expect("present"),
content
);
assert!(
store.exists(&addr).expect("exists"),
"and a plain read that worked must start it answering again"
);
drop(dir);
}
#[tokio::test]
async fn waiting_for_a_key_waits_for_every_write_of_it() {
let (store, dir) = test_store().await;
let store = Arc::new(store);
let (addr, content) = addressed("two-writers");
let first = store.begin_write(&addr);
let second = store.begin_write(&addr);
let waiting = {
let store = Arc::clone(&store);
tokio::spawn(async move { store.wait_for_write(&addr).await })
};
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(!waiting.is_finished());
drop(first);
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(
!waiting.is_finished(),
"one write finishing does not mean the key is free"
);
drop(second);
waiting
.await
.expect("the wait ends once both have finished");
store.put(&addr, &content).await.expect("put");
assert!(store.exists(&addr).expect("exists"));
drop(dir);
}
#[cfg(unix)]
#[tokio::test]
async fn a_chunk_that_cannot_be_read_is_kept_but_not_claimed() {
use std::os::unix::fs::PermissionsExt;
let (store, dir) = test_store().await;
let (addr, content) = addressed("unreadable-for-now");
store.put(&addr, &content).await.expect("put");
assert!(store.exists(&addr).expect("exists"));
let path = store.chunk_path(&addr);
let mut perms = std::fs::metadata(&path).expect("meta").permissions();
perms.set_mode(0o000);
std::fs::set_permissions(&path, perms).expect("chmod");
assert!(
store.put(&addr, &content).await.is_err(),
"an unreadable chunk must not be reported as stored"
);
assert!(path.exists(), "and the file must be left alone");
assert!(
!store.exists(&addr).expect("exists"),
"but the node must stop claiming it"
);
assert!(!store.all_keys().await.expect("keys").contains(&addr));
let mut perms = std::fs::metadata(&path).expect("meta").permissions();
perms.set_mode(0o600);
std::fs::set_permissions(&path, perms).expect("chmod back");
assert!(!store.put(&addr, &content).await.expect("put again"));
assert!(store.exists(&addr).expect("exists"));
assert!(store.all_keys().await.expect("keys").contains(&addr));
drop(dir);
}
fn addressed(seed: &str) -> (XorName, Vec<u8>) {
let content = format!("chunk-content-{seed}").into_bytes();
(crate::client::compute_address(&content), content)
}
#[tokio::test]
async fn put_then_get_returns_the_same_bytes() {
let (store, _dir) = test_store().await;
let (addr, content) = addressed("a");
assert!(store.put(&addr, &content).await.expect("put"));
let got = store.get(&addr).await.expect("get").expect("present");
assert_eq!(got, content);
}
#[tokio::test]
async fn a_second_put_of_the_same_chunk_reports_not_new() {
let (store, _dir) = test_store().await;
let (addr, content) = addressed("b");
assert!(store.put(&addr, &content).await.expect("first put"));
assert!(!store.put(&addr, &content).await.expect("second put"));
assert_eq!(store.current_chunks().expect("count"), 1);
assert_eq!(store.stats().duplicates, 1);
}
#[tokio::test]
async fn get_of_an_unknown_address_is_none() {
let (store, _dir) = test_store().await;
let (addr, _) = addressed("missing");
assert!(store.get(&addr).await.expect("get").is_none());
}
#[tokio::test]
async fn exists_tracks_the_store() {
let (store, _dir) = test_store().await;
let (addr, content) = addressed("c");
assert!(!store.exists(&addr).expect("exists"));
store.put(&addr, &content).await.expect("put");
assert!(store.exists(&addr).expect("exists"));
store.delete(&addr).await.expect("delete");
assert!(!store.exists(&addr).expect("exists"));
}
#[tokio::test]
async fn delete_unlinks_the_file_and_returns_the_space() {
let (store, _dir) = test_store().await;
let (addr, content) = addressed("d");
store.put(&addr, &content).await.expect("put");
let path = store.chunk_path(&addr);
assert!(path.exists(), "the chunk file should be on disk");
assert!(store.delete(&addr).await.expect("delete"));
assert!(!path.exists(), "delete must actually unlink the file");
assert_eq!(store.current_chunks().expect("count"), 0);
assert!(!store.delete(&addr).await.expect("second delete"));
}
#[tokio::test]
async fn content_that_does_not_hash_to_its_address_is_rejected() {
let (store, _dir) = test_store().await;
let (addr, _) = addressed("e");
let err = store
.put(&addr, b"different content")
.await
.expect_err("must reject");
assert!(
format!("{err}").contains("Content address mismatch"),
"unexpected error: {err}"
);
assert_eq!(store.current_chunks().expect("count"), 0);
}
#[tokio::test]
async fn a_chunk_is_filed_under_the_last_two_hex_characters_of_its_address() {
let (store, dir) = test_store().await;
let (addr, content) = addressed("f");
store.put(&addr, &content).await.expect("put");
let name = hex::encode(addr);
let expected_shard = name
.get(name.len() - 2..)
.expect("64-character name")
.to_string();
let path = dir
.path()
.join(CHUNKS_DIR_NAME)
.join(&expected_shard)
.join(&name);
assert!(path.exists(), "expected the chunk at {}", path.display());
}
#[tokio::test]
async fn the_index_is_rebuilt_from_the_filesystem_on_restart() {
let (store, dir) = test_store().await;
let mut written = Vec::new();
for i in 0..64 {
let (addr, content) = addressed(&format!("restart-{i}"));
store.put(&addr, &content).await.expect("put");
written.push(addr);
}
drop(store);
let reopened = reopen(&dir).await;
assert_eq!(reopened.current_chunks().expect("count"), 64);
for addr in &written {
assert!(reopened.exists(addr).expect("exists"), "lost a key");
}
}
#[tokio::test]
async fn all_keys_is_sorted_ascending() {
let (store, dir) = test_store().await;
for i in 0..128 {
let (addr, content) = addressed(&format!("sorted-{i}"));
store.put(&addr, &content).await.expect("put");
}
let keys = store.all_keys().await.expect("all_keys");
let mut sorted = keys.clone();
sorted.sort_unstable();
assert_eq!(keys, sorted, "all_keys() must be ordered");
drop(store);
let reopened = reopen(&dir).await;
assert_eq!(reopened.all_keys().await.expect("all_keys"), keys);
}
#[tokio::test]
async fn get_raw_skips_verification() {
let (store, _dir) = test_store().await;
let (addr, content) = addressed("raw");
store.put(&addr, &content).await.expect("put");
std::fs::write(store.chunk_path(&addr), b"tampered").expect("tamper");
let raw = store.get_raw(&addr).await.expect("get_raw").expect("bytes");
assert_eq!(raw, b"tampered");
}
#[tokio::test]
async fn reads_allocate_exactly_the_chunk() {
let (store, _dir) = test_store().await;
let content: Vec<u8> = (0..=u8::MAX).cycle().take(MAX_CHUNK_SIZE).collect();
let addr = crate::client::compute_address(&content);
store.put(&addr, &content).await.expect("put");
let verified = store.get(&addr).await.expect("get").expect("bytes");
assert_eq!(verified, content);
assert_eq!(verified.capacity(), MAX_CHUNK_SIZE);
let raw = store.get_raw(&addr).await.expect("get_raw").expect("bytes");
assert_eq!(raw.capacity(), MAX_CHUNK_SIZE);
}
#[cfg(unix)]
#[tokio::test]
#[allow(clippy::await_holding_lock)]
async fn a_cancelled_put_does_not_admit_a_key_whose_bytes_were_never_read() {
let dir = TempDir::new().expect("temp dir");
let store = Arc::new(reopen(&dir).await);
let content = b"the bytes that belong under this name".to_vec();
let addr = crate::client::compute_address(&content);
let shard = dir
.path()
.join(CHUNKS_DIR_NAME)
.join(format!("{:02x}", addr[31]));
std::fs::create_dir_all(&shard).expect("mkdir");
let path = shard.join(hex::encode(addr));
let name = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())
.expect("a path with no interior nul");
#[allow(clippy::undocumented_unsafe_blocks, unsafe_code)]
let made = unsafe { libc::mkfifo(name.as_ptr(), 0o644) };
assert_eq!(made, 0, "could not make the fifo this test needs");
let gate = store.test_put_gate();
let held = gate.write();
let put = {
let store = Arc::clone(&store);
let content = content.clone();
tokio::spawn(async move { store.put(&addr, &content).await })
};
let deadline = std::time::Instant::now() + Duration::from_secs(30);
while store.tasks_in_flight() == 0 {
assert!(
std::time::Instant::now() < deadline,
"the put never reached the closure, so there was nothing to cancel"
);
tokio::time::sleep(Duration::from_millis(5)).await;
}
put.abort();
let _ = put.await;
drop(held);
store.wait_idle().await;
assert!(
!store.is_indexed(&addr),
"a cancelled put admitted {} on bytes nothing read; the fifo under that name \
would then be advertised, committed to, and audited against",
hex::encode(addr)
);
assert!(
!store.exists(&addr).unwrap_or(true),
"and the node must not claim it either"
);
}
#[tokio::test]
async fn a_leftover_marker_temporary_is_swept_and_its_neighbours_are_not() {
let dir = TempDir::new().expect("temp dir");
let root = dir.path();
let leftover = root.join(format!("{TEMP_PREFIX}1234.abcdef01.marker"));
std::fs::write(&leftover, b"an interrupted marker write").expect("plant");
let keep = [
root.join("migration-state.json"),
root.join(format!("{TEMP_PREFIX}1234.abcdef01.chunk")),
root.join("notes.txt"),
root.join(format!("{TEMP_PREFIX}operator-notes.marker")),
root.join(format!("{TEMP_PREFIX}1234.nothex01.marker")),
root.join(format!("{TEMP_PREFIX}1234.abcdef0.marker")),
root.join(format!("{TEMP_PREFIX}1234.abcdef01.extra.marker")),
];
for path in &keep {
std::fs::write(path, b"keep me").expect("plant");
}
let store = reopen(&dir).await;
drop(store);
assert!(
!leftover.exists(),
"the leftover marker temporary is still in the node root"
);
for path in &keep {
assert!(
path.exists(),
"{} was swept and should not have been",
path.display()
);
}
}
#[tokio::test]
async fn a_corrupt_chunk_is_removed_so_replication_can_repair_it() {
let (store, _dir) = test_store().await;
let (addr, content) = addressed("corrupt");
store.put(&addr, &content).await.expect("put");
std::fs::write(store.chunk_path(&addr), b"tampered").expect("tamper");
let err = store.get(&addr).await.expect_err("verification must fail");
assert!(format!("{err}").contains("verification failed"), "{err}");
assert!(!store.chunk_path(&addr).exists(), "corrupt file must go");
assert!(!store.exists(&addr).expect("exists"));
assert!(
!store.all_keys().await.expect("all_keys").contains(&addr),
"a corrupt chunk must stop being advertised"
);
assert_eq!(store.stats().verification_failures, 1);
}
#[tokio::test]
async fn a_file_removed_underneath_the_store_drops_out_of_the_index() {
let (store, _dir) = test_store().await;
let (addr, content) = addressed("vanished");
store.put(&addr, &content).await.expect("put");
std::fs::remove_file(store.chunk_path(&addr)).expect("remove behind our back");
assert!(store.get(&addr).await.expect("get").is_none());
assert!(!store.exists(&addr).expect("exists"));
assert_eq!(store.current_chunks().expect("count"), 0);
}
#[tokio::test]
async fn interrupted_writes_are_swept_at_startup() {
let (store, dir) = test_store().await;
let (addr, content) = addressed("sweep");
store.put(&addr, &content).await.expect("put");
let shard = store
.chunk_path(&addr)
.parent()
.expect("shard")
.to_path_buf();
drop(store);
let orphan = shard.join(format!("{TEMP_PREFIX}999.7"));
std::fs::write(&orphan, b"half a chunk").expect("write orphan");
let stray_root = dir
.path()
.join(CHUNKS_DIR_NAME)
.join(format!("{TEMP_PREFIX}999.8"));
std::fs::write(&stray_root, b"half a marker").expect("write stray");
let reopened = reopen(&dir).await;
assert!(!orphan.exists(), "an interrupted write must not survive");
assert!(!stray_root.exists(), "nor one at the store root");
assert_eq!(reopened.current_chunks().expect("count"), 1);
}
#[tokio::test]
async fn concurrent_writers_of_one_address_store_it_exactly_once() {
let (store, _dir) = test_store().await;
let store = Arc::new(store);
let (addr, content) = addressed("racing");
let mut tasks = Vec::new();
for _ in 0..16 {
let store = Arc::clone(&store);
let content = content.clone();
tasks.push(tokio::spawn(
async move { store.put(&addr, &content).await },
));
}
let mut new_count = 0;
for task in tasks {
if task.await.expect("join").expect("put") {
new_count += 1;
}
}
assert_eq!(new_count, 1, "exactly one writer may report a new chunk");
assert_eq!(store.current_chunks().expect("count"), 1);
assert_eq!(
store.get(&addr).await.expect("get").expect("present"),
content
);
}
#[tokio::test]
async fn names_that_are_not_lowercase_hex_are_ignored_by_the_scan() {
let (store, dir) = test_store().await;
let (addr, content) = addressed("scan");
store.put(&addr, &content).await.expect("put");
let shard = store
.chunk_path(&addr)
.parent()
.expect("shard")
.to_path_buf();
drop(store);
let upper = shard.join(hex::encode_upper(addressed("upper").0));
std::fs::write(&upper, b"x").expect("write upper");
std::fs::write(shard.join("not-a-chunk"), b"x").expect("write junk");
std::fs::write(shard.join("deadbeef"), b"x").expect("write short");
let reopened = reopen(&dir).await;
assert_eq!(reopened.current_chunks().expect("count"), 1);
}
#[tokio::test]
async fn a_chunk_filed_in_the_wrong_shard_is_not_indexed() {
let (store, dir) = test_store().await;
let (addr, content) = addressed("misfiled");
store.put(&addr, &content).await.expect("put");
drop(store);
let correct = dir
.path()
.join(CHUNKS_DIR_NAME)
.join(shard_name(&addr))
.join(hex::encode(addr));
let wrong_shard_index = (shard_index(&addr) + 1) % SHARD_COUNT;
let wrong_dir = dir
.path()
.join(CHUNKS_DIR_NAME)
.join(format!("{wrong_shard_index:02x}"));
std::fs::create_dir_all(&wrong_dir).expect("mkdir");
std::fs::rename(&correct, wrong_dir.join(hex::encode(addr))).expect("misfile");
let reopened = reopen(&dir).await;
assert_eq!(reopened.current_chunks().expect("count"), 0);
assert!(!reopened.exists(&addr).expect("exists"));
}
#[tokio::test]
async fn the_layout_marker_is_written_once_and_checked_on_reopen() {
let (store, dir) = test_store().await;
drop(store);
let marker = dir.path().join(CHUNKS_DIR_NAME).join(LAYOUT_FILE_NAME);
let layout: StoreLayout =
serde_json::from_slice(&std::fs::read(&marker).expect("read marker"))
.expect("parse marker");
assert_eq!(layout, StoreLayout::default());
let future = StoreLayout {
schema: LAYOUT_SCHEMA + 1,
..StoreLayout::default()
};
std::fs::write(&marker, serde_json::to_vec(&future).expect("encode")).expect("write");
let err = FileStore::new(FileStoreConfig {
root_dir: dir.path().to_path_buf(),
verify_on_read: true,
disk_reserve: 0,
})
.await
.expect_err("must refuse a newer layout");
assert!(format!("{err}").contains("newer than this build"), "{err}");
}
#[tokio::test]
async fn an_unknown_shard_scheme_is_refused() {
let (store, dir) = test_store().await;
drop(store);
let marker = dir.path().join(CHUNKS_DIR_NAME).join(LAYOUT_FILE_NAME);
let other = StoreLayout {
scheme: "prefix-hex".to_string(),
..StoreLayout::default()
};
std::fs::write(&marker, serde_json::to_vec(&other).expect("encode")).expect("write");
let err = FileStore::new(FileStoreConfig {
root_dir: dir.path().to_path_buf(),
verify_on_read: true,
disk_reserve: 0,
})
.await
.expect_err("must refuse an unknown scheme");
assert!(format!("{err}").contains("shard scheme"), "{err}");
}
#[tokio::test]
async fn writes_are_refused_when_the_disk_reserve_cannot_be_met() {
let dir = TempDir::new().expect("temp dir");
let store = FileStore::new(FileStoreConfig {
root_dir: dir.path().to_path_buf(),
verify_on_read: true,
disk_reserve: u64::MAX / 2,
})
.await
.expect("open store");
let (addr, content) = addressed("full");
let err = store.put(&addr, &content).await.expect_err("must refuse");
assert!(
format!("{err}").contains("Insufficient disk space"),
"{err}"
);
assert!(store.check_capacity().is_err());
}
#[tokio::test]
async fn capacity_is_size_aware() {
const MARGIN: u64 = 512 * 1024 * 1024;
let dir = TempDir::new().expect("temp dir");
let available = fs2::available_space(dir.path()).expect("free space");
let store = FileStore::new(FileStoreConfig {
root_dir: dir.path().to_path_buf(),
verify_on_read: true,
disk_reserve: available.saturating_sub(MARGIN),
})
.await
.expect("open store");
assert!(store.check_capacity_for(1024).is_ok());
assert!(store.check_capacity_for(4 * MARGIN).is_err());
}
#[test]
fn suffix_shards_stay_uniform_for_a_close_group_of_keys() {
let mut prefix_dirs = HashSet::new();
let mut suffix_dirs = HashSet::new();
for i in 0u32..4096 {
let mut key = [0u8; XORNAME_LEN];
let tail = crate::client::compute_address(&i.to_le_bytes());
key.copy_from_slice(&tail);
if let Some(b) = key.first_mut() {
*b = 0xab;
}
if let Some(b) = key.get_mut(1) {
*b = 0xcd;
}
if let Some(b) = key.get_mut(2) {
*b &= 0x0f;
}
prefix_dirs.insert(key.first().copied().unwrap_or(0));
suffix_dirs.insert(shard_index(&key));
}
assert_eq!(
prefix_dirs.len(),
1,
"prefix sharding collapses for a node's own holdings"
);
assert!(
suffix_dirs.len() > 250,
"suffix sharding must stay uniform, got {} of 256 directories",
suffix_dirs.len()
);
}
#[test]
fn no_chunk_filename_can_spell_a_reserved_windows_device_name() {
for reserved in ["con", "prn", "aux", "nul", "com1", "com9", "lpt1", "lpt9"] {
assert!(
!is_lower_hex(reserved),
"{reserved} must not be a valid chunk or shard name"
);
}
}
#[test]
fn only_full_length_lowercase_hex_decodes_to_an_address() {
assert!(decode_chunk_name(&hex::encode([0xabu8; XORNAME_LEN])).is_some());
assert!(decode_chunk_name(&hex::encode_upper([0xabu8; XORNAME_LEN])).is_none());
assert!(decode_chunk_name("deadbeef").is_none());
assert!(decode_chunk_name("").is_none());
assert!(decode_chunk_name(&"g".repeat(CHUNK_NAME_LEN)).is_none());
}
#[tokio::test]
async fn repair_replaces_bad_bytes_without_the_file_ever_being_absent() {
let (store, _dir) = test_store().await;
let (addr, content) = addressed("repairable");
store.put(&addr, &content).await.expect("put");
let path = store.chunk_path(&addr);
std::fs::write(&path, b"rotted").expect("corrupt");
store.repair(&addr, &content).await.expect("repair");
assert_eq!(
store.get(&addr).await.expect("get").expect("present"),
content
);
assert!(store.exists(&addr).expect("exists"));
}
#[tokio::test]
async fn a_repair_with_the_wrong_bytes_is_refused_and_changes_nothing() {
let (store, _dir) = test_store().await;
let (addr, content) = addressed("guarded");
store.put(&addr, &content).await.expect("put");
let path = store.chunk_path(&addr);
let err = store
.repair(&addr, b"not this chunk")
.await
.expect_err("must refuse");
assert!(format!("{err}").contains("Refusing to repair"), "{err}");
assert!(
path.exists(),
"the existing file must survive a refused repair"
);
assert_eq!(
store.get(&addr).await.expect("get").expect("present"),
content
);
}
#[tokio::test]
async fn a_chunk_can_be_deleted_and_stored_again() {
let (store, _dir) = test_store().await;
let (addr, content) = addressed("cycle");
assert!(store.put(&addr, &content).await.expect("put"));
assert!(store.delete(&addr).await.expect("delete"));
assert!(
store.put(&addr, &content).await.expect("re-put"),
"a re-stored chunk is new again"
);
assert_eq!(
store.get(&addr).await.expect("get").expect("present"),
content
);
}
fn plant(chunks_dir: &Path, key: &XorName) {
let dir = chunks_dir.join(shard_name(key));
std::fs::create_dir_all(&dir).expect("mkdir");
std::fs::write(dir.join(hex::encode(key)), key).expect("plant");
}
#[tokio::test]
async fn a_populated_and_churned_store_scans_correctly_at_scale() {
const PLANTED: u32 = 20_000;
const CHURN: u32 = 1_000;
let dir = TempDir::new().expect("temp dir");
let chunks_dir = dir.path().join(CHUNKS_DIR_NAME);
std::fs::create_dir_all(&chunks_dir).expect("mkdir");
let mut expected: Vec<XorName> = Vec::new();
for i in 0..PLANTED {
let key = crate::client::compute_address(&i.to_le_bytes());
plant(&chunks_dir, &key);
expected.push(key);
}
for i in 0..CHURN {
let key = crate::client::compute_address(&i.to_le_bytes());
std::fs::remove_file(chunks_dir.join(shard_name(&key)).join(hex::encode(key)))
.expect("churn out");
let replacement = crate::client::compute_address(&(PLANTED + i).to_le_bytes());
plant(&chunks_dir, &replacement);
}
expected.retain(|k| chunks_dir.join(shard_name(k)).join(hex::encode(k)).exists());
for i in 0..CHURN {
expected.push(crate::client::compute_address(&(PLANTED + i).to_le_bytes()));
}
expected.sort_unstable();
expected.dedup();
let started = std::time::Instant::now();
let store = reopen(&dir).await;
let scan = started.elapsed();
assert_eq!(
store.current_chunks().expect("count"),
expected.len() as u64
);
assert_eq!(store.all_keys().await.expect("all_keys"), expected);
let occupied = std::fs::read_dir(&chunks_dir)
.expect("read store root")
.filter_map(std::result::Result::ok)
.filter(|e| e.file_name().to_str().is_some_and(|n| n.len() == 2))
.count();
assert_eq!(occupied, SHARD_COUNT, "the suffix must reach every shard");
println!(
"scan of {} keys across {SHARD_COUNT} shards took {scan:?}",
expected.len()
);
}
#[tokio::test]
async fn wait_idle_returns_once_writes_have_drained() {
let (store, _dir) = test_store().await;
let store = Arc::new(store);
for i in 0..32 {
let store = Arc::clone(&store);
let (addr, content) = addressed(&format!("drain-{i}"));
tokio::spawn(async move { store.put(&addr, &content).await });
}
store.wait_idle().await;
let (addr, content) = addressed("after-drain");
assert!(store.put(&addr, &content).await.expect("put after drain"));
}
}