use std::collections::{HashMap, HashSet};
use futures_io::{AsyncRead, AsyncWrite};
use ostrya_core::{
Checksum, Commit, CommitLink, MAX_COLLECTION_ID_LEN, ObjectName, ObjectType, Ref,
};
use super::invalid;
use super::refspec::{PushTarget, in_collection};
use super::source::RepoSource;
use crate::error::{Error, Result};
use crate::lock::{LockGuard, LockKind};
use crate::read::CommitState;
use crate::related::{self, HeldAttachment, RelatedRule, RelationField};
use crate::remote::{
Compression, Endpoint, Expected, PushOutcome, PushProgress, PushSession, RefUpdate, ServerInfo,
SessionOptions,
};
use crate::repo::Repo;
#[derive(Clone, Debug, Default)]
pub struct RepoPushOptions {
pub refspecs: Vec<String>,
pub depth: Option<i32>,
pub collection: Option<String>,
pub tags: Vec<Ref>,
pub disable_verify_bindings: bool,
pub compression: Compression,
pub force: bool,
pub progress: Option<PushProgress>,
pub break_lock: bool,
#[doc(hidden)]
pub part_size: Option<u64>,
#[doc(hidden)]
pub bucket_max_outstanding: Option<usize>,
}
fn refuse_bucket_fields(opts: &RepoPushOptions) -> Result<()> {
let set = [
("break_lock", opts.break_lock),
("part_size", opts.part_size.is_some()),
(
"bucket_max_outstanding",
opts.bucket_max_outstanding.is_some(),
),
];
match set.iter().find(|(_, set)| *set) {
Some((name, _)) => Err(invalid(format!(
"{name} applies to a push to an s3:// address"
))),
None => Ok(()),
}
}
impl RepoPushOptions {
pub fn check(&self, to_bucket: bool) -> Result<()> {
if to_bucket {
#[cfg(feature = "s3")]
super::s3::refuse_options(self)?;
#[cfg(not(feature = "s3"))]
return Err(Error::Unsupported(
"a push to an s3:// address needs the S3 support of ostrya, and this build has \
none: turn on the feature s3 of ostrya"
.into(),
));
} else {
refuse_bucket_fields(self)?;
}
self.checked_tags().map(drop)
}
fn checked_tags(&self) -> Result<Vec<Ref>> {
if let Some(depth) = self.depth
&& depth < -1
{
return Err(invalid(format!("depth {depth} is below -1")));
}
let collection = self.collection.as_deref();
if let Some(reason) = collection.and_then(collection_id_refusal) {
return Err(invalid(reason));
}
check_tag_names(&self.tags, collection)
}
}
#[derive(Debug, Clone, Copy)]
pub(super) enum Local {
Held(CommitLink),
Partial,
Absent,
}
pub(super) fn link_of(commit: &Commit) -> CommitLink {
CommitLink {
parent: commit.parent,
root_dirtree: commit.root_dirtree,
root_dirmeta: commit.root_dirmeta,
}
}
type Loaded = (CommitLink, Result<Vec<(String, Checksum)>>);
#[derive(Default)]
pub(super) struct Commits {
pub(super) local: HashMap<Checksum, Local>,
fields: HashMap<Checksum, Result<Vec<(String, Checksum)>>>,
known: HashSet<Checksum>,
}
impl Commits {
pub(super) fn record(&mut self, commit: Checksum, field: Result<Vec<(String, Checksum)>>) {
if !field.as_ref().is_ok_and(Vec::is_empty) {
self.fields.insert(commit, field);
}
}
pub(super) fn check_fields<'a>(
&mut self,
commits: impl IntoIterator<Item = &'a Checksum>,
) -> Result<()> {
for commit in commits {
if self.fields.get(commit).is_some_and(Result::is_err) {
return self
.fields
.remove(commit)
.expect("the field is recorded")
.map(drop);
}
}
Ok(())
}
fn attachments_of(&self, commit: &Checksum) -> impl Iterator<Item = Checksum> + use<'_> {
self.fields
.get(commit)
.into_iter()
.flat_map(|field| field.iter().flatten())
.map(|(_, attachment)| *attachment)
}
pub(super) fn full_set<'a>(
&self,
commits: impl IntoIterator<Item = &'a Checksum>,
seen: &mut HashSet<Checksum>,
) -> Vec<Checksum> {
let mut found = Vec::new();
let mut add = |commit: &Checksum, found: &mut Vec<Checksum>| {
for attachment in self.attachments_of(commit) {
if seen.insert(attachment) {
found.push(attachment);
}
}
};
for commit in commits {
add(commit, &mut found);
}
let mut at = 0;
while let Some(commit) = found.get(at).copied() {
add(&commit, &mut found);
at += 1;
}
found
}
pub(super) async fn check_attachments<'a>(
&mut self,
repo: &Repo,
commits: impl IntoIterator<Item = &'a Checksum>,
) -> Result<()> {
let mut level: Vec<Checksum> = commits.into_iter().copied().collect();
while !level.is_empty() {
let mut named: Vec<(Checksum, Checksum, String)> = Vec::new();
for commit in &level {
let entries = match self.fields.get(commit) {
Some(Ok(entries)) => entries,
Some(Err(_)) => {
unreachable!("the field 2 of a resolved commit passed the check")
}
None => continue,
};
for (name, attachment) in entries {
if self.known.insert(*attachment) {
named.push((*attachment, *commit, name.clone()));
}
}
}
let unread: Vec<Checksum> = named
.iter()
.map(|(attachment, _, _)| *attachment)
.filter(|attachment| !self.local.contains_key(attachment))
.collect();
let mut loaded: HashMap<_, Result<HeldAttachment<Loaded>>> = if unread.is_empty() {
HashMap::new()
} else {
let repo = repo.clone();
ostrya_rt::unblock(move || {
unread
.into_iter()
.map(|key| {
let state = related::held_attachment_blocking(
&repo,
None,
&key,
|b, entries| {
let field = related::checked_entries(
RelationField::Attachments,
Some(key),
entries,
);
Ok((Commit::parse_link(b)?, field))
},
);
(key, state)
})
.collect()
})
.await
};
level.clear();
for (attachment, naming, name) in named {
if let Some(result) = loaded.remove(&attachment) {
let local = match result? {
HeldAttachment::Absent => Local::Absent,
HeldAttachment::Partial => Local::Partial,
HeldAttachment::Complete {
value: (link, field),
} => {
self.record(attachment, field);
Local::Held(link)
}
};
self.local.insert(attachment, local);
}
match self.local[&attachment] {
Local::Absent => {
return Err(Error::InvalidRelations {
commit: Some(naming),
field: RelationField::Attachments,
reason: related::attachment_reason(
&name,
&attachment,
related::ABSENT_REASON,
),
});
}
Local::Partial => {
return Err(related::partial_attachment(
Some(naming),
&name,
&attachment,
));
}
Local::Held(_) => self.check_fields([&attachment])?,
}
level.push(attachment);
}
}
Ok(())
}
}
pub(super) struct Plan {
pub(super) repo: Repo,
pub(super) _lock: LockGuard,
pub(super) refs: Vec<String>,
pub(super) targets: Vec<PushTarget>,
pub(super) tags: Vec<Ref>,
pub(super) sources: Vec<(Checksum, Option<String>)>,
pub(super) chains: Vec<Vec<Checksum>>,
pub(super) commits: Commits,
}
impl Repo {
pub async fn push(&self, endpoint: Endpoint, opts: RepoPushOptions) -> Result<PushOutcome> {
#[cfg(feature = "s3")]
let endpoint = match endpoint {
Endpoint::S3(s3) => {
return Ok(Box::pin(self.push_to_bucket(s3, opts)).await?.outcome);
}
other => other,
};
refuse_bucket_fields(&opts)?;
let transport = PushSession::prepare(endpoint).await?;
let plan = self.plan_push(&opts).await?;
let session = transport
.open(&plan.refs, plan.session_options(&opts))
.await?;
plan.run(session, &opts).await
}
pub async fn push_over_stream<R, W>(
&self,
input: R,
output: W,
opts: RepoPushOptions,
) -> Result<PushOutcome>
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
refuse_bucket_fields(&opts)?;
let plan = self.plan_push(&opts).await?;
let session =
PushSession::over_stream(input, output, &plan.refs, plan.session_options(&opts))
.await?;
plan.run(session, &opts).await
}
pub(super) async fn plan_push(&self, opts: &RepoPushOptions) -> Result<Plan> {
let tags = opts.checked_tags()?;
let collection = opts.collection.as_deref();
let lock = self.lock_repo(LockKind::Shared).await?;
let targets = self.push_targets(&opts.refspecs, collection).await?;
let mut sources: Vec<(Checksum, Commit)> = Vec::new();
let mut commits = Commits::default();
for target in &targets {
let Some(checksum) = target.commit else {
continue;
};
let position = match sources.iter().position(|(c, _)| *c == checksum) {
Some(position) => position,
None => {
let (mut commit, state) = self.load_commit(&checksum).await?;
if state == CommitState::Partial {
return Err(invalid(format!(
"commit {checksum} for '{}' is marked partial in the local \
repository",
target.dst
)));
}
commits
.local
.insert(checksum, Local::Held(link_of(&commit)));
let related = std::mem::take(&mut commit.related);
commits.record(checksum, related::checked_attachments(&checksum, related));
sources.push((checksum, commit));
sources.len() - 1
}
};
if !opts.disable_verify_bindings {
check_ref_binding(&checksum, &sources[position].1, &target.dst)?;
}
}
check_tags(&tags, &targets, &sources, opts.disable_verify_bindings)?;
let sources: Vec<(Checksum, Option<String>)> = sources
.into_iter()
.map(|(checksum, commit)| (checksum, commit.collection_binding().map(str::to_owned)))
.collect();
check_binding_ids(&sources)?;
for (name, commit) in updates(&targets, &tags, &sources) {
check_named_collection(&commit, binding(&sources, &commit), name, false)?;
}
let depth = opts.depth.unwrap_or(-1);
let mut chains = Vec::with_capacity(targets.len());
for target in &targets {
let mut chain = Vec::new();
if let Some(source) = target.commit {
let mut next = match commits.local[&source] {
Local::Held(link) => link.parent,
Local::Partial | Local::Absent => unreachable!("a source commit is held"),
};
let mut remaining = depth;
while remaining != 0
&& let Some(parent) = next
{
match self.history_commit(&parent, &mut commits).await? {
Local::Held(link) => {
chain.push(parent);
next = link.parent;
}
Local::Partial => {
if opts.depth.is_none() {
chain.push(parent);
}
break;
}
Local::Absent => break,
}
if remaining > 0 {
remaining -= 1;
}
}
}
chains.push(chain);
}
let walked = sources
.iter()
.map(|(checksum, _)| checksum)
.chain(chains.iter().flatten());
commits.check_fields(walked.clone())?;
match opts.depth {
Some(_) => commits.check_attachments(self, walked).await?,
None => {
let sources = sources.iter().map(|(checksum, _)| checksum);
commits.check_attachments(self, sources).await?;
}
}
Ok(Plan {
repo: self.clone(),
_lock: lock,
refs: targets
.iter()
.map(|t| &t.dst)
.chain(&tags)
.map(Ref::to_string)
.collect(),
targets,
tags,
chains,
sources,
commits,
})
}
pub(super) async fn history_commit(
&self,
checksum: &Checksum,
commits: &mut Commits,
) -> Result<Local> {
if let Some(local) = commits.local.get(checksum) {
return Ok(*local);
}
let repo = self.clone();
let key = *checksum;
let (local, field) = ostrya_rt::unblock(move || -> Result<_> {
let Some(bytes) = repo.held_object_bytes_blocking(ObjectType::Commit, &key)? else {
return Ok((Local::Absent, None));
};
Ok(match repo.commit_state_blocking(&key)? {
CommitState::Normal => {
let field = related::parse_attachments(&bytes).and_then(|entries| {
related::checked_entries(RelationField::Attachments, Some(key), entries)
});
(Local::Held(Commit::parse_link(&bytes)?), Some(field))
}
CommitState::Partial => (Local::Partial, None),
})
})
.await?;
commits.local.insert(*checksum, local);
if let Some(field) = field {
commits.record(*checksum, field);
}
Ok(local)
}
}
pub(super) fn check_tag_names(tags: &[Ref], collection: Option<&str>) -> Result<Vec<Ref>> {
let mut checked = Vec::with_capacity(tags.len());
for tag in tags {
tag.validate()?;
match tag {
Ref::Remote { .. } => return Err(Error::InvalidRefspec(tag.to_string())),
Ref::Local { name } if ostrya_core::is_checksum_shaped(name) => {
return Err(Error::InvalidRefspec(tag.to_string()));
}
_ => {}
}
checked.push(in_collection(tag.clone(), collection, "tag")?);
}
let mut seen = HashSet::new();
for tag in &checked {
if !seen.insert(tag) {
return Err(invalid(format!("the tag '{tag}' is named twice")));
}
}
Ok(checked)
}
fn check_tags(
tags: &[Ref],
targets: &[PushTarget],
sources: &[(Checksum, Commit)],
skip_ref_binding: bool,
) -> Result<()> {
if tags.is_empty() {
return Ok(());
}
let dsts: HashSet<&Ref> = targets.iter().map(|t| &t.dst).collect();
if let Some(tag) = tags.iter().find(|tag| dsts.contains(tag)) {
return Err(invalid(format!(
"the tag '{tag}' is also the destination of a refspec"
)));
}
let (checksum, commit) = match sources {
[] => return Err(invalid("a tag needs a refspec that is not a delete")),
[source] => source,
_ => {
return Err(invalid(format!(
"a tag needs one source commit, and the refspecs give {}",
sources.len()
)));
}
};
if skip_ref_binding {
return Ok(());
}
let bindings = commit.ref_bindings();
for tag in tags {
if !bindings.contains(&tag.name()) {
return Err(binding_mismatch(format!(
"commit {checksum} is bound to the refs {bindings:?}, which do not hold the \
tag '{}'",
tag.name()
)));
}
}
Ok(())
}
pub(super) fn collection_id_refusal(id: &str) -> Option<String> {
if id.len() > MAX_COLLECTION_ID_LEN {
Some(format!(
"the collection id of {} bytes is longer than {MAX_COLLECTION_ID_LEN} bytes",
id.len()
))
} else if !ostrya_core::is_collection_id(id) {
Some(format!("invalid collection id '{id}'"))
} else {
None
}
}
fn check_binding_ids(sources: &[(Checksum, Option<String>)]) -> Result<()> {
for (checksum, binding) in sources {
if let Some(reason) = binding.as_deref().and_then(collection_id_refusal) {
return Err(invalid(format!(
"commit {checksum} has a collection binding that a push cannot name: {reason}"
)));
}
}
Ok(())
}
fn updates<'a>(
targets: &'a [PushTarget],
tags: &'a [Ref],
sources: &'a [(Checksum, Option<String>)],
) -> impl Iterator<Item = (&'a Ref, Checksum)> {
let written = targets
.iter()
.filter_map(|t| t.commit.map(|commit| (&t.dst, commit)));
let tagged = sources
.first()
.into_iter()
.flat_map(move |(commit, _)| tags.iter().map(move |tag| (tag, *commit)));
written.chain(tagged)
}
pub(super) fn binding<'a>(
sources: &'a [(Checksum, Option<String>)],
commit: &Checksum,
) -> Option<&'a str> {
sources
.iter()
.find(|(c, _)| c == commit)
.and_then(|(_, binding)| binding.as_deref())
}
pub(super) fn check_named_collection(
checksum: &Checksum,
bound: Option<&str>,
name: &Ref,
refuse_unbound: bool,
) -> Result<()> {
let Ref::Collection { id, .. } = name else {
return Ok(());
};
match bound {
Some(bound) if bound != id => Err(binding_mismatch(format!(
"commit {checksum} is bound to the collection '{bound}', not '{id}' of ref '{name}'"
))),
None if refuse_unbound => Err(unbound_in_collection(checksum, name)),
_ => Ok(()),
}
}
pub(super) fn check_collection_binding(
checksum: &Checksum,
bound: Option<&str>,
name: &Ref,
own: Option<&str>,
) -> Result<()> {
if matches!(name, Ref::Remote { .. }) && own.is_none() {
return Ok(());
}
let collection = match name {
Ref::Collection { id, .. } if Some(id.as_str()) != own => Some(id.as_str()),
_ => None,
};
match (bound, collection.or(own)) {
(Some(bound), Some(id)) if bound == id => Ok(()),
(Some(bound), Some(id)) => Err(binding_mismatch(format!(
"commit {checksum} is bound to the collection '{bound}', not '{id}' of ref '{name}'"
))),
(Some(bound), None) => Err(binding_mismatch(format!(
"commit {checksum} is bound to the collection '{bound}', and ref '{name}' is a \
local ref of a repository with no collection id"
))),
(None, _) if collection.is_some() => Err(unbound_in_collection(checksum, name)),
(None, _) => Ok(()),
}
}
fn unbound_in_collection(checksum: &Checksum, name: &Ref) -> Error {
binding_mismatch(format!(
"commit {checksum} has no collection binding, which a ref of the collection of ref \
'{name}' needs"
))
}
fn check_namespaces(
server: &ServerInfo,
targets: &[PushTarget],
tags: &[Ref],
sources: &[(Checksum, Option<String>)],
) -> Result<()> {
let own = server.collection_id.as_deref();
check_written_shape(own, updates(targets, tags, sources).map(|(name, _)| name))?;
for (name, commit) in updates(targets, tags, sources) {
check_collection_binding(&commit, binding(sources, &commit), name, own)?;
}
Ok(())
}
pub(super) fn check_written_shape<'a>(
own: Option<&str>,
written: impl IntoIterator<Item = &'a Ref>,
) -> Result<()> {
for r in written {
let name = match r {
Ref::Local { name } => name,
Ref::Collection { id, name } if Some(id.as_str()) == own => name,
_ => continue,
};
if ostrya_core::is_checksum_shaped(name) {
return Err(Error::InvalidRefspec(r.to_string()));
}
}
Ok(())
}
fn binding_mismatch(message: String) -> Error {
Error::Remote(crate::remote::Error::BindingMismatch(message))
}
pub(super) fn check_ref_binding(checksum: &Checksum, commit: &Commit, dst: &Ref) -> Result<()> {
if commit.metadata_value("ostree.ref-binding").is_none() {
return Ok(());
}
let bindings = commit.ref_bindings();
let name = dst.name();
if bindings.contains(&name) {
return Ok(());
}
Err(binding_mismatch(format!(
"commit {checksum} is bound to the refs {bindings:?}, which do not hold '{name}'"
)))
}
impl Plan {
fn session_options(&self, opts: &RepoPushOptions) -> SessionOptions {
SessionOptions {
progress: opts.progress.clone(),
..SessionOptions::default()
}
}
async fn run(mut self, session: PushSession, opts: &RepoPushOptions) -> Result<PushOutcome> {
match self.negotiate(&session, opts).await {
Ok(updates) => Ok(session.commit(&updates, opts.force).await?),
Err(e) => {
let _ = session.abort().await;
Err(e)
}
}
}
async fn negotiate(
&mut self,
session: &PushSession,
opts: &RepoPushOptions,
) -> Result<Vec<RefUpdate>> {
let server = session.server();
check_namespaces(server, &self.targets, &self.tags, &self.sources)?;
if let Some((tag, current)) = self.tags.iter().find_map(|tag| {
let tag = tag.to_string();
server.tip(&tag).map(|tip| (tag, tip))
}) {
return Err(Error::Remote(crate::remote::Error::RefMismatch {
message: format!("ref '{tag}' is at {current}"),
name: tag,
current: Some(current),
}));
}
let chains = std::mem::take(&mut self.chains);
let mut offered: HashSet<Checksum> = HashSet::new();
let mut names = Vec::new();
for (target, chain) in self.targets.iter().zip(&chains) {
let Some(source) = target.commit else {
continue;
};
let tip = server.tip(&target.dst.to_string());
let history = offered_history(opts.depth, tip, chain);
for commit in std::iter::once(&source).chain(history) {
if offered.insert(*commit) {
names.push(ObjectName::new(*commit, ObjectType::Commit));
}
}
}
drop(chains);
if opts.depth.is_none() {
let offer = names.iter().map(|name| &name.checksum);
self.commits.check_attachments(&self.repo, offer).await?;
}
let attachments = self
.commits
.full_set(names.iter().map(|name| &name.checksum), &mut offered);
names.extend(
attachments
.into_iter()
.map(|attachment| ObjectName::new(attachment, ObjectType::Commit)),
);
drop(offered);
let commits = std::mem::take(&mut self.commits);
if !names.is_empty() {
let missing_commits = session.missing(&names).await?;
drop(names);
let lacking: HashSet<Checksum> = missing_commits.iter().map(|n| n.checksum).collect();
let sources: HashSet<Checksum> = self.sources.iter().map(|(c, _)| *c).collect();
let walked = self
.sources
.iter()
.map(|(c, _)| *c)
.chain(
missing_commits
.iter()
.map(|n| n.checksum)
.filter(|c| !sources.contains(c)),
)
.collect::<Vec<_>>();
let mut seen = HashSet::new();
let mut tree_names = Vec::new();
for commit in &walked {
let Local::Held(link) = commits.local[commit] else {
unreachable!("an offered commit is held");
};
self.repo
.collect_tree_strict(
link.root_dirtree,
link.root_dirmeta,
&mut seen,
&mut tree_names,
)
.await?;
}
drop(commits);
drop(seen);
let missing_trees = session.missing(&tree_names).await?;
drop(tree_names);
let mut needed = missing_commits;
needed.extend(missing_trees);
let mut metadata: Vec<Checksum> = needed
.iter()
.filter(|n| n.ty == ObjectType::Commit)
.map(|n| n.checksum)
.collect();
metadata.extend(
self.sources
.iter()
.map(|(c, _)| *c)
.filter(|c| !lacking.contains(c)),
);
let source = RepoSource::new(self.repo.clone(), RelatedRule::default());
session
.send(&source, &needed, &metadata, opts.compression)
.await?;
}
let tags = self.tags.iter().map(|tag| RefUpdate {
name: tag.to_string(),
expected: Expected::Absent,
new: self.sources.first().map(|(c, _)| *c),
});
Ok(self
.targets
.iter()
.map(|target| {
let name = target.dst.to_string();
let expected = match (opts.force, server.tip(&name)) {
(true, _) => Expected::Any,
(false, Some(tip)) => Expected::Commit(tip),
(false, None) => Expected::Absent,
};
RefUpdate {
name,
expected,
new: target.commit,
}
})
.chain(tags)
.collect())
}
}
pub(super) fn offered_history(
depth: Option<i32>,
tip: Option<Checksum>,
chain: &[Checksum],
) -> &[Checksum] {
match (depth, tip) {
(Some(_), _) => chain,
(None, Some(tip)) => match chain.iter().position(|c| *c == tip) {
Some(at) => &chain[..at],
None => &[],
},
(None, None) => &[],
}
}
#[cfg(test)]
mod tests {
use super::*;
fn csum(byte: u8) -> Checksum {
Checksum::from_bytes([byte; 32])
}
fn sources(bindings: &[Option<&str>]) -> Vec<(Checksum, Option<String>)> {
bindings
.iter()
.enumerate()
.map(|(i, b)| (csum(i as u8 + 1), b.map(str::to_owned)))
.collect()
}
fn mismatch<T: std::fmt::Debug>(result: Result<T>) -> String {
match result {
Err(Error::Remote(crate::remote::Error::BindingMismatch(message))) => message,
other => panic!("expected BindingMismatch, got {other:?}"),
}
}
fn server(collection_id: Option<&str>) -> ServerInfo {
ServerInfo {
version: 1,
mode: "archive".into(),
collection_id: collection_id.map(str::to_owned),
max_frame: 1 << 20,
max_have: 16_384,
encodings: Vec::new(),
parallel_uploads: 1,
refs: Vec::new(),
}
}
fn invalid_input<T: std::fmt::Debug>(result: Result<T>) -> String {
match result {
Err(Error::Remote(crate::remote::Error::InvalidInput(message))) => message,
other => panic!("expected InvalidInput, got {other:?}"),
}
}
fn r(text: &str) -> Ref {
text.parse().unwrap()
}
#[test]
fn a_binding_that_names_no_namespace_is_invalid_input() {
let longest = format!("org.{}", "a".repeat(251));
let over = format!("org.{}", "a".repeat(252));
assert_eq!(collection_id_refusal(&longest), None);
check_binding_ids(&sources(&[None, Some(&longest)])).unwrap();
for (binding, needle) in [("no-dot", "'no-dot'"), (over.as_str(), "256 bytes")] {
let message = invalid_input(check_binding_ids(&sources(&[None, Some(binding)])));
assert!(message.contains(needle), "{message}");
assert!(message.contains(&csum(2).to_string()), "{message}");
assert!(
collection_id_refusal(binding).is_some_and(|reason| reason.contains(needle)),
"{binding}"
);
}
}
#[test]
fn a_ref_of_a_collection_needs_a_commit_of_that_collection() {
let c = csum(1);
let x = r("@org.example.X:a");
check_named_collection(&c, Some("org.example.X"), &x, true).unwrap();
check_named_collection(&c, None, &x, false).unwrap();
let message = mismatch(check_named_collection(&c, None, &x, true));
assert!(message.contains("no collection binding"), "{message}");
assert!(message.contains("'@org.example.X:a'"), "{message}");
let message = mismatch(check_named_collection(&c, Some("org.example.Y"), &x, false));
assert!(
message.contains("'org.example.Y', not 'org.example.X'"),
"{message}"
);
for name in [r("main"), r("o:main")] {
for bound in [None, Some("org.example.Y")] {
check_named_collection(&c, bound, &name, true).unwrap();
}
}
}
#[test]
fn each_ref_takes_the_binding_of_its_namespace() {
let c = csum(1);
let x = Some("org.example.X");
let y = Some("org.example.Y");
let check = |bound, name: &str, own| check_collection_binding(&c, bound, &r(name), own);
check(None, "main", None).unwrap();
check(None, "main", x).unwrap();
check(x, "main", x).unwrap();
let message = mismatch(check(x, "main", None));
assert!(message.contains("no collection id"), "{message}");
let message = mismatch(check(y, "main", x));
assert!(message.contains("not 'org.example.X'"), "{message}");
check(None, "@org.example.X:a", x).unwrap();
check(x, "@org.example.X:a", x).unwrap();
mismatch(check(y, "@org.example.X:a", x));
check(x, "@org.example.X:a", None).unwrap();
check(x, "@org.example.X:a", y).unwrap();
let message = mismatch(check(None, "@org.example.X:a", y));
assert!(message.contains("no collection binding"), "{message}");
mismatch(check(None, "@org.example.X:a", None));
mismatch(check(y, "@org.example.X:a", y));
check(x, "o:main", None).unwrap();
check(x, "o:main", x).unwrap();
let message = mismatch(check(y, "o:main", x));
assert!(message.contains("not 'org.example.X'"), "{message}");
}
#[test]
fn the_checks_after_hello_reply_use_the_collection_id_of_the_server() {
let target = |dst: &str, commit| PushTarget {
dst: r(dst),
commit,
};
let x = Some("org.example.X");
let os = sources(&[x]);
let targets = [
target("main", Some(csum(1))),
target("@org.example.X:b", Some(csum(1))),
];
check_namespaces(&server(x), &targets, &[r("t")], &os).unwrap();
let message = mismatch(check_namespaces(&server(None), &targets, &[], &os));
assert!(message.contains("ref 'main'"), "{message}");
check_namespaces(&server(None), &[target("main", None)], &[], &[]).unwrap();
let unbound = sources(&[None]);
let message = mismatch(check_namespaces(
&server(x),
&[target("main", Some(csum(1)))],
&[r("@org.example.Y:t")],
&unbound,
));
assert!(message.contains("'@org.example.Y:t'"), "{message}");
}
#[test]
fn a_written_ref_of_the_own_id_and_64_hex_is_refused() {
let own = format!("@org.example.X:{}", "ab".repeat(32));
let target = |dst: &str, commit| PushTarget {
dst: r(dst),
commit,
};
let x = Some("org.example.X");
let os = sources(&[x]);
let refused = |result: Result<()>| match result {
Err(Error::InvalidRefspec(text)) => assert_eq!(text, own),
other => panic!("expected InvalidRefspec, got {other:?}"),
};
let written = [target(&own, Some(csum(1)))];
refused(check_namespaces(&server(x), &written, &[], &os));
let main = [target("main", Some(csum(1)))];
refused(check_namespaces(&server(x), &main, &[r(&own)], &os));
check_namespaces(&server(x), &[target(&own, None)], &[], &[]).unwrap();
check_namespaces(&server(None), &written, &[], &os).unwrap();
check_namespaces(&server(Some("org.example.Y")), &written, &[], &os).unwrap();
}
#[test]
fn a_tag_takes_the_collection_of_the_push() {
let hex = "ab".repeat(32);
let x = Some("org.example.X");
assert_eq!(
check_tag_names(&[r("a"), r("@org.example.X:b")], x).unwrap(),
[r("@org.example.X:a"), r("@org.example.X:b")]
);
assert_eq!(
check_tag_names(&[r("a"), r("@org.example.Y:b")], None).unwrap(),
[r("a"), r("@org.example.Y:b")]
);
for tag in [
Ref::remote("o", "a"),
Ref::local(hex.as_str()),
Ref::local("a b"),
] {
match check_tag_names(std::slice::from_ref(&tag), None) {
Err(Error::InvalidRefspec(text)) => assert_eq!(text, tag.to_string()),
other => panic!("{tag}: {other:?}"),
}
}
let message = invalid_input(check_tag_names(&[r("@org.example.Y:b")], x));
assert!(
message.contains("names the collection 'org.example.Y'"),
"{message}"
);
let message = invalid_input(check_tag_names(&[r("a"), r("@org.example.X:a")], x));
assert!(
message.contains("'@org.example.X:a' is named twice"),
"{message}"
);
check_tag_names(&[Ref::collection("org.example.X", hex.as_str())], None).unwrap();
}
#[test]
fn the_offered_history_ends_before_the_tip() {
let chain = [csum(1), csum(2), csum(3)];
assert_eq!(offered_history(Some(0), Some(csum(2)), &chain), chain);
assert_eq!(
offered_history(None, Some(csum(3)), &chain),
[csum(1), csum(2)]
);
assert_eq!(offered_history(None, Some(csum(1)), &chain), []);
assert!(offered_history(None, Some(csum(9)), &chain).is_empty());
assert!(offered_history(None, None, &chain).is_empty());
}
#[test]
fn the_bucket_fields_are_refused_for_a_session_push() {
refuse_bucket_fields(&RepoPushOptions::default()).unwrap();
for (opts, name) in [
(
RepoPushOptions {
break_lock: true,
..RepoPushOptions::default()
},
"break_lock",
),
(
RepoPushOptions {
part_size: Some(5 << 20),
..RepoPushOptions::default()
},
"part_size",
),
(
RepoPushOptions {
bucket_max_outstanding: Some(2),
..RepoPushOptions::default()
},
"bucket_max_outstanding",
),
] {
match refuse_bucket_fields(&opts) {
Err(Error::Remote(crate::remote::Error::InvalidInput(message))) => {
assert_eq!(
message,
format!("{name} applies to a push to an s3:// address")
);
}
other => panic!("{name}: {other:?}"),
}
}
}
#[test]
fn check_refuses_the_options_that_need_no_repository() {
let d = RepoPushOptions::default;
let message = |result: Result<()>| match result {
Err(Error::Remote(crate::remote::Error::InvalidInput(message))) => message,
other => panic!("expected InvalidInput, got {other:?}"),
};
let valid = RepoPushOptions {
depth: Some(-1),
collection: Some("org.example.A".into()),
tags: vec![Ref::local("v1")],
force: true,
..d()
};
valid.check(false).unwrap();
let deep = RepoPushOptions {
depth: Some(-2),
..d()
};
assert_eq!(message(deep.check(false)), "depth -2 is below -1");
let bad_id = RepoPushOptions {
collection: Some("a".into()),
..d()
};
assert!(bad_id.check(false).is_err());
let checksum_tag = RepoPushOptions {
tags: vec![Ref::local("a".repeat(64))],
..d()
};
assert!(matches!(
checksum_tag.check(false),
Err(Error::InvalidRefspec(_))
));
let both = RepoPushOptions {
break_lock: true,
..deep.clone()
};
assert_eq!(
message(both.check(false)),
"break_lock applies to a push to an s3:// address"
);
#[cfg(feature = "s3")]
{
let compressed = RepoPushOptions {
compression: Compression::Deflate { level: 6 },
..deep.clone()
};
assert!(message(compressed.check(true)).contains("names a compression"));
assert!(message(valid.check(true)).contains("creates no tag"));
assert_eq!(message(deep.check(true)), "depth -2 is below -1");
RepoPushOptions {
break_lock: true,
..d()
}
.check(true)
.unwrap();
}
#[cfg(not(feature = "s3"))]
assert!(matches!(d().check(true), Err(Error::Unsupported(_))));
}
}