use std::collections::{HashMap, HashSet};
use std::os::fd::{AsFd, BorrowedFd};
use ostrya_core::{Checksum, Commit, ObjectName, ObjectType, Value};
use rustix::fs::{Mode, OFlags};
use rustix::io::Errno;
use crate::error::{Error, Result};
use crate::refs::walk_ref_dir;
use crate::repo::Repo;
const GC_ROOT_SIGNATURE: &str = "aay";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ParentBound {
Depth(i32),
Since(u64),
}
impl ParentBound {
pub(crate) fn depth(depth: i32) -> ParentBound {
ParentBound::Depth(if depth == -1 { -1 } else { depth.max(0) })
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct WeakBounds {
depth: Option<i32>,
since: Option<u64>,
}
impl WeakBounds {
pub(crate) fn add(&mut self, bound: ParentBound) {
match bound {
ParentBound::Depth(depth) => {
if !self.depth.is_some_and(|prev| reaches_at_least(prev, depth)) {
self.depth = Some(depth);
}
}
ParentBound::Since(since) => {
if self.since.is_none_or(|prev| prev > since) {
self.since = Some(since);
}
}
}
}
fn seeds(self) -> impl Iterator<Item = ParentBound> {
self.depth
.map(ParentBound::Depth)
.into_iter()
.chain(self.since.map(ParentBound::Since))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RefSpace {
Heads,
Remotes,
Mirrors,
}
#[derive(Debug)]
pub(crate) struct ListedRef {
pub(crate) space: RefSpace,
pub(crate) name: String,
pub(crate) addressable: bool,
pub(crate) checksum: Checksum,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Arrival {
Root,
Parent,
TimedParent,
}
impl Arrival {
fn inherited(self) -> bool {
self != Arrival::Root
}
}
#[derive(Debug, Clone, Copy, Default)]
struct Expanded {
depth: Option<i32>,
since: Option<u64>,
rejected_since: Option<u64>,
}
impl Expanded {
fn covers(&self, bound: ParentBound) -> bool {
if self.depth == Some(-1) {
return true;
}
match bound {
ParentBound::Depth(depth) => {
self.depth.is_some_and(|prev| reaches_at_least(prev, depth))
}
ParentBound::Since(since) => self.since.is_some_and(|prev| prev <= since),
}
}
fn rejects(&self, bound: ParentBound) -> bool {
match bound {
ParentBound::Since(since) => self.rejected_since.is_some_and(|prev| since >= prev),
ParentBound::Depth(_) => false,
}
}
fn record(&mut self, bound: ParentBound) {
match bound {
ParentBound::Depth(depth) => {
if !self.depth.is_some_and(|prev| reaches_at_least(prev, depth)) {
self.depth = Some(depth);
}
}
ParentBound::Since(since) => {
if self.since.is_none_or(|prev| prev > since) {
self.since = Some(since);
}
}
}
}
fn reject(&mut self, since: u64) {
if self.rejected_since.is_none_or(|prev| prev > since) {
self.rejected_since = Some(since);
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct GcRoots {
pub metadata_keys: Vec<String>,
pub traverse_parent: bool,
pub traverse_tree: bool,
pub weak_roots: HashMap<Checksum, WeakBounds>,
}
impl GcRoots {
fn parents_only() -> GcRoots {
GcRoots {
metadata_keys: Vec::new(),
traverse_parent: true,
traverse_tree: true,
weak_roots: HashMap::new(),
}
}
}
impl Repo {
pub async fn list_objects(&self) -> Result<HashSet<ObjectName>> {
let repo = self.clone();
ostrya_rt::unblock(move || list_objects_blocking(repo.objects_fd())).await
}
pub(crate) async fn list_objects_of_type(&self, ty: ObjectType) -> Result<Vec<Checksum>> {
let repo = self.clone();
let mut names = ostrya_rt::unblock(move || -> Result<Vec<Checksum>> {
let mut out = Vec::new();
for_each_object(
repo.objects_fd(),
|candidate| candidate == ty,
|name| out.push(name.checksum),
)?;
Ok(out)
})
.await?;
names.sort();
Ok(names)
}
pub(crate) async fn count_objects<F>(&self, keep: F) -> Result<usize>
where
F: Fn(ObjectType) -> bool + Send + 'static,
{
let repo = self.clone();
ostrya_rt::unblock(move || count_objects_blocking(repo.objects_fd(), keep)).await
}
pub async fn traverse_commit(
&self,
commit: &Checksum,
max_depth: i32,
) -> Result<HashSet<ObjectName>> {
if !self.has_object(ObjectType::Commit, commit).await? {
return Err(Error::ObjectNotFound {
checksum: *commit,
ty: ObjectType::Commit,
});
}
let bound = ParentBound::depth(max_depth);
let mut reachable = HashSet::new();
self.collect_reachable(
vec![(*commit, bound, Arrival::Root)],
bound,
&GcRoots::parents_only(),
&HashSet::new(),
None,
&mut reachable,
)
.await?;
Ok(reachable)
}
pub async fn traverse_reachable(
&self,
roots: impl IntoIterator<Item = Checksum>,
max_depth: i32,
) -> Result<HashSet<ObjectName>> {
let bound = ParentBound::depth(max_depth);
self.traverse_reachable_gc(
roots.into_iter().map(|c| (c, bound)),
bound,
&GcRoots::parents_only(),
&HashSet::new(),
None,
)
.await
}
pub(crate) async fn traverse_reachable_gc(
&self,
roots: impl IntoIterator<Item = (Checksum, ParentBound)>,
root_bound: ParentBound,
gc: &GcRoots,
bounded_roots: &HashSet<Checksum>,
pending_delete: Option<Checksum>,
) -> Result<HashSet<ObjectName>> {
let seeds = roots
.into_iter()
.map(|(c, bound)| (c, bound, Arrival::Root))
.collect();
let mut reachable = HashSet::new();
self.collect_reachable(
seeds,
root_bound,
gc,
bounded_roots,
pending_delete,
&mut reachable,
)
.await?;
Ok(reachable)
}
async fn collect_reachable(
&self,
seeds: Vec<(Checksum, ParentBound, Arrival)>,
root_bound: ParentBound,
gc: &GcRoots,
bounded_roots: &HashSet<Checksum>,
pending_delete: Option<Checksum>,
reachable: &mut HashSet<ObjectName>,
) -> Result<()> {
let mut commit_stack = seeds;
let mut seen_commits: HashMap<Checksum, Expanded> = HashMap::new();
let mut seen_dirtrees: HashSet<Checksum> = HashSet::new();
let mut weak_seeded: HashSet<Checksum> = HashSet::new();
while let Some((commit_checksum, bound, arrival)) = commit_stack.pop() {
if let Some(bounds) = gc.weak_roots.get(&commit_checksum)
&& weak_seeded.insert(commit_checksum)
{
for weak_bound in bounds.seeds() {
commit_stack.push((commit_checksum, weak_bound, Arrival::Root));
}
}
if arrival.inherited()
&& (bounded_roots.contains(&commit_checksum)
|| gc.weak_roots.contains_key(&commit_checksum))
{
continue;
}
let seen = seen_commits
.get(&commit_checksum)
.copied()
.unwrap_or_default();
if seen.covers(bound) {
continue;
}
if arrival == Arrival::TimedParent && seen.rejects(bound) {
continue;
}
let loaded = if pending_delete == Some(commit_checksum) {
None
} else {
self.try_load_commit(&commit_checksum).await?
};
if arrival == Arrival::TimedParent
&& let ParentBound::Since(since) = bound
&& let Some(commit) = &loaded
&& commit.timestamp < since
{
seen_commits
.entry(commit_checksum)
.or_default()
.reject(since);
continue;
}
seen_commits
.entry(commit_checksum)
.or_default()
.record(bound);
reachable.insert(ObjectName::new(commit_checksum, ObjectType::Commit));
let Some(commit) = loaded else {
continue;
};
if gc.traverse_tree {
reachable.insert(ObjectName::new(commit.root_dirmeta, ObjectType::DirMeta));
self.walk_tree(commit.root_dirtree, &mut seen_dirtrees, reachable)
.await?;
}
if !gc.metadata_keys.is_empty() {
self.push_metadata_key_edges(
&commit_checksum,
&commit.metadata,
gc,
root_bound,
&mut commit_stack,
)
.await?;
}
if gc.traverse_parent
&& let Some(parent) = commit.parent
{
match bound {
ParentBound::Depth(0) => {}
ParentBound::Depth(depth) => {
let next = if depth < 0 { -1 } else { depth - 1 };
commit_stack.push((parent, ParentBound::Depth(next), Arrival::Parent));
}
ParentBound::Since(since) => {
commit_stack.push((
parent,
ParentBound::Since(since),
Arrival::TimedParent,
));
}
}
}
}
Ok(())
}
async fn walk_tree(
&self,
root_dirtree: Checksum,
seen_dirtrees: &mut HashSet<Checksum>,
reachable: &mut HashSet<ObjectName>,
) -> Result<()> {
let mut stack = vec![root_dirtree];
while let Some(dirtree_checksum) = stack.pop() {
if !seen_dirtrees.insert(dirtree_checksum) {
continue;
}
reachable.insert(ObjectName::new(dirtree_checksum, ObjectType::DirTree));
let Some(dirtree) = self.try_load_dirtree(&dirtree_checksum).await? else {
continue;
};
for (_, file_checksum) in dirtree.files {
reachable.insert(ObjectName::new(file_checksum, ObjectType::File));
}
for (_, subtree, submeta) in dirtree.dirs {
reachable.insert(ObjectName::new(submeta, ObjectType::DirMeta));
stack.push(subtree);
}
}
Ok(())
}
#[cfg(feature = "push")]
pub(crate) async fn collect_tree_strict(
&self,
root_dirtree: Checksum,
root_dirmeta: Checksum,
seen: &mut HashSet<ObjectName>,
out: &mut Vec<ObjectName>,
) -> Result<()> {
self.collect_dirmeta_strict(root_dirmeta, seen, out).await?;
let mut stack = vec![root_dirtree];
let mut batch = Vec::with_capacity(STRICT_TREE_LOADS);
while !stack.is_empty() {
batch.clear();
while batch.len() < STRICT_TREE_LOADS
&& let Some(dirtree_checksum) = stack.pop()
{
let name = ObjectName::new(dirtree_checksum, ObjectType::DirTree);
if seen.insert(name) {
out.push(name);
batch.push(dirtree_checksum);
}
}
let dirtrees = join_all(batch.iter().map(|c| self.load_dirtree(c))).await;
for dirtree in dirtrees {
let dirtree = dirtree?;
for (_, file_checksum) in dirtree.files {
let name = ObjectName::new(file_checksum, ObjectType::File);
if seen.insert(name) {
out.push(name);
}
}
for (_, subtree, submeta) in dirtree.dirs {
self.collect_dirmeta_strict(submeta, seen, out).await?;
stack.push(subtree);
}
}
}
Ok(())
}
#[cfg(feature = "push")]
async fn collect_dirmeta_strict(
&self,
checksum: Checksum,
seen: &mut HashSet<ObjectName>,
out: &mut Vec<ObjectName>,
) -> Result<()> {
let name = ObjectName::new(checksum, ObjectType::DirMeta);
if !seen.insert(name) {
return Ok(());
}
if !self.has_object(ObjectType::DirMeta, &checksum).await? {
return Err(Error::ObjectNotFound {
checksum,
ty: ObjectType::DirMeta,
});
}
out.push(name);
Ok(())
}
async fn push_metadata_key_edges(
&self,
commit: &Checksum,
metadata: &Value,
gc: &GcRoots,
root_bound: ParentBound,
stack: &mut Vec<(Checksum, ParentBound, Arrival)>,
) -> Result<()> {
let detached = self.read_commit_detached_metadata(commit).await?;
for key in &gc.metadata_keys {
for source in [Some(metadata), detached.as_ref()].into_iter().flatten() {
let Some(value) = source.dict_get(key) else {
continue;
};
for target in metadata_key_targets(commit, key, value)? {
stack.push((target, root_bound, Arrival::Root));
}
}
}
Ok(())
}
async fn try_load_commit(&self, checksum: &Checksum) -> Result<Option<Commit>> {
match self.load_object_bytes(ObjectType::Commit, checksum).await {
Ok(bytes) => Ok(Some(Commit::parse(&bytes)?)),
Err(Error::ObjectNotFound { .. }) => Ok(None),
Err(e) => Err(e),
}
}
async fn try_load_dirtree(&self, checksum: &Checksum) -> Result<Option<ostrya_core::DirTree>> {
match self.load_dirtree(checksum).await {
Ok(dirtree) => Ok(Some(dirtree)),
Err(Error::ObjectNotFound { .. }) => Ok(None),
Err(e) => Err(e),
}
}
pub(crate) async fn list_all_ref_targets(&self) -> Result<Vec<Checksum>> {
Ok(self
.list_all_refs()
.await?
.into_iter()
.map(|listed| listed.checksum)
.collect())
}
pub(crate) async fn list_all_refs(&self) -> Result<Vec<ListedRef>> {
let repo = self.clone();
ostrya_rt::unblock(move || {
let mut out = Vec::new();
for (space, top) in [
(RefSpace::Heads, "refs/heads"),
(RefSpace::Remotes, "refs/remotes"),
(RefSpace::Mirrors, "refs/mirrors"),
] {
collect_named_refs(repo.repo_fd(), space, top, &mut out)?;
}
Ok(out)
})
.await
}
}
#[cfg(feature = "push")]
const STRICT_TREE_LOADS: usize = 8;
#[cfg(feature = "push")]
async fn join_all<F: Future>(futures: impl IntoIterator<Item = F>) -> Vec<F::Output> {
let mut futures: Vec<_> = futures.into_iter().map(|f| Some(Box::pin(f))).collect();
let mut outputs: Vec<Option<F::Output>> = futures.iter().map(|_| None).collect();
std::future::poll_fn(|cx| {
let mut pending = false;
for (future, output) in futures.iter_mut().zip(outputs.iter_mut()) {
if let Some(running) = future {
match running.as_mut().poll(cx) {
std::task::Poll::Ready(value) => {
*output = Some(value);
*future = None;
}
std::task::Poll::Pending => pending = true,
}
}
}
if pending {
std::task::Poll::Pending
} else {
std::task::Poll::Ready(())
}
})
.await;
outputs
.into_iter()
.map(|output| output.expect("each future is ready"))
.collect()
}
fn metadata_key_targets(commit: &Checksum, key: &str, value: &Value) -> Result<Vec<Checksum>> {
let invalid = |reason: String| Error::InvalidGcRoot {
commit: *commit,
metadata_key: key.to_owned(),
reason,
};
let Some((ty, elements)) = value.as_variant() else {
return Err(invalid("value is not a variant".into()));
};
let signature = ty.signature();
if signature != GC_ROOT_SIGNATURE {
return Err(invalid(format!(
"type is `{signature}`, not `{GC_ROOT_SIGNATURE}`"
)));
}
let Some(elements) = elements.as_array() else {
return Err(invalid("value is not an array".into()));
};
let mut targets = Vec::with_capacity(elements.len());
for (index, element) in elements.iter().enumerate() {
let Some(bytes) = element.as_bytes() else {
return Err(invalid(format!("element {index} is not a byte array")));
};
let checksum = Checksum::from_ay(bytes)
.map_err(|_| invalid(format!("element {index} is {} bytes, not 32", bytes.len())))?;
targets.push(checksum);
}
Ok(targets)
}
pub(crate) fn reaches_at_least(prev: i32, depth: i32) -> bool {
if prev < 0 {
true
} else if depth < 0 {
false
} else {
prev >= depth
}
}
fn for_each_object(
objects_fd: BorrowedFd<'_>,
keep: impl Fn(ObjectType) -> bool,
mut f: impl FnMut(ObjectName),
) -> Result<()> {
for_each_dir_name(objects_fd, |fanout| {
if fanout.len() != 2 || !fanout.bytes().all(|b| b.is_ascii_hexdigit()) {
return Ok(());
}
let dir = match rustix::fs::openat(
objects_fd,
fanout,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => fd,
Err(Errno::NOENT) => return Ok(()),
Err(e) => return Err(Error::Io(e.into())),
};
for_each_dir_name(dir.as_fd(), |entry| {
if let Some(name) = parse_object_entry(fanout, entry, &keep) {
f(name);
}
Ok(())
})
})
}
fn list_objects_blocking(objects_fd: BorrowedFd<'_>) -> Result<HashSet<ObjectName>> {
let mut out = HashSet::new();
for_each_object(
objects_fd,
|_| true,
|name| {
out.insert(name);
},
)?;
Ok(out)
}
fn count_objects_blocking(
objects_fd: BorrowedFd<'_>,
keep: impl Fn(ObjectType) -> bool,
) -> Result<usize> {
let mut count = 0usize;
for_each_object(objects_fd, keep, |_| {
count += 1;
})?;
Ok(count)
}
fn parse_object_entry(
fanout: &str,
entry: &str,
keep: &impl Fn(ObjectType) -> bool,
) -> Option<ObjectName> {
let (rest, ext) = entry.rsplit_once('.')?;
if fanout.len() != 2 || rest.len() != 62 {
return None;
}
let ty = ObjectType::from_extension(ext)?;
if !keep(ty) {
return None;
}
let mut hex = [0u8; 64];
hex[..2].copy_from_slice(fanout.as_bytes());
hex[2..].copy_from_slice(rest.as_bytes());
let checksum = Checksum::from_hex(std::str::from_utf8(&hex).ok()?).ok()?;
Some(ObjectName::new(checksum, ty))
}
fn for_each_dir_name(dir: BorrowedFd<'_>, mut f: impl FnMut(&str) -> Result<()>) -> Result<()> {
let reader = rustix::fs::Dir::read_from(dir).map_err(|e| Error::Io(e.into()))?;
for entry in reader {
let entry = entry.map_err(|e| Error::Io(e.into()))?;
let bytes = entry.file_name().to_bytes();
if bytes == b"." || bytes == b".." {
continue;
}
if let Ok(name) = std::str::from_utf8(bytes) {
f(name)?;
}
}
Ok(())
}
pub(crate) fn read_dir_names(dir: BorrowedFd<'_>) -> Result<Vec<String>> {
let mut names = Vec::new();
for_each_dir_name(dir, |name| {
names.push(name.to_owned());
Ok(())
})?;
Ok(names)
}
fn collect_named_refs(
repo_fd: BorrowedFd<'_>,
space: RefSpace,
top: &str,
out: &mut Vec<ListedRef>,
) -> Result<()> {
let dir = match rustix::fs::openat(
repo_fd,
top,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => fd,
Err(Errno::NOENT) => return Ok(()),
Err(e) => return Err(Error::Io(e.into())),
};
walk_ref_dir(dir.as_fd(), "", &mut |entry| {
if let Some(checksum) = read_ref_target(entry.dir, entry.name)? {
let name = match space {
RefSpace::Remotes => entry.path.replacen('/', ":", 1),
RefSpace::Heads | RefSpace::Mirrors => entry.path.to_owned(),
};
let addressable = crate::refs::listed_name_addresses_it(&name, top, entry.path);
out.push(ListedRef {
space,
name,
addressable,
checksum,
});
}
Ok(())
})
}
const REF_READ_CAP: u64 = 4096;
fn read_ref_target(dir: BorrowedFd<'_>, name: &str) -> Result<Option<Checksum>> {
use std::io::Read;
let fd = match rustix::fs::openat(dir, name, OFlags::RDONLY | OFlags::CLOEXEC, Mode::empty()) {
Ok(fd) => fd,
Err(Errno::NOENT) => return Ok(None),
Err(e) => return Err(Error::Io(e.into())),
};
let mut buf = Vec::new();
std::fs::File::from(fd)
.take(REF_READ_CAP)
.read_to_end(&mut buf)
.map_err(Error::Io)?;
let text = std::str::from_utf8(&buf)
.map_err(|_| Error::InvalidFormat("ref content is not valid UTF-8".into()))?;
Ok(Some(Checksum::from_hex(text.trim())?))
}