use std::collections::HashMap;
use std::collections::hash_map::Entry;
use ostrya_core::Checksum;
use crate::error::Result;
use crate::repo::Repo;
use crate::repo_fs::{self, FsError, FsResultExt, Opened, Publish, RepoDir, RepoLayout};
pub(crate) const IMAGE_DIR: &str = "extensions/ostrya/composefs";
const IMAGE_SUBDIR: &str = "ostrya/composefs";
const EXTENSION: &str = "cfs";
pub(crate) fn rel_path(commit: &Checksum) -> String {
let hex = commit.to_hex();
format!("{}/{}.{EXTENSION}", &hex[..2], &hex[2..])
}
pub(crate) fn staging_name(commit: &Checksum) -> String {
format!("{}.{EXTENSION}", commit.to_hex())
}
pub(crate) fn open_blocking(repo: &Repo, commit: &Checksum) -> Result<Option<Opened>> {
let path = format!("{IMAGE_DIR}/{}", rel_path(commit));
Ok(repo.root_dir().open_regular(&path).optional()?)
}
fn open_store(root: &RepoDir) -> std::result::Result<Option<RepoDir>, FsError> {
let Some(extensions) = root.open_layout(RepoLayout::Extensions).optional()? else {
return Ok(None);
};
extensions.open_dir(IMAGE_SUBDIR).optional()
}
pub(crate) fn list_blocking(root: &RepoDir) -> Result<Vec<Checksum>> {
let Some(store) = open_store(root)? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
for entry in store.list()? {
let Ok(fanout) = std::str::from_utf8(&entry.name) else {
continue;
};
if !is_lower_hex(fanout, 2) {
continue;
}
let Some(sub) = store.open_dir(fanout).optional_walked_dir()? else {
continue;
};
for entry in sub.list()? {
let Some(rest) = std::str::from_utf8(&entry.name)
.ok()
.and_then(|name| name.strip_suffix(".cfs"))
else {
continue;
};
if !is_lower_hex(rest, 62) {
continue;
}
if let Ok(commit) = Checksum::from_hex(&format!("{fanout}{rest}")) {
out.push(commit);
}
}
}
out.sort();
Ok(out)
}
fn is_lower_hex(name: &str, len: usize) -> bool {
name.len() == len && name.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
pub(crate) fn unlink_blocking(
root: &RepoDir,
commits: impl IntoIterator<Item = Checksum>,
fsync: bool,
) -> Result<()> {
let Some(store) = open_store(root)? else {
return Ok(());
};
let mut fanouts: HashMap<String, Option<(RepoDir, bool)>> = HashMap::new();
for commit in commits {
let path = rel_path(&commit);
let (fanout, name) = path.split_at(2);
let entry = match fanouts.entry(fanout.to_owned()) {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
entry.insert(store.open_dir(fanout).optional()?.map(|sub| (sub, false)))
}
};
if let Some((sub, removed)) = entry {
*removed |= sub.remove_file(&name[1..], false)?;
}
}
if fsync {
for (sub, _) in fanouts.values().flatten().filter(|(_, removed)| *removed) {
sub.sync()?;
}
}
Ok(())
}
pub(crate) fn publish_blocking(
root: &RepoDir,
staging: &RepoDir,
images: &[(String, String)],
fsync: bool,
) -> Result<()> {
if images.is_empty() {
return Ok(());
}
let store = root
.ensure_layout(RepoLayout::Extensions, fsync)?
.ensure_dir(IMAGE_SUBDIR, fsync)?;
let mut fanouts: Vec<(&str, RepoDir)> = Vec::new();
for (staged, dest) in images {
let (fanout, name) = dest.split_at(2);
let index = match fanouts.iter().position(|(f, _)| *f == fanout) {
Some(index) => index,
None => {
fanouts.push((fanout, store.ensure_dir(fanout, false)?));
fanouts.len() - 1
}
};
let sub = &fanouts[index].1;
repo_fs::rename(staging, staged, sub, &name[1..], Publish::Replace, false)?;
}
if fsync {
for (_, sub) in &fanouts {
sub.sync()?;
}
store.sync()?;
}
Ok(())
}