use std::collections::{HashMap, HashSet};
use std::fmt;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use ostrya_core::{Checksum, RefSelector, Value, is_collection_id};
use crate::endpoint::{EndpointOverrides, resolve_pull};
use crate::error::{Error, Result};
use crate::fetch::{Fetcher, Priority};
use crate::refs::{MAX_COLLECTION_ID_LEN, check_ref_path};
use crate::remote::proto::{MAX_REF_ENTRY_LEN, MAX_REF_ENTRY_PARTS, MAX_REF_PATTERNS};
use crate::remote::{Endpoint, PullSession, StreamSession, StreamSessionOptions};
use crate::repo::Repo;
use crate::send::write_escaped;
use crate::summary::{
COLLECTION_ID_KEY, COMMIT_TIMESTAMP_KEY, SUMMARY_FILE, Summary, SummaryRef,
collection_map_refs, parse_ref_list,
};
use crate::verify::PullTrust;
use super::http::{MAX_ROOT_FILE, Pinned, Wanted, connect, session_options};
use super::source::RemoteSource;
use super::subpath::Subpaths;
use super::verify::Verification;
use super::{
PullFlags, PullOptions, PullStats, PullVerify, RefPlace, check_depth, refuse_remote_collection,
};
const LISTING_PATH: &str = "_ostrya/refs/v1";
const MAX_LISTING_TARGET: usize = 16 * 1024;
const LISTING_BUDGET: usize = MAX_LISTING_TARGET - LISTING_PATH.len();
#[derive(Default)]
#[non_exhaustive]
pub struct CollectionPullOptions {
pub pull: PullOptions,
pub on_event: Option<Box<dyn FnMut(CollectionPullEvent) + Send>>,
}
impl fmt::Debug for CollectionPullOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CollectionPullOptions")
.field("pull", &self.pull)
.field("on_event", &self.on_event.as_ref().map(|_| "<callback>"))
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CollectionPullEvent {
#[non_exhaustive]
RemoteSkipped {
remote: String,
message: String,
},
}
impl fmt::Display for CollectionPullEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CollectionPullEvent::RemoteSkipped { remote, message } => {
f.write_str("remote ")?;
write_escaped(f, remote)?;
f.write_str(" skipped: ")?;
write_escaped(f, message)
}
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct CollectionPullStats {
pub refs: Vec<CollectionPullRef>,
pub stats: PullStats,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CollectionPullRef {
pub name: String,
pub remote: String,
pub commit: Checksum,
pub timestamp: u64,
}
struct Candidate<'a> {
name: &'a str,
transport: Transport,
trust: PullTrust,
}
enum Transport {
Http(Fetcher),
Ssh(Box<Endpoint>, StreamSessionOptions),
}
impl Transport {
async fn new(endpoint: Endpoint, max_outstanding: Option<usize>) -> Result<Transport> {
let (endpoint, stream) = session_options(endpoint, max_outstanding);
Ok(match endpoint {
Endpoint::Http(_) => {
let PullSession::Http(fetcher) = connect(endpoint, stream).await? else {
unreachable!("an HTTP endpoint opens an HTTP session");
};
Transport::Http(fetcher)
}
Endpoint::Ssh {
ref address,
ref options,
} => {
StreamSession::check_command_line(address, options)?;
Transport::Ssh(Box::new(endpoint), stream)
}
})
}
async fn open(&self) -> Result<PullSession> {
match self {
Transport::Http(fetcher) => Ok(PullSession::Http(fetcher.clone())),
Transport::Ssh(endpoint, stream) => {
connect(Endpoint::clone(endpoint), stream.clone()).await
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Listed {
name: String,
commit: Checksum,
timestamp: u64,
}
struct Probed {
listed: Vec<Listed>,
summary: Option<Arc<Vec<u8>>>,
session: PullSession,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Selected {
remote: usize,
listed: Listed,
}
impl Repo {
pub async fn pull_collection(
&self,
collection_id: &str,
remotes: &[&str],
opts: CollectionPullOptions,
) -> Result<CollectionPullStats> {
let started = Instant::now();
let CollectionPullOptions {
pull: opts,
mut on_event,
} = opts;
let subpaths = check_collection_pull(collection_id, remotes, &opts)?;
let names = first_of_each(opts.refs.iter().map(String::as_str));
let mut candidates = Vec::with_capacity(remotes.len());
for name in first_of_each(remotes.iter().copied()) {
let endpoint = resolve_pull(Some(self.config()), name, opts.overrides.clone()).await?;
let trust = PullTrust::from_remote(self, name, &opts.verify).await?;
let transport = Transport::new(endpoint, opts.max_outstanding_fetches).await?;
candidates.push(Candidate {
name,
transport,
trust,
});
}
let mut answers = Vec::with_capacity(candidates.len());
let mut sessions = Vec::with_capacity(candidates.len());
let mut summaries = Vec::with_capacity(candidates.len());
for candidate in &candidates {
let probed = Box::pin(probe(candidate, collection_id, &names)).await;
match probed {
Ok(probed) => {
answers.push(Some(probed.listed));
sessions.push(Some(probed.session));
summaries.push(probed.summary);
}
Err(e) => {
if let Some(on_event) = on_event.as_mut() {
on_event(CollectionPullEvent::RemoteSkipped {
remote: candidate.name.to_owned(),
message: e.to_string(),
});
}
answers.push(None);
sessions.push(None);
summaries.push(None);
}
}
}
let selected = match select(collection_id, &names, &answers) {
Ok(selected) => selected,
Err(e) => {
end_sessions(sessions.into_iter().flatten()).await;
return Err(e);
}
};
drop(answers);
let unselected = take_unselected(&mut sessions, &mut summaries, |index| {
selected.iter().any(|s| s.remote == index)
});
end_sessions(unselected).await;
let place = if self.config().collection_id() == Some(collection_id) {
RefPlace::Heads
} else {
RefPlace::Collection(collection_id)
};
let candidate_names: Vec<&str> = candidates.iter().map(|c| c.name).collect();
let mut stats = PullStats::default();
for (index, candidate) in candidates.into_iter().enumerate() {
let Some(session) = sessions[index].take() else {
continue;
};
let mine: Vec<&Listed> = selected
.iter()
.filter(|selected| selected.remote == index)
.map(|selected| &selected.listed)
.collect();
let pinned = Pinned {
targets: mine.iter().map(|l| (l.name.clone(), l.commit)).collect(),
listed: mine.iter().map(|l| (l.name.clone(), l.timestamp)).collect(),
collection: collection_id,
place,
summary: Mutex::new(summaries[index].take()),
};
let run = PullOptions {
refs: pinned
.targets
.iter()
.map(|(name, _)| name.clone())
.collect(),
verify: PullVerify::default(),
max_outstanding_fetches: None,
overrides: EndpointOverrides::default(),
..opts.clone()
};
let pulled = self
.run_session(
session,
candidate.trust,
run,
Wanted::Pinned(&pinned),
subpaths.clone(),
None,
Instant::now(),
)
.await;
match pulled {
Ok(pulled) => add_stats(&mut stats, &pulled),
Err(e) => {
end_sessions(sessions.into_iter().flatten()).await;
return Err(e);
}
}
}
stats.elapsed = started.elapsed();
let refs = selected
.into_iter()
.map(|selected| CollectionPullRef {
name: selected.listed.name,
remote: candidate_names[selected.remote].to_owned(),
commit: selected.listed.commit,
timestamp: selected.listed.timestamp,
})
.collect();
Ok(CollectionPullStats { refs, stats })
}
}
fn first_of_each<'a>(values: impl Iterator<Item = &'a str>) -> Vec<&'a str> {
let mut seen = HashSet::new();
values.filter(|value| seen.insert(*value)).collect()
}
fn take_unselected<S, M>(
sessions: &mut [Option<S>],
summaries: &mut [Option<M>],
selected: impl Fn(usize) -> bool,
) -> Vec<S> {
sessions
.iter_mut()
.zip(summaries.iter_mut())
.enumerate()
.filter(|(index, _)| !selected(*index))
.filter_map(|(_, (session, summary))| {
*summary = None;
session.take()
})
.collect()
}
async fn end_sessions(sessions: impl IntoIterator<Item = PullSession>) {
for session in sessions {
let _ = session.finish().await;
}
}
fn check_collection_pull(
collection_id: &str,
remotes: &[&str],
opts: &PullOptions,
) -> Result<Option<Subpaths>> {
if !is_collection_id(collection_id) || collection_id.len() > MAX_COLLECTION_ID_LEN {
return Err(Error::InvalidInput(format!(
"invalid collection id: {collection_id}"
)));
}
if remotes.is_empty() {
return Err(Error::InvalidInput(
"a collection pull needs at least one remote".into(),
));
}
let subpaths = Subpaths::parse(&opts.subpaths)?;
check_depth(opts.depth)?;
refuse_remote_collection(opts)?;
if opts.remote.is_some() {
return Err(Error::InvalidInput(
"a collection pull writes the refs of the collection, and takes no remote option"
.into(),
));
}
if opts.flags.contains(PullFlags::MIRROR) {
return Err(Error::InvalidInput(
"a collection pull takes no MIRROR flag".into(),
));
}
if opts.flags.contains(PullFlags::DISABLE_VERIFY_BINDINGS) {
return Err(Error::InvalidInput(
"a collection pull checks the bindings of each commit, and takes no \
DISABLE_VERIFY_BINDINGS flag"
.into(),
));
}
if opts.static_deltas.is_some() {
return Err(Error::InvalidInput(
"a collection pull takes no static_deltas list".into(),
));
}
if opts.overrides.url.is_some() {
return Err(Error::InvalidInput(
"a collection pull reads the address of each remote from the config, and takes \
no url override"
.into(),
));
}
for name in &opts.refs {
check_ref_path(name)?;
}
for name in &opts.refs {
check_listing_name(collection_id, name)?;
}
Ok(subpaths)
}
fn check_listing_name(id: &str, name: &str) -> Result<()> {
let entry_len = id.len() + 1 + name.len();
let parts = 1 + name.split('/').count();
if entry_len > MAX_REF_ENTRY_LEN
|| parts > MAX_REF_ENTRY_PARTS
|| name_cost(id, name) > LISTING_BUDGET
{
return Err(Error::InvalidInput(format!(
"the ref name '{name}' is too long for a ref listing request of the collection \
'{id}'"
)));
}
Ok(())
}
fn encoded_len(value: &str) -> usize {
value
.bytes()
.map(|byte| {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
1
} else {
3
}
})
.sum()
}
fn name_cost(id: &str, name: &str) -> usize {
let pattern = "pattern=".len() + encoded_len(name);
let collection = "collection=".len() + encoded_len(id) + encoded_len("/") + encoded_len(name);
pattern + collection + 2
}
async fn probe(candidate: &Candidate<'_>, id: &str, names: &[&str]) -> Result<Probed> {
let session = candidate.transport.open().await?;
let http = matches!(session, PullSession::Http(_));
let source = RemoteSource::new(session, Vec::new());
let verification = Verification::from_trust(candidate.trust.clone());
match probe_source(&source, &verification, id, names, http).await {
Ok((listed, summary)) => Ok(Probed {
listed,
summary,
session: source.into_session(),
}),
Err(e) => source.finish(Err(e)).await,
}
}
type Refs = (Vec<Listed>, Option<Arc<Vec<u8>>>);
async fn probe_source(
source: &RemoteSource,
verification: &Verification,
id: &str,
names: &[&str],
http: bool,
) -> Result<Refs> {
if verification.checks_summary() {
return summary_refs(source, verification, id, names).await;
}
if names.is_empty() {
return every_ref(source, verification, id).await;
}
let mut listed = Vec::new();
for chunk in listing_chunks(id, names, http) {
let refs = RefSelector::parse(chunk.iter().copied())?;
let entries: Vec<String> = chunk.iter().map(|name| format!("{id}/{name}")).collect();
let collections = RefSelector::parse(entries.iter().map(String::as_str))?;
let Some(bytes) = read_listing(source, &refs, Some(&collections)).await? else {
return summary_refs(source, verification, id, names).await;
};
listed.extend(parse_refs(Arc::new(bytes), id, chunk).await?.1);
}
Ok((listed, None))
}
async fn every_ref(source: &RemoteSource, verification: &Verification, id: &str) -> Result<Refs> {
let no_local = RefSelector::parse(["!**"])?;
let entry = format!("{id}/**");
let collections = RefSelector::parse([entry.as_str()])?;
let Some(bytes) = read_listing(source, &no_local, Some(&collections)).await? else {
return summary_refs(source, verification, id, &[]).await;
};
let (own, listed) = parse_refs(Arc::new(bytes), id, &[]).await?;
if !own {
return Ok((listed, None));
}
let each_local = RefSelector::parse(std::iter::empty())?;
let Some(bytes) = read_listing(source, &each_local, None).await? else {
return summary_refs(source, verification, id, &[]).await;
};
Ok((parse_refs(Arc::new(bytes), id, &[]).await?.1, None))
}
async fn read_listing(
source: &RemoteSource,
refs: &RefSelector,
collections: Option<&RefSelector>,
) -> Result<Option<Vec<u8>>> {
match source.ref_listing(refs, collections).await {
Err(Error::HttpStatus {
status: 400..=499, ..
}) => Ok(None),
other => other,
}
}
async fn summary_refs(
source: &RemoteSource,
verification: &Verification,
id: &str,
names: &[&str],
) -> Result<Refs> {
let summary = if verification.checks_summary() {
let (summary, signature) = source.summary_files().await?;
verification
.check_summary(summary.as_deref(), signature)
.await?;
summary
} else {
source
.read_optional(SUMMARY_FILE, Priority::High, MAX_ROOT_FILE)
.await?
};
let Some(bytes) = summary else {
return Ok((Vec::new(), None));
};
let bytes = Arc::new(bytes);
let (_, listed) = parse_refs(Arc::clone(&bytes), id, names).await?;
Ok((listed, Some(bytes)))
}
async fn parse_refs(bytes: Arc<Vec<u8>>, id: &str, names: &[&str]) -> Result<(bool, Vec<Listed>)> {
let id = id.to_owned();
let wanted: Option<HashSet<String>> =
(!names.is_empty()).then(|| names.iter().map(|name| (*name).to_owned()).collect());
ostrya_rt::unblock(move || collection_refs(&bytes, &id, wanted.as_ref())).await
}
fn collection_refs(
bytes: &[u8],
id: &str,
wanted: Option<&HashSet<String>>,
) -> Result<(bool, Vec<Listed>)> {
let metadata = Summary::parse_metadata(bytes)?;
let own = metadata
.dict_get(COLLECTION_ID_KEY)
.and_then(Value::as_variant)
.and_then(|(_, value)| value.as_str())
== Some(id);
let entries = if own {
drop(metadata);
parse_ref_list(bytes)?
} else {
collection_map_refs(&metadata, id)?
};
let mut seen = HashSet::new();
let mut out = Vec::new();
for entry in &entries {
if wanted.is_some_and(|wanted| !wanted.contains(&entry.name))
|| !seen.insert(entry.name.as_str())
{
continue;
}
check_ref_path(&entry.name)?;
out.push(Listed {
name: entry.name.clone(),
commit: entry.commit,
timestamp: listed_timestamp(entry)?,
});
}
Ok((own, out))
}
fn listed_timestamp(entry: &SummaryRef) -> Result<u64> {
match entry
.metadata
.dict_get(COMMIT_TIMESTAMP_KEY)
.and_then(Value::as_variant)
{
Some((ty, Value::U64(raw))) if ty.signature() == "t" => Ok(raw.swap_bytes()),
_ => Err(Error::InvalidFormat(format!(
"the ref '{}' is listed with no {COMMIT_TIMESTAMP_KEY} of type t",
entry.name
))),
}
}
fn listing_chunks<'n, 'a>(id: &str, names: &'n [&'a str], http: bool) -> Vec<&'n [&'a str]> {
let mut chunks = Vec::new();
let mut start = 0;
let mut cost = 0;
for (index, name) in names.iter().enumerate() {
let this = if http { name_cost(id, name) } else { 0 };
if index > start
&& (2 * (index - start) >= MAX_REF_PATTERNS || cost + this > LISTING_BUDGET)
{
chunks.push(&names[start..index]);
start = index;
cost = 0;
}
cost += this;
}
if start < names.len() {
chunks.push(&names[start..]);
}
chunks
}
fn select(id: &str, names: &[&str], answers: &[Option<Vec<Listed>>]) -> Result<Vec<Selected>> {
if answers.iter().all(Option::is_none) {
return Err(Error::Pull(format!(
"no remote of collection '{id}' answered"
)));
}
let mut best: HashMap<&str, (usize, &Listed)> = HashMap::new();
for (remote, listed) in answers.iter().enumerate() {
for listed in listed.iter().flatten() {
best.entry(listed.name.as_str())
.and_modify(|current| {
if listed.timestamp > current.1.timestamp {
*current = (remote, listed);
}
})
.or_insert((remote, listed));
}
}
let order: Vec<&str> = if names.is_empty() {
if best.is_empty() {
return Err(Error::Pull(format!(
"no remote lists a ref of collection '{id}'"
)));
}
let mut all: Vec<&str> = best.keys().copied().collect();
all.sort_unstable();
all
} else {
names.to_vec()
};
order
.into_iter()
.map(|name| match best.get(name) {
Some((remote, listed)) => Ok(Selected {
remote: *remote,
listed: (*listed).clone(),
}),
None => Err(Error::Pull(format!(
"no remote of collection '{id}' lists the ref '{name}'"
))),
})
.collect()
}
fn add_stats(total: &mut PullStats, pulled: &PullStats) {
total.metadata_imported += pulled.metadata_imported;
total.content_imported += pulled.content_imported;
total.content_bytes_written += pulled.content_bytes_written;
total.content_bytes_unpacked += pulled.content_bytes_unpacked;
total.metadata_fetched += pulled.metadata_fetched;
total.content_fetched += pulled.content_fetched;
total.delta_parts += pulled.delta_parts;
total.bytes_transferred += pulled.bytes_transferred;
}
const _: fn() = || {
fn assert_send<T: Send>(_: &T) {}
fn assert_send_sync<T: Send + Sync>() {}
let _ = |repo: &Repo| {
assert_send(&repo.pull_collection(
"org.example.Os",
&["origin"],
CollectionPullOptions::default(),
))
};
assert_send_sync::<CollectionPullStats>();
assert_send_sync::<CollectionPullEvent>();
};
#[cfg(test)]
mod tests {
use ostrya_core::{Type, to_bytes};
use super::*;
use crate::fetch::FetcherOptions;
fn csum(byte: u8) -> Checksum {
Checksum::from_bytes([byte; 32])
}
fn listed(name: &str, byte: u8, timestamp: u64) -> Listed {
Listed {
name: name.to_owned(),
commit: csum(byte),
timestamp,
}
}
type TestRefs<'a> = &'a [(&'a str, u8, u64)];
fn ref_value(name: &str, byte: u8, metadata: Value) -> Value {
Value::Tuple(vec![
Value::Str(name.to_owned()),
Value::Tuple(vec![
Value::U64(1),
Value::Bytes(csum(byte).as_bytes().to_vec()),
metadata,
]),
])
}
fn ref_values(refs: TestRefs<'_>) -> Vec<Value> {
refs.iter()
.map(|(name, byte, ts)| {
let timestamp = Value::Tuple(vec![
Value::Str(COMMIT_TIMESTAMP_KEY.to_owned()),
Value::Variant(Box::new((
Type::parse("t").unwrap(),
Value::U64(ts.swap_bytes()),
))),
]);
ref_value(name, *byte, Value::Array(vec![timestamp]))
})
.collect()
}
fn summary_of(field0: Vec<Value>, map: &[(&str, TestRefs<'_>)], own: Option<&str>) -> Vec<u8> {
let mut metadata = Vec::new();
if !map.is_empty() {
let entries = map
.iter()
.map(|(id, refs)| {
Value::Tuple(vec![
Value::Str((*id).to_owned()),
Value::Array(ref_values(refs)),
])
})
.collect();
metadata.push(Value::Tuple(vec![
Value::Str("ostree.summary.collection-map".to_owned()),
Value::Variant(Box::new((
Type::parse("a{sa(s(taya{sv}))}").unwrap(),
Value::Array(entries),
))),
]));
}
if let Some(own) = own {
metadata.push(Value::Tuple(vec![
Value::Str(COLLECTION_ID_KEY.to_owned()),
Value::Variant(Box::new((
Type::parse("s").unwrap(),
Value::Str(own.to_owned()),
))),
]));
}
let value = Value::Tuple(vec![Value::Array(field0), Value::Array(metadata)]);
to_bytes(&Type::parse("(a(s(taya{sv}))a{sv})").unwrap(), &value).unwrap()
}
fn summary(field0: TestRefs<'_>, map: &[(&str, TestRefs<'_>)], own: Option<&str>) -> Vec<u8> {
summary_of(ref_values(field0), map, own)
}
#[test]
fn the_unselected_remotes_leave_their_sessions_and_summaries() {
let mut sessions = vec![Some('a'), None, Some('c'), Some('d')];
let mut summaries = vec![Some(1), None, Some(3), Some(4)];
let taken = take_unselected(&mut sessions, &mut summaries, |index| index == 2);
assert_eq!(taken, ['a', 'd']);
assert_eq!(sessions, [None, None, Some('c'), None]);
assert_eq!(summaries, [None, None, Some(3), None]);
}
#[test]
fn the_own_collection_reads_field_0() {
let s = summary(
&[("os/stable", 1, 10), ("os/next", 2, 20)],
&[("org.example.Os", &[("os/stable", 9, 99)])],
Some("org.example.Os"),
);
let refs = collection_refs(&s, "org.example.Os", None).unwrap();
assert_eq!(
refs,
(
true,
vec![listed("os/stable", 1, 10), listed("os/next", 2, 20)]
)
);
}
#[test]
fn another_collection_reads_the_map_and_ignores_field_0() {
let s = summary(
&[("os/stable", 1, 10)],
&[
("org.example.Other", &[("os/stable", 7, 70)]),
(
"org.example.Os",
&[("os/stable", 3, 30), ("os/next", 4, 40)],
),
],
Some("org.example.Mine"),
);
let wanted: HashSet<String> = ["os/stable".to_owned()].into();
let refs = collection_refs(&s, "org.example.Os", Some(&wanted)).unwrap();
assert_eq!(refs, (false, vec![listed("os/stable", 3, 30)]));
let s = summary(&[("os/stable", 1, 10)], &[], None);
assert_eq!(
collection_refs(&s, "org.example.Os", None).unwrap(),
(false, Vec::new())
);
}
#[test]
fn a_ref_with_no_valid_timestamp_fails() {
let no_key = summary_of(
vec![ref_value("os/stable", 1, Value::Array(Vec::new()))],
&[],
Some("org.example.Os"),
);
let other_type = summary_of(
vec![ref_value(
"os/stable",
1,
Value::Array(vec![Value::Tuple(vec![
Value::Str(COMMIT_TIMESTAMP_KEY.to_owned()),
Value::Variant(Box::new((Type::parse("u").unwrap(), Value::U32(1)))),
])]),
)],
&[],
Some("org.example.Os"),
);
for s in [no_key, other_type] {
assert!(matches!(
collection_refs(&s, "org.example.Os", None),
Err(Error::InvalidFormat(_))
));
}
}
#[test]
fn the_newest_commit_wins_and_a_tie_goes_to_the_earlier_remote() {
let answers = vec![
Some(vec![listed("a", 1, 10), listed("b", 2, 20)]),
None,
Some(vec![listed("a", 3, 30), listed("b", 4, 20)]),
];
let selected = select("org.example.Os", &["b", "a"], &answers).unwrap();
assert_eq!(
selected,
[
Selected {
remote: 0,
listed: listed("b", 2, 20)
},
Selected {
remote: 2,
listed: listed("a", 3, 30)
},
]
);
}
#[test]
fn selection_takes_each_listed_ref_or_fails_a_missing_one() {
let answers = vec![
Some(vec![listed("b", 2, 20)]),
Some(vec![listed("a", 1, 10)]),
];
let names: Vec<String> = select("org.example.Os", &[], &answers)
.unwrap()
.into_iter()
.map(|s| s.listed.name)
.collect();
assert_eq!(names, ["a", "b"]);
let err = select("org.example.Os", &["c"], &answers).unwrap_err();
assert!(
matches!(&err, Error::Pull(m) if m.contains("'c'") && m.contains("org.example.Os")),
"{err:?}"
);
let err = select("org.example.Os", &["a"], &[None, None]).unwrap_err();
assert!(matches!(err, Error::Pull(_)), "{err:?}");
let err = select("org.example.Os", &[], &[Some(Vec::new()), None]).unwrap_err();
assert!(
matches!(&err, Error::Pull(m) if m == "no remote lists a ref of collection 'org.example.Os'"),
"{err:?}"
);
}
#[test]
fn the_names_split_by_the_entry_limit_and_the_byte_budget() {
let short: Vec<String> = (0..300).map(|n| format!("r{n}")).collect();
let short: Vec<&str> = short.iter().map(String::as_str).collect();
for http in [true, false] {
let chunks = listing_chunks("org.example.Os", &short, http);
assert_eq!(
chunks.iter().map(|c| c.len()).collect::<Vec<_>>(),
[
MAX_REF_PATTERNS / 2,
MAX_REF_PATTERNS / 2,
300 - MAX_REF_PATTERNS
]
);
}
let long = "x".repeat(4000);
let names = [long.as_str(), long.as_str(), long.as_str(), "a"];
let chunks = listing_chunks("org.example.Os", &names, true);
assert_eq!(chunks.iter().map(|c| c.len()).collect::<Vec<_>>(), [2, 2]);
assert_eq!(listing_chunks("org.example.Os", &names, false).len(), 1);
assert!(listing_chunks("org.example.Os", &[], true).is_empty());
}
#[test]
fn the_byte_budget_matches_the_request_target_of_the_client() {
ostrya_rt::block_on(async {
let id = "org.example.Oss";
let mut opts = FetcherOptions::new("http://127.0.0.1:1/");
opts.max_retries = 0;
let session = PullSession::Http(Fetcher::new(opts).await.unwrap());
let fetch = |names: Vec<String>| {
let session = &session;
async move {
let refs = RefSelector::parse(names.iter().map(String::as_str)).unwrap();
let entries: Vec<String> =
names.iter().map(|name| format!("{id}/{name}")).collect();
let collections =
RefSelector::parse(entries.iter().map(String::as_str)).unwrap();
session.fetch_refs(&refs, Some(&collections)).await
}
};
let fill = |last: usize| -> Vec<String> {
let mut names: Vec<String> =
(0..4).map(|n| format!("{n}{}", "x".repeat(1616))).collect();
names.push("y".repeat(last));
names
};
let exact = fill(1619);
let cost: usize = exact.iter().map(|name| name_cost(id, name)).sum();
assert_eq!(cost, LISTING_BUDGET);
let names: Vec<&str> = exact.iter().map(String::as_str).collect();
assert_eq!(listing_chunks(id, &names, true).len(), 1);
let sent = fetch(exact.clone()).await;
assert!(
!matches!(sent, Err(crate::remote::Error::InvalidInput(_))),
"{sent:?}"
);
let over = fill(1620);
let names: Vec<&str> = over.iter().map(String::as_str).collect();
assert_eq!(listing_chunks(id, &names, true).len(), 2);
let refused = fetch(over.clone()).await;
assert!(
matches!(refused, Err(crate::remote::Error::InvalidInput(_))),
"{refused:?}"
);
});
}
#[test]
fn a_name_that_no_listing_request_can_hold_is_refused() {
let id = "org.example.Os";
let at_len = "x".repeat(MAX_REF_ENTRY_LEN - id.len() - 1);
let over_len = format!("{at_len}x");
let at_parts = vec!["p"; MAX_REF_ENTRY_PARTS - 1].join("/");
let over_parts = format!("{at_parts}/p");
let wide = "é".repeat(2000);
assert!(id.len() + 1 + wide.len() <= MAX_REF_ENTRY_LEN);
for name in [&at_len, &at_parts] {
check_listing_name(id, name).unwrap();
}
for name in [&over_len, &over_parts, &wide] {
let err = check_listing_name(id, name).unwrap_err();
assert!(
matches!(&err, Error::InvalidInput(m) if m.contains("too long")),
"{err:?}"
);
}
}
#[test]
fn the_skip_event_escapes_control_characters() {
let event = CollectionPullEvent::RemoteSkipped {
remote: "mirror".to_owned(),
message: "bad\nline".to_owned(),
};
assert_eq!(event.to_string(), "remote mirror skipped: bad\\nline");
}
}