1use 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
19pub struct DirBackend {
34 root: PathBuf,
35 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 generation: Option<u64>,
53}
54
55const PUT_MANY_WORKERS: usize = 8;
58
59const GENERATION_FILE: &str = ".content-store.gen";
63
64#[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
104type 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 #[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 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 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 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 let _ = std::fs::remove_file(&path);
208 index.generation = None;
209 }
210 }
211
212 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 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 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 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 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 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 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 #[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 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#[derive(Clone, Copy, PartialEq, Eq)]
532enum BatchFlush {
533 Whole,
536 Each,
539 None,
541}
542
543fn 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 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 if self.intact(&path, &hash, usize::MAX) {
576 self.written_now(&path);
577 return Ok(());
578 }
579 let (generation, scanned) = self.refresh_index(&mut index)?;
582 if let Err(refusal) = check_admission(&self.limits, &index, &hash, len) {
583 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 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 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 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 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 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 #[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 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 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 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
877fn 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}