use std::collections::{BTreeSet, HashMap, HashSet};
use std::ops::ControlFlow;
use std::sync::Arc;
use ostrya_core::{Checksum, ObjectName, ObjectType, Ref, RepoMode, loose_path};
use rustix::fs::FileType;
use rustix::io::Errno;
use crate::error::{Error, Result};
use crate::lock::LockKind;
use crate::related::RelationWarning;
use crate::repo::Repo;
use crate::repo_fs::{FsError, FsResultExt, RepoDir, RepoLayout};
use crate::tombstone::write_tombstone;
use crate::traverse::{ListedRef, ParentBound, RefSpace, WeakBounds};
pub type WeakRefFilterFn = Arc<dyn Fn(&Ref, &Checksum) -> bool + Send + Sync>;
#[derive(Clone, Default)]
pub struct WeakRefFilter(Option<WeakRefFilterFn>);
impl WeakRefFilter {
pub fn new<F>(f: F) -> WeakRefFilter
where
F: Fn(&Ref, &Checksum) -> bool + Send + Sync + 'static,
{
WeakRefFilter(Some(Arc::new(f)))
}
pub fn from_fn(f: WeakRefFilterFn) -> WeakRefFilter {
WeakRefFilter(Some(f))
}
pub(crate) fn is_set(&self) -> bool {
self.0.is_some()
}
pub(crate) fn is_strong(&self, r: &Ref, target: &Checksum) -> bool {
match &self.0 {
Some(f) => f(r, target),
None => true,
}
}
}
impl std::fmt::Debug for WeakRefFilter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
Some(_) => f.write_str("WeakRefFilter(set)"),
None => f.write_str("WeakRefFilter(unset)"),
}
}
}
#[derive(Debug, Clone)]
pub struct PruneOptions {
pub refs_only: bool,
pub depth: i32,
pub no_prune: bool,
pub delete_commit: Option<Checksum>,
pub keep_younger_than: Option<u64>,
pub only_branch: Vec<Ref>,
pub retain_branch_depth: Vec<(Ref, i32)>,
pub commit_only: bool,
pub static_deltas_only: bool,
pub traverse_parent: bool,
pub weak_ref_filter: WeakRefFilter,
}
impl Default for PruneOptions {
fn default() -> Self {
PruneOptions {
refs_only: false,
depth: -1,
no_prune: false,
delete_commit: None,
keep_younger_than: None,
only_branch: Vec::new(),
retain_branch_depth: Vec::new(),
commit_only: false,
static_deltas_only: false,
traverse_parent: true,
weak_ref_filter: WeakRefFilter::default(),
}
}
}
impl PruneOptions {
pub fn new() -> PruneOptions {
PruneOptions::default()
}
pub(crate) fn global_bound(&self) -> ParentBound {
match self.keep_younger_than {
Some(since) => ParentBound::Since(since),
None => ParentBound::depth(self.depth),
}
}
pub fn roots_on_refs_alone(&self) -> bool {
let PruneOptions {
refs_only,
depth: _,
no_prune: _,
delete_commit: _,
keep_younger_than,
only_branch,
retain_branch_depth,
commit_only: _,
static_deltas_only: _,
traverse_parent: _,
weak_ref_filter: _,
} = self;
*refs_only
|| keep_younger_than.is_some()
|| !only_branch.is_empty()
|| !retain_branch_depth.is_empty()
}
fn with_canonical_branches(&self, own: Option<&str>) -> PruneOptions {
PruneOptions {
only_branch: self
.only_branch
.iter()
.map(|r| r.clone().canonical(own))
.collect(),
retain_branch_depth: self
.retain_branch_depth
.iter()
.map(|(r, depth)| (r.clone().canonical(own), *depth))
.collect(),
..self.clone()
}
}
fn ref_bound(&self, r: Option<&Ref>) -> ParentBound {
let Some(r) = r else {
return self.unnamed_bound();
};
let entry = self
.retain_branch_depth
.iter()
.rev()
.find(|(branch, _)| branch == r)
.map(|(_, depth)| *depth);
match entry {
Some(depth) if depth != 0 => ParentBound::depth(depth),
entry => {
let named = entry.is_some() || self.only_branch.contains(r);
if named {
self.global_bound()
} else {
self.unnamed_bound()
}
}
}
}
fn unnamed_bound(&self) -> ParentBound {
if self.only_branch.is_empty() {
self.global_bound()
} else {
ParentBound::Depth(-1)
}
}
}
pub(crate) fn counted(ty: ObjectType, commit_only: bool) -> bool {
if commit_only {
ty == ObjectType::Commit
} else {
!ty.is_commit_sidecar() && ty != ObjectType::TombstoneCommit
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PruneStats {
pub total_objects: usize,
pub pruned_objects: usize,
pub freed_bytes: u64,
pub deleted_refs: Vec<Ref>,
pub warnings: Vec<RelationWarning>,
}
fn listed_ref(space: RefSpace, mut name: String, addressable: bool) -> Option<Ref> {
match space {
RefSpace::Heads => addressable.then(|| Ref::local(name)),
RefSpace::Remotes => {
let colon = name.find(':').filter(|_| addressable)?;
let ref_name = name.split_off(colon + 1);
name.truncate(colon);
Some(Ref::remote(name, ref_name))
}
RefSpace::Mirrors => {
let (id, ref_name) = name.split_once('/')?;
if !ostrya_core::is_valid_collection_id(id) || !ostrya_core::is_ref_name(ref_name) {
return None;
}
let slash = id.len();
let ref_name = name.split_off(slash + 1);
name.truncate(slash);
Some(Ref::collection(name, ref_name))
}
}
}
#[derive(Debug, Clone, Copy)]
struct Sweep {
mode: RepoMode,
no_prune: bool,
tombstones: bool,
fsync: bool,
commit_only: bool,
}
impl Repo {
pub async fn prune(&self, opts: &PruneOptions) -> Result<PruneStats> {
let mode = self.mode();
if opts.static_deltas_only && opts.delete_commit.is_none() {
return Err(Error::InvalidFormat(
"static_deltas_only requires delete_commit".into(),
));
}
if opts.weak_ref_filter.is_set() && !opts.refs_only {
return Err(Error::InvalidFormat(
"weak_ref_filter requires refs_only".into(),
));
}
for r in &opts.only_branch {
if self.resolve_ref_tip(r).await?.is_none() {
return Err(Error::RefNotFound(r.to_string()));
}
}
let _lock = self.lock_repo(LockKind::Exclusive).await?;
let Some(delta_target) = opts.delete_commit else {
return self.prune_objects(opts, mode).await;
};
if opts.static_deltas_only {
let commit_only = opts.commit_only;
let total_objects = self
.count_objects(move |ty| counted(ty, commit_only))
.await?;
if !opts.no_prune {
let fsync = self.config().fsync()?;
let root = self.root_dir().clone();
ostrya_rt::unblock(move || {
crate::delta::prune_delta_dirs(&root, fsync, |to| *to == delta_target)
})
.await?;
}
return Ok(PruneStats {
total_objects,
pruned_objects: 0,
freed_bytes: 0,
deleted_refs: Vec::new(),
warnings: Vec::new(),
});
}
self.prune_objects(opts, mode).await
}
async fn prune_objects(&self, opts: &PruneOptions, mode: RepoMode) -> Result<PruneStats> {
if let Some(commit) = opts.delete_commit {
self.refuse_referenced_commit(&commit).await?;
}
let named_refs = self.list_all_refs().await?;
let own = self.config().collection_id();
let opts = &opts.with_canonical_branches(own);
let filtering = opts.weak_ref_filter.is_set();
let mut roots: Vec<(Checksum, ParentBound)> = Vec::new();
let mut ref_targets: HashSet<Checksum> = HashSet::new();
let mut weak_refs: Vec<(Ref, Checksum)> = Vec::new();
let mut weak_roots: HashMap<Checksum, WeakBounds> = HashMap::new();
for ListedRef {
space,
name,
addressable,
checksum,
} in named_refs
{
let own_mirror = space == RefSpace::Mirrors
&& name.split_once('/').is_some_and(|(id, _)| Some(id) == own);
if own_mirror {
roots.push((checksum, opts.unnamed_bound()));
ref_targets.insert(checksum);
continue;
}
let listed = listed_ref(space, name, addressable);
let bound = opts.ref_bound(listed.as_ref());
if let Some(r) =
listed.filter(|r| filtering && !opts.weak_ref_filter.is_strong(r, &checksum))
{
weak_roots.entry(checksum).or_default().add(bound);
weak_refs.push((r, checksum));
continue;
}
roots.push((checksum, bound));
ref_targets.insert(checksum);
}
let mut all_objects = self.list_objects().await?;
if let Some(commit) = opts.delete_commit {
all_objects.remove(&ObjectName::new(commit, ObjectType::Commit));
all_objects.remove(&ObjectName::new(commit, ObjectType::CommitMeta));
}
let global_bound = opts.global_bound();
if !opts.roots_on_refs_alone() {
roots.extend(
all_objects
.iter()
.filter(|o| o.ty == ObjectType::Commit)
.map(|o| (o.checksum, global_bound)),
);
}
let gc = crate::traverse::GcRoots {
attachments: true,
supplements: true,
traverse_parent: opts.traverse_parent,
traverse_tree: !opts.commit_only,
weak_roots,
};
let (keep, warnings) = self
.traverse_reachable_gc(
roots,
global_bound,
&gc,
&ref_targets,
opts.delete_commit,
&all_objects,
)
.await?;
let kept = |o: &ObjectName| {
keep.contains(o)
|| (o.ty.is_commit_sidecar()
&& keep.contains(&ObjectName::new(o.checksum, ObjectType::Commit)))
};
let mut doomed: Vec<ObjectName> =
Vec::with_capacity(all_objects.len().saturating_sub(keep.len()));
doomed.extend(
all_objects
.iter()
.filter(|o| o.ty != ObjectType::TombstoneCommit && !kept(o))
.filter(|o| {
!opts.commit_only || o.ty == ObjectType::Commit || o.ty.is_commit_sidecar()
})
.copied(),
);
let total_objects = all_objects
.iter()
.filter(|o| counted(o.ty, opts.commit_only))
.count();
let sweep = Sweep {
mode,
no_prune: opts.no_prune,
tombstones: opts.delete_commit.is_some() || self.config().tombstone_commits()?,
fsync: self.config().fsync()?,
commit_only: opts.commit_only,
};
let mut doomed_refs = weak_refs;
doomed_refs
.retain(|(_, target)| !keep.contains(&ObjectName::new(*target, ObjectType::Commit)));
let (state, mut deleted_refs): (Option<RepoDir>, Vec<Ref>) = if opts.no_prune {
let repo = self.clone();
let (state, doomed_refs) = ostrya_rt::unblock(move || {
let state = repo.root_dir().open_layout(RepoLayout::State).optional()?;
crate::refs::check_refs_to_delete_blocking(repo.root_dir(), &doomed_refs, |r| {
crate::refs::ref_relpath(None, r)
})?;
Ok::<_, Error>((state, doomed_refs))
})
.await?;
(state, doomed_refs.into_iter().map(|(r, _)| r).collect())
} else {
let repo = self.clone();
let fsync = sweep.fsync;
ostrya_rt::unblock(move || {
let state = repo.root_dir().open_layout(RepoLayout::State).optional()?;
let deleted = crate::refs::delete_matching_refs_blocking(
repo.root_dir(),
doomed_refs,
|r| crate::refs::ref_relpath(None, r),
fsync,
)?;
Ok::<_, Error>((state, deleted))
})
.await?
};
deleted_refs.sort();
if !opts.no_prune
&& let Some(commit) = opts.delete_commit
{
self.delete_commit_object(&commit, &sweep).await?;
}
let present_commits: HashSet<Checksum> = if opts.no_prune {
HashSet::new()
} else {
all_objects
.iter()
.filter(|o| o.ty == ObjectType::Commit && keep.contains(o))
.map(|o| o.checksum)
.collect()
};
drop(all_objects);
drop(keep);
let fsync = sweep.fsync;
let repo = self.clone();
let (pruned_objects, freed_bytes) =
ostrya_rt::unblock(move || sweep_blocking(&repo, &sweep, &doomed)).await?;
if !opts.no_prune {
let repo = self.clone();
ostrya_rt::unblock(move || {
crate::delta::prune_delta_dirs(repo.root_dir(), fsync, |to| {
!present_commits.contains(to)
})?;
sweep_orphan_markers_blocking(state.as_ref(), &present_commits, fsync)
})
.await?;
}
Ok(PruneStats {
total_objects,
pruned_objects,
freed_bytes,
deleted_refs,
warnings,
})
}
async fn refuse_referenced_commit(&self, commit: &Checksum) -> Result<()> {
let referenced = self.list_all_ref_targets().await?;
if referenced.contains(commit) {
return Err(Error::InvalidFormat(format!(
"cannot delete commit {commit}: it is the target of a ref"
)));
}
Ok(())
}
async fn delete_commit_object(&self, commit: &Checksum, sweep: &Sweep) -> Result<()> {
self.refuse_referenced_commit(commit).await?;
let commit = *commit;
let sweep = *sweep;
let repo = self.clone();
ostrya_rt::unblock(move || {
let path = loose_path(&commit, ObjectType::Commit, sweep.mode);
let fanout = open_fanout(repo.objects(), &path)?;
let mut touched = BTreeSet::new();
remove_commit(
repo.objects(),
fanout.as_ref(),
&sweep,
&commit,
true,
&mut touched,
)?;
sync_dirs(repo.objects(), &touched)
})
.await
}
}
fn sweep_orphan_markers_blocking(
state: Option<&RepoDir>,
present: &HashSet<Checksum>,
fsync: bool,
) -> Result<()> {
let Some(state) = state else {
return Ok(());
};
let mut orphans = Vec::new();
state.for_each_entry(|name, file_type| {
if file_type != FileType::Directory
&& let Some(commit) = name
.to_str()
.ok()
.and_then(|name| name.strip_suffix(".commitpartial"))
.and_then(|hex| Checksum::from_hex_lower(hex).ok())
&& !present.contains(&commit)
{
orphans.push(commit);
}
ControlFlow::Continue(())
})?;
let mut removed = false;
for commit in orphans {
match state.remove_file(&crate::pull::partial_name(&commit), false) {
Ok(unlinked) => removed |= unlinked,
Err(FsError::Io(e)) if e.raw_os_error() == Some(Errno::ISDIR.raw_os_error()) => {}
Err(e) => return Err(e.into()),
}
}
if removed && fsync {
state.sync()?;
}
Ok(())
}
fn remove_commit(
objects: &RepoDir,
fanout: Option<&RepoDir>,
sweep: &Sweep,
commit: &Checksum,
meta: bool,
touched: &mut BTreeSet<u8>,
) -> Result<()> {
if sweep.tombstones {
write_tombstone(objects, commit, sweep.mode, sweep.fsync)?;
}
let Some(fanout) = fanout else {
return Ok(());
};
let path = loose_path(commit, ObjectType::Commit, sweep.mode);
let mut unlinked = fanout.remove_file(leaf_of(&path), false)?;
if meta {
let path = loose_path(commit, ObjectType::CommitMeta, sweep.mode);
unlinked |= fanout.remove_file(leaf_of(&path), false)?;
}
if unlinked && sweep.fsync {
touched.insert(commit.as_bytes()[0]);
}
Ok(())
}
fn sync_dirs(objects: &RepoDir, fanouts: &BTreeSet<u8>) -> Result<()> {
for fanout in fanouts {
objects.sync_dir(&format!("{fanout:02x}"))?;
}
Ok(())
}
fn open_fanout(objects: &RepoDir, path: &str) -> Result<Option<RepoDir>> {
let fanout = path.split_once('/').map_or(path, |(fanout, _)| fanout);
objects
.open_dir(fanout)
.optional()
.map_err(|e| crate::read::object_path_error(e, path).into())
}
fn leaf_of(path: &str) -> &str {
path.split_once('/').map_or(path, |(_, leaf)| leaf)
}
fn remove_object(
objects: &RepoDir,
sweep: &Sweep,
name: &ObjectName,
touched: &mut BTreeSet<u8>,
) -> Result<Option<u64>> {
let path = name.loose_path(sweep.mode);
let Some(fanout) = open_fanout(objects, &path)? else {
return Ok(None);
};
let leaf = leaf_of(&path);
let Some(stat) = fanout.lstat(leaf).optional()? else {
return Ok(None);
};
if fanout.remove_file(leaf, false)? && sweep.fsync {
touched.insert(name.checksum.as_bytes()[0]);
}
Ok(Some(stat.size))
}
fn sweep_blocking(repo: &Repo, sweep: &Sweep, doomed: &[ObjectName]) -> Result<(usize, u64)> {
let mut count = 0usize;
let mut freed = 0u64;
let mut tally = |ty: ObjectType, size: u64| {
if counted(ty, sweep.commit_only) {
count += 1;
freed += size;
}
};
let doomed_meta: HashSet<Checksum> = doomed
.iter()
.filter(|o| o.ty == ObjectType::CommitMeta)
.map(|o| o.checksum)
.collect();
let objects = repo.objects();
let mut touched = BTreeSet::new();
let mut removed_commits = HashSet::new();
for name in doomed.iter().filter(|o| o.ty == ObjectType::Commit) {
let path = name.loose_path(sweep.mode);
let size = if sweep.no_prune {
objects.lstat(&path).optional()?.map(|stat| stat.size)
} else {
let Some(fanout) = open_fanout(objects, &path)? else {
continue;
};
let size = fanout
.lstat(leaf_of(&path))
.optional()?
.map(|stat| stat.size);
if size.is_some() {
remove_commit(
objects,
Some(&fanout),
sweep,
&name.checksum,
doomed_meta.contains(&name.checksum),
&mut touched,
)?;
}
size
};
let Some(size) = size else {
continue;
};
removed_commits.insert(name.checksum);
tally(name.ty, size);
}
for name in doomed
.iter()
.filter(|o| o.ty.is_commit_sidecar() && !removed_commits.contains(&o.checksum))
{
let size = if sweep.no_prune {
objects
.lstat(&name.loose_path(sweep.mode))
.optional()?
.map(|stat| stat.size)
} else {
remove_object(objects, sweep, name, &mut touched)?
};
if let Some(size) = size {
tally(name.ty, size);
}
}
sync_dirs(objects, &touched)?;
let mut touched = BTreeSet::new();
for name in doomed
.iter()
.filter(|o| o.ty != ObjectType::Commit && !o.ty.is_commit_sidecar())
{
let size = if sweep.no_prune {
objects
.lstat(&name.loose_path(sweep.mode))
.optional()?
.map(|stat| stat.size)
} else {
remove_object(objects, sweep, name, &mut touched)?
};
if let Some(size) = size {
tally(name.ty, size);
}
}
sync_dirs(objects, &touched)?;
Ok((count, freed))
}