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::pull::drive::Slots;
use crate::refs::walk_ref_dir;
use crate::related::{self, RelatedEntry, RelatedField, RelatedWarning};
use crate::repo::Repo;
#[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)]
enum Read {
#[default]
Unread,
Absent,
Present {
parent: Option<Checksum>,
timestamp: u64,
},
}
#[derive(Debug, Clone, Copy, Default)]
struct Expanded {
depth: Option<i32>,
since: Option<u64>,
rejected_since: Option<u64>,
read: Read,
}
impl Expanded {
fn expanded(&self) -> bool {
self.depth.is_some() || self.since.is_some()
}
fn covers(&self, bound: ParentBound) -> bool {
if self.depth == Some(-1) {
return true;
}
match bound {
ParentBound::Depth(0) => self.expanded(),
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 dependencies: bool,
pub build_sources: bool,
pub traverse_parent: bool,
pub traverse_tree: bool,
pub weak_roots: HashMap<Checksum, WeakBounds>,
}
impl GcRoots {
fn parents_only() -> GcRoots {
GcRoots {
dependencies: false,
build_sources: false,
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_commits(&self) -> Result<Vec<Checksum>> {
let repo = self.clone();
let mut commits = ostrya_rt::unblock(move || -> Result<Vec<Checksum>> {
let mut out = Vec::new();
for_each_object(
repo.objects_fd(),
|ty| ty == ObjectType::Commit,
|name| out.push(name.checksum),
)?;
Ok(out)
})
.await?;
commits.sort();
Ok(commits)
}
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();
let mut warnings = Vec::new();
collect_reachable(
self,
vec![(*commit, bound, Arrival::Root)],
bound,
&GcRoots::parents_only(),
&HashSet::new(),
None,
&mut reachable,
&mut warnings,
)
.await?;
Ok(reachable)
}
pub async fn traverse_reachable(
&self,
roots: impl IntoIterator<Item = Checksum>,
max_depth: i32,
) -> Result<HashSet<ObjectName>> {
walk_reachable(self, roots, max_depth).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>,
listing: &HashSet<ObjectName>,
) -> Result<(HashSet<ObjectName>, Vec<RelatedWarning>)> {
let store = ListedLoose {
repo: self,
listing,
};
walk_reachable_gc(&store, roots, root_bound, gc, bounded_roots, pending_delete).await
}
#[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(())
}
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
}
}
pub(crate) trait MetadataSource: Sync {
fn load_metadata(
&self,
ty: ObjectType,
checksum: Checksum,
) -> impl Future<Output = Result<Option<Vec<u8>>>> + Send;
fn max_reads(&self) -> usize {
1
}
fn load_build_source_dict(
&self,
commit: Checksum,
) -> impl Future<Output = Result<Option<Value>>> + Send {
async move {
match self.load_metadata(ObjectType::CommitMeta, commit).await? {
Some(bytes) => {
ostrya_rt::unblock(move || crate::commit::parse_build_source_dict(&bytes)).await
}
None => Ok(None),
}
}
}
fn load_commit_with_build_source_dict(
&self,
commit: Checksum,
) -> impl Future<Output = Result<Option<(Vec<u8>, Option<Value>)>>> + Send {
async move {
let Some(bytes) = self.load_metadata(ObjectType::Commit, commit).await? else {
return Ok(None);
};
Ok(Some((bytes, self.load_build_source_dict(commit).await?)))
}
}
}
impl MetadataSource for Repo {
async fn load_metadata(&self, ty: ObjectType, checksum: Checksum) -> Result<Option<Vec<u8>>> {
match self.load_object_bytes(ty, &checksum).await {
Ok(bytes) => Ok(Some(bytes)),
Err(Error::ObjectNotFound { .. }) => Ok(None),
Err(e) => Err(e),
}
}
async fn load_build_source_dict(&self, commit: Checksum) -> Result<Option<Value>> {
let repo = self.clone();
ostrya_rt::unblock(move || repo.read_build_source_dict_blocking(&commit)).await
}
async fn load_commit_with_build_source_dict(
&self,
commit: Checksum,
) -> Result<Option<(Vec<u8>, Option<Value>)>> {
match self.load_commit_and_build_source_dict(&commit).await {
Ok(loaded) => Ok(Some(loaded)),
Err(Error::ObjectNotFound {
ty: ObjectType::Commit,
..
}) => Ok(None),
Err(e) => Err(e),
}
}
}
struct ListedLoose<'a> {
repo: &'a Repo,
listing: &'a HashSet<ObjectName>,
}
impl ListedLoose<'_> {
fn has_detached(&self, commit: Checksum) -> bool {
self.listing
.contains(&ObjectName::new(commit, ObjectType::CommitMeta))
}
}
impl MetadataSource for ListedLoose<'_> {
async fn load_metadata(&self, ty: ObjectType, checksum: Checksum) -> Result<Option<Vec<u8>>> {
if ty == ObjectType::CommitMeta && !self.has_detached(checksum) {
return Ok(None);
}
self.repo.load_metadata(ty, checksum).await
}
async fn load_build_source_dict(&self, commit: Checksum) -> Result<Option<Value>> {
if !self.has_detached(commit) {
return Ok(None);
}
self.repo.load_build_source_dict(commit).await
}
async fn load_commit_with_build_source_dict(
&self,
commit: Checksum,
) -> Result<Option<(Vec<u8>, Option<Value>)>> {
if !self.has_detached(commit) {
let bytes = self.repo.load_metadata(ObjectType::Commit, commit).await?;
return Ok(bytes.map(|bytes| (bytes, None)));
}
self.repo.load_commit_with_build_source_dict(commit).await
}
}
pub(crate) async fn walk_reachable<S: MetadataSource>(
store: &S,
roots: impl IntoIterator<Item = Checksum>,
max_depth: i32,
) -> Result<HashSet<ObjectName>> {
let bound = ParentBound::depth(max_depth);
let (reachable, _) = walk_reachable_gc(
store,
roots.into_iter().map(|c| (c, bound)),
bound,
&GcRoots::parents_only(),
&HashSet::new(),
None,
)
.await?;
Ok(reachable)
}
pub(crate) async fn walk_reachable_gc<S: MetadataSource>(
store: &S,
roots: impl IntoIterator<Item = (Checksum, ParentBound)>,
root_bound: ParentBound,
gc: &GcRoots,
bounded_roots: &HashSet<Checksum>,
pending_delete: Option<Checksum>,
) -> Result<(HashSet<ObjectName>, Vec<RelatedWarning>)> {
let seeds = roots
.into_iter()
.map(|(c, bound)| (c, bound, Arrival::Root))
.collect();
let mut reachable = HashSet::new();
let mut warnings = Vec::new();
collect_reachable(
store,
seeds,
root_bound,
gc,
bounded_roots,
pending_delete,
&mut reachable,
&mut warnings,
)
.await?;
warnings.sort_by_key(|w| (w.commit, w.field == RelatedField::BuildSources));
Ok((reachable, warnings))
}
#[allow(clippy::too_many_arguments)]
async fn collect_reachable<S: MetadataSource>(
store: &S,
seeds: Vec<(Checksum, ParentBound, Arrival)>,
root_bound: ParentBound,
gc: &GcRoots,
bounded_roots: &HashSet<Checksum>,
pending_delete: Option<Checksum>,
reachable: &mut HashSet<ObjectName>,
warnings: &mut Vec<RelatedWarning>,
) -> 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();
let mut seeded: HashSet<Checksum> = HashSet::new();
let mut edges_read: HashSet<Checksum> = HashSet::new();
let reads_edges = gc.dependencies || gc.build_sources;
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;
}
if arrival == Arrival::TimedParent
&& let ParentBound::Since(since) = bound
&& let Read::Present { timestamp, .. } = seen.read
&& timestamp < since
{
seen_commits
.entry(commit_checksum)
.or_default()
.reject(since);
continue;
}
if seen.expanded() {
seen_commits
.entry(commit_checksum)
.or_default()
.record(bound);
if gc.traverse_parent
&& let Read::Present {
parent: Some(parent),
..
} = seen.read
{
push_parent(&mut commit_stack, parent, bound);
}
continue;
}
let mut prefetched: Option<std::result::Result<Option<Vec<RelatedEntry>>, String>> = None;
let loaded = if pending_delete == Some(commit_checksum) {
None
} else if gc.build_sources
&& arrival != Arrival::TimedParent
&& !edges_read.contains(&commit_checksum)
{
match store
.load_commit_with_build_source_dict(commit_checksum)
.await?
{
Some((bytes, detached)) => {
prefetched = Some(related::build_sources(detached.as_ref()));
Some(Commit::parse(&bytes)?)
}
None => None,
}
} else {
try_load_commit(store, &commit_checksum).await?
};
let entry = seen_commits.entry(commit_checksum).or_default();
entry.read = match &loaded {
Some(commit) => Read::Present {
parent: commit.parent,
timestamp: commit.timestamp,
},
None => Read::Absent,
};
if arrival == Arrival::TimedParent
&& let ParentBound::Since(since) = bound
&& let Some(commit) = &loaded
&& commit.timestamp < since
{
entry.reject(since);
continue;
}
entry.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));
walk_tree(store, commit.root_dirtree, &mut seen_dirtrees, reachable).await?;
}
if reads_edges && edges_read.insert(commit_checksum) {
let mut push = |target: Checksum| {
if seeded.insert(target) {
commit_stack.push((target, root_bound, Arrival::Root));
}
};
if gc.dependencies {
let (targets, defects) =
related::split_entries(related::entries_of(&commit.related));
warnings.extend(defects.into_iter().map(|reason| RelatedWarning {
commit: commit_checksum,
field: RelatedField::Dependencies,
reason,
}));
targets.into_iter().for_each(&mut push);
}
if gc.build_sources {
let sources = match prefetched {
Some(sources) => sources,
None => related::build_sources(
store
.load_build_source_dict(commit_checksum)
.await?
.as_ref(),
),
};
let (targets, defects) = match sources {
Ok(entries) => related::split_entries(entries.unwrap_or_default()),
Err(reason) => (Vec::new(), vec![reason]),
};
warnings.extend(defects.into_iter().map(|reason| RelatedWarning {
commit: commit_checksum,
field: RelatedField::BuildSources,
reason,
}));
targets.into_iter().for_each(&mut push);
}
}
if gc.traverse_parent
&& let Some(parent) = commit.parent
{
push_parent(&mut commit_stack, parent, bound);
}
}
Ok(())
}
fn push_parent(
commit_stack: &mut Vec<(Checksum, ParentBound, Arrival)>,
parent: Checksum,
bound: ParentBound,
) {
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));
}
}
}
async fn walk_tree<S: MetadataSource>(
store: &S,
root_dirtree: Checksum,
seen_dirtrees: &mut HashSet<Checksum>,
reachable: &mut HashSet<ObjectName>,
) -> Result<()> {
let mut stack = vec![root_dirtree];
let mut reads = Slots::new(store.max_reads());
loop {
while reads.has_room()
&& let Some(dirtree_checksum) = stack.pop()
{
if !seen_dirtrees.insert(dirtree_checksum) {
continue;
}
reachable.insert(ObjectName::new(dirtree_checksum, ObjectType::DirTree));
reads.push(async move { try_load_dirtree(store, &dirtree_checksum).await });
}
let Some(loaded) = reads.next_ready().await else {
break;
};
let Some(dirtree) = loaded? 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(())
}
async fn try_load_commit<S: MetadataSource>(
store: &S,
checksum: &Checksum,
) -> Result<Option<Commit>> {
match store.load_metadata(ObjectType::Commit, *checksum).await? {
Some(bytes) => Ok(Some(Commit::parse(&bytes)?)),
None => Ok(None),
}
}
async fn try_load_dirtree<S: MetadataSource>(
store: &S,
checksum: &Checksum,
) -> Result<Option<ostrya_core::DirTree>> {
match store.load_metadata(ObjectType::DirTree, *checksum).await? {
Some(bytes) => Ok(Some(ostrya_core::DirTree::parse(&bytes)?)),
None => Ok(None),
}
}
#[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()
}
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())?))
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
struct Counted {
objects: HashMap<ObjectName, Vec<u8>>,
limit: usize,
reads: std::sync::Mutex<Vec<ObjectName>>,
in_flight: AtomicUsize,
high_water: AtomicUsize,
}
impl Counted {
fn new(objects: HashMap<ObjectName, Vec<u8>>, limit: usize) -> Counted {
Counted {
objects,
limit,
reads: Default::default(),
in_flight: AtomicUsize::new(0),
high_water: AtomicUsize::new(0),
}
}
}
impl MetadataSource for Counted {
async fn load_metadata(
&self,
ty: ObjectType,
checksum: Checksum,
) -> Result<Option<Vec<u8>>> {
let name = ObjectName::new(checksum, ty);
self.reads.lock().unwrap().push(name);
let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
self.high_water.fetch_max(now, Ordering::SeqCst);
futures_lite::future::yield_now().await;
self.in_flight.fetch_sub(1, Ordering::SeqCst);
Ok(self.objects.get(&name).cloned())
}
fn max_reads(&self) -> usize {
self.limit
}
}
fn put_dirtree(
objects: &mut HashMap<ObjectName, Vec<u8>>,
expected: &mut HashSet<ObjectName>,
tree: &ostrya_core::DirTree,
) -> Checksum {
let bytes = tree.serialize().unwrap();
let checksum = Checksum::sha256(&bytes);
let name = ObjectName::new(checksum, ObjectType::DirTree);
objects.insert(name, bytes);
expected.insert(name);
checksum
}
fn wide_tree() -> (HashMap<ObjectName, Vec<u8>>, Checksum, HashSet<ObjectName>) {
let mut objects = HashMap::new();
let mut expected = HashSet::new();
let dirmeta = Checksum::sha256(b"dirmeta");
expected.insert(ObjectName::new(dirmeta, ObjectType::DirMeta));
let mut root = ostrya_core::DirTree::default();
for outer in 0..12 {
let mut middle = ostrya_core::DirTree::default();
for inner in 0..3 {
let file = Checksum::sha256(format!("file {outer} {inner}").as_bytes());
expected.insert(ObjectName::new(file, ObjectType::File));
let leaf = ostrya_core::DirTree {
files: vec![("f".to_owned(), file)],
dirs: Vec::new(),
};
let leaf = put_dirtree(&mut objects, &mut expected, &leaf);
middle.dirs.push((format!("e{inner}"), leaf, dirmeta));
}
let middle = put_dirtree(&mut objects, &mut expected, &middle);
root.dirs.push((format!("d{outer:02}"), middle, dirmeta));
}
let root = put_dirtree(&mut objects, &mut expected, &root);
let commit = Commit {
metadata: Value::Array(Vec::new()),
parent: None,
related: Vec::new(),
subject: String::new(),
body: String::new(),
timestamp: 0,
root_dirtree: root,
root_dirmeta: dirmeta,
};
let bytes = commit.serialize().unwrap();
let checksum = Checksum::sha256(&bytes);
let name = ObjectName::new(checksum, ObjectType::Commit);
objects.insert(name, bytes);
expected.insert(name);
(objects, checksum, expected)
}
#[test]
fn a_tree_walk_runs_at_most_the_limit_of_reads_at_a_time() {
let (objects, commit, expected) = wide_tree();
let commit_name = ObjectName::new(commit, ObjectType::Commit);
let mut depth_first = vec![commit_name];
let mut stack = vec![Commit::parse(&objects[&commit_name]).unwrap().root_dirtree];
while let Some(dirtree) = stack.pop() {
let name = ObjectName::new(dirtree, ObjectType::DirTree);
depth_first.push(name);
let parsed = ostrya_core::DirTree::parse(&objects[&name]).unwrap();
stack.extend(parsed.dirs.iter().map(|(_, subtree, _)| *subtree));
}
for limit in [1, 4, 8] {
let store = Counted::new(objects.clone(), limit);
let reached = ostrya_rt::block_on(walk_reachable(&store, [commit], 0)).unwrap();
assert_eq!(reached, expected, "limit {limit}");
let reads = store.reads.lock().unwrap();
let once: HashSet<ObjectName> = reads.iter().copied().collect();
assert_eq!(reads.len(), objects.len(), "limit {limit}");
assert_eq!(once.len(), objects.len(), "limit {limit}");
let high_water = store.high_water.load(Ordering::SeqCst);
if limit == 1 {
assert_eq!(*reads, depth_first);
assert_eq!(high_water, 1);
} else {
assert!(
high_water > 1 && high_water <= limit,
"limit {limit}: {high_water}"
);
}
}
}
#[test]
fn a_dirtree_that_does_not_parse_fails_the_walk_at_each_limit() {
let (mut objects, commit, _) = wide_tree();
let root = Commit::parse(&objects[&ObjectName::new(commit, ObjectType::Commit)])
.unwrap()
.root_dirtree;
let root =
ostrya_core::DirTree::parse(&objects[&ObjectName::new(root, ObjectType::DirTree)])
.unwrap();
let (_, sibling, _) = root.dirs[5];
objects.insert(
ObjectName::new(sibling, ObjectType::DirTree),
b"not a dirtree".to_vec(),
);
let errors: Vec<String> = [1, 4]
.into_iter()
.map(|limit| {
let store = Counted::new(objects.clone(), limit);
let err = ostrya_rt::block_on(walk_reachable(&store, [commit], 0)).unwrap_err();
assert!(matches!(err, Error::Core(_)), "limit {limit}: {err}");
err.to_string()
})
.collect();
assert_eq!(errors[0], errors[1]);
}
}