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,
};
const KEEP_FREE_SMALL_DISK: u64 = 1024 * 1024 * 1024;
const KEEP_FREE_PERCENT: u64 = 2;
pub struct WorkspaceStores {
dir: PathBuf,
limits: ContentLimits,
stores: Mutex<BTreeMap<String, Kept>>,
low: Arc<AtomicBool>,
}
impl WorkspaceStores {
#[must_use]
pub fn in_dir(dir: impl Into<PathBuf>, limits: ContentLimits) -> Self {
Self {
dir: dir.into(),
limits,
stores: Mutex::default(),
low: Arc::default(),
}
}
pub fn get(&self, workspace: &str) -> Result<ContentStore, String> {
Ok(self.kept(workspace)?.store)
}
#[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))
}
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())
}
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)
}
#[must_use]
pub fn dir(&self) -> &Path {
&self.dir
}
#[must_use]
pub const fn limits(&self) -> ContentLimits {
self.limits
}
}
#[derive(Clone)]
struct Kept {
store: ContentStore,
dir: Arc<DirBackend>,
}
#[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))
}
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 {
fn free_disk(&self) -> Result<(), ContentError> {
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>> {
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()
}
}
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)
))
}