Skip to main content

tilo_content/
workspaces.rs

1//! A host's content, one store per workspace it serves.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::io::Read;
5use std::path::{Path, PathBuf};
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::{Arc, Mutex, PoisonError};
8use std::time::SystemTime;
9
10use crate::{
11    Collected, ContentBackend, ContentError, ContentLimits, ContentReader, ContentState,
12    ContentStore, DirBackend, Stored,
13};
14
15/// The most a host keeps free on a small disk for its own state: a tenth of
16/// the disk, up to this.
17const KEEP_FREE_SMALL_DISK: u64 = 1024 * 1024 * 1024;
18const KEEP_FREE_PERCENT: u64 = 2;
19
20/// Each workspace's content store under one directory, by the workspace's
21/// id.
22pub struct WorkspaceStores {
23    dir: PathBuf,
24    limits: ContentLimits,
25    stores: Mutex<BTreeMap<String, Kept>>,
26    /// Whether the disk was found low at the last write: the error is logged
27    /// once when it runs low, not at every refusal.
28    low: Arc<AtomicBool>,
29}
30
31impl WorkspaceStores {
32    /// The stores under `dir`, each bounded by `limits`.
33    #[must_use]
34    pub fn in_dir(dir: impl Into<PathBuf>, limits: ContentLimits) -> Self {
35        Self {
36            dir: dir.into(),
37            limits,
38            stores: Mutex::default(),
39            low: Arc::default(),
40        }
41    }
42
43    /// The content store of `workspace`: one store per workspace, however
44    /// often it is asked for, so its limits hold across everyone who keeps
45    /// content there.
46    ///
47    /// # Errors
48    ///
49    /// `workspace` is not a workspace's id (a UUID).
50    pub fn get(&self, workspace: &str) -> Result<ContentStore, String> {
51        Ok(self.kept(workspace)?.store)
52    }
53
54    /// Whether a stored item was last written before the given time.
55    #[must_use]
56    pub fn written_before(&self, workspace: &str, hash: &str, before: SystemTime) -> bool {
57        self.kept(workspace)
58            .is_ok_and(|kept| kept.dir.written_before(hash, before))
59    }
60
61    /// Remove from `workspace`'s store what nothing in `live` names and was
62    /// last written before `before`: content the workspace no longer
63    /// references, once whoever wrote it had time to reference it.
64    ///
65    /// # Errors
66    ///
67    /// `workspace` is not a workspace's id, or its store could not be read or
68    /// changed.
69    pub fn collect(
70        &self,
71        workspace: &str,
72        live: &BTreeSet<String>,
73        before: SystemTime,
74    ) -> Result<Collected, String> {
75        self.kept(workspace)?
76            .dir
77            .collect_unreferenced_before(live, before)
78            .map_err(|error| error.to_string())
79    }
80
81    /// Remove everything `workspace` keeps here, deleted: its store and its
82    /// directory. A store asked for afterwards starts empty.
83    ///
84    /// # Errors
85    ///
86    /// `workspace` is not a workspace's id, or its directory could not be
87    /// removed.
88    pub fn remove(&self, workspace: &str) -> Result<(), String> {
89        let workspace = workspace_dir(workspace).ok_or("the workspace is not a uuid")?;
90        self.stores
91            .lock()
92            .unwrap_or_else(PoisonError::into_inner)
93            .remove(&workspace);
94        match std::fs::remove_dir_all(self.dir.join(&workspace)) {
95            Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.to_string()),
96            _ => Ok(()),
97        }
98    }
99
100    #[must_use]
101    pub fn workspaces(&self) -> Vec<String> {
102        let Ok(entries) = std::fs::read_dir(&self.dir) else {
103            return Vec::new();
104        };
105        entries
106            .filter_map(Result::ok)
107            .filter_map(|entry| {
108                let name = entry.file_name().into_string().ok()?;
109                (workspace_dir(&name).as_deref() == Some(name.as_str())).then_some(name)
110            })
111            .collect()
112    }
113
114    fn kept(&self, workspace: &str) -> Result<Kept, String> {
115        let workspace = workspace_dir(workspace).ok_or("the workspace is not a uuid")?;
116        let kept = self
117            .stores
118            .lock()
119            .unwrap_or_else(PoisonError::into_inner)
120            .entry(workspace)
121            .or_insert_with_key(|workspace| {
122                let dir = Arc::new(DirBackend::with_limits(
123                    self.dir.join(workspace),
124                    self.limits,
125                ));
126                Kept {
127                    store: ContentStore::new(RoomChecked {
128                        inner: Arc::clone(&dir),
129                        disk: self.dir.clone(),
130                        low: Arc::clone(&self.low),
131                    }),
132                    dir,
133                }
134            })
135            .clone();
136        Ok(kept)
137    }
138
139    /// The directory each workspace's store is under.
140    #[must_use]
141    pub fn dir(&self) -> &Path {
142        &self.dir
143    }
144
145    /// The limits every workspace's store is bounded by.
146    #[must_use]
147    pub const fn limits(&self) -> ContentLimits {
148        self.limits
149    }
150}
151
152#[derive(Clone)]
153struct Kept {
154    store: ContentStore,
155    dir: Arc<DirBackend>,
156}
157
158/// What a host keeps free on a disk of `total` bytes: a tenth of a small
159/// disk, a gigabyte of a larger one, and a fiftieth of one so large that is
160/// more.
161#[must_use]
162pub fn keep_free(total: u64) -> u64 {
163    let share = (total / 100).saturating_mul(KEEP_FREE_PERCENT);
164    share.max((total / 10).min(KEEP_FREE_SMALL_DISK))
165}
166
167/// The free and total bytes of the disk holding `path`, or of the nearest
168/// directory above it that exists; `None` where that cannot be read.
169fn disk_of(path: &Path) -> Option<(u64, u64)> {
170    let existing = path.ancestors().find(|dir| dir.exists())?;
171    room_at(existing)
172}
173
174#[cfg(unix)]
175fn room_at(path: &Path) -> Option<(u64, u64)> {
176    let stat = rustix::fs::statvfs(path).ok()?;
177    let block = stat.f_frsize;
178    Some((
179        stat.f_bavail.saturating_mul(block),
180        stat.f_blocks.saturating_mul(block),
181    ))
182}
183
184#[cfg(not(unix))]
185fn room_at(_path: &Path) -> Option<(u64, u64)> {
186    None
187}
188
189struct RoomChecked {
190    inner: Arc<DirBackend>,
191    disk: PathBuf,
192    low: Arc<AtomicBool>,
193}
194
195impl RoomChecked {
196    /// Whether the disk has room for new content, saying so in the log as it
197    /// runs low and as it has room again.
198    fn free_disk(&self) -> Result<(), ContentError> {
199        // A disk whose room cannot be read is not refused for it: the write
200        // itself says when there is no room at all.
201        let Some((free, total)) = disk_of(&self.disk) else {
202            return Ok(());
203        };
204        let keep_free = keep_free(total);
205        if free < keep_free {
206            if !self.low.swap(true, Ordering::AcqRel) {
207                tracing::error!(
208                    disk = %self.disk.display(),
209                    free,
210                    keep_free,
211                    "the disk holding the host's content is nearly full: \
212                     no new content is kept until there is room, and nothing kept is dropped"
213                );
214            }
215            return Err(ContentError::DiskLow { free, keep_free });
216        }
217        if self.low.swap(false, Ordering::AcqRel) {
218            tracing::warn!(
219                disk = %self.disk.display(),
220                free,
221                "the disk holding the host's content has room again"
222            );
223        }
224        Ok(())
225    }
226}
227
228impl ContentBackend for RoomChecked {
229    fn put(&self, reader: &mut dyn Read, mime: &str) -> Result<Stored, ContentError> {
230        self.free_disk()?;
231        self.inner.put(reader, mime)
232    }
233
234    fn put_many(&self, items: &[(&[u8], &str)]) -> Vec<Result<Stored, ContentError>> {
235        // The disk is asked once for the set, then the store writes it
236        // together: what a folder of small files needs not to pay a flush and
237        // a free-disk check for each.
238        match self.free_disk() {
239            Ok(()) => self.inner.put_many(items),
240            Err(_) => items
241                .iter()
242                .map(|(bytes, mime)| self.put(&mut &bytes[..], mime))
243                .collect(),
244        }
245    }
246
247    fn open(&self, hash: &str) -> Result<Option<ContentReader>, ContentError> {
248        self.inner.open(hash)
249    }
250
251    fn open_at(&self, hash: &str, offset: u64) -> Result<Option<ContentReader>, ContentError> {
252        self.inner.open_at(hash, offset)
253    }
254
255    fn has(&self, hash: &str) -> bool {
256        self.inner.has(hash)
257    }
258
259    fn size(&self, hash: &str) -> Option<u64> {
260        self.inner.size(hash)
261    }
262
263    fn state(&self, hash: &str) -> ContentState {
264        self.inner.state(hash)
265    }
266
267    fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
268        self.inner.collect_unreferenced(live)
269    }
270
271    fn release(&self, hash: &str) -> Result<Collected, ContentError> {
272        self.inner.release(hash)
273    }
274
275    fn max_item_bytes(&self) -> usize {
276        self.inner.max_item_bytes()
277    }
278
279    fn scratch_dir(&self) -> Option<PathBuf> {
280        self.inner.scratch_dir()
281    }
282}
283
284/// `workspace` as the name of its directory: a UUID, lower-case and
285/// hyphenated, whichever way it was written. Anything else names no
286/// directory.
287fn workspace_dir(workspace: &str) -> Option<String> {
288    let digits: String = workspace.chars().filter(|c| *c != '-').collect();
289    if digits.len() != 32 || !digits.chars().all(|c| c.is_ascii_hexdigit()) {
290        return None;
291    }
292    let digits = digits.to_ascii_lowercase();
293    let part = |from: usize, to: usize| digits.get(from..to).unwrap_or_default();
294    Some(format!(
295        "{}-{}-{}-{}-{}",
296        part(0, 8),
297        part(8, 12),
298        part(12, 16),
299        part(16, 20),
300        part(20, 32)
301    ))
302}