Skip to main content

tilo_content/
files.rs

1//! Content in a `tilo-files` location: how a host whose files have no native
2//! path (a browser page) keeps content across restarts.
3
4use std::collections::BTreeSet;
5use std::io::Read;
6
7use tilo_files::{Dir, FsError, Kind, Location, VPath, blocking};
8
9use crate::memory::check_new_item;
10use crate::{
11    Collected, ContentBackend, ContentError, ContentLimits, ContentReader, Stored, hash_bytes,
12    valid_hash,
13};
14
15/// Content stored one file per address in a [`Location`], through
16/// `tilo-files`' synchronous operations (in a page, the profile's mirror of
17/// its app files, written through to the origin-private file system).
18pub struct FilesBackend {
19    location: Location,
20    limits: ContentLimits,
21}
22
23fn io(error: &FsError) -> ContentError {
24    ContentError::Io(error.to_string())
25}
26
27impl FilesBackend {
28    pub fn new(location: Location, limits: ContentLimits) -> Self {
29        Self { location, limits }
30    }
31
32    pub fn limits(&self) -> ContentLimits {
33        self.limits
34    }
35
36    fn dir(&self) -> Result<Dir, ContentError> {
37        Dir::open(self.location.clone()).map_err(|error| io(&error))
38    }
39
40    fn path(hash: &str) -> Result<VPath, ContentError> {
41        if !valid_hash(hash) {
42            return Err(ContentError::InvalidHash(hash.to_owned()));
43        }
44        VPath::new(&hash.to_ascii_lowercase()).map_err(|_| ContentError::InvalidHash(hash.into()))
45    }
46
47    fn entries(&self, dir: &Dir) -> Result<Vec<(String, u64)>, ContentError> {
48        let listed = match blocking::list(dir, &VPath::root()) {
49            Ok(listed) => listed,
50            Err(FsError::NotFound) => return Ok(Vec::new()),
51            Err(error) => return Err(io(&error)),
52        };
53        if listed.len() > self.limits.max_scan_entries {
54            return Err(ContentError::ScanLimitExceeded {
55                limit: self.limits.max_scan_entries,
56            });
57        }
58        Ok(listed
59            .into_iter()
60            .filter(|entry| entry.kind == Kind::File && valid_hash(&entry.name))
61            .filter_map(|entry| {
62                let len = blocking::metadata(dir, &VPath::new(&entry.name).ok()?)
63                    .ok()?
64                    .len;
65                Some((entry.name, len))
66            })
67            .collect())
68    }
69}
70
71impl ContentBackend for FilesBackend {
72    fn put(&self, reader: &mut dyn Read, _mime: &str) -> Result<Stored, ContentError> {
73        let mut bytes = Vec::new();
74        let sentinel = u64::try_from(self.limits.max_item_bytes)
75            .unwrap_or(u64::MAX)
76            .saturating_add(1);
77        reader.take(sentinel).read_to_end(&mut bytes)?;
78        let hash = hash_bytes(&bytes);
79        let len = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
80        let dir = self.dir()?;
81        let path = Self::path(&hash)?;
82        // Re-storing content already retained consumes no more quota.
83        if blocking::metadata(&dir, &path).is_ok() {
84            return Ok(Stored { hash, len });
85        }
86        let entries = self.entries(&dir)?;
87        let held = entries.iter().fold(0_usize, |sum, (_, len)| {
88            sum.saturating_add(usize::try_from(*len).unwrap_or(usize::MAX))
89        });
90        check_new_item(&self.limits, held, entries.len(), bytes.len())?;
91        blocking::write_atomic(&dir, &path, &bytes).map_err(|error| io(&error))?;
92        Ok(Stored { hash, len })
93    }
94
95    fn open(&self, hash: &str) -> Result<Option<ContentReader>, ContentError> {
96        let path = Self::path(hash)?;
97        match blocking::read(&self.dir()?, &path) {
98            Ok(bytes) => Ok(Some(Box::new(std::io::Cursor::new(bytes)))),
99            Err(FsError::NotFound) => Ok(None),
100            Err(error) => Err(io(&error)),
101        }
102    }
103
104    fn has(&self, hash: &str) -> bool {
105        match (self.dir(), Self::path(hash)) {
106            (Ok(dir), Ok(path)) => blocking::metadata(&dir, &path).is_ok(),
107            _ => false,
108        }
109    }
110
111    fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
112        let dir = self.dir()?;
113        let mut collected = Collected::default();
114        for (hash, len) in self.entries(&dir)? {
115            if live.contains(&hash) {
116                continue;
117            }
118            let path = Self::path(&hash)?;
119            blocking::remove(&dir, &path).map_err(|error| io(&error))?;
120            collected.bytes = collected.bytes.saturating_add(len);
121            collected.hashes.push(hash);
122        }
123        collected.hashes.sort();
124        Ok(collected)
125    }
126
127    fn max_item_bytes(&self) -> usize {
128        self.limits.max_item_bytes
129    }
130}