tilo-content 0.5.0

Content-addressed binary storage for apps: the explicit, secondary alternative to versioned resources
Documentation
//! A host's content, one store per workspace it serves.

use std::collections::{BTreeMap, BTreeSet};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::SystemTime;

use crate::{
    Collected, ContentBackend, ContentError, ContentLimits, ContentReader, ContentState,
    ContentStore, DirBackend, Stored,
};

/// The most a host keeps free on a small disk for its own state: a tenth of
/// the disk, up to this.
const KEEP_FREE_SMALL_DISK: u64 = 1024 * 1024 * 1024;
const KEEP_FREE_PERCENT: u64 = 2;

/// Each workspace's content store under one directory, by the workspace's
/// id.
pub struct WorkspaceStores {
    dir: PathBuf,
    limits: ContentLimits,
    stores: Mutex<BTreeMap<String, Kept>>,
    /// Whether the disk was found low at the last write: the error is logged
    /// once when it runs low, not at every refusal.
    low: Arc<AtomicBool>,
}

impl WorkspaceStores {
    /// The stores under `dir`, each bounded by `limits`.
    #[must_use]
    pub fn in_dir(dir: impl Into<PathBuf>, limits: ContentLimits) -> Self {
        Self {
            dir: dir.into(),
            limits,
            stores: Mutex::default(),
            low: Arc::default(),
        }
    }

    /// The content store of `workspace`: one store per workspace, however
    /// often it is asked for, so its limits hold across everyone who keeps
    /// content there.
    ///
    /// # Errors
    ///
    /// `workspace` is not a workspace's id (a UUID).
    pub fn get(&self, workspace: &str) -> Result<ContentStore, String> {
        Ok(self.kept(workspace)?.store)
    }

    /// Whether a stored item was last written before the given time.
    #[must_use]
    pub fn written_before(&self, workspace: &str, hash: &str, before: SystemTime) -> bool {
        self.kept(workspace)
            .is_ok_and(|kept| kept.dir.written_before(hash, before))
    }

    /// Remove from `workspace`'s store what nothing in `live` names and was
    /// last written before `before`: content the workspace no longer
    /// references, once whoever wrote it had time to reference it.
    ///
    /// # Errors
    ///
    /// `workspace` is not a workspace's id, or its store could not be read or
    /// changed.
    pub fn collect(
        &self,
        workspace: &str,
        live: &BTreeSet<String>,
        before: SystemTime,
    ) -> Result<Collected, String> {
        self.kept(workspace)?
            .dir
            .collect_unreferenced_before(live, before)
            .map_err(|error| error.to_string())
    }

    /// Remove everything `workspace` keeps here, deleted: its store and its
    /// directory. A store asked for afterwards starts empty.
    ///
    /// # Errors
    ///
    /// `workspace` is not a workspace's id, or its directory could not be
    /// removed.
    pub fn remove(&self, workspace: &str) -> Result<(), String> {
        let workspace = workspace_dir(workspace).ok_or("the workspace is not a uuid")?;
        self.stores
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(&workspace);
        match std::fs::remove_dir_all(self.dir.join(&workspace)) {
            Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.to_string()),
            _ => Ok(()),
        }
    }

    #[must_use]
    pub fn workspaces(&self) -> Vec<String> {
        let Ok(entries) = std::fs::read_dir(&self.dir) else {
            return Vec::new();
        };
        entries
            .filter_map(Result::ok)
            .filter_map(|entry| {
                let name = entry.file_name().into_string().ok()?;
                (workspace_dir(&name).as_deref() == Some(name.as_str())).then_some(name)
            })
            .collect()
    }

    fn kept(&self, workspace: &str) -> Result<Kept, String> {
        let workspace = workspace_dir(workspace).ok_or("the workspace is not a uuid")?;
        let kept = self
            .stores
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .entry(workspace)
            .or_insert_with_key(|workspace| {
                let dir = Arc::new(DirBackend::with_limits(
                    self.dir.join(workspace),
                    self.limits,
                ));
                Kept {
                    store: ContentStore::new(RoomChecked {
                        inner: Arc::clone(&dir),
                        disk: self.dir.clone(),
                        low: Arc::clone(&self.low),
                    }),
                    dir,
                }
            })
            .clone();
        Ok(kept)
    }

    /// The directory each workspace's store is under.
    #[must_use]
    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// The limits every workspace's store is bounded by.
    #[must_use]
    pub const fn limits(&self) -> ContentLimits {
        self.limits
    }
}

#[derive(Clone)]
struct Kept {
    store: ContentStore,
    dir: Arc<DirBackend>,
}

