use std::collections::{HashMap, HashSet, VecDeque};
use std::pin::Pin;
use std::sync::{Arc, Mutex, PoisonError};
use std::task::{Context, Poll, ready};
use std::time::Instant;
use async_compression::futures::bufread::DeflateDecoder;
use futures_io::AsyncRead;
use futures_lite::{AsyncReadExt, AsyncWriteExt};
use ostrya_core::{
Checksum, Commit, DirTree, FileHeader, ObjectName, ObjectType, Ref, RepoMode, Value, loose_path,
};
use crate::config::{self, RepoConfig, repo};
use crate::delta::IO_CHUNK;
use crate::endpoint::{EndpointOverrides, Origin, resolve_origin};
use crate::error::{Error, Result};
use crate::fetch::gate::Gate;
use crate::fetch::{FetchRequest, Fetched, Fetcher, Priority};
use crate::inflate::BufSource;
use crate::object::{MAX_FILE_HEADER_SIZE, MAX_METADATA_SIZE};
use crate::read::CommitState;
use crate::refs::{HEADS_DIR, MIRRORS_DIR};
use crate::related::{self, RelatedRule};
use crate::remote::session::is_absent_status;
use crate::remote::{Endpoint, PullSession, StreamSessionOptions};
use crate::repo::Repo;
use crate::repo_fs::{RepoDir, RootFile};
use crate::summary::{COLLECTION_ID_KEY, Summary, collection_map_refs};
use crate::transaction::Transaction;
use crate::traverse::reaches_at_least;
use crate::verify::PullTrust;
use crate::verify::trust::FieldGroup;
use crate::write::FileMeta;
use super::attachment;
use super::chain::Edges;
use super::delta::{
self, AttachmentDeltas, CommitCheck, DeltaAdvert, DeltaJob, DeltaPlan, DeltaSource, PART_CAP,
};
use super::drive::Slots;
use super::source::{Connection, RemoteSource, RootFiles, Transfer, http_error, session_error};
use super::subpath::{Scope, Subpaths};
use super::verify::Verification;
use super::{
CheckedMeta, ChecksumTargets, ModeChecks, Operand, Pinned, PullCounters, PullFlags,
PullOptions, PullReport, PullStats, PullVerify, READ_CHUNK, RefPlace, TimestampBase, TipChecks,
apply_durability, check_commit_operands, check_commit_signatures_filtered, check_depth,
check_one_place, check_remote_operands, check_remote_option, check_static_deltas,
check_tip_refs, commit_operands_alone, completes_marked, operand_collection,
take_static_deltas,
};
const WRITE_THROTTLE: usize = 3;
pub(super) const MAX_ROOT_FILE: u64 = 64 * 1024 * 1024;
const MAX_REF_FILE: u64 = 1024;
pub(super) const CONFIG_FILE: &str = "config";
impl Repo {
pub async fn pull(&self, remote: &str, opts: PullOptions) -> Result<PullStats> {
self.pull_remote(remote, opts, false)
.await
.map(|report| report.stats)
}
pub async fn pull_with_report(&self, remote: &str, opts: PullOptions) -> Result<PullReport> {
self.pull_remote(remote, opts, true).await
}
async fn pull_remote(
&self,
remote: &str,
mut opts: PullOptions,
record: bool,
) -> Result<PullReport> {
let started = Instant::now();
let subpaths = Subpaths::parse(&opts.subpaths)?;
check_depth(opts.depth)?;
check_remote_option(&opts)?;
check_static_deltas(&opts)?;
check_remote_operands(&opts)?;
check_commit_operands(self, &opts).await?;
let commit_collection = match self.config().section::<config::remote::Group>(remote) {
Some(section)
if opts
.refs
.iter()
.any(|name| matches!(Operand::parse(name), Ok(Operand::Commit(_)))) =>
{
section.get::<config::remote::CollectionId>()?
}
_ => None,
};
let related = RelatedRule::of(self.config())?;
self.config().get::<repo::Fsync>()?;
self.config().get::<repo::PerObjectFsync>()?;
if opts.refs.is_empty()
&& !opts.flags.contains(PullFlags::MIRROR)
&& let Some(section) = self.config().section::<config::remote::Group>(remote)
{
section.get::<config::remote::PullBranches>()?;
for name in section
.get::<config::remote::Branches>()?
.unwrap_or_default()
{
crate::refs::check_ref_path(&name)?;
}
}
let edges = take_static_deltas(&mut opts).await?;
let overrides = std::mem::take(&mut opts.overrides);
let origin = resolve_origin(self, remote, overrides).await?;
let mut group = opts.trust_group.as_deref().map(FieldGroup::new);
let trust = PullTrust::for_pull(self, remote, &opts.verify, group.as_mut()).await?;
let endpoint = match origin {
Origin::Endpoint(endpoint) => endpoint,
Origin::Local(path) => {
if trust.checks_signatures() {
opts.flags |= PullFlags::UNTRUSTED;
}
opts.remote = opts.remote.or_else(|| Some(remote.to_owned()));
let src = ostrya_rt::unblock(move || open_local_blocking(path)).await?;
return Box::pin(self.pull_local_from(
&src,
trust,
related,
opts,
subpaths,
super::LocalWanted::Config {
remote,
commit_collection: commit_collection.as_deref(),
},
edges,
started,
record,
))
.await;
}
};
let (endpoint, stream) = session_options(endpoint, opts.max_outstanding_fetches);
let connection = connect(endpoint, stream).await?;
opts.verify = PullVerify::default();
opts.trust_group = None;
opts.max_outstanding_fetches = None;
opts.remote = opts.remote.or_else(|| Some(remote.to_owned()));
self.run_session(
connection,
trust,
related,
opts,
Wanted::Config {
remote,
commit_collection: commit_collection.as_deref(),
},
subpaths,
edges,
started,
record,
)
.await
}
pub async fn pull_with_session(
&self,
session: PullSession,
trust: PullTrust,
mut opts: PullOptions,
) -> Result<PullStats> {
let started = Instant::now();
let checked = match RelatedRule::of(self.config())
.and_then(|related| self.config().get::<repo::Fsync>().map(|_| related))
.and_then(|related| self.config().get::<repo::PerObjectFsync>().map(|_| related))
{
Ok(related) => match check_session_pull(&mut opts).await {
Ok(checked) => check_commit_operands(self, &opts)
.await
.map(|()| (related, checked)),
Err(e) => Err(e),
},
Err(e) => Err(e),
};
let (related, (subpaths, edges)) = match checked {
Ok(checked) => checked,
Err(e) => {
let _ = session.finish().await;
return Err(e);
}
};
self.run_session(
session.into(),
trust,
related,
opts,
Wanted::Named,
subpaths,
edges,
started,
false,
)
.await
.map(|report| report.stats)
}
#[allow(clippy::too_many_arguments)]
pub(super) async fn run_session(
&self,
connection: Connection,
trust: PullTrust,
related: RelatedRule,
opts: PullOptions,
wanted: Wanted<'_>,
subpaths: Option<Subpaths>,
edges: Option<Edges>,
started: Instant,
record: bool,
) -> Result<PullReport> {
let counters = PullCounters::new(opts.progress.as_ref());
let source = RemoteSource::new(connection, counters.transferred_sinks());
let verification = Verification::from_trust(trust);
Box::pin(self.pull_from(
wanted,
source,
&opts,
&verification,
related,
subpaths,
edges,
&counters,
started,
record,
))
.await
}
#[allow(clippy::too_many_arguments)]
async fn pull_from(
&self,
wanted: Wanted<'_>,
source: RemoteSource,
opts: &PullOptions,
verification: &Verification,
related: RelatedRule,
subpaths: Option<Subpaths>,
edges: Option<Edges>,
counters: &PullCounters,
started: Instant,
record: bool,
) -> Result<PullReport> {
let mirror = opts.flags.contains(PullFlags::MIRROR);
let place = match wanted {
Wanted::Pinned(pinned) => pinned.place,
_ => RefPlace::Operands {
remote: opts.remote.as_deref().filter(|_| !mirror),
own: self.config().collection_id(),
},
};
let mut marked = Vec::new();
let mut marker_fsync = false;
let fetched = self
.fetch_from(
&source,
wanted,
opts,
place,
verification,
related,
subpaths,
edges,
counters,
&mut marked,
&mut marker_fsync,
)
.await;
let fetched = source.finish(fetched).await;
let published = match fetched {
Ok(fetched) => {
let FetchedPull {
txn,
targets,
summary,
signature,
} = fetched;
if !opts.no_ref_writes {
for (name, tip) in &targets {
place.queue(&txn, name, tip);
}
}
txn.commit_reporting(record)
.await
.map(|(stats, changed)| (stats, changed, summary, signature))
}
Err(e) => Err(e),
};
let (stats, changed_refs, summary_bytes, signature) = match published {
Ok(published) => published,
Err(e) => {
self.clear_markers_for_absent_commits(&marked, marker_fsync)
.await;
return Err(e);
}
};
if completes_marked(opts) {
self.clear_markers(std::mem::take(&mut marked), marker_fsync)
.await?;
}
if mirror
&& opts.refs.is_empty()
&& !opts.no_ref_writes
&& let Some(bytes) = summary_bytes
{
self.write_mirror_summary(bytes, signature, opts).await?;
}
Ok(PullReport {
stats: PullStats {
metadata_imported: stats.metadata_written,
content_imported: stats.content_written,
content_bytes_written: stats.content_bytes_written,
content_bytes_unpacked: stats.content_bytes_unpacked,
metadata_fetched: counters.metadata(),
content_fetched: counters.content(),
delta_parts: counters.parts(),
bytes_transferred: counters.bytes(),
elapsed: started.elapsed(),
},
changed_refs,
})
}
#[allow(clippy::too_many_arguments)]
async fn fetch_from(
&self,
source: &RemoteSource,
wanted: Wanted<'_>,
opts: &PullOptions,
place: RefPlace<'_>,
verification: &Verification,
related: RelatedRule,
subpaths: Option<Subpaths>,
edges: Option<Edges>,
counters: &PullCounters,
marked: &mut Vec<Checksum>,
marker_fsync: &mut bool,
) -> Result<FetchedPull> {
let mut root;
let probed = match wanted {
Wanted::Pinned(pinned) => pinned
.summary
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take(),
_ => None,
};
let by_checksum_only = match wanted {
Wanted::Pinned(pinned) => pinned.commits_alone,
_ => commit_operands_alone(&opts.refs),
};
let (summary, picked, probed_advert) = if let Some(bytes) = probed {
root = RootFiles::default();
let advert =
ostrya_rt::unblock(move || Summary::parse(&bytes).map(DeltaAdvert::from_summary))
.await?;
(None, None, Some(advert))
} else if by_checksum_only {
root = RootFiles::default();
(None, None, None)
} else {
root = source.root_files().await?;
let copies_summary = opts.flags.contains(PullFlags::MIRROR)
&& opts.refs.is_empty()
&& !opts.no_ref_writes;
let summary = root.summary.take().map(Arc::new);
root.signature = verification
.check_summary(summary.as_ref(), root.signature.take())
.await?
.filter(|_| copies_summary);
let pick = SummaryPick::of(self, wanted, opts);
match summary {
Some(bytes) => {
let (parsed, bytes) = ostrya_rt::unblock(move || {
let parsed = Summary::parse(&bytes).map(|summary| {
let picked = pick.map(|pick| pick.targets(&summary));
(IndexedSummary::new(summary), picked)
});
(parsed, copies_summary.then(|| Arc::unwrap_or_clone(bytes)))
})
.await;
root.summary = bytes;
let (parsed, picked) = parsed?;
(Some(parsed), picked, None)
}
None => (None, None, None),
}
};
let remote_config = check_remote_mode(root.config(source).await?)?;
let resolved = self
.remote_targets(
wanted,
opts,
place,
summary.as_ref(),
picked,
remote_config.collection_id.as_deref(),
(!verification.checks_summary()).then_some(RefFiles::Remote(source)),
)
.await;
let (targets, mut by_checksum) = match resolved {
Ok(resolved) => resolved,
Err(err) => return Err(drop_unblocked(summary, err).await),
};
by_checksum.all = by_checksum_only;
let advert = match (summary, probed_advert) {
(Some(summary), _) => Some(
ostrya_rt::unblock(move || DeltaAdvert::from_summary(summary.into_summary())).await,
),
(None, Some(advert)) => Some(advert),
(None, None) if by_checksum_only && remote_config.indexed_deltas => {
Some(DeltaAdvert::index_alone())
}
(None, None) => None,
};
counters.restart_transferred();
let timestamp = if targets.is_empty() {
TimestampBase::Off
} else {
TimestampBase::resolve(self, &opts.timestamp_check).await?
};
let tip_checks = match wanted {
Wanted::Pinned(pinned) => TipChecks {
collection: Some(pinned.collection),
allow_unbound: pinned.allow_unbound,
listed: Some(&pinned.listed),
by_checksum: Some(&by_checksum),
..TipChecks::new(opts.flags, timestamp, place)
},
_ => TipChecks {
operand_collections: !opts.no_ref_writes,
by_checksum: Some(&by_checksum),
..TipChecks::new(opts.flags, timestamp, place)
},
};
let delta_source = DeltaSource::Remote(source);
let mut deltas = delta::discover(
self,
&delta_source,
advert.as_ref(),
&targets,
opts,
tip_checks,
edges,
verification,
related,
counters,
)
.await?;
deltas.plan_parts(counters);
let follows = !opts.flags.contains(PullFlags::COMMIT_ONLY) && opts.subpaths.is_empty();
let looks = follows && !opts.disable_static_deltas;
let edges = deltas.take_edges().filter(|_| looks);
let advert = advert.filter(|_| looks && edges.is_none());
let mut txn = self.transaction().await?;
apply_durability(&mut txn, opts);
*marker_fsync = txn.fsync_flags().0;
let none = HashMap::new();
let mut done = HashSet::new();
let mut carry = Carry::default();
carry.attachments.inner = attachment::Attachments::new(!looks);
for level in deltas.levels() {
let jobs = deltas.parse_level(self, &delta_source, level).await?;
let phase = Phase {
roots: level,
tips: &none,
depth: 0,
subpaths: None,
deltas: RunDeltas::Ready(&jobs),
done: &done,
last: false,
attachment_run: false,
};
self.drive(
&txn,
source,
opts,
tip_checks,
phase,
&deltas,
verification,
related,
counters,
&mut carry,
marked,
*marker_fsync,
)
.await?;
drop(jobs);
done.extend(level.iter().copied());
}
let jobs = deltas.target_jobs(self, &delta_source).await?;
let mut tips: HashMap<Checksum, Vec<String>> = HashMap::new();
for (name, tip) in &targets {
tips.entry(*tip).or_default().push(name.clone());
}
let roots: Vec<Checksum> = targets.iter().map(|(_, tip)| *tip).collect();
let phase = Phase {
roots: &roots,
tips: &tips,
depth: opts.depth,
subpaths,
deltas: RunDeltas::Ready(&jobs),
done: &done,
last: !follows,
attachment_run: false,
};
self.drive(
&txn,
source,
opts,
tip_checks,
phase,
&deltas,
verification,
related,
counters,
&mut carry,
marked,
*marker_fsync,
)
.await?;
drop(jobs);
drop(deltas);
if follows {
let mut start = 0;
let mut above: Option<Vec<(Checksum, Option<Checksum>)>> = None;
loop {
let order = carry.attachments.inner.order();
let mut pending: Vec<Checksum> = order[start..]
.iter()
.filter(|attachment| !carry.parents.contains_key(*attachment))
.copied()
.collect();
start = order.len();
if pending.is_empty() {
break;
}
pending.sort_unstable();
let (roots, found) = if looks {
let level = match &above {
None => attachment::Level::First,
Some(above) => attachment::Level::Later(above),
};
let named = attachment::pair_targets(
&targets,
opts.depth,
&carry.parents,
carry.attachments.inner.naming(),
&level,
pending,
);
let roots: Vec<Checksum> = named.iter().map(|named| named.checksum).collect();
let (lookups, known) =
attachment::lookups(self, &targets, place, named, HashMap::new()).await?;
let froms: HashMap<Checksum, Checksum> = lookups
.iter()
.filter_map(|lookup| lookup.from.map(|from| (lookup.checksum, from)))
.collect();
above = Some(
roots
.iter()
.map(|root| (*root, froms.get(root).copied()))
.collect(),
);
let found = delta::discover_attachments(
self,
&delta_source,
advert.as_ref(),
edges.as_ref(),
lookups,
&known,
opts,
counters,
)
.await?;
(roots, found)
} else {
(pending, AttachmentDeltas::default())
};
let phase = Phase {
roots: &roots,
tips: &none,
depth: 0,
subpaths: None,
deltas: RunDeltas::Lazy(&found),
done: &done,
last: false,
attachment_run: true,
};
self.drive(
&txn,
source,
opts,
tip_checks,
phase,
&DeltaPlan::default(),
verification,
related,
counters,
&mut carry,
marked,
*marker_fsync,
)
.await?;
drop(found);
}
counters.report(u32::try_from(carry.started).unwrap_or(u32::MAX), false);
}
let mut targets = targets;
targets.retain(|(name, commit)| !by_checksum.is_bare(name, commit));
Ok(FetchedPull {
txn,
targets,
summary: root.summary,
signature: root.signature,
})
}
pub async fn remote_fetch_summary(
&self,
remote: &str,
) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
self.remote_fetch_summary_with(remote, EndpointOverrides::default())
.await
}
pub async fn remote_fetch_summary_with(
&self,
remote: &str,
overrides: EndpointOverrides,
) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
let endpoint = match resolve_origin(self, remote, overrides).await? {
Origin::Endpoint(endpoint) => endpoint,
Origin::Local(path) => return read_local_summary_files(path).await,
};
let connection = connect(endpoint, StreamSessionOptions::default()).await?;
let source = RemoteSource::new(connection, Vec::new());
let read = source.summary_files().await;
source.finish(read).await
}
#[allow(clippy::too_many_arguments)]
pub(super) async fn remote_targets(
&self,
wanted: Wanted<'_>,
opts: &PullOptions,
place: RefPlace<'_>,
summary: Option<&IndexedSummary>,
picked: Option<Result<Vec<(String, Checksum)>>>,
remote_id: Option<&str>,
refs: Option<RefFiles<'_>>,
) -> Result<(Vec<(String, Checksum)>, ChecksumTargets)> {
let mut by_checksum = ChecksumTargets::default();
if let Wanted::Pinned(pinned) = wanted {
by_checksum.bare.clone_from(&pinned.bare);
return Ok((pinned.targets.clone(), by_checksum));
}
let indexed = summary;
let summary = indexed.map(IndexedSummary::summary);
let mirror = opts.flags.contains(PullFlags::MIRROR);
let summary_collection_id = summary
.and_then(|summary| summary.metadata_value(COLLECTION_ID_KEY))
.and_then(Value::as_str);
let summary_id = summary_collection_id.filter(|_| mirror);
let (names, mut selected) = if !opts.refs.is_empty() {
(opts.refs.clone(), Vec::new())
} else if mirror {
let Some(summary) = summary else {
return Err(Error::Pull(
"fetching all refs was requested in mirror mode, but the remote \
repository does not have a summary"
.into(),
));
};
let targets =
picked.unwrap_or_else(|| summary_targets(summary, summary_id, |_| true))?;
check_one_place(
place,
targets
.iter()
.map(|(text, _)| (text.as_str(), text.as_str())),
)?;
return Ok((targets, by_checksum));
} else {
let Wanted::Config { remote, .. } = wanted else {
return Err(no_refs());
};
let section = self.config().section::<config::remote::Group>(remote);
let pull_branches = match §ion {
Some(section) => section.get::<config::remote::PullBranches>()?,
None => None,
};
let selected = match pull_branches {
Some(selector) => {
let Some(summary) = summary else {
return Err(Error::Pull(format!(
"[remote \"{remote}\"] pull-branches selects refs of the summary, \
but the remote repository does not have a summary"
)));
};
Some(picked.unwrap_or_else(|| {
summary_targets(summary, None, |r| {
selector.matches(r, summary_collection_id)
})
})?)
}
None => None,
};
let branches = match section {
Some(section) => section
.get::<config::remote::Branches>()?
.unwrap_or_default(),
None => Vec::new(),
};
if branches.is_empty() {
match &selected {
None => {
return Err(Error::Pull(format!(
"no configured branches for remote {remote}"
)));
}
Some(targets) if targets.is_empty() => {
return Err(Error::Pull(format!(
"no ref of the summary matches [remote \"{remote}\"] pull-branches"
)));
}
Some(_) => {}
}
}
(branches, selected.unwrap_or_default())
};
let operands = !opts.refs.is_empty();
let mut seen = HashSet::new();
let mut wanted_refs = Vec::with_capacity(names.len());
let mut own_name = HashSet::new();
for name in names {
if !seen.insert(name.clone()) {
continue;
}
let parsed = if operands {
Operand::parse(&name)?
} else {
Operand::Name(&name)
};
let (ref_text, commit) = match parsed {
Operand::Commit(commit) => {
by_checksum.bare.insert(commit);
wanted_refs.push((name, commit.to_hex(), Resolved::Bare(commit)));
continue;
}
Operand::NameAt { name: r, commit } => (r, Some(commit)),
Operand::Name(r) => (r, None),
};
let operand = operand_collection(ref_text)
.filter(|_| operands)
.map(|(id, ref_name)| (id.to_owned(), ref_name.to_owned()));
let target = match (&operand, commit) {
(Some(_), _) => ref_text.to_owned(),
(None, commit) => {
crate::refs::check_ref_path(ref_text)?;
match (summary_id, commit) {
(Some(id), None) => Ref::collection(id, ref_text).to_string(),
(_, Some(commit)) => {
if Checksum::from_hex_lower(ref_text) == Ok(commit) {
own_name.insert(commit);
}
by_checksum.named.insert(ref_text.to_owned());
ref_text.to_owned()
}
(None, None) => ref_text.to_owned(),
}
}
};
let resolved = match commit {
Some(commit) => Resolved::At(commit),
None => Resolved::Lookup(operand),
};
wanted_refs.push((name, target, resolved));
}
if !own_name.is_empty() {
by_checksum.bare.retain(|commit| !own_name.contains(commit));
wanted_refs.retain(|(_, _, resolved)| {
!matches!(resolved, Resolved::Bare(commit) if own_name.contains(commit))
});
}
if let Wanted::Config {
commit_collection, ..
} = wanted
{
by_checksum.bare_collection = commit_collection.map(str::to_owned);
}
selected.retain(|(target, _)| !seen.contains(target));
if !(operands && opts.no_ref_writes) {
check_one_place(
place,
wanted_refs
.iter()
.filter(|(_, _, resolved)| !matches!(resolved, Resolved::Bare(_)))
.map(|(name, target, _)| (name.as_str(), target.as_str()))
.chain(
selected
.iter()
.map(|(target, _)| (target.as_str(), target.as_str())),
),
)?;
}
let mut out = resolve_tips(wanted_refs, indexed, remote_id, refs).await?;
out.extend(selected);
Ok((out, by_checksum))
}
#[allow(clippy::too_many_arguments)]
async fn drive(
&self,
txn: &Transaction,
source: &RemoteSource,
opts: &PullOptions,
tip_checks: TipChecks<'_>,
phase: Phase<'_>,
delta_plan: &DeltaPlan,
verification: &Verification,
related: RelatedRule,
progress: &PullCounters,
carry: &mut Carry,
marked: &mut Vec<Checksum>,
marker_fsync: bool,
) -> Result<()> {
let whole = !opts.flags.contains(PullFlags::COMMIT_ONLY) && opts.subpaths.is_empty();
let ctx = StepCtx {
txn,
source,
writes: Arc::new(Gate::new(WRITE_THROTTLE)),
sources: &opts.localcache_repos,
flags: opts.flags,
checks: ModeChecks::new(opts.flags, self.mode()),
tip_checks,
tips: phase.tips,
deltas: phase.deltas,
done: phase.done,
delta_plan,
verification,
related,
attachments: whole,
attachment_run: phase.attachment_run,
marking: Mutex::new(Vec::new()),
marker_fsync,
progress,
};
let mut plan = Plan::new(phase.subpaths);
plan.queued = std::mem::take(&mut carry.queued);
plan.attachments = std::mem::take(&mut carry.attachments);
if phase.attachment_run {
plan.attachments.level += 1;
}
for root in phase.roots {
plan.push_commit(CommitItem {
checksum: *root,
depth: phase.depth,
optional: phase.attachment_run,
});
}
let mut slots = Slots::new(source.max_outstanding());
let mut buffers: Vec<Vec<u8>> = Vec::new();
let mut started = carry.started;
let earlier = marked.len();
let ran = async {
loop {
while slots.has_room()
&& let Some(item) = plan.next()
{
let counted = !matches!(item, Item::Load(_));
let buffer = buffers.pop().unwrap_or_default();
slots.push(self.step(&ctx, item, buffer));
started += usize::from(counted);
}
plan.report(progress, started, !phase.last);
let Some(outcome) = slots.next_ready().await else {
return plan.check_attachments();
};
let (step, buffer) = outcome?;
buffers.push(buffer);
if !matches!(step, Step::Loaded(_)) {
progress.object_done();
}
let part = match step {
Step::Part(commit) => Some(commit),
_ => None,
};
plan.apply(step, marked);
if let Some(commit) = part
&& !plan.delta_parts.contains_key(&commit)
{
ctx.deltas.release(&commit);
}
}
}
.await;
if let Err(e) = ran {
drop(slots);
ctx.txn.settle().await;
let marking = ctx
.marking
.into_inner()
.unwrap_or_else(PoisonError::into_inner);
marked.truncate(earlier);
marked.extend(marking);
return Err(e);
}
carry.queued = plan.queued;
carry.attachments = plan.attachments;
if whole {
if carry.parents.is_empty() {
carry.parents = plan.parents;
} else {
carry.parents.extend(plan.parents);
}
}
carry.started = started;
Ok(())
}
async fn step(
&self,
ctx: &StepCtx<'_>,
item: Item,
mut read_buf: Vec<u8>,
) -> Result<(Step, Vec<u8>)> {
let step = match item {
Item::Commit(commit) => self.fetch_commit(ctx, commit).await?,
Item::Object(name) if name.ty == ObjectType::File => {
self.fetch_content(ctx, name, &mut read_buf).await?
}
Item::Object(name) => self.fetch_metadata(ctx, name).await?,
Item::Load(commit) => {
if let RunDeltas::Lazy(found) = ctx.deltas {
found.load_job(self, &commit).await?;
}
Step::Loaded(commit)
}
Item::Part(part) => {
let loaded;
let job = match ctx.deltas {
RunDeltas::Ready(jobs) => jobs.get(&part.commit),
RunDeltas::Lazy(found) => {
loaded = found.live_job(&part.commit);
loaded.as_deref()
}
}
.expect("a queued part belongs to a delta this pull found");
delta::apply_job_part(
ctx.txn,
&DeltaSource::Remote(ctx.source),
job,
part.index,
ctx.checks,
ctx.progress,
)
.await?;
Step::Part(part.commit)
}
};
Ok((step, read_buf))
}
async fn fetch_commit(&self, ctx: &StepCtx<'_>, item: CommitItem) -> Result<Step> {
let checksum = item.checksum;
let name = ObjectName::new(checksum, ObjectType::Commit);
if ctx.done.contains(&checksum) {
ctx.deltas.release(&checksum);
return self.done_commit(ctx, checksum).await;
}
let (prechecked, filtered, mut known) = match ctx.delta_plan.commit_check(&checksum).await?
{
CommitCheck::NotChecked => (false, false, None),
CommitCheck::Checked { detached, filtered } => (true, filtered, Some(detached)),
};
let repo = self.clone();
let held = ostrya_rt::unblock(move || {
if !repo.has_object_blocking(ObjectType::Commit, &checksum)? {
return Ok::<_, Error>(None);
}
let complete = repo.commit_state_blocking(&checksum)? == CommitState::Normal;
let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, &checksum)?;
Ok(Some((complete, bytes)))
})
.await?;
let complete = held.as_ref().is_some_and(|(complete, _)| *complete);
let mut staging = CommitStaging::Held;
let (detached, bytes) = if let Some((_, bytes)) = held {
let detached = match known.take() {
Some(detached) => detached,
None if ctx.attachment_run && complete => None,
None => {
fetch_detached_metadata(ctx.source, ctx.sources, ctx.progress, &checksum)
.await?
}
};
(detached, Arc::new(bytes))
} else if let Some(src) = cached_source(ctx.sources, name).await? {
let detached = match known.take() {
Some(detached) => detached,
None => {
fetch_detached_metadata(ctx.source, ctx.sources, ctx.progress, &checksum)
.await?
}
};
let bytes = Arc::new(src.load_object_bytes(ObjectType::Commit, &checksum).await?);
#[cfg(test)]
super::import_seam::run(self.repo_fd());
staging = CommitStaging::Write(Arc::clone(&bytes));
(detached, bytes)
} else if let Some(commit_bytes) = ctx.deltas.commit_bytes(&checksum).await? {
staging = CommitStaging::Write(Arc::clone(&commit_bytes));
let detached = match known.take() {
Some(detached) => detached,
None => {
fetch_detached_metadata(ctx.source, ctx.sources, ctx.progress, &checksum)
.await?
}
};
(detached, commit_bytes)
} else {
match self
.fetch_remote_commit(ctx, &checksum, item.optional)
.await?
{
(detached, Some(bytes)) => {
ctx.progress.metadata_fetched();
let bytes = Arc::new(bytes);
staging = CommitStaging::Write(Arc::clone(&bytes));
(detached, bytes)
}
(_, None) if item.optional => return Ok(Step::Absent(checksum)),
(_, None) => {
return Err(Error::ObjectNotFound {
checksum,
ty: ObjectType::Commit,
});
}
}
};
let shared = Arc::clone(&bytes);
let (commit, attachments) = ostrya_rt::unblock(move || {
let mut commit = Commit::parse(&shared)?;
let related = std::mem::take(&mut commit.related);
let attachments = related::checked_attachments(&checksum, related);
Ok::<_, Error>((commit, attachments))
})
.await?;
let detached = if prechecked {
match known {
None if filtered => Some(CheckedMeta::Filtered(detached)),
_ => detached.map(CheckedMeta::Source),
}
} else if ctx.attachment_run {
detached.map(CheckedMeta::Source)
} else {
let detached = check_commit_signatures_filtered(
self,
ctx.verification,
ctx.related,
&checksum,
(&bytes).into(),
detached,
)
.await?;
self.check_tips(ctx, &checksum, &commit).await?;
detached
};
let attachments = attachments?;
drop(bytes);
if !complete {
ctx.marking
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(checksum);
ctx.txn
.track(self.partial_marker_job(&checksum, ctx.marker_fsync))
.await?;
}
match staging {
CommitStaging::Held => {}
CommitStaging::Write(bytes) => match Arc::try_unwrap(bytes) {
Ok(bytes) => {
ctx.txn
.write_metadata_owned(ObjectType::Commit, Some(&checksum), bytes)
.await?;
}
Err(bytes) => {
ctx.txn
.write_metadata(ObjectType::Commit, Some(&checksum), &bytes)
.await?;
}
},
}
if let Some(meta) = detached
&& let Some(meta) = meta.filtered(ctx.related, &checksum).await?
{
ctx.txn.stage_commit_detached_bytes(&checksum, meta).await?;
}
let tree = vec![
ObjectName::new(commit.root_dirmeta, ObjectType::DirMeta),
ObjectName::new(commit.root_dirtree, ObjectType::DirTree),
];
let next = if complete || ctx.flags.contains(PullFlags::COMMIT_ONLY) {
ctx.deltas.release(&checksum);
CommitNext::Nothing
} else {
ctx.deltas.commit_next(&checksum, tree)
};
Ok(Step::Commit(CommitOutcome {
checksum,
next,
parent: commit.parent,
attachments: if ctx.attachments {
attachments
} else {
Vec::new()
},
marked: !complete,
}))
}
async fn check_tips(
&self,
ctx: &StepCtx<'_>,
checksum: &Checksum,
commit: &Commit,
) -> Result<()> {
let refs: Vec<&str> = ctx
.tips
.get(checksum)
.into_iter()
.flatten()
.map(String::as_str)
.collect();
check_tip_refs(self, ctx.tip_checks, checksum, commit, &refs).await
}
async fn done_commit(&self, ctx: &StepCtx<'_>, checksum: Checksum) -> Result<Step> {
let mut commit = ctx.txn.load_commit_staged_first(&checksum).await?;
if !ctx.delta_plan.checked(&checksum) {
self.check_tips(ctx, &checksum, &commit).await?;
}
let related = std::mem::take(&mut commit.related);
let attachments =
ostrya_rt::unblock(move || related::checked_attachments(&checksum, related)).await?;
Ok(Step::Commit(CommitOutcome {
checksum,
next: CommitNext::Nothing,
parent: commit.parent,
attachments: if ctx.attachments {
attachments
} else {
Vec::new()
},
marked: false,
}))
}
async fn fetch_remote_commit(
&self,
ctx: &StepCtx<'_>,
commit: &Checksum,
optional: bool,
) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
let path = object_path(commit, ObjectType::Commit);
let fetch = || async {
if optional {
ctx.source
.read_optional(&path, Priority::High, MAX_METADATA_SIZE)
.await
} else {
ctx.source
.read_found(&path, Priority::High, MAX_METADATA_SIZE)
.await
}
};
match cached_detached_metadata(ctx.sources, commit).await? {
Some(detached) => Ok((Some(detached), fetch().await?)),
None if matches!(ctx.source.transfer(), Transfer::Stream(_)) => {
let (detached, fetched) = futures_lite::future::zip(
fetch_remote_detached(ctx.source, ctx.progress, commit),
fetch(),
)
.await;
Ok((detached?, fetched?))
}
None => {
let detached = fetch_remote_detached(ctx.source, ctx.progress, commit).await?;
Ok((detached, fetch().await?))
}
}
}
async fn fetch_metadata(&self, ctx: &StepCtx<'_>, name: ObjectName) -> Result<Step> {
if ctx.txn.is_staged(&name.checksum, name.ty)
|| self.has_object(name.ty, &name.checksum).await?
{
return self
.walked(name, || ctx.txn.load_dirtree_staged_first(&name.checksum))
.await;
}
if let Some(src) = cached_source(ctx.sources, name).await? {
let bytes = src.load_object_bytes(name.ty, &name.checksum).await?;
#[cfg(test)]
super::import_seam::run(self.repo_fd());
ctx.txn
.write_metadata(name.ty, Some(&name.checksum), &bytes)
.await?;
return match name.ty {
ObjectType::DirTree => Ok(Step::DirTree(name.checksum, DirTree::parse(&bytes)?)),
_ => Ok(Step::Done),
};
}
let path = object_path(&name.checksum, name.ty);
let bytes = ctx
.source
.read_found(&path, Priority::High, MAX_METADATA_SIZE)
.await?
.ok_or(Error::ObjectNotFound {
checksum: name.checksum,
ty: name.ty,
})?;
ctx.txn
.write_metadata(name.ty, Some(&name.checksum), &bytes)
.await?;
ctx.progress.metadata_fetched();
match name.ty {
ObjectType::DirTree => Ok(Step::DirTree(name.checksum, DirTree::parse(&bytes)?)),
_ => Ok(Step::Done),
}
}
async fn walked<F>(&self, name: ObjectName, load: impl FnOnce() -> F) -> Result<Step>
where
F: Future<Output = Result<DirTree>>,
{
if name.ty != ObjectType::DirTree {
return Ok(Step::Done);
}
Ok(Step::DirTree(name.checksum, load().await?))
}
async fn fetch_content(
&self,
ctx: &StepCtx<'_>,
name: ObjectName,
read_buf: &mut Vec<u8>,
) -> Result<Step> {
if ctx.txn.is_staged(&name.checksum, ObjectType::File)
|| self.has_object(ObjectType::File, &name.checksum).await?
{
return Ok(Step::Done);
}
if let Some(src) = cached_source(ctx.sources, name).await? {
self.import_from(
ctx.txn,
src,
name,
ctx.flags | PullFlags::UNTRUSTED,
read_buf,
)
.await?;
return Ok(Step::Done);
}
let path = object_path(&name.checksum, ObjectType::File);
let fetcher = match ctx.source.transfer() {
Transfer::Http(fetcher) => fetcher,
Transfer::Stream(stream) => {
let body = stream
.get(&path, u64::MAX)
.await?
.ok_or(Error::ObjectNotFound {
checksum: name.checksum,
ty: name.ty,
})?;
self.store_content(ctx, &name.checksum, body, read_buf)
.await
.map_err(session_error)?;
ctx.progress.content_fetched();
return Ok(Step::Done);
}
};
let mut refetch = fetcher.refetching(FetchRequest {
priority: Priority::Low,
..FetchRequest::path(&path)
});
loop {
let body = match refetch.fetch().await {
Ok(Fetched::Body(body)) => body,
Ok(Fetched::NotModified) => {
return Err(Error::Fetch(format!(
"{path}: the remote answered 304 to an unconditional request"
)));
}
Err(e) => return Err(object_not_found(e.into(), name)),
};
let permit = ctx.writes.acquire(Priority::Normal).await;
let stored = self
.store_content(ctx, &name.checksum, body, read_buf)
.await;
drop(permit);
match stored {
Ok(()) => {
ctx.progress.content_fetched();
return Ok(Step::Done);
}
Err(e) => refetch.retry(e).await?,
}
}
}
async fn store_content<R: AsyncRead + Unpin>(
&self,
ctx: &StepCtx<'_>,
expected: &Checksum,
body: R,
read_buf: &mut Vec<u8>,
) -> Result<()> {
let (header, declared, framed_header, body) = read_archive_header(body).await?;
let FileHeader {
uid,
gid,
mode,
symlink_target: _,
xattrs,
} = header.clone();
let meta = FileMeta {
uid,
gid,
mode,
xattrs,
};
ctx.checks.check(expected, &meta)?;
store_filez_payload(
ctx.txn,
expected,
&header,
&meta,
declared,
&framed_header,
body,
read_buf,
)
.await
}
}
struct FetchedPull {
txn: Transaction,
targets: Vec<(String, Checksum)>,
summary: Option<Vec<u8>>,
signature: Option<Vec<u8>>,
}
pub(super) fn session_options(
endpoint: Endpoint,
max_outstanding: Option<usize>,
) -> (Endpoint, StreamSessionOptions) {
match endpoint {
Endpoint::Http(mut http) => {
if let Some(n) = max_outstanding {
http.max_outstanding = n;
}
(Endpoint::Http(http), StreamSessionOptions::default())
}
ssh @ Endpoint::Ssh { .. } => (
ssh,
StreamSessionOptions {
agent: None,
max_outstanding,
},
),
#[cfg(feature = "s3")]
Endpoint::S3(mut s3) => {
if let Some(n) = max_outstanding {
s3.http.max_outstanding = n;
}
(Endpoint::S3(s3), StreamSessionOptions::default())
}
other => (other, StreamSessionOptions::default()),
}
}
pub(super) async fn connect(
endpoint: Endpoint,
stream: StreamSessionOptions,
) -> Result<Connection> {
match endpoint {
Endpoint::Http(http) => PullSession::connect(Endpoint::Http(http), stream)
.await
.map(Connection::from)
.map_err(http_error),
ssh @ Endpoint::Ssh { .. } => Ok(PullSession::connect(ssh, stream).await?.into()),
#[cfg(feature = "s3")]
Endpoint::S3(s3) => {
let fetcher = s3_fetcher(&s3, stream).await?;
let bucket = crate::remote::s3::Bucket::from_fetcher(&s3, fetcher.clone());
Ok(Connection {
session: PullSession::Http(fetcher),
bucket: Some(bucket),
})
}
_ => Err(crate::endpoint::neither_ssh_nor_http("a pull")),
}
}
pub(super) fn open_local_blocking(path: std::path::PathBuf) -> Result<Repo> {
let root = RepoDir::open_root(rustix::fs::CWD, &path)?;
Repo::open_strict_blocking(root, path)
}
async fn read_local_summary_files(
path: std::path::PathBuf,
) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
ostrya_rt::unblock(move || {
let src = open_local_blocking(path)?;
let root = src.root_dir();
let signature = crate::summary::read_root_file_blocking(root, RootFile::SummarySig.name())?;
let summary = crate::summary::read_root_file_blocking(root, RootFile::Summary.name())?;
Ok((summary, signature))
})
.await
}
#[cfg(feature = "s3")]
pub(super) async fn s3_fetcher(
s3: &crate::remote::s3::S3Endpoint,
stream: StreamSessionOptions,
) -> Result<Fetcher> {
let options = s3.pull_options().map_err(http_error)?;
let session = Box::pin(PullSession::connect(Endpoint::Http(options), stream))
.await
.map_err(http_error)?;
let PullSession::Http(fetcher) = session else {
unreachable!("an HTTP endpoint opens an HTTP session");
};
Ok(fetcher)
}
async fn check_session_pull(opts: &mut PullOptions) -> Result<(Option<Subpaths>, Option<Edges>)> {
let subpaths = Subpaths::parse(&opts.subpaths)?;
check_depth(opts.depth)?;
check_remote_option(opts)?;
check_static_deltas(opts)?;
if opts.refs.is_empty() {
return Err(no_refs());
}
check_remote_operands(opts)?;
if opts.verify != PullVerify::default() {
return Err(Error::InvalidInput(
"a pull with a session takes its signature policy from its trust, and \
takes no verify option"
.into(),
));
}
if opts.trust_group.is_some() {
return Err(Error::InvalidInput(
"a pull with a session takes its signature policy from its trust, and \
takes no trust group"
.into(),
));
}
if opts.max_outstanding_fetches.is_some() {
return Err(Error::InvalidInput(
"a pull with a session takes its request limit from the session, and \
takes no max_outstanding_fetches option"
.into(),
));
}
if opts.overrides != EndpointOverrides::default() {
return Err(Error::InvalidInput(
"a pull with a session takes its server from the session, and takes \
no endpoint overrides"
.into(),
));
}
let edges = take_static_deltas(opts).await?;
Ok((subpaths, edges))
}
fn no_refs() -> Error {
Error::InvalidInput("a pull with a session needs at least one ref name".into())
}
pub(super) enum Resolved {
Lookup(Option<(String, String)>),
At(Checksum),
Bare(Checksum),
}
#[derive(Clone, Copy)]
pub(super) enum Wanted<'a> {
Named,
Config {
remote: &'a str,
commit_collection: Option<&'a str>,
},
Pinned(&'a Pinned<'a>),
}
struct StepCtx<'a> {
txn: &'a Transaction,
source: &'a RemoteSource,
writes: Arc<Gate>,
sources: &'a [Repo],
flags: PullFlags,
checks: ModeChecks,
tip_checks: TipChecks<'a>,
tips: &'a HashMap<Checksum, Vec<String>>,
deltas: RunDeltas<'a>,
done: &'a HashSet<Checksum>,
delta_plan: &'a DeltaPlan,
verification: &'a Verification,
related: RelatedRule,
attachments: bool,
attachment_run: bool,
marking: Mutex<Vec<Checksum>>,
marker_fsync: bool,
progress: &'a PullCounters,
}
struct Phase<'a> {
roots: &'a [Checksum],
tips: &'a HashMap<Checksum, Vec<String>>,
depth: i32,
subpaths: Option<Subpaths>,
deltas: RunDeltas<'a>,
done: &'a HashSet<Checksum>,
last: bool,
attachment_run: bool,
}
#[derive(Clone, Copy)]
enum RunDeltas<'a> {
Ready(&'a HashMap<Checksum, DeltaJob>),
Lazy(&'a AttachmentDeltas),
}
impl RunDeltas<'_> {
async fn commit_bytes(self, commit: &Checksum) -> Result<Option<Arc<Vec<u8>>>> {
match self {
RunDeltas::Ready(jobs) => Ok(jobs.get(commit).map(|job| Arc::clone(&job.commit_bytes))),
RunDeltas::Lazy(found) => Ok(found.commit_bytes(commit).await?.map(Arc::new)),
}
}
fn commit_next(self, commit: &Checksum, tree: Vec<ObjectName>) -> CommitNext {
let delta = match self {
RunDeltas::Ready(jobs) => jobs
.get(commit)
.map(|job| (job.parts(), job.fallbacks(), false)),
RunDeltas::Lazy(found) => found
.take_commit_delta(commit)
.map(|(parts, fallbacks)| (parts, fallbacks, true)),
};
match delta {
Some((parts, fallbacks, lazy)) => CommitNext::Delta {
parts,
fallbacks,
tree,
lazy,
},
None => CommitNext::Scan(tree),
}
}
fn release(self, commit: &Checksum) {
if let RunDeltas::Lazy(found) = self {
found.release_job(commit);
}
}
}
#[derive(Default)]
struct Carry {
queued: HashSet<ObjectName>,
started: usize,
attachments: PlanAttachments,
parents: HashMap<Checksum, Option<Checksum>>,
}
struct CommitItem {
checksum: Checksum,
depth: i32,
optional: bool,
}
struct PartItem {
commit: Checksum,
index: usize,
}
enum Item {
Commit(CommitItem),
Object(ObjectName),
Load(Checksum),
Part(PartItem),
}
enum Step {
Commit(CommitOutcome),
DirTree(Checksum, DirTree),
Loaded(Checksum),
Part(Checksum),
Done,
Absent(Checksum),
}
struct CommitOutcome {
checksum: Checksum,
next: CommitNext,
parent: Option<Checksum>,
attachments: Vec<(String, Checksum)>,
marked: bool,
}
enum CommitStaging {
Held,
Write(Arc<Vec<u8>>),
}
enum CommitNext {
Scan(Vec<ObjectName>),
Delta {
parts: usize,
fallbacks: Vec<ObjectName>,
tree: Vec<ObjectName>,
lazy: bool,
},
Nothing,
}
#[derive(Default)]
struct Plan {
commits: VecDeque<CommitItem>,
parts: VecDeque<PartItem>,
parts_in_flight: usize,
loads: VecDeque<Checksum>,
loaded: HashSet<Checksum>,
waiting_parts: usize,
delta_parts: HashMap<Checksum, usize>,
delta_trees: HashMap<Checksum, Vec<ObjectName>>,
scan: VecDeque<ObjectName>,
content: VecDeque<ObjectName>,
queued: HashSet<ObjectName>,
subpaths: Option<Subpaths>,
root: Scope,
partial_trees: HashMap<Checksum, PartialTree>,
seen: HashMap<Checksum, i32>,
parents: HashMap<Checksum, Option<Checksum>>,
attachments: PlanAttachments,
}
#[derive(Default)]
struct PlanAttachments {
inner: attachment::Attachments,
absent: HashSet<Checksum>,
level: usize,
}
struct PartialTree {
scope: Scope,
walked: bool,
}
impl Plan {
fn new(subpaths: Option<Subpaths>) -> Plan {
Plan {
root: subpaths.as_ref().map(Subpaths::root).unwrap_or_default(),
subpaths,
..Plan::default()
}
}
fn push_commit(&mut self, mut item: CommitItem) {
loop {
if let Some(&prev) = self.seen.get(&item.checksum)
&& reaches_at_least(prev, item.depth)
{
return;
}
let depth = item.depth;
if self.seen.insert(item.checksum, depth).is_none() {
self.commits.push_back(item);
return;
}
if depth == 0 {
return;
}
let Some(Some(parent)) = self.parents.get(&item.checksum).copied() else {
return;
};
item = CommitItem {
checksum: parent,
depth: one_less(depth),
optional: true,
};
}
}
fn push_object(&mut self, name: ObjectName, scope: Scope) {
if self.queued.insert(name) {
if name.ty == ObjectType::DirTree && scope != Scope::All {
self.partial_trees.insert(
name.checksum,
PartialTree {
scope,
walked: false,
},
);
}
match name.ty {
ObjectType::File => self.content.push_back(name),
_ => self.scan.push_back(name),
}
return;
}
if name.ty != ObjectType::DirTree {
return;
}
let Some(tree) = self.partial_trees.get_mut(&name.checksum) else {
return;
};
if tree.scope.covers(&scope) {
return;
}
tree.scope.widen(&scope);
if tree.walked {
tree.walked = false;
self.scan.push_back(name);
}
}
fn push_root(&mut self, name: ObjectName) {
let scope = if name.ty == ObjectType::DirTree {
self.root.clone()
} else {
Scope::All
};
self.push_object(name, scope);
}
fn apply_dirtree(&mut self, checksum: Checksum, dirtree: &DirTree) {
let Some(subpaths) = &self.subpaths else {
for name in children_of(dirtree) {
self.push_object(name, Scope::All);
}
return;
};
let scope = match self.partial_trees.get_mut(&checksum) {
Some(tree) => {
tree.walked = true;
tree.scope.clone()
}
None => Scope::All,
};
for (name, scope) in subpaths.children(dirtree, &scope) {
self.push_object(name, scope);
}
}
fn next(&mut self) -> Option<Item> {
if let Some(commit) = self.commits.pop_front() {
return Some(Item::Commit(commit));
}
if self.parts_in_flight < PART_CAP
&& let Some(part) = self.parts.pop_front()
{
self.parts_in_flight += 1;
return Some(Item::Part(part));
}
if self.loaded.len() < PART_CAP
&& let Some(commit) = self.loads.pop_front()
{
self.loaded.insert(commit);
return Some(Item::Load(commit));
}
if let Some(name) = self.scan.pop_front() {
return Some(Item::Object(name));
}
self.content.pop_front().map(Item::Object)
}
fn report(&self, progress: &PullCounters, started: usize, more: bool) {
let queued = self.commits.len()
+ self.parts.len()
+ self.waiting_parts
+ self.scan.len()
+ self.content.len();
let total = u32::try_from(started + queued).unwrap_or(u32::MAX);
progress.report(
total,
more || !self.commits.is_empty() || !self.scan.is_empty(),
);
}
fn apply(&mut self, step: Step, marked: &mut Vec<Checksum>) {
match step {
Step::Commit(outcome) => self.apply_commit(outcome, marked),
Step::DirTree(checksum, dirtree) => self.apply_dirtree(checksum, &dirtree),
Step::Loaded(commit) => self.apply_load(commit),
Step::Part(commit) => self.apply_part(commit),
Step::Absent(commit) => self.apply_absent(commit),
Step::Done => {}
}
}
fn check_attachments(&self) -> Result<()> {
let unheld = self
.attachments
.absent
.iter()
.filter(|commit| self.attachments.inner.named(commit).is_some())
.min();
match unheld.and_then(|commit| {
self.attachments
.inner
.named_error(commit, related::UNHELD_REASON)
}) {
Some(err) => Err(err),
None => Ok(()),
}
}
fn apply_load(&mut self, commit: Checksum) {
let parts = *self
.delta_parts
.get(&commit)
.expect("a loaded job belongs to a commit whose delta is counted");
self.waiting_parts -= parts;
for index in 0..parts {
self.parts.push_back(PartItem { commit, index });
}
}
fn apply_part(&mut self, commit: Checksum) {
self.parts_in_flight -= 1;
let left = self
.delta_parts
.get_mut(&commit)
.expect("an applied part belongs to a commit whose delta is counted");
*left -= 1;
if *left > 0 {
return;
}
self.delta_parts.remove(&commit);
self.loaded.remove(&commit);
for name in self.delta_trees.remove(&commit).unwrap_or_default() {
self.push_root(name);
}
}
fn apply_commit(&mut self, outcome: CommitOutcome, marked: &mut Vec<Checksum>) {
if outcome.marked {
marked.push(outcome.checksum);
}
self.parents.insert(outcome.checksum, outcome.parent);
match outcome.next {
CommitNext::Nothing => {}
CommitNext::Scan(tree) => {
for name in tree {
self.push_root(name);
}
}
CommitNext::Delta {
parts,
fallbacks,
tree,
lazy,
} => {
for name in fallbacks {
self.push_object(name, Scope::All);
}
if parts == 0 {
for name in tree {
self.push_root(name);
}
} else if lazy {
self.delta_parts.insert(outcome.checksum, parts);
self.delta_trees.insert(outcome.checksum, tree);
self.loads.push_back(outcome.checksum);
self.waiting_parts += parts;
} else {
self.delta_parts.insert(outcome.checksum, parts);
self.delta_trees.insert(outcome.checksum, tree);
for index in 0..parts {
self.parts.push_back(PartItem {
commit: outcome.checksum,
index,
});
}
}
}
}
let depth = self.seen.get(&outcome.checksum).copied().unwrap_or(0);
if depth != 0
&& let Some(parent) = outcome.parent
{
self.push_commit(CommitItem {
checksum: parent,
depth: one_less(depth),
optional: true,
});
}
self.apply_attachments(outcome.checksum, outcome.attachments);
}
fn apply_attachments(&mut self, commit: Checksum, attachments: Vec<(String, Checksum)>) {
let level = self.attachments.level;
self.attachments.inner.record_at(level, commit, attachments);
}
fn apply_absent(&mut self, commit: Checksum) {
self.attachments.absent.insert(commit);
}
}
fn one_less(depth: i32) -> i32 {
if depth > 0 { depth - 1 } else { depth }
}
fn children_of(dirtree: &DirTree) -> Vec<ObjectName> {
let mut out = Vec::with_capacity(dirtree.files.len() + 2 * dirtree.dirs.len());
for (_, file) in &dirtree.files {
out.push(ObjectName::new(*file, ObjectType::File));
}
for (_, subtree, submeta) in &dirtree.dirs {
out.push(ObjectName::new(*submeta, ObjectType::DirMeta));
out.push(ObjectName::new(*subtree, ObjectType::DirTree));
}
out
}
pub(super) fn object_path(checksum: &Checksum, ty: ObjectType) -> String {
format!("objects/{}", loose_path(checksum, ty, RepoMode::Archive))
}
pub(super) async fn fetch_detached_metadata(
source: &RemoteSource,
sources: &[Repo],
progress: &PullCounters,
commit: &Checksum,
) -> Result<Option<Vec<u8>>> {
if let Some(bytes) = cached_detached_metadata(sources, commit).await? {
return Ok(Some(bytes));
}
fetch_remote_detached(source, progress, commit).await
}
pub(super) async fn fetch_remote_detached(
source: &RemoteSource,
progress: &PullCounters,
commit: &Checksum,
) -> Result<Option<Vec<u8>>> {
let path = object_path(commit, ObjectType::CommitMeta);
let fetched = source
.read_optional(&path, Priority::High, MAX_METADATA_SIZE)
.await?;
if fetched.is_some() {
progress.metadata_fetched();
}
Ok(fetched)
}
async fn cached_detached_metadata(sources: &[Repo], commit: &Checksum) -> Result<Option<Vec<u8>>> {
for src in sources {
if let Some(bytes) = src
.held_object_bytes(ObjectType::CommitMeta, commit)
.await?
{
return Ok(Some(bytes));
}
}
Ok(None)
}
pub(super) async fn cached_source(sources: &[Repo], name: ObjectName) -> Result<Option<&Repo>> {
for src in sources {
if src.has_object(name.ty, &name.checksum).await? {
return Ok(Some(src));
}
}
Ok(None)
}
fn object_not_found(error: Error, name: ObjectName) -> Error {
match error {
Error::HttpStatus { status: 404, .. } => Error::ObjectNotFound {
checksum: name.checksum,
ty: name.ty,
},
other => other,
}
}
#[derive(Default)]
struct RemoteConfig {
collection_id: Option<String>,
indexed_deltas: bool,
}
fn check_remote_mode(config: Option<Vec<u8>>) -> Result<RemoteConfig> {
let Some(bytes) = config else {
return Ok(RemoteConfig::default());
};
let text = String::from_utf8(bytes)
.map_err(|_| Error::InvalidFormat("the remote config is not valid utf-8".into()))?;
let config = RepoConfig::parse(&text)?;
if config.mode().is_archive() {
return Ok(RemoteConfig {
collection_id: config.collection_id().map(str::to_owned),
indexed_deltas: matches!(config.file_value::<repo::IndexedDeltas>(), Ok(Some(true))),
});
}
Err(Error::Unsupported(format!(
"can't pull from a remote in mode {}: an http pull reads an archive \
repository, whose content objects are served in the framed, deflated \
form a client can store",
config.mode().as_mode_str()
)))
}
pub(super) enum SummaryPick {
All,
Selected(crate::pattern::ReceiveSelector),
}
impl SummaryPick {
pub(super) fn of(repo: &Repo, wanted: Wanted<'_>, opts: &PullOptions) -> Option<SummaryPick> {
if !opts.refs.is_empty() || matches!(wanted, Wanted::Pinned(_)) {
return None;
}
if opts.flags.contains(PullFlags::MIRROR) {
return Some(SummaryPick::All);
}
let Wanted::Config { remote, .. } = wanted else {
return None;
};
repo.config()
.section::<config::remote::Group>(remote)?
.get::<config::remote::PullBranches>()
.ok()
.flatten()
.map(SummaryPick::Selected)
}
pub(super) fn targets(&self, summary: &Summary) -> Result<Vec<(String, Checksum)>> {
let summary_collection_id = summary
.metadata_value(COLLECTION_ID_KEY)
.and_then(Value::as_str);
match self {
SummaryPick::All => summary_targets(summary, summary_collection_id, |_| true),
SummaryPick::Selected(selector) => summary_targets(summary, None, |r| {
selector.matches(r, summary_collection_id)
}),
}
}
}
fn summary_targets(
summary: &Summary,
summary_id: Option<&str>,
keep: impl Fn(&Ref) -> bool,
) -> Result<Vec<(String, Checksum)>> {
let mut refs = Vec::with_capacity(summary.refs.len());
for entry in &summary.refs {
let r = match summary_id {
Some(id) => Ref::collection(id, entry.name.as_str()),
None => Ref::local(entry.name.as_str()),
};
if keep(&r) {
refs.push((r, entry.commit));
}
}
for (id, entries) in summary.collection_map()? {
for entry in entries {
let r = Ref::collection(id.as_str(), entry.name);
if keep(&r) {
refs.push((r, entry.commit));
}
}
}
let mut seen = HashSet::new();
let mut out = Vec::with_capacity(refs.len());
for (r, commit) in refs {
r.validate()?;
let text = r.to_string();
if seen.insert(text.clone()) {
out.push((text, commit));
}
}
Ok(out)
}
pub(super) async fn resolve_tips(
wanted: Vec<(String, String, Resolved)>,
summary: Option<&IndexedSummary>,
remote_id: Option<&str>,
refs: Option<RefFiles<'_>>,
) -> Result<Vec<(String, Checksum)>> {
let summary_id = summary
.and_then(|summary| summary.summary().metadata_value(COLLECTION_ID_KEY))
.and_then(Value::as_str);
let mut listed = HashMap::new();
let mut tips = Vec::with_capacity(wanted.len());
let mut failed = None;
for (name, target, resolved) in wanted {
let tip = match resolved {
Resolved::Bare(commit) | Resolved::At(commit) => Ok(Tip::Known(commit)),
Resolved::Lookup(Some((id, ref_name))) => {
remote_collection_ref(summary, summary_id, &mut listed, remote_id, &id, ref_name)
}
Resolved::Lookup(None) => Ok(match summary.and_then(|summary| summary.get(&name)) {
Some(commit) => Tip::Known(commit),
None => Tip::File(HEADS_DIR.to_owned(), name.clone()),
}),
};
let tip = match tip {
Ok(Tip::File(..)) if refs.is_none() => Err(Error::RefNotFound(name.clone())),
tip => tip,
};
match tip {
Ok(tip) => tips.push((name, target, tip)),
Err(err) => {
failed = Some(err);
break;
}
}
}
let files = tips
.iter()
.filter_map(|(_, _, tip)| match tip {
Tip::File(dir, name) => Some((dir.as_str(), name.as_str())),
Tip::Known(_) => None,
})
.collect();
let mut read = match refs {
Some(refs) => refs.read_all(files).await,
None => Vec::new(),
}
.into_iter();
let mut out = Vec::with_capacity(tips.len());
for (name, target, tip) in tips {
let checksum = match tip {
Tip::Known(commit) => Some(commit),
Tip::File(..) => read.next().transpose()?.flatten(),
};
let Some(checksum) = checksum else {
return Err(Error::RefNotFound(name));
};
out.push((target, checksum));
}
if let Some(err) = failed {
return Err(err);
}
Ok(out)
}
fn remote_collection_ref(
summary: Option<&IndexedSummary>,
summary_id: Option<&str>,
listed: &mut HashMap<String, HashMap<String, Checksum>>,
remote_id: Option<&str>,
id: &str,
name: String,
) -> Result<Tip> {
if let Some(summary) = summary {
let commit = if summary_id == Some(id) {
summary.get(&name)
} else {
let refs = match listed.get(id) {
Some(refs) => refs,
None => {
let mut refs = HashMap::new();
for entry in collection_map_refs(&summary.summary().metadata, id)? {
refs.entry(entry.name).or_insert(entry.commit);
}
listed.entry(id.to_owned()).or_insert(refs)
}
};
refs.get(&name).copied()
};
if let Some(commit) = commit {
return Ok(Tip::Known(commit));
}
}
if remote_id.or(summary_id) == Some(id) {
Ok(Tip::File(HEADS_DIR.to_owned(), name))
} else {
Ok(Tip::File(format!("{MIRRORS_DIR}/{id}"), name))
}
}
enum Tip {
Known(Checksum),
File(String, String),
}
pub(super) struct IndexedSummary {
summary: Summary,
by_name: Vec<usize>,
}
impl IndexedSummary {
pub(super) fn new(summary: Summary) -> IndexedSummary {
let mut by_name: Vec<usize> = (0..summary.refs.len()).collect();
by_name.sort_by(|&a, &b| summary.refs[a].name.cmp(&summary.refs[b].name));
IndexedSummary { summary, by_name }
}
pub(super) fn summary(&self) -> &Summary {
&self.summary
}
pub(super) fn into_summary(self) -> Summary {
self.summary
}
pub(super) fn get(&self, name: &str) -> Option<Checksum> {
let refs = &self.summary.refs;
let at = self
.by_name
.partition_point(|&i| refs[i].name.as_str() < name);
self.by_name
.get(at)
.map(|&i| &refs[i])
.filter(|entry| entry.name == name)
.map(|entry| entry.commit)
}
}
pub(super) async fn drop_unblocked<T: Send + 'static>(value: T, err: Error) -> Error {
ostrya_rt::unblock(move || drop(value)).await;
err
}
#[derive(Clone, Copy)]
pub(super) enum RefFiles<'a> {
Remote(&'a RemoteSource),
Local(&'a Repo),
}
impl RefFiles<'_> {
async fn read_all(self, files: Vec<(&str, &str)>) -> Vec<Result<Option<Checksum>>> {
let mut out = Vec::with_capacity(files.len());
match self {
RefFiles::Remote(source) => {
for (dir, name) in files {
let read = fetch_remote_ref(source, dir, name).await;
let last = !matches!(read, Ok(Some(_)));
out.push(read);
if last {
break;
}
}
}
RefFiles::Local(_) if files.is_empty() => {}
RefFiles::Local(src) => {
let relpaths: Vec<String> = files
.into_iter()
.map(|(dir, name)| format!("{dir}/{name}"))
.collect();
let src = src.clone();
out = ostrya_rt::unblock(move || {
for relpath in &relpaths {
let read = src.resolve_relpath_tip_blocking(relpath);
let last = !matches!(read, Ok(Some(_)));
out.push(read);
if last {
break;
}
}
out
})
.await;
}
}
out
}
}
async fn fetch_remote_ref(
source: &RemoteSource,
dir: &str,
name: &str,
) -> Result<Option<Checksum>> {
let path = source.ref_path(dir, name);
let Some(bytes) = source
.read_optional(&path, Priority::High, MAX_REF_FILE)
.await?
else {
return Ok(None);
};
let text = std::str::from_utf8(&bytes)
.map_err(|_| Error::InvalidFormat(format!("the remote ref {name} is not valid utf-8")))?;
Ok(Some(Checksum::from_hex(text.trim())?))
}
pub(super) fn ref_request_path(dir: &str, name: &str) -> String {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
let mut out = format!("{dir}/");
for byte in name.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
out.push(char::from(byte));
}
other => {
out.push('%');
out.push(char::from(HEX[usize::from(other >> 4)]));
out.push(char::from(HEX[usize::from(other & 0x0f)]));
}
}
}
out
}
pub(crate) async fn fetch_optional(
fetcher: &Fetcher,
path: &str,
priority: Priority,
max_size: u64,
) -> Result<Option<Vec<u8>>> {
fetch_unless(fetcher, path, priority, max_size, is_absent_status).await
}
pub(crate) async fn fetch_found(
fetcher: &Fetcher,
path: &str,
priority: Priority,
max_size: u64,
) -> Result<Option<Vec<u8>>> {
fetch_unless(fetcher, path, priority, max_size, |status| status == 404).await
}
async fn fetch_unless(
fetcher: &Fetcher,
path: &str,
priority: Priority,
max_size: u64,
absent: fn(u16) -> bool,
) -> Result<Option<Vec<u8>>> {
match fetch_whole(fetcher, path, priority, max_size).await {
Ok(bytes) => Ok(Some(bytes)),
Err(Error::HttpStatus { status, .. }) if absent(status) => Ok(None),
Err(e) => Err(e),
}
}
async fn fetch_whole(
fetcher: &Fetcher,
path: &str,
priority: Priority,
max_size: u64,
) -> Result<Vec<u8>> {
let mut refetch = fetcher.refetching(FetchRequest {
priority,
max_size: Some(max_size),
..FetchRequest::path(path)
});
loop {
let Fetched::Body(body) = refetch.fetch().await? else {
return Err(Error::Fetch(format!(
"{path}: the remote answered 304 to an unconditional request"
)));
};
let declared = body.content_length();
match read_whole(body, declared, max_size).await {
Ok(out) => return Ok(out),
Err(e) => refetch.retry(Error::from(e)).await?,
}
}
}
pub(super) async fn read_whole<R: AsyncRead + Unpin>(
mut body: R,
declared: Option<u64>,
max_size: u64,
) -> std::io::Result<Vec<u8>> {
let declared = usize::try_from(declared.unwrap_or(0).min(max_size)).unwrap_or(0);
let mut out = Vec::with_capacity(declared);
let mut chunk = vec![0u8; declared.saturating_add(1).clamp(4096, IO_CHUNK)];
loop {
let n = body.read(&mut chunk).await?;
if n == 0 {
return Ok(out);
}
out.extend_from_slice(&chunk[..n]);
}
}
pub(crate) async fn read_archive_header<R: AsyncRead + Unpin>(
mut stream: R,
) -> Result<(FileHeader, u64, Vec<u8>, R)> {
let mut prefix = [0u8; 8];
stream.read_exact(&mut prefix).await?;
if prefix[4..] != [0u8; 4] {
return Err(Error::InvalidFormat(
"content framing padding is not zero".into(),
));
}
let header_len =
u32::from_be_bytes(prefix[..4].try_into().expect("four bytes of a length")) as u64;
if header_len > MAX_FILE_HEADER_SIZE {
return Err(Error::InvalidFormat(
"content header exceeds the size cap".into(),
));
}
let mut bytes = vec![0u8; header_len as usize];
stream.read_exact(&mut bytes).await?;
let (header, uncompressed) = FileHeader::parse_archive(&bytes)?;
let mut framed = prefix.to_vec();
framed.extend_from_slice(&bytes);
Ok((header, uncompressed, framed, stream))
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn store_filez_payload<R: AsyncRead + Unpin>(
txn: &Transaction,
expected: &Checksum,
header: &FileHeader,
meta: &FileMeta,
declared: u64,
framed_header: &[u8],
mut body: R,
read_buf: &mut Vec<u8>,
) -> Result<()> {
if header.is_symlink() {
check_stream_end(expected, "symlink header", &mut body).await?;
txn.write_symlink(&header.symlink_target, meta, Some(expected))
.await?;
return Ok(());
}
let source = BoundedInput::new(body, *expected, compressed_bound(declared));
if txn.repo().mode().is_archive() {
txn.write_archive_payload(expected, header, framed_header, declared, source, read_buf)
.await
.map_err(payload_refusal)?;
return Ok(());
}
let mut writer = txn.content_writer(Some(expected), meta).await?;
let mut payload = DeflateDecoder::new(BufSource::new(source));
let short = copy_bounded(&mut payload, &mut writer, read_buf, expected, declared)
.await
.map_err(payload_refusal)?;
if short != 0 {
return Err(Error::InvalidFormat(format!(
"content object {expected}: the payload inflates to {} byte(s), not the \
{declared} its header declares",
declared - short
)));
}
check_stream_end(expected, "deflated payload", payload.into_inner())
.await
.map_err(payload_refusal)?;
writer.finish().await?;
Ok(())
}
async fn copy_bounded<R, W>(
mut reader: R,
writer: &mut W,
buf: &mut Vec<u8>,
expected: &Checksum,
declared: u64,
) -> Result<u64>
where
R: AsyncRead + Unpin,
W: futures_io::AsyncWrite + Unpin,
{
if buf.len() < READ_CHUNK {
buf.resize(READ_CHUNK, 0);
}
let mut left = declared;
loop {
let window = buf.len().min(
usize::try_from(left)
.unwrap_or(usize::MAX)
.saturating_add(1),
);
let n = reader.read(&mut buf[..window]).await?;
if n == 0 {
return Ok(left);
}
if n as u64 > left {
return Err(Error::InvalidFormat(format!(
"content object {expected}: the payload outgrew the {declared} \
byte(s) its header declares"
)));
}
left -= n as u64;
writer.write_all(&buf[..n]).await?;
}
}
pub(crate) fn compressed_bound(declared: u64) -> u64 {
declared
.saturating_add(declared / 1024)
.saturating_add(64 * 1024)
}
pub(crate) struct BoundedInput<R> {
inner: R,
checksum: Checksum,
bound: u64,
taken: u64,
}
impl<R> BoundedInput<R> {
pub(crate) fn new(inner: R, checksum: Checksum, bound: u64) -> BoundedInput<R> {
BoundedInput {
inner,
checksum,
bound,
taken: 0,
}
}
}
impl<R: AsyncRead + Unpin> AsyncRead for BoundedInput<R> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
let me = self.get_mut();
let n = ready!(Pin::new(&mut me.inner).poll_read(cx, buf))?;
me.taken += n as u64;
if me.taken > me.bound {
return Poll::Ready(Err(std::io::Error::other(Error::InvalidFormat(format!(
"content object {}: the compressed payload passed the {} byte(s) \
its declared size allows",
me.checksum, me.bound
)))));
}
Poll::Ready(Ok(n))
}
}
pub(crate) fn payload_refusal(error: Error) -> Error {
match error {
Error::Io(io) => io.downcast::<Error>().unwrap_or_else(Error::Io),
other => other,
}
}
pub(crate) async fn check_stream_end<R: AsyncRead + Unpin>(
expected: &Checksum,
after: &str,
mut stream: R,
) -> Result<()> {
let mut byte = [0u8; 1];
if stream.read(&mut byte).await? != 0 {
return Err(Error::InvalidFormat(format!(
"content object {expected}: bytes follow the {after}"
)));
}
Ok(())
}
const _: fn() = || {
fn assert_send<T: Send>(_: &T) {}
let _ = |repo: &Repo| assert_send(&repo.pull("origin", PullOptions::default()));
let _ = |repo: &Repo| assert_send(&repo.pull_with_report("origin", PullOptions::default()));
let _ = |repo: &Repo, session: PullSession| {
assert_send(&repo.pull_with_session(
session,
PullTrust::unverified(),
PullOptions::default(),
))
};
let _ = |repo: &Repo, src: &Repo| assert_send(&repo.pull_local(src, PullOptions::default()));
let _ = |repo: &Repo, src: &Repo| {
assert_send(&repo.pull_local_with_report(src, PullOptions::default()))
};
};
#[cfg(test)]
#[path = "../../tests/common/pipe.rs"]
mod test_pipe;
#[cfg(test)]
mod tests {
use super::*;
use crate::Ref;
use async_compression::futures::bufread::DeflateEncoder;
use futures_lite::io::Cursor;
use ostrya_core::Xattrs;
use ostrya_rt::block_on;
use std::pin::Pin;
use std::task::{Context, Poll};
fn framed(header: &FileHeader, uncompressed: u64, payload: &[u8]) -> Vec<u8> {
let bytes = header.serialize_archive(uncompressed).unwrap();
let mut out = Vec::new();
out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
out.extend_from_slice(&[0u8; 4]);
out.extend_from_slice(&bytes);
out.extend_from_slice(payload);
out
}
fn regular_header() -> FileHeader {
FileHeader {
uid: 0,
gid: 0,
mode: 0o100644,
symlink_target: String::new(),
xattrs: Xattrs::default(),
}
}
#[test]
fn the_header_is_read_off_the_front_and_the_payload_is_left() {
block_on(async {
let stored = framed(®ular_header(), 4, b"payload bytes");
let (header, declared, raw, mut rest) =
read_archive_header(Cursor::new(stored.clone()))
.await
.unwrap();
assert_eq!(header, regular_header());
assert_eq!(declared, 4);
assert_eq!(raw, stored[..stored.len() - b"payload bytes".len()]);
let mut payload = Vec::new();
rest.read_to_end(&mut payload).await.unwrap();
assert_eq!(payload, b"payload bytes");
});
}
#[test]
fn a_symlink_header_names_its_target() {
block_on(async {
let header = FileHeader {
uid: 0,
gid: 0,
mode: 0o120777,
symlink_target: "hello.txt".to_owned(),
xattrs: Xattrs::default(),
};
let stored = framed(&header, 0, b"");
let (parsed, _declared, _raw, mut rest) =
read_archive_header(Cursor::new(stored)).await.unwrap();
assert!(parsed.is_symlink());
assert_eq!(parsed.symlink_target, "hello.txt");
let mut payload = Vec::new();
rest.read_to_end(&mut payload).await.unwrap();
assert!(payload.is_empty());
});
}
#[test]
fn nonzero_framing_padding_is_rejected() {
block_on(async {
let mut stored = framed(®ular_header(), 0, b"");
stored[5] = 1;
let err = read_archive_header(Cursor::new(stored)).await.unwrap_err();
assert!(err.to_string().contains("padding"), "{err}");
});
}
#[test]
fn a_truncated_stream_fails_rather_than_ending() {
block_on(async {
let stored = framed(®ular_header(), 0, b"");
for cut in [4, 8, stored.len() - 1] {
let err = read_archive_header(Cursor::new(stored[..cut].to_vec()))
.await
.unwrap_err();
assert!(matches!(err, Error::Io(_)), "cut at {cut}: {err}");
}
});
}
struct Endless {
handed_out: usize,
}
impl AsyncRead for Endless {
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
if self.handed_out >= 4096 {
return Poll::Ready(Err(std::io::Error::other("the check read past the header")));
}
buf.fill(0);
self.handed_out += buf.len();
Poll::Ready(Ok(buf.len()))
}
}
#[test]
fn a_symlink_payload_is_refused_without_reading_it() {
block_on(async {
let mut stream = Endless { handed_out: 0 };
let err = check_stream_end(&csum(1), "symlink header", &mut stream)
.await
.unwrap_err();
assert!(err.to_string().contains("bytes follow"), "{err}");
assert_eq!(stream.handed_out, 1);
});
}
#[test]
fn the_check_sees_what_the_decoder_left_behind() {
block_on(async {
let mut encoder = DeflateEncoder::new(Cursor::new(b"hello ostree\n".to_vec()));
let mut compressed = Vec::new();
encoder.read_to_end(&mut compressed).await.unwrap();
for (trailing, expect_end) in [(&b""[..], true), (b"junk", false)] {
let mut stored = compressed.clone();
stored.extend_from_slice(trailing);
let mut decoder = DeflateDecoder::new(BufSource::new(Cursor::new(stored)));
let mut out = Vec::new();
copy_bounded(&mut decoder, &mut out, &mut Vec::new(), &csum(1), 13)
.await
.unwrap();
assert_eq!(out, b"hello ostree\n");
let result =
check_stream_end(&csum(1), "deflated payload", decoder.into_inner()).await;
assert_eq!(
result.is_ok(),
expect_end,
"trailing {trailing:?}: {result:?}"
);
}
});
}
#[test]
fn a_payload_outgrowing_its_declared_size_is_refused() {
block_on(async {
let mut stream = Endless { handed_out: 0 };
let mut out = Vec::new();
let err = copy_bounded(&mut stream, &mut out, &mut Vec::new(), &csum(1), 4)
.await
.unwrap_err();
assert!(err.to_string().contains("outgrew the 4 byte"), "{err}");
assert_eq!(stream.handed_out, 5);
});
}
struct EmptyBlocks {
handed_out: usize,
}
impl AsyncRead for EmptyBlocks {
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
const BLOCK: [u8; 5] = [0x00, 0x00, 0x00, 0xff, 0xff];
if self.handed_out >= 1024 * 1024 {
return Poll::Ready(Err(std::io::Error::other(
"the payload read past its compressed bound",
)));
}
let base = self.handed_out;
for (i, byte) in buf.iter_mut().enumerate() {
*byte = BLOCK[(base + i) % BLOCK.len()];
}
self.handed_out += buf.len();
Poll::Ready(Ok(buf.len()))
}
}
#[test]
fn a_compressed_payload_passing_its_bound_is_refused() {
block_on(async {
let mut source = EmptyBlocks { handed_out: 0 };
let mut out = Vec::new();
let bound = compressed_bound(13);
let err = {
let source = BoundedInput::new(&mut source, csum(1), bound);
let mut payload = DeflateDecoder::new(BufSource::new(source));
copy_bounded(&mut payload, &mut out, &mut Vec::new(), &csum(1), 13)
.await
.unwrap_err()
};
let err = payload_refusal(err);
assert!(matches!(err, Error::InvalidFormat(_)), "{err}");
assert!(
err.to_string()
.contains(&format!("passed the {bound} byte")),
"{err}"
);
assert!(out.is_empty());
assert!(
source.handed_out <= bound as usize + 16 * 1024,
"{} bytes taken for a {bound}-byte bound",
source.handed_out
);
});
}
#[test]
fn the_compressed_bound_holds_incompressible_data() {
block_on(async {
let mut state = 1u32;
let data: Vec<u8> = (0..200_000)
.map(|_| {
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(state >> 24) as u8
})
.collect();
let mut encoder = DeflateEncoder::new(Cursor::new(data.clone()));
let mut compressed = Vec::new();
encoder.read_to_end(&mut compressed).await.unwrap();
let declared = data.len() as u64;
let bound = compressed_bound(declared);
assert!(
compressed.len() as u64 <= bound,
"{} compressed bytes for a {bound}-byte bound",
compressed.len()
);
let source = BoundedInput::new(Cursor::new(compressed), csum(1), bound);
let mut payload = DeflateDecoder::new(BufSource::new(source));
let mut out = Vec::new();
copy_bounded(&mut payload, &mut out, &mut Vec::new(), &csum(1), declared)
.await
.unwrap();
assert_eq!(out, data);
});
}
#[test]
fn a_payload_within_its_declared_size_is_stored() {
block_on(async {
let mut buf = Vec::new();
for payload in [&b"four"[..], b"two"] {
let mut out = Vec::new();
copy_bounded(
Cursor::new(payload.to_vec()),
&mut out,
&mut buf,
&csum(1),
4,
)
.await
.unwrap();
assert_eq!(out, payload);
}
assert_eq!(buf.len(), READ_CHUNK);
});
}
#[test]
fn an_oversized_header_length_is_refused() {
block_on(async {
for header_len in [MAX_FILE_HEADER_SIZE as u32 + 1, u32::MAX] {
let mut stored = Vec::new();
stored.extend_from_slice(&header_len.to_be_bytes());
stored.extend_from_slice(&[0u8; 4]);
let err = read_archive_header(Cursor::new(stored)).await.unwrap_err();
assert!(err.to_string().contains("size cap"), "{header_len}: {err}");
}
});
}
#[test]
fn a_ref_request_path_encodes_the_name() {
let heads = |name| ref_request_path("refs/heads", name);
assert_eq!(heads("test/main"), "refs/heads/test/main");
assert_eq!(heads("a-b.c_d~e"), "refs/heads/a-b.c_d~e");
assert_eq!(heads("a?b"), "refs/heads/a%3Fb");
assert_eq!(heads("a#b"), "refs/heads/a%23b");
assert_eq!(heads("a%2fb"), "refs/heads/a%252fb");
assert_eq!(heads("a b\r\n"), "refs/heads/a%20b%0D%0A");
assert_eq!(heads("é"), "refs/heads/%C3%A9");
assert_eq!(
ref_request_path("refs/mirrors/org.example.Os", "a b"),
"refs/mirrors/org.example.Os/a%20b"
);
}
fn csum(byte: u8) -> Checksum {
Checksum::from_bytes([byte; 32])
}
fn object(byte: u8, ty: ObjectType) -> ObjectName {
ObjectName::new(csum(byte), ty)
}
fn fetched(checksum: Checksum, tree: Vec<ObjectName>, parent: Option<Checksum>) -> Step {
Step::Commit(CommitOutcome {
checksum,
next: CommitNext::Scan(tree),
parent,
attachments: Vec::new(),
marked: true,
})
}
fn by_delta(
checksum: Checksum,
parts: usize,
fallbacks: Vec<ObjectName>,
tree: Vec<ObjectName>,
) -> Step {
delta_outcome(checksum, parts, fallbacks, tree, false)
}
fn by_attachment_delta(checksum: Checksum, parts: usize, tree: Vec<ObjectName>) -> Step {
delta_outcome(checksum, parts, Vec::new(), tree, true)
}
fn delta_outcome(
checksum: Checksum,
parts: usize,
fallbacks: Vec<ObjectName>,
tree: Vec<ObjectName>,
lazy: bool,
) -> Step {
Step::Commit(CommitOutcome {
checksum,
next: CommitNext::Delta {
parts,
fallbacks,
tree,
lazy,
},
parent: None,
attachments: Vec::new(),
marked: true,
})
}
fn drain(plan: &mut Plan, marked: &mut Vec<Checksum>) {
while let Some(item) = plan.next() {
let step = match item {
Item::Object(name) if name.ty == ObjectType::DirTree => {
Step::DirTree(name.checksum, DirTree::default())
}
Item::Object(_) => Step::Done,
Item::Load(commit) => Step::Loaded(commit),
Item::Part(part) => Step::Part(part.commit),
Item::Commit(_) => panic!("the test queues no further commits"),
};
plan.apply(step, marked);
}
}
#[test]
fn a_commit_queues_the_objects_it_references() {
let mut plan = Plan::default();
let mut marked = Vec::new();
plan.push_commit(CommitItem {
checksum: csum(1),
depth: 0,
optional: false,
});
assert!(matches!(plan.next(), Some(Item::Commit(_))));
plan.apply(
fetched(
csum(1),
vec![
object(2, ObjectType::DirMeta),
object(3, ObjectType::DirTree),
],
None,
),
&mut marked,
);
assert_eq!(plan.scan.len(), 2);
drain(&mut plan, &mut marked);
assert!(plan.next().is_none());
assert_eq!(marked, [csum(1)]);
}
#[test]
fn an_object_several_commits_reach_is_queued_once() {
let mut plan = Plan::default();
let mut marked = Vec::new();
let shared = object(9, ObjectType::DirMeta);
for byte in [1u8, 2] {
plan.apply(fetched(csum(byte), vec![shared], None), &mut marked);
}
assert_eq!(plan.scan.len(), 1);
drain(&mut plan, &mut marked);
plan.apply(fetched(csum(3), vec![shared], None), &mut marked);
assert!(plan.next().is_none());
}
#[test]
fn a_commit_reached_deeper_resumes_at_its_parent() {
let mut plan = Plan::default();
let mut marked = Vec::new();
let tip = CommitItem {
checksum: csum(1),
depth: 0,
optional: false,
};
plan.push_commit(tip);
assert!(matches!(plan.next(), Some(Item::Commit(_))));
plan.apply(fetched(csum(1), Vec::new(), Some(csum(2))), &mut marked);
assert!(plan.next().is_none());
plan.push_commit(CommitItem {
checksum: csum(1),
depth: 1,
optional: false,
});
let Some(Item::Commit(next)) = plan.next() else {
panic!("the parent was not queued");
};
assert_eq!(next.checksum, csum(2));
assert_eq!(next.depth, 0);
assert!(next.optional);
assert!(plan.next().is_none());
}
#[test]
fn the_plan_drains_commits_then_scan_then_content() {
let mut plan = Plan::default();
let mut marked = Vec::new();
plan.apply(
fetched(
csum(1),
vec![
object(4, ObjectType::File),
object(2, ObjectType::DirMeta),
object(3, ObjectType::DirTree),
],
None,
),
&mut marked,
);
plan.push_commit(CommitItem {
checksum: csum(5),
depth: 0,
optional: false,
});
let mut drained = Vec::new();
while let Some(item) = plan.next() {
drained.push(match item {
Item::Commit(commit) => commit.checksum,
Item::Object(name) => name.checksum,
Item::Load(commit) => commit,
Item::Part(part) => part.commit,
});
}
assert_eq!(drained, [csum(5), csum(2), csum(3), csum(4)]);
}
#[test]
fn a_delta_queues_its_parts_before_the_tree() {
let mut plan = Plan::default();
let mut marked = Vec::new();
let fallback = object(7, ObjectType::File);
let tree = vec![
object(2, ObjectType::DirMeta),
object(3, ObjectType::DirTree),
];
plan.apply(by_delta(csum(1), 2, vec![fallback], tree), &mut marked);
assert!(matches!(plan.next(), Some(Item::Part(_))));
assert!(matches!(plan.next(), Some(Item::Part(_))));
let Some(Item::Object(name)) = plan.next() else {
panic!("the fallback was not queued");
};
assert_eq!(name, fallback);
assert!(plan.next().is_none());
plan.apply(Step::Part(csum(1)), &mut marked);
assert!(plan.next().is_none());
plan.apply(Step::Part(csum(1)), &mut marked);
let Some(Item::Object(name)) = plan.next() else {
panic!("the tree was not queued after the last part");
};
assert_eq!(name, object(2, ObjectType::DirMeta));
}
#[test]
fn the_part_cap_holds_however_many_parts_a_delta_has() {
let mut plan = Plan::default();
let mut marked = Vec::new();
plan.apply(by_delta(csum(1), 5, Vec::new(), Vec::new()), &mut marked);
let mut in_flight = 0;
let mut high_water = 0;
let mut applied = 0;
loop {
while let Some(item) = plan.next() {
assert!(matches!(item, Item::Part(_)));
in_flight += 1;
high_water = high_water.max(in_flight);
}
if in_flight == 0 {
break;
}
plan.apply(Step::Part(csum(1)), &mut marked);
in_flight -= 1;
applied += 1;
}
assert_eq!(high_water, PART_CAP);
assert_eq!(applied, 5);
}
#[test]
fn the_load_of_an_attachment_job_comes_before_its_parts() {
let mut plan = Plan::default();
let mut marked = Vec::new();
let tree = vec![object(2, ObjectType::DirMeta)];
plan.apply(by_attachment_delta(csum(1), 2, tree), &mut marked);
assert!(matches!(plan.next(), Some(Item::Load(commit)) if commit == csum(1)));
assert!(plan.loaded.contains(&csum(1)));
assert!(plan.next().is_none());
plan.apply(Step::Loaded(csum(1)), &mut marked);
assert!(matches!(plan.next(), Some(Item::Part(_))));
assert!(matches!(plan.next(), Some(Item::Part(_))));
assert!(plan.next().is_none());
plan.apply(Step::Part(csum(1)), &mut marked);
assert!(plan.loaded.contains(&csum(1)));
assert!(plan.delta_parts.contains_key(&csum(1)));
assert!(plan.next().is_none());
plan.apply(Step::Part(csum(1)), &mut marked);
assert!(plan.loaded.is_empty());
assert!(!plan.delta_parts.contains_key(&csum(1)));
let Some(Item::Object(name)) = plan.next() else {
panic!("the tree was not queued after the last part");
};
assert_eq!(name, object(2, ObjectType::DirMeta));
}
#[test]
fn an_attachment_run_holds_at_most_part_cap_jobs() {
block_on(async {
let dir = ScratchDir::new("dependency-jobs");
let archive = || crate::CreateOptions::new(RepoMode::Archive);
let src = Repo::create(&dir.0.join("src"), archive()).await.unwrap();
let dest = Repo::create(&dir.0.join("dest"), archive()).await.unwrap();
let mut deltas = Vec::new();
for name in ["d1", "d2", "d3", "d4", "d5"] {
let commit = commit_under(&src, name, name.as_bytes()).await;
src.generate_static_delta(None, &commit, &crate::DeltaOptions::default())
.await
.unwrap();
deltas.push((None, commit));
}
assert!(deltas.len() > PART_CAP);
let found = AttachmentDeltas::kept_from(&dest, &src, &deltas).await;
let run = RunDeltas::Lazy(&found);
let mut plan = Plan::default();
let mut marked = Vec::new();
for (_, commit) in &deltas {
let bytes = run.commit_bytes(commit).await.unwrap().unwrap();
assert_eq!(Checksum::sha256(&bytes), *commit);
assert!(found.holds_commit_data(commit));
let next = run.commit_next(commit, Vec::new());
let CommitNext::Delta {
parts, lazy: true, ..
} = next
else {
panic!("the attachment has no delta");
};
assert!(parts > 0);
assert!(run.commit_bytes(commit).await.unwrap().is_none());
assert!(!found.holds_commit_data(commit));
assert!(found.has_head(commit));
plan.apply(by_attachment_delta(*commit, parts, Vec::new()), &mut marked);
}
let mut in_flight = VecDeque::new();
let mut high_water = 0;
let mut loads = 0;
loop {
while let Some(item) = plan.next() {
in_flight.push_back(match item {
Item::Load(commit) => {
found.load_job(&dest, &commit).await.unwrap();
loads += 1;
Step::Loaded(commit)
}
Item::Part(part) => {
assert!(found.live_job(&part.commit).is_some());
Step::Part(part.commit)
}
Item::Object(_) => Step::Done,
Item::Commit(_) => panic!("the test queues no further commits"),
});
high_water = high_water.max(found.live_jobs());
assert!(found.live_jobs() <= PART_CAP);
}
let Some(step) = in_flight.pop_front() else {
break;
};
let part = match step {
Step::Part(commit) => Some(commit),
_ => None,
};
plan.apply(step, &mut marked);
if let Some(commit) = part
&& !plan.delta_parts.contains_key(&commit)
{
run.release(&commit);
assert!(found.live_job(&commit).is_none());
}
}
assert_eq!(loads, deltas.len());
assert_eq!(high_water, PART_CAP);
assert_eq!(found.live_jobs(), 0);
assert!(found.is_empty());
});
}
#[test]
fn a_commit_that_needs_no_delta_releases_the_attachment_head() {
block_on(async {
let dir = ScratchDir::new("dependency-head-release");
let archive = || crate::CreateOptions::new(RepoMode::Archive);
let src = Repo::create(&dir.0.join("src"), archive()).await.unwrap();
let dest = Repo::create(&dir.0.join("dest"), archive()).await.unwrap();
let commit = commit_under(&src, "d1", b"d1").await;
src.generate_static_delta(None, &commit, &crate::DeltaOptions::default())
.await
.unwrap();
let found = AttachmentDeltas::kept_from(&dest, &src, &[(None, commit)]).await;
assert!(found.holds_commit_data(&commit));
RunDeltas::Lazy(&found).release(&commit);
assert!(!found.has_head(&commit));
assert_eq!(found.live_jobs(), 0);
assert!(found.is_empty());
});
}
#[test]
fn the_progress_total_counts_the_parts_of_a_job_before_its_load() {
let total = |progress: &PullCounters| {
progress
.own
.objects_total
.load(std::sync::atomic::Ordering::Relaxed)
};
let tree = || vec![object(2, ObjectType::DirMeta)];
let mut marked = Vec::new();
let eager_progress = PullCounters::new(None);
let mut eager = Plan::default();
eager.apply(by_delta(csum(1), 3, Vec::new(), tree()), &mut marked);
eager.report(&eager_progress, 1, false);
let lazy_progress = PullCounters::new(None);
let mut lazy = Plan::default();
lazy.apply(by_attachment_delta(csum(1), 3, tree()), &mut marked);
lazy.report(&lazy_progress, 1, false);
assert_eq!(total(&lazy_progress), total(&eager_progress));
assert_eq!(total(&lazy_progress), 1 + 3);
assert!(matches!(lazy.next(), Some(Item::Load(_))));
lazy.report(&lazy_progress, 1, false);
assert_eq!(total(&lazy_progress), 1 + 3);
lazy.apply(Step::Loaded(csum(1)), &mut marked);
lazy.report(&lazy_progress, 1, false);
assert_eq!(total(&lazy_progress), 1 + 3);
assert_eq!(lazy.waiting_parts, 0);
}
struct EndBeforeStore<'a> {
inner: Cursor<Vec<u8>>,
txn: &'a Transaction,
checksum: Checksum,
ended: bool,
}
impl AsyncRead for EndBeforeStore<'_> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
let me = self.get_mut();
let n = ready!(Pin::new(&mut me.inner).poll_read(cx, buf))?;
if n == 0 && !buf.is_empty() {
assert!(
!me.txn.is_staged(&me.checksum, ObjectType::File),
"the object was stored before its stream ended"
);
me.ended = true;
}
Poll::Ready(Ok(n))
}
}
#[test]
fn the_stream_ends_before_the_object_is_stored() {
let dir =
std::env::temp_dir().join(format!("ostrya-pull-stream-end-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let payload = b"payload of a regular file".to_vec();
let symlink = FileHeader {
symlink_target: "target".to_owned(),
mode: 0o120777,
..regular_header()
};
block_on(async {
for (mode, header) in [
(RepoMode::Archive, regular_header()),
(RepoMode::BareUser, regular_header()),
(RepoMode::BareUser, symlink.clone()),
] {
let root = dir.join(format!("{}-{}", mode.as_mode_str(), header.is_symlink()));
let repo = Repo::create(&root, crate::CreateOptions::new(mode))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
let body = if header.is_symlink() {
Vec::new()
} else {
payload.clone()
};
let mut hasher = ostrya_core::ContentHasher::new(&header).unwrap();
hasher.update(&body);
let checksum = hasher.finish();
let mut deflated = Vec::new();
if !header.is_symlink() {
DeflateEncoder::new(&body[..])
.read_to_end(&mut deflated)
.await
.unwrap();
}
let stored = framed(&header, body.len() as u64, &deflated);
let (parsed, declared, framed_header, rest) =
read_archive_header(Cursor::new(stored)).await.unwrap();
let FileHeader {
uid,
gid,
mode: file_mode,
xattrs,
..
} = parsed.clone();
let meta = FileMeta {
uid,
gid,
mode: file_mode,
xattrs,
};
let mut stream = EndBeforeStore {
inner: rest,
txn: &txn,
checksum,
ended: false,
};
store_filez_payload(
&txn,
&checksum,
&parsed,
&meta,
declared,
&framed_header,
&mut stream,
&mut Vec::new(),
)
.await
.unwrap();
assert!(stream.ended, "{mode:?}: the stream was not read to its end");
assert!(txn.is_staged(&checksum, ObjectType::File), "{mode:?}");
}
});
let _ = std::fs::remove_dir_all(&dir);
}
fn pop_dirtree(plan: &mut Plan, byte: u8) {
loop {
match plan.next() {
Some(Item::Object(name)) if name.ty == ObjectType::DirMeta => continue,
Some(Item::Object(name)) => {
assert_eq!(name, object(byte, ObjectType::DirTree));
return;
}
_ => panic!("dirtree {byte} was not queued"),
}
}
}
#[test]
fn a_dirtree_reached_again_under_a_wider_scope_is_walked_again() {
let values = ["/p/x/".to_owned(), "/q/x".to_owned()];
let mut plan = Plan::new(Subpaths::parse(&values).unwrap());
let mut marked = Vec::new();
let root = DirTree {
files: Vec::new(),
dirs: vec![
("p".into(), csum(10), csum(2)),
("q".into(), csum(11), csum(2)),
],
};
let parent = DirTree {
files: Vec::new(),
dirs: vec![("x".into(), csum(20), csum(2))],
};
let x = DirTree {
files: vec![("f".into(), csum(30))],
dirs: Vec::new(),
};
plan.apply(
fetched(
csum(1),
vec![
object(2, ObjectType::DirMeta),
object(1, ObjectType::DirTree),
],
None,
),
&mut marked,
);
pop_dirtree(&mut plan, 1);
plan.apply(Step::DirTree(csum(1), root), &mut marked);
pop_dirtree(&mut plan, 10);
pop_dirtree(&mut plan, 11);
plan.apply(Step::DirTree(csum(10), parent.clone()), &mut marked);
pop_dirtree(&mut plan, 20);
plan.apply(Step::DirTree(csum(20), x.clone()), &mut marked);
assert!(plan.content.is_empty());
plan.apply(Step::DirTree(csum(11), parent), &mut marked);
pop_dirtree(&mut plan, 20);
plan.apply(Step::DirTree(csum(20), x.clone()), &mut marked);
assert_eq!(
plan.content.iter().copied().collect::<Vec<_>>(),
[object(30, ObjectType::File)]
);
plan.push_object(object(20, ObjectType::DirTree), Scope::All);
assert!(plan.scan.is_empty());
}
#[test]
fn a_delta_with_no_parts_queues_its_tree_at_once() {
let mut plan = Plan::default();
let mut marked = Vec::new();
plan.apply(
by_delta(
csum(1),
0,
vec![object(7, ObjectType::File)],
vec![object(2, ObjectType::DirMeta)],
),
&mut marked,
);
assert_eq!(plan.scan.len(), 1);
assert_eq!(plan.content.len(), 1);
assert!(plan.parts.is_empty());
}
fn naming(checksum: Checksum, parent: Option<Checksum>, atts: &[(&str, u8)]) -> Step {
Step::Commit(CommitOutcome {
checksum,
next: CommitNext::Nothing,
parent,
attachments: atts
.iter()
.map(|(name, byte)| ((*name).to_owned(), csum(*byte)))
.collect(),
marked: true,
})
}
fn next_commit(plan: &mut Plan) -> CommitItem {
match plan.next() {
Some(Item::Commit(item)) => item,
_ => panic!("the plan gave no commit"),
}
}
fn invalid_relations(err: Error) -> (Option<Checksum>, String) {
match err {
Error::InvalidRelations {
commit,
field: crate::related::RelationField::Attachments,
reason,
} => (commit, reason),
other => panic!("expected InvalidRelations in field 2, got {other:?}"),
}
}
#[test]
fn an_attachment_is_recorded_and_not_queued() {
let mut plan = Plan::default();
let mut marked = Vec::new();
plan.push_commit(CommitItem {
checksum: csum(1),
depth: -1,
optional: false,
});
next_commit(&mut plan);
plan.apply(
naming(csum(1), Some(csum(2)), &[("boot/uki", 3)]),
&mut marked,
);
let parent = next_commit(&mut plan);
assert_eq!((parent.checksum, parent.depth), (csum(2), -1));
assert!(parent.optional);
assert!(plan.next().is_none());
assert_eq!(marked, [csum(1)]);
assert_eq!(
plan.attachments.inner.named(&csum(3)),
Some((csum(1), "boot/uki"))
);
assert_eq!(
plan.attachments.inner.naming().get(&csum(1)),
Some(&vec![("boot/uki".to_owned(), csum(3))])
);
}
#[test]
fn an_attachment_two_commits_name_keeps_the_lowest_commit() {
for order in [[1, 2], [2, 1]] {
let mut plan = Plan::default();
let mut marked = Vec::new();
for byte in order {
let entries: &[(&str, u8)] = if byte == 1 {
&[("a/x", 3), ("a/y", 3)]
} else {
&[("b/x", 3)]
};
plan.apply(naming(csum(byte), None, entries), &mut marked);
}
assert!(plan.next().is_none());
assert_eq!(
plan.attachments.inner.named(&csum(3)),
Some((csum(1), "a/x")),
"{order:?}"
);
assert_eq!(plan.attachments.inner.order(), [csum(3)]);
assert_eq!(plan.attachments.inner.naming().len(), 2);
plan.apply(naming(csum(3), None, &[]), &mut marked);
assert_eq!(plan.parents.get(&csum(3)), Some(&None));
}
let mut plan = Plan::default();
let mut marked = Vec::new();
plan.apply(naming(csum(2), None, &[("b/x", 3)]), &mut marked);
plan.attachments.level += 1;
plan.apply(naming(csum(1), None, &[("a/x", 3)]), &mut marked);
assert_eq!(
plan.attachments.inner.named(&csum(3)),
Some((csum(2), "b/x"))
);
}
#[test]
fn a_nested_attachment_is_recorded_in_either_order() {
let mut plan = Plan::default();
let mut marked = Vec::new();
plan.apply(naming(csum(1), None, &[("lib/b", 2)]), &mut marked);
plan.apply(naming(csum(2), None, &[("lib/c", 3)]), &mut marked);
assert_eq!(marked, [csum(1), csum(2)]);
assert_eq!(plan.attachments.inner.order(), [csum(2), csum(3)]);
assert_eq!(
plan.attachments.inner.named(&csum(2)),
Some((csum(1), "lib/b"))
);
assert_eq!(
plan.attachments.inner.named(&csum(3)),
Some((csum(2), "lib/c"))
);
let mut plan = Plan::default();
plan.apply(naming(csum(2), None, &[("lib/c", 3)]), &mut marked);
plan.apply(naming(csum(1), None, &[("lib/b", 2)]), &mut marked);
assert_eq!(plan.attachments.inner.order(), [csum(3), csum(2)]);
assert_eq!(
plan.attachments.inner.named(&csum(3)),
Some((csum(2), "lib/c"))
);
assert!(plan.next().is_none());
}
#[test]
fn an_absent_parent_that_is_an_attachment_fails_in_each_order() {
let unheld = format!(
"attachment lib/b names commit {}, which neither a source nor this repository holds",
csum(2)
);
let steps = || {
[
naming(csum(1), None, &[("lib/b", 2)]),
naming(csum(4), None, &[("lib/x", 2)]),
Step::Absent(csum(2)),
]
};
for order in [
[0, 1, 2],
[0, 2, 1],
[1, 0, 2],
[1, 2, 0],
[2, 0, 1],
[2, 1, 0],
] {
let mut marked = Vec::new();
let mut plan = Plan::default();
let mut steps = steps().map(Some);
for at in order {
plan.apply(steps[at].take().unwrap(), &mut marked);
}
let err = plan.check_attachments().unwrap_err();
assert_eq!(
invalid_relations(err),
(Some(csum(1)), unheld.clone()),
"{order:?}"
);
}
let mut marked = Vec::new();
let mut plan = Plan::default();
plan.apply(Step::Absent(csum(2)), &mut marked);
plan.apply(naming(csum(1), None, &[("lib/b", 3)]), &mut marked);
plan.check_attachments().unwrap();
assert!(plan.attachments.inner.named(&csum(3)).is_some());
assert!(!plan.parents.contains_key(&csum(2)));
}
struct ScratchDir(std::path::PathBuf);
impl ScratchDir {
fn new(tag: &str) -> ScratchDir {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir()
.join(format!("ostrya-pull-jobs-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
ScratchDir(dir)
}
}
impl Drop for ScratchDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
const JOB_END: std::time::Duration = std::time::Duration::from_secs(120);
async fn commit_under(repo: &Repo, name: &str, content: &[u8]) -> Checksum {
let txn = repo.transaction().await.unwrap();
let dirmeta = ostrya_core::DirMeta {
uid: 0,
gid: 0,
mode: 0o40755,
xattrs: Default::default(),
};
let dirmeta = txn
.write_metadata(ObjectType::DirMeta, None, &dirmeta.serialize().unwrap())
.await
.unwrap();
let file = txn
.write_regfile_inline(None, &FileMeta::regular(0, 0, 0o644), content)
.await
.unwrap();
let mut mtree = crate::mtree::MutableTree::new();
mtree.set_metadata_checksum(dirmeta);
mtree.replace_file("f", file).unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let options = crate::commit::CommitOptions {
parent: None,
subject: None,
body: None,
timestamp: Some(1_700_000_000),
metadata: None,
attachments: Vec::new(),
};
let commit = txn.write_commit(options, &root).await.unwrap();
txn.set_ref(&Ref::local(name), Some(&commit));
txn.commit().await.unwrap();
commit
}
struct TwoRefs {
dir: ScratchDir,
src: Repo,
dest: Repo,
left: Checksum,
right: Checksum,
}
async fn two_refs(tag: &str) -> TwoRefs {
let dir = ScratchDir::new(tag);
let archive = || crate::CreateOptions::new(RepoMode::Archive);
let src = Repo::create(&dir.0.join("src"), archive()).await.unwrap();
let dest = Repo::create(&dir.0.join("dest"), archive()).await.unwrap();
let left = commit_under(&src, "left", b"left content").await;
let right = commit_under(&src, "right", b"right content").await;
TwoRefs {
dir,
src,
dest,
left,
right,
}
}
async fn pull_both_refs(src: &Repo, dest: &Repo) -> Result<PullStats> {
let opts = PullOptions {
refs: vec!["left".to_owned(), "right".to_owned()],
..PullOptions::default()
};
pull_over_stream(src, dest, opts).await
}
async fn pull_over_stream(src: &Repo, dest: &Repo, opts: PullOptions) -> Result<PullStats> {
let (to_server, server_in) = test_pipe::pipe(64 * 1024);
let (server_out, from_server) = test_pipe::pipe(64 * 1024);
let access = crate::access::ReadAccess::new(
Arc::new(crate::access::ClientAccess::implicit(None)),
crate::access::AuthItem::Anonymous,
None,
);
let (pulled, _) = futures_lite::future::zip(
async {
let session = PullSession::over_stream(
from_server,
to_server,
StreamSessionOptions::default(),
)
.await?;
dest.pull_with_session(session, PullTrust::unverified(), opts)
.await
},
async move { src.send(server_in, server_out, &access).await },
)
.await;
pulled
}
fn marker(repo: &Repo, commit: &Checksum) -> std::path::PathBuf {
repo.path().join(super::super::partial_path(commit))
}
#[test]
fn a_failed_pull_clears_the_marker_of_a_dropped_step() {
let fixture = block_on(two_refs("marker"));
let dest_root = fixture.dest.path().to_path_buf();
let held = format!("marker {}", fixture.left.to_hex());
let finished = crate::jobs::job_gate::hold(&dest_root, held.clone());
crate::jobs::job_gate::fail(
&dest_root,
format!("marker {}", fixture.right.to_hex()),
held,
);
let pulled = block_on(pull_both_refs(&fixture.src, &fixture.dest));
let err = pulled.unwrap_err();
assert!(err.to_string().contains("injected job failure"), "{err}");
finished.recv_timeout(JOB_END).unwrap();
for commit in [&fixture.left, &fixture.right] {
let path = marker(&fixture.dest, commit);
assert!(!path.exists(), "{} stays", path.display());
}
drop(fixture.dir);
}
#[test]
fn a_failed_pull_removes_the_staging_directory_after_a_dropped_step() {
let fixture = block_on(two_refs("staging"));
let dest_root = fixture.dest.path().to_path_buf();
let (commit, _) = block_on(fixture.src.load_commit(&fixture.left)).unwrap();
let held = format!("stage {}", commit.root_dirtree.to_hex());
let finished = crate::jobs::job_gate::hold(&dest_root, held.clone());
crate::jobs::job_gate::fail(
&dest_root,
format!("marker {}", fixture.right.to_hex()),
held,
);
let pulled = block_on(pull_both_refs(&fixture.src, &fixture.dest));
let err = pulled.unwrap_err();
assert!(err.to_string().contains("injected job failure"), "{err}");
let linked = finished.recv_timeout(JOB_END).unwrap();
assert!(
linked,
"the job ran after the removal of the staging directory"
);
let staging: Vec<_> = std::fs::read_dir(dest_root.join("tmp"))
.unwrap()
.map(|entry| entry.unwrap())
.filter(|entry| {
entry.file_name().to_string_lossy().starts_with("staging-")
&& entry.file_type().unwrap().is_dir()
})
.map(|entry| entry.file_name())
.collect();
assert!(staging.is_empty(), "{staging:?}");
drop(fixture.dir);
}
fn object_file(repo: &Repo, checksum: &Checksum, ty: ObjectType) -> std::path::PathBuf {
repo.path()
.join("objects")
.join(ostrya_core::loose_path(checksum, ty, RepoMode::Archive))
}
fn put_object_file(from: &std::path::Path, to: &std::path::Path) {
let _ = std::fs::remove_file(to);
std::fs::create_dir_all(to.parent().unwrap()).unwrap();
std::fs::copy(from, to).unwrap();
}
#[test]
fn a_localcache_commit_that_changes_after_the_checks_fails_the_pull() {
let fixture = block_on(two_refs("cache-commit"));
let cache = block_on(Repo::create(
&fixture.dir.0.join("cache"),
crate::CreateOptions::new(RepoMode::Archive),
))
.unwrap();
let commit =
|repo: &Repo, checksum: &Checksum| object_file(repo, checksum, ObjectType::Commit);
let cached = commit(&cache, &fixture.left);
put_object_file(&commit(&fixture.src, &fixture.right), &cached);
let good = commit(&fixture.src, &fixture.left);
let dest_root = fixture.dest.path().to_path_buf();
super::super::import_seam::arm(&dest_root, move || put_object_file(&good, &cached));
let opts = PullOptions {
refs: vec!["left".to_owned()],
localcache_repos: vec![cache],
..PullOptions::default()
};
let pulled = block_on(pull_over_stream(&fixture.src, &fixture.dest, opts));
let armed = super::super::import_seam::disarm(&dest_root);
assert!(!armed, "the pull did not read the cache");
match pulled {
Err(Error::ChecksumMismatch { expected, actual }) => {
assert_eq!((expected, actual), (fixture.left, fixture.right));
}
other => panic!("{other:?}"),
}
let stored = block_on(fixture.dest.has_object(ObjectType::Commit, &fixture.left));
assert!(!stored.unwrap(), "the pull stored the commit");
drop(fixture.dir);
}
#[test]
fn the_walk_reads_the_localcache_dirtree_that_the_pull_staged() {
let fixture = block_on(two_refs("cache-dirtree"));
let cache = block_on(Repo::create(
&fixture.dir.0.join("cache"),
crate::CreateOptions::new(RepoMode::Archive),
))
.unwrap();
let root = |commit: &Checksum| {
let (commit, _) = block_on(fixture.src.load_commit(commit)).unwrap();
commit.root_dirtree
};
let (left_root, right_root) = (root(&fixture.left), root(&fixture.right));
let dirtree =
|repo: &Repo, checksum: &Checksum| object_file(repo, checksum, ObjectType::DirTree);
let cached = dirtree(&cache, &left_root);
put_object_file(&dirtree(&fixture.src, &left_root), &cached);
let other = dirtree(&fixture.src, &right_root);
let dest_root = fixture.dest.path().to_path_buf();
super::super::import_seam::arm(&dest_root, move || put_object_file(&other, &cached));
let opts = PullOptions {
refs: vec!["left".to_owned()],
localcache_repos: vec![cache],
..PullOptions::default()
};
let pulled = block_on(pull_over_stream(&fixture.src, &fixture.dest, opts));
let armed = super::super::import_seam::disarm(&dest_root);
assert!(!armed, "the pull did not read the cache");
pulled.unwrap();
let file = |root: &Checksum| block_on(fixture.src.load_dirtree(root)).unwrap().files[0].1;
let (left_file, right_file) = (file(&left_root), file(&right_root));
let held = |checksum: &Checksum| {
block_on(fixture.dest.has_object(ObjectType::File, checksum)).unwrap()
};
assert!(held(&left_file), "the pull did not store the file of left");
assert!(!held(&right_file), "the pull stored the file of right");
drop(fixture.dir);
}
}