Skip to main content

tilo_content/
dir.rs

1//! Content in a local directory, sharded one level on the first two hex digits of the address so
2//! no directory accumulates everything the machine has ever stored.
3
4use std::collections::{BTreeMap, BTreeSet, HashMap};
5use std::io::{Read, Write};
6use std::path::{Path, PathBuf};
7use std::sync::Mutex;
8#[cfg(test)]
9use std::sync::atomic::AtomicUsize;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::time::SystemTime;
12
13use crate::memory::check_new_item;
14use crate::{
15    Collected, ContentBackend, ContentError, ContentLimits, ContentReader, ContentState, Stored,
16    Verifying, valid_hash,
17};
18
19/// Content in `<root>/<hash[..2]>/<hash>`. Writes stream into a temporary file beside the target
20/// and are renamed into place once complete and hashed, so a reader never sees a partial item
21/// under an address that promises whole content; reads verify as they stream.
22///
23/// A durable store (the default) publishes an item behind a barrier: the item is flushed before
24/// the rename, and the shard directory after it — and the root too when the write created the
25/// shard — so an item `put` has returned for survives a power loss under its address.
26/// [`DirBackend::regenerable`] stores skip every flush.
27///
28/// [`ContentBackend::has`] hashes a file once per file identity (inode, length, timestamps) per
29/// backend: a file replaced or rewritten since is verified again. The quota total is kept in
30/// memory between writes and rescanned only when another writer has written since (every writer
31/// bumps `<root>/.content-store.gen` under the root lock), or before refusing a write, since files
32/// removed behind the store's back make the kept total over-count.
33pub struct DirBackend {
34    root: PathBuf,
35    /// Directories consulted, read-only, when content is not under `root` — where an earlier
36    /// layout kept it.
37    also_read: Vec<PathBuf>,
38    limits: ContentLimits,
39    durable: bool,
40    state: Mutex<Index>,
41    verified: Mutex<HashMap<PathBuf, FileSig>>,
42    #[cfg(test)]
43    probes: Probes,
44}
45
46#[derive(Default)]
47struct Index {
48    bytes: usize,
49    entries: BTreeMap<String, usize>,
50    /// The root's write generation this index was last brought up to date with, or `None` when it
51    /// must be rescanned before it is trusted.
52    generation: Option<u64>,
53}
54
55/// How many items of one batch are received at once: each waits on the disk,
56/// so a folder of small files flushes a few in parallel.
57const PUT_MANY_WORKERS: usize = 8;
58
59/// Bumped under the root write lock by every writer after it changes the store, so a backend
60/// whose kept index names the current generation knows nobody else has written since. Read and
61/// written only under that lock; a missing or unreadable file means "rescan".
62const GENERATION_FILE: &str = ".content-store.gen";
63
64/// What identifies one version of a file without reading it: a file renamed over the item, or
65/// rewritten in place, differs in at least one of these.
66#[derive(Clone, Copy, PartialEq, Eq, Debug)]
67struct FileSig {
68    len: u64,
69    modified: Option<SystemTime>,
70    #[cfg(unix)]
71    dev: u64,
72    #[cfg(unix)]
73    ino: u64,
74    #[cfg(unix)]
75    ctime_ns: i128,
76}
77
78impl FileSig {
79    fn of(meta: &std::fs::Metadata) -> Self {
80        #[cfg(unix)]
81        use std::os::unix::fs::MetadataExt;
82        Self {
83            len: meta.len(),
84            modified: meta.modified().ok(),
85            #[cfg(unix)]
86            dev: meta.dev(),
87            #[cfg(unix)]
88            ino: meta.ino(),
89            #[cfg(unix)]
90            ctime_ns: i128::from(meta.ctime())
91                .saturating_mul(1_000_000_000)
92                .saturating_add(i128::from(meta.ctime_nsec())),
93        }
94    }
95}
96
97#[cfg(test)]
98#[derive(Default)]
99pub(crate) struct Probes {
100    pub(crate) dir_syncs: AtomicUsize,
101    pub(crate) file_syncs: AtomicUsize,
102}
103
104/// Held around every mutation and the quota scan before it. Separate from [`Index`]: two backends
105/// (or two processes) on one root must not each admit a write from a stale local total.
106type RootWriteLock = advisory_lock::FileLock;
107
108static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
109
110impl DirBackend {
111    pub fn new(root: impl Into<PathBuf>) -> Self {
112        Self::with_limits(root, ContentLimits::default())
113    }
114
115    pub fn with_limits(root: impl Into<PathBuf>, limits: ContentLimits) -> Self {
116        Self {
117            root: root.into(),
118            also_read: Vec::new(),
119            limits,
120            durable: true,
121            state: Mutex::new(Index::default()),
122            verified: Mutex::new(HashMap::new()),
123            #[cfg(test)]
124            probes: Probes::default(),
125        }
126    }
127
128    #[cfg(test)]
129    pub(crate) fn probes(&self) -> &Probes {
130        &self.probes
131    }
132
133    #[must_use]
134    pub fn reading_also(mut self, dir: impl Into<PathBuf>) -> Self {
135        self.also_read.push(dir.into());
136        self
137    }
138
139    /// Hold content its owner can recreate, such as a cache: writes are not flushed to disk, so
140    /// a write never waits for the filesystem to flush every other dirty page first. After a
141    /// crash an item may be missing or torn; reads verify it against its address, so a torn item
142    /// reads as absent.
143    #[must_use]
144    pub fn regenerable(mut self) -> Self {
145        self.durable = false;
146        self
147    }
148
149    pub fn root(&self) -> &Path {
150        &self.root
151    }
152
153    pub fn limits(&self) -> ContentLimits {
154        self.limits
155    }
156
157    fn path_in(root: &Path, hash: &str) -> Option<PathBuf> {
158        // The address reaches here from documents and peers: anything but plain hex is refused, since
159        // a key with a separator in it would otherwise name a file outside the store.
160        if !valid_hash(hash) {
161            return None;
162        }
163        let hash = hash.to_ascii_lowercase();
164        let prefix = hash.get(..2)?;
165        Some(root.join(prefix).join(&hash))
166    }
167
168    fn existing(&self, hash: &str) -> Option<PathBuf> {
169        std::iter::once(&self.root)
170            .chain(&self.also_read)
171            .filter_map(|root| Self::path_in(root, hash))
172            .find(|path| path.is_file())
173    }
174
175    fn lock_root_for_write(&self) -> Result<RootWriteLock, ContentError> {
176        std::fs::create_dir_all(&self.root)?;
177        Ok(advisory_lock::FileLock::open(
178            &self.root.join(".content-store.lock"),
179            advisory_lock::LockMode::Exclusive,
180        )?)
181    }
182
183    /// The root's write generation. Call only under the root write lock.
184    fn read_generation(&self) -> Option<u64> {
185        std::fs::read_to_string(self.root.join(GENERATION_FILE))
186            .ok()?
187            .trim()
188            .parse()
189            .ok()
190    }
191
192    /// Record that this backend changed the store, whose generation was `current` (as read under
193    /// the root write lock still held), and bring `index` — already updated for the change — to
194    /// the new generation.
195    fn bump_generation(&self, index: &mut Index, current: Option<u64>) {
196        let next = current.map_or_else(
197            || tilo_clock::try_unix_now_ns().unwrap_or(1),
198            |current| current.wrapping_add(1),
199        );
200        let path = self.root.join(GENERATION_FILE);
201        if std::fs::write(&path, next.to_string()).is_ok() {
202            index.generation = Some(next);
203        } else {
204            // Without a readable generation every backend rescans, which stays correct. A
205            // generation left as it was would let another backend trust an index missing this
206            // write.
207            let _ = std::fs::remove_file(&path);
208            index.generation = None;
209        }
210    }
211
212    /// Bring `index` up to date for a write: trust it when it names the root's current
213    /// generation, otherwise rescan. Call only under the root write lock. Returns the generation
214    /// read and whether a scan ran.
215    fn refresh_index(&self, index: &mut Index) -> Result<(Option<u64>, bool), ContentError> {
216        let current = self.read_generation();
217        if current.is_some() && index.generation == current {
218            return Ok((current, false));
219        }
220        self.load_index(index)?;
221        index.generation = current;
222        Ok((current, true))
223    }
224
225    /// Flush `dir`'s entries to disk, for a durable store; a regenerable one never waits on it.
226    fn sync_dir(&self, dir: &Path) -> Result<(), ContentError> {
227        if !self.durable {
228            return Ok(());
229        }
230        #[cfg(test)]
231        self.probes.dir_syncs.fetch_add(1, Ordering::Relaxed);
232        tilo_files::native::atomic::sync_directory(dir)?;
233        Ok(())
234    }
235
236    fn load_index(&self, index: &mut Index) -> Result<(), ContentError> {
237        index.generation = None;
238        let shards = match std::fs::read_dir(&self.root) {
239            Ok(shards) => shards,
240            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
241            Err(error) => return Err(error.into()),
242        };
243        let mut scanned = 0usize;
244        let mut entries = BTreeMap::new();
245        let mut total = 0usize;
246        let mut count = || -> Result<(), ContentError> {
247            scanned = scanned.saturating_add(1);
248            if scanned > self.limits.max_scan_entries {
249                return Err(ContentError::ScanLimitExceeded {
250                    limit: self.limits.max_scan_entries,
251                });
252            }
253            Ok(())
254        };
255        for shard in shards {
256            let shard = shard?;
257            count()?;
258            let name = shard.file_name();
259            let Some(prefix) = name.to_str() else {
260                continue;
261            };
262            if prefix.len() != 2
263                || !prefix.bytes().all(|b| b.is_ascii_hexdigit())
264                || !shard.file_type().is_ok_and(|kind| kind.is_dir())
265            {
266                continue;
267            }
268            for item in std::fs::read_dir(shard.path())? {
269                let item = item?;
270                count()?;
271                let name = item.file_name();
272                let Some(hash) = name.to_str().filter(|hash| {
273                    valid_hash(hash) && !hash.bytes().any(|b| b.is_ascii_uppercase())
274                }) else {
275                    continue;
276                };
277                if !item.file_type().is_ok_and(|kind| kind.is_file()) {
278                    continue;
279                }
280                let len = usize::try_from(item.metadata()?.len()).map_err(|_| {
281                    ContentError::TotalQuotaExceeded {
282                        attempted: usize::MAX,
283                        limit: self.limits.max_total_bytes,
284                    }
285                })?;
286                total = total.saturating_add(len);
287                entries.insert(hash.to_string(), len);
288            }
289        }
290        index.bytes = total;
291        index.entries = entries;
292        Ok(())
293    }
294
295    /// Receive `reader` into a temporary file under the root, answering its
296    /// temporary file, hash and length. `sync` flushes it before answering.
297    fn receive(
298        &self,
299        reader: &mut dyn Read,
300        sync: bool,
301    ) -> Result<(PathBuf, String, usize), ContentError> {
302        std::fs::create_dir_all(&self.root)?;
303        let serial = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
304        let tmp = self
305            .root
306            .join(format!(".incoming-{}-{serial}", std::process::id()));
307        let result = (|| -> Result<(String, usize), ContentError> {
308            let mut file = std::fs::OpenOptions::new()
309                .write(true)
310                .create_new(true)
311                .open(&tmp)?;
312            let mut hasher = blake3::Hasher::new();
313            let mut len = 0usize;
314            let mut buf = vec![0u8; 64 * 1024];
315            loop {
316                let n = match reader.read(&mut buf) {
317                    Ok(0) => break,
318                    Ok(n) => n,
319                    Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
320                    Err(error) => return Err(error.into()),
321                };
322                len = len.saturating_add(n);
323                if len > self.limits.max_item_bytes {
324                    return Err(ContentError::ItemTooLarge {
325                        actual: len,
326                        limit: self.limits.max_item_bytes,
327                    });
328                }
329                let chunk = buf.get(..n).unwrap_or_default();
330                hasher.update(chunk);
331                file.write_all(chunk)?;
332            }
333            if sync {
334                file.sync_all()?;
335                #[cfg(test)]
336                self.probes.file_syncs.fetch_add(1, Ordering::Relaxed);
337            }
338            Ok((hasher.finalize().to_hex().to_string(), len))
339        })();
340        match result {
341            Ok((hash, len)) => Ok((tmp, hash, len)),
342            Err(error) => {
343                let _ = std::fs::remove_file(&tmp);
344                Err(error)
345            }
346        }
347    }
348
349    /// Whether `path` holds the content at `hash`, no larger than `limit`. A file this backend has
350    /// already found intact, and which has not changed since, is not read again.
351    fn intact(&self, path: &Path, hash: &str, limit: usize) -> bool {
352        let Ok(meta) = std::fs::metadata(path) else {
353            return false;
354        };
355        if !meta.is_file()
356            || usize::try_from(meta.len())
357                .ok()
358                .is_none_or(|len| len > limit)
359        {
360            return false;
361        }
362        if self
363            .verified
364            .lock()
365            .is_ok_and(|verified| verified.get(path) == Some(&FileSig::of(&meta)))
366        {
367            return true;
368        }
369        let Ok(file) = std::fs::File::open(path) else {
370            return false;
371        };
372        // The identity of the file actually hashed, taken before reading it: a change while it
373        // is read leaves a different identity behind, which the next call verifies afresh.
374        let Ok(meta) = file.metadata() else {
375            return false;
376        };
377        if usize::try_from(meta.len())
378            .ok()
379            .is_none_or(|len| len > limit)
380        {
381            return false;
382        }
383        let mut reader = Verifying::new(file, hash);
384        if std::io::copy(&mut reader, &mut std::io::sink()).is_err() {
385            return false;
386        }
387        self.remember_intact(path.to_path_buf(), FileSig::of(&meta));
388        true
389    }
390
391    fn remember_intact(&self, path: PathBuf, sig: FileSig) {
392        if let Ok(mut verified) = self.verified.lock() {
393            verified.insert(path, sig);
394        }
395    }
396
397    fn forget_intact(&self, path: &Path) {
398        if let Ok(mut verified) = self.verified.lock() {
399            verified.remove(path);
400        }
401    }
402
403    /// Admit the received items of [`ContentBackend::put_many`] under one
404    /// lock: the index, its generation and each shard directory are written
405    /// once for the whole set instead of once per item.
406    fn admit_received(
407        &self,
408        outcomes: &mut [Option<Result<Stored, ContentError>>],
409        received: &[(usize, PathBuf, String, usize)],
410        flush: BatchFlush,
411    ) -> Result<(), String> {
412        if received.is_empty() {
413            return Ok(());
414        }
415        let mut index = self
416            .state
417            .lock()
418            .map_err(|_| "content store lock poisoned".to_string())?;
419        let root_lock = self
420            .lock_root_for_write()
421            .map_err(|error| error.to_string())?;
422        let (generation, _) = self
423            .refresh_index(&mut index)
424            .map_err(|error| error.to_string())?;
425        let mut shards: BTreeSet<PathBuf> = BTreeSet::new();
426        let mut wrote = false;
427        for (at, tmp, hash, len) in received {
428            let stored = Stored {
429                hash: hash.clone(),
430                len: u64::try_from(*len).unwrap_or(u64::MAX),
431            };
432            let Some(path) = Self::path_in(&self.root, hash) else {
433                let _ = std::fs::remove_file(tmp);
434                note(outcomes, *at, Err(ContentError::InvalidHash(hash.clone())));
435                continue;
436            };
437            if self.intact(&path, hash, usize::MAX) {
438                self.written_now(&path);
439                let _ = std::fs::remove_file(tmp);
440                note(outcomes, *at, Ok(stored));
441                continue;
442            }
443            if check_admission(&self.limits, &index, hash, *len).is_err() {
444                // Files removed behind the store's back make the kept total
445                // over-count: look again before refusing on it.
446                self.load_index(&mut index)
447                    .map_err(|error| error.to_string())?;
448                if let Err(refusal) = check_admission(&self.limits, &index, hash, *len) {
449                    let _ = std::fs::remove_file(tmp);
450                    note(outcomes, *at, Err(refusal));
451                    continue;
452                }
453            }
454            let Some(dir) = path.parent() else {
455                let _ = std::fs::remove_file(tmp);
456                note(outcomes, *at, Err(ContentError::InvalidHash(hash.clone())));
457                continue;
458            };
459            let dir = dir.to_path_buf();
460            if !dir.is_dir() {
461                if let Err(error) = std::fs::create_dir_all(&dir) {
462                    let _ = std::fs::remove_file(tmp);
463                    note(outcomes, *at, Err(error.into()));
464                    continue;
465                }
466                if flush == BatchFlush::Each {
467                    let _ = self.sync_dir(&self.root);
468                }
469            }
470            if let Err(error) = std::fs::rename(tmp, &path) {
471                let _ = std::fs::remove_file(tmp);
472                note(outcomes, *at, Err(error.into()));
473                continue;
474            }
475            if let Some(old_len) = index.entries.insert(hash.clone(), *len) {
476                index.bytes = index.bytes.saturating_sub(old_len);
477            }
478            index.bytes = index.bytes.saturating_add(*len);
479            match std::fs::metadata(&path) {
480                Ok(meta) => self.remember_intact(path.clone(), FileSig::of(&meta)),
481                Err(_) => self.forget_intact(&path),
482            }
483            shards.insert(dir);
484            wrote = true;
485            note(outcomes, *at, Ok(stored));
486        }
487        if wrote {
488            self.bump_generation(&mut index, generation);
489        }
490        drop(root_lock);
491        drop(index);
492        if flush == BatchFlush::Each {
493            self.sync_dirs(shards);
494        }
495        Ok(())
496    }
497
498    /// Flush everything this backend wrote under its root in one call: the batch's items, their
499    /// renames and their directories. The platform flushes a filesystem; elsewhere the items are
500    /// flushed one by one instead ([`BatchFlush::Each`]).
501    #[cfg(target_os = "linux")]
502    fn sync_store(&self) -> Result<(), String> {
503        let root = std::fs::File::open(&self.root).map_err(|error| error.to_string())?;
504        rustix::fs::syncfs(&root).map_err(|error| error.to_string())?;
505        Ok(())
506    }
507
508    /// Flush the shard directories a batch was renamed into: a few at once,
509    /// since a batch spreads over many shards and each flush waits on the
510    /// disk.
511    fn sync_dirs(&self, shards: BTreeSet<PathBuf>) {
512        if shards.is_empty() || !self.durable {
513            return;
514        }
515        let dirs: Vec<PathBuf> = shards.into_iter().collect();
516        let workers = PUT_MANY_WORKERS.min(dirs.len()).max(1);
517        let per = dirs.len().div_ceil(workers);
518        std::thread::scope(|scope| {
519            for chunk in dirs.chunks(per) {
520                scope.spawn(move || {
521                    for dir in chunk {
522                        let _ = self.sync_dir(dir);
523                    }
524                });
525            }
526        });
527    }
528}
529
530/// How a batch's items reach the disk.
531#[derive(Clone, Copy, PartialEq, Eq)]
532enum BatchFlush {
533    /// The platform flushes the whole filesystem once, after the batch is in place: nothing is
534    /// answered for until it returns.
535    Whole,
536    /// Each item is flushed as it is received, and the directories it was renamed into after:
537    /// where the platform has no filesystem-wide flush.
538    Each,
539    /// Every flush is skipped: a store that can regenerate what it keeps.
540    None,
541}
542
543/// Mark item `index`'s outcome of [`DirBackend::admit_received`].
544fn note(
545    outcomes: &mut [Option<Result<Stored, ContentError>>],
546    index: usize,
547    result: Result<Stored, ContentError>,
548) {
549    if let Some(outcome) = outcomes.get_mut(index) {
550        *outcome = Some(result);
551    }
552}
553
554impl ContentBackend for DirBackend {
555    fn put(&self, reader: &mut dyn Read, _mime: &str) -> Result<Stored, ContentError> {
556        // Flushed only once it is known to be new: content already here, as most of what a
557        // warm start puts again, costs no wait on the disk.
558        let (tmp, hash, len) = self.receive(reader, false)?;
559        let stored = Stored {
560            hash: hash.clone(),
561            len: u64::try_from(len).unwrap_or(u64::MAX),
562        };
563        let admit = || -> Result<(), ContentError> {
564            let Some(path) = Self::path_in(&self.root, &hash) else {
565                return Err(ContentError::InvalidHash(hash.clone()));
566            };
567            let mut index = self
568                .state
569                .lock()
570                .map_err(|_| ContentError::Io("content store lock poisoned".into()))?;
571            let root_lock = self.lock_root_for_write()?;
572            // Content already here is an idempotent write, even if a later configuration tightened
573            // the limits. It is written again just now, as far as a collection that spares what
574            // was written lately goes: under the lock, so no collection removes it in between.
575            if self.intact(&path, &hash, usize::MAX) {
576                self.written_now(&path);
577                return Ok(());
578            }
579            // The kept index is authority for admission only while no other writer has written
580            // since: every writer bumps the generation under this lock.
581            let (generation, scanned) = self.refresh_index(&mut index)?;
582            if let Err(refusal) = check_admission(&self.limits, &index, &hash, len) {
583                // Files removed behind the store's back make a kept total over-count: look again
584                // before refusing on it.
585                if scanned {
586                    return Err(refusal);
587                }
588                self.load_index(&mut index)?;
589                index.generation = generation;
590                check_admission(&self.limits, &index, &hash, len)?;
591            }
592            let Some(dir) = path.parent() else {
593                return Err(ContentError::InvalidHash(hash.clone()));
594            };
595            let created_shard = !dir.is_dir();
596            std::fs::create_dir_all(dir)?;
597            if created_shard {
598                self.sync_dir(&self.root)?;
599            }
600            if self.durable {
601                // Write access, which some platforms need to flush a file.
602                std::fs::OpenOptions::new()
603                    .write(true)
604                    .open(&tmp)?
605                    .sync_all()?;
606                #[cfg(test)]
607                self.probes.file_syncs.fetch_add(1, Ordering::Relaxed);
608            }
609            std::fs::rename(&tmp, &path)?;
610            // A file under this name that failed verification above was not retained content;
611            // the rename replaced it, and with it the quota it held.
612            if let Some(old_len) = index.entries.insert(hash.clone(), len) {
613                index.bytes = index.bytes.saturating_sub(old_len);
614            }
615            index.bytes = index.bytes.saturating_add(len);
616            self.bump_generation(&mut index, generation);
617            match std::fs::metadata(&path) {
618                Ok(meta) => self.remember_intact(path.clone(), FileSig::of(&meta)),
619                Err(_) => self.forget_intact(&path),
620            }
621            self.sync_dir(dir)?;
622            drop(root_lock);
623            drop(index);
624            Ok(())
625        };
626        let result = admit();
627        let _ = std::fs::remove_file(&tmp);
628        result.map(|()| stored)
629    }
630
631    /// Store `items` together: each is received and flushed as [`Self::put`]
632    /// does, and the index, its generation and each shard directory are
633    /// written once for the whole set instead of once per item.
634    fn put_many(&self, items: &[(&[u8], &str)]) -> Vec<Result<Stored, ContentError>> {
635        let started = tilo_clock::now();
636        let mut outcomes: Vec<Option<Result<Stored, ContentError>>> =
637            (0..items.len()).map(|_| None).collect();
638        let mut received: Vec<(usize, PathBuf, String, usize)> = Vec::new();
639        // Where the platform flushes a filesystem, the batch's items are written whole and
640        // flushed together after they are renamed; elsewhere each item waits on its own flush.
641        let flush = if self.durable {
642            if cfg!(target_os = "linux") {
643                BatchFlush::Whole
644            } else {
645                BatchFlush::Each
646            }
647        } else {
648            BatchFlush::None
649        };
650        // The items are written a few at a time: each waits on the disk.
651        let workers = PUT_MANY_WORKERS.min(items.len()).max(1);
652        let per = items.len().div_ceil(workers);
653        std::thread::scope(|scope| {
654            let mut handles = Vec::new();
655            for (part, chunk) in items.chunks(per).enumerate() {
656                let start = part.saturating_mul(per);
657                handles.push(scope.spawn(move || {
658                    let mut done = Vec::new();
659                    for (offset, (bytes, _mime)) in chunk.iter().enumerate() {
660                        let index = start.saturating_add(offset);
661                        let entry = self
662                            .receive(&mut &bytes[..], flush == BatchFlush::Each)
663                            .map_err(|error| (index, error));
664                        done.push((index, entry));
665                    }
666                    done
667                }));
668            }
669            for handle in handles {
670                let Ok(done) = handle.join() else {
671                    continue;
672                };
673                for (index, entry) in done {
674                    match entry {
675                        Ok((tmp, hash, len)) => received.push((index, tmp, hash, len)),
676                        Err((index, error)) => note(&mut outcomes, index, Err(error)),
677                    }
678                }
679            }
680        });
681        let received_ms = started.elapsed().as_millis();
682        let admitted = self.admit_received(&mut outcomes, &received, flush);
683        let admitted = if admitted.is_ok() && flush == BatchFlush::Whole {
684            // Nothing is answered for until the store's filesystem has written the batch: its
685            // items, their renames and their directories.
686            #[cfg(target_os = "linux")]
687            {
688                self.sync_store()
689            }
690            #[cfg(not(target_os = "linux"))]
691            {
692                Ok(())
693            }
694        } else {
695            admitted
696        };
697        tracing::debug!(
698            items = items.len(),
699            received_ms,
700            admitted_ms = started.elapsed().as_millis().saturating_sub(received_ms),
701            total_ms = started.elapsed().as_millis(),
702            "content: a batch was written"
703        );
704        match admitted {
705            Ok(()) => {}
706            Err(why) => {
707                for (index, tmp, _, _) in &received {
708                    if outcomes.get(*index).is_some_and(Option::is_none) {
709                        note(&mut outcomes, *index, Err(ContentError::Io(why.clone())));
710                    }
711                    let _ = std::fs::remove_file(tmp);
712                }
713            }
714        }
715        outcomes
716            .into_iter()
717            .map(|outcome| {
718                outcome.unwrap_or_else(|| Err(ContentError::Io("no item was received".into())))
719            })
720            .collect()
721    }
722
723    fn open(&self, hash: &str) -> Result<Option<ContentReader>, ContentError> {
724        if !valid_hash(hash) {
725            return Err(ContentError::InvalidHash(hash.to_string()));
726        }
727        let Some(path) = self.existing(hash) else {
728            return Ok(None);
729        };
730        let file = match std::fs::File::open(&path) {
731            Ok(file) => file,
732            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
733            Err(error) => return Err(error.into()),
734        };
735        let declared = usize::try_from(file.metadata()?.len()).unwrap_or(usize::MAX);
736        // Never stream an arbitrarily large file merely because a peer named its address.
737        if declared > self.limits.max_item_bytes {
738            return Ok(None);
739        }
740        let cap = u64::try_from(self.limits.max_item_bytes)
741            .unwrap_or(u64::MAX)
742            .saturating_add(1);
743        Ok(Some(Box::new(Verifying::new(file.take(cap), hash))))
744    }
745
746    fn open_at(&self, hash: &str, offset: u64) -> Result<Option<ContentReader>, ContentError> {
747        use std::io::{Seek as _, SeekFrom};
748        if !valid_hash(hash) {
749            return Err(ContentError::InvalidHash(hash.to_string()));
750        }
751        let Some(path) = self.existing(hash) else {
752            return Ok(None);
753        };
754        let mut file = match std::fs::File::open(&path) {
755            Ok(file) => file,
756            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
757            Err(error) => return Err(error.into()),
758        };
759        file.seek(SeekFrom::Start(offset))?;
760        Ok(Some(Box::new(file)))
761    }
762
763    fn has(&self, hash: &str) -> bool {
764        self.existing(hash)
765            .is_some_and(|path| self.intact(&path, hash, self.limits.max_item_bytes))
766    }
767
768    fn size(&self, hash: &str) -> Option<u64> {
769        let path = Self::path_in(&self.root, hash)?;
770        std::fs::metadata(path).ok().map(|metadata| metadata.len())
771    }
772
773    fn state(&self, hash: &str) -> ContentState {
774        if self.has(hash) {
775            ContentState::Resolved
776        } else {
777            ContentState::Unavailable
778        }
779    }
780
781    fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
782        self.remove_where(|hash| !live.contains(hash))
783    }
784
785    fn release(&self, hash: &str) -> Result<Collected, ContentError> {
786        self.remove_where(|kept| kept == hash)
787    }
788
789    fn max_item_bytes(&self) -> usize {
790        self.limits.max_item_bytes
791    }
792
793    fn scratch_dir(&self) -> Option<PathBuf> {
794        Some(self.root.clone())
795    }
796}
797
798impl DirBackend {
799    pub(crate) fn written_before(&self, hash: &str, before: SystemTime) -> bool {
800        Self::path_in(&self.root, hash)
801            .and_then(|path| std::fs::metadata(path).ok()?.modified().ok())
802            .is_some_and(|written| written < before)
803    }
804
805    /// Remove every item not in `live` that was last written before `before`: what a store
806    /// collects when an item may be referenced only after it is written (an upload a record
807    /// names once it is kept). Writing an item that is already here counts as writing it.
808    ///
809    /// # Errors
810    ///
811    /// The store could not be read or changed.
812    pub fn collect_unreferenced_before(
813        &self,
814        live: &BTreeSet<String>,
815        before: SystemTime,
816    ) -> Result<Collected, ContentError> {
817        self.remove_where(|hash| !live.contains(hash) && self.written_before(hash, before))
818    }
819
820    fn written_now(&self, path: &Path) {
821        let touched = std::fs::File::options()
822            .append(true)
823            .open(path)
824            .and_then(|file| {
825                file.set_modified(tilo_clock::to_std(tilo_clock::wall()))?;
826                file.metadata()
827            });
828        match touched {
829            Ok(meta) => self.remember_intact(path.to_path_buf(), FileSig::of(&meta)),
830            Err(_) => self.forget_intact(path),
831        }
832    }
833
834    fn remove_where(&self, gone: impl Fn(&str) -> bool) -> Result<Collected, ContentError> {
835        let mut index = self
836            .state
837            .lock()
838            .map_err(|_| ContentError::Io("content store lock poisoned".into()))?;
839        let root_lock = self.lock_root_for_write()?;
840        let generation = self.read_generation();
841        self.load_index(&mut index)?;
842        let stale: Vec<(String, usize)> = index
843            .entries
844            .iter()
845            .filter(|(hash, _)| gone(hash))
846            .map(|(hash, len)| (hash.clone(), *len))
847            .collect();
848        let mut collected = Collected::default();
849        for (hash, len) in stale {
850            let Some(path) = Self::path_in(&self.root, &hash) else {
851                continue;
852            };
853            self.forget_intact(&path);
854            match std::fs::remove_file(&path) {
855                Ok(()) => {}
856                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
857                Err(error) => {
858                    // What was removed before the failure is a change other writers must see.
859                    self.bump_generation(&mut index, generation);
860                    return Err(error.into());
861                }
862            }
863            index.entries.remove(&hash);
864            index.bytes = index.bytes.saturating_sub(len);
865            collected.bytes = collected
866                .bytes
867                .saturating_add(u64::try_from(len).unwrap_or(u64::MAX));
868            collected.hashes.push(hash);
869        }
870        self.bump_generation(&mut index, generation);
871        drop(root_lock);
872        drop(index);
873        Ok(collected)
874    }
875}
876
877/// Admit `len` new bytes under `hash` against `index`'s total. A file already under the name that
878/// failed verification is not retained content and must not count against the write that
879/// replaces it.
880fn check_admission(
881    limits: &ContentLimits,
882    index: &Index,
883    hash: &str,
884    len: usize,
885) -> Result<(), ContentError> {
886    let (bytes, entries) = match index.entries.get(hash) {
887        Some(old_len) => (
888            index.bytes.saturating_sub(*old_len),
889            index.entries.len().saturating_sub(1),
890        ),
891        None => (index.bytes, index.entries.len()),
892    };
893    check_new_item(limits, bytes, entries, len)
894}