/// What a host keeps free on a disk of `total` bytes: a tenth of a small
/// disk, a gigabyte of a larger one, and a fiftieth of one so large that is
/// more.
#[must_use]
pub fn keep_free(total: u64) -> u64 {
    let share = (total / 100).saturating_mul(KEEP_FREE_PERCENT);
    share.max((total / 10).min(KEEP_FREE_SMALL_DISK))
}

/// The free and total bytes of the disk holding `path`, or of the nearest
/// directory above it that exists; `None` where that cannot be read.
fn disk_of(path: &Path) -> Option<(u64, u64)> {
    let existing = path.ancestors().find(|dir| dir.exists())?;
    room_at(existing)
}

#[cfg(unix)]
fn room_at(path: &Path) -> Option<(u64, u64)> {
    let stat = rustix::fs::statvfs(path).ok()?;
    let block = stat.f_frsize;
    Some((
        stat.f_bavail.saturating_mul(block),
        stat.f_blocks.saturating_mul(block),
    ))
}

#[cfg(not(unix))]
fn room_at(_path: &Path) -> Option<(u64, u64)> {
    None
}

struct RoomChecked {
    inner: Arc<DirBackend>,
    disk: PathBuf,
    low: Arc<AtomicBool>,
}

impl RoomChecked {
    /// Whether the disk has room for new content, saying so in the log as it
    /// runs low and as it has room again.
    fn free_disk(&self) -> Result<(), ContentError> {
        // A disk whose room cannot be read is not refused for it: the write
        // itself says when there is no room at all.
        let Some((free, total)) = disk_of(&self.disk) else {
            return Ok(());
        };
        let keep_free = keep_free(total);
        if free < keep_free {
            if !self.low.swap(true, Ordering::AcqRel) {
                tracing::error!(
                    disk = %self.disk.display(),
                    free,
                    keep_free,
                    "the disk holding the host's content is nearly full: \
                     no new content is kept until there is room, and nothing kept is dropped"
                );
            }
            return Err(ContentError::DiskLow { free, keep_free });
        }
        if self.low.swap(false, Ordering::AcqRel) {
            tracing::warn!(
                disk = %self.disk.display(),
                free,
                "the disk holding the host's content has room again"
            );
        }
        Ok(())
    }
}

impl ContentBackend for RoomChecked {
    fn put(&self, reader: &mut dyn Read, mime: &str) -> Result<Stored, ContentError> {
        self.free_disk()?;
        self.inner.put(reader, mime)
    }

    fn put_many(&self, items: &[(&[u8], &str)]) -> Vec<Result<Stored, ContentError>> {
        // The disk is asked once for the set, then the store writes it
        // together: what a folder of small files needs not to pay a flush and
        // a free-disk check for each.
        match self.free_disk() {
            Ok(()) => self.inner.put_many(items),
            Err(_) => items
                .iter()
                .map(|(bytes, mime)| self.put(&mut &bytes[..], mime))
                .collect(),
        }
    }

    fn open(&self, hash: &str) -> Result<Option<ContentReader>, ContentError> {
        self.inner.open(hash)
    }

    fn open_at(&self, hash: &str, offset: u64) -> Result<Option<ContentReader>, ContentError> {
        self.inner.open_at(hash, offset)
    }

    fn has(&self, hash: &str) -> bool {
        self.inner.has(hash)
    }

    fn size(&self, hash: &str) -> Option<u64> {
        self.inner.size(hash)
    }

    fn state(&self, hash: &str) -> ContentState {
        self.inner.state(hash)
    }

    fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
        self.inner.collect_unreferenced(live)
    }

    fn release(&self, hash: &str) -> Result<Collected, ContentError> {
        self.inner.release(hash)
    }

    fn max_item_bytes(&self) -> usize {
        self.inner.max_item_bytes()
    }

    fn scratch_dir(&self) -> Option<PathBuf> {
        self.inner.scratch_dir()
    }
}

/// `workspace` as the name of its directory: a UUID, lower-case and
/// hyphenated, whichever way it was written. Anything else names no
/// directory.
fn workspace_dir(workspace: &str) -> Option<String> {
    let digits: String = workspace.chars().filter(|c| *c != '-').collect();
    if digits.len() != 32 || !digits.chars().all(|c| c.is_ascii_hexdigit()) {
        return None;
    }
    let digits = digits.to_ascii_lowercase();
    let part = |from: usize, to: usize| digits.get(from..to).unwrap_or_default();
    Some(format!(
        "{}-{}-{}-{}-{}",
        part(0, 8),
        part(8, 12),
        part(12, 16),
        part(16, 20),
        part(20, 32)
    ))
}