#![allow(dead_code)]
use std::collections::{HashMap, HashSet};
use std::convert::Infallible;
use std::future::Future;
use std::io::{self, IoSlice};
use std::net::SocketAddr;
use std::os::fd::AsFd;
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, ready};
use futures_io::{AsyncRead, AsyncWrite};
use hyper::body::{Bytes, Frame, SizeHint};
use hyper::service::service_fn;
use hyper::{Request, Response, StatusCode};
use ostrya::fetch::{FetcherOptions, Proxy, TrustRoots};
use ostrya::{
AdvertisedDelta, Checksum, CommitModifier, CommitModifierFlags, CommitOptions, CreateOptions,
Error, MutableTree, PullOptions, Ref, Repo, RepoMode, SummaryOptions, Type, Value,
};
use ostrya_rt::{TcpListener, spawn};
pub const CA_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/ca.pem");
pub const SERVER_CERT_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/server.pem");
pub const SERVER_KEY_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/server.key.pem");
pub const OTHERNAME_CERT_PEM: &[u8] =
include_bytes!("../../../../tests/fixtures/tls/server-othername.pem");
pub const OTHERNAME_KEY_PEM: &[u8] =
include_bytes!("../../../../tests/fixtures/tls/server-othername.key.pem");
pub const UNTRUSTED_CERT_PEM: &[u8] =
include_bytes!("../../../../tests/fixtures/tls/server-untrusted.pem");
pub const UNTRUSTED_KEY_PEM: &[u8] =
include_bytes!("../../../../tests/fixtures/tls/server-untrusted.key.pem");
pub const CLIENT_CERT_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/client.pem");
pub const CLIENT_KEY_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/client.key.pem");
pub const FIXED_TS: u64 = 1_700_000_000;
pub const SUMMARY_SIG: &[u8] = b"summary signature bytes";
pub struct TestIo<S> {
inner: S,
scratch: Vec<u8>,
}
impl<S: AsyncRead + Unpin> hyper::rt::Read for TestIo<S> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
mut buf: hyper::rt::ReadBufCursor<'_>,
) -> Poll<io::Result<()>> {
let want = buf.remaining().min(16 * 1024);
if want == 0 {
return Poll::Ready(Ok(()));
}
let me = self.get_mut();
if me.scratch.len() < want {
me.scratch.resize(want, 0);
}
let n = ready!(Pin::new(&mut me.inner).poll_read(cx, &mut me.scratch[..want]))?;
buf.put_slice(&me.scratch[..n]);
Poll::Ready(Ok(()))
}
}
impl<S: AsyncWrite + Unpin> hyper::rt::Write for TestIo<S> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().inner).poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().inner).poll_close(cx)
}
fn is_write_vectored(&self) -> bool {
true
}
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.get_mut().inner).poll_write_vectored(cx, bufs)
}
}
#[derive(Clone, Copy)]
pub struct TestExecutor;
impl<F> hyper::rt::Executor<F> for TestExecutor
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
fn execute(&self, future: F) {
drop(spawn(future));
}
}
pub struct FileBody {
chunks: Vec<Bytes>,
declared: u64,
}
impl hyper::body::Body for FileBody {
type Data = Bytes;
type Error = Infallible;
fn poll_frame(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Bytes>, Infallible>>> {
let me = self.get_mut();
if me.chunks.is_empty() {
return Poll::Ready(None);
}
Poll::Ready(Some(Ok(Frame::data(me.chunks.remove(0)))))
}
fn size_hint(&self) -> SizeHint {
SizeHint::with_exact(self.declared)
}
}
#[derive(Default)]
pub struct Policy {
hidden: HashSet<String>,
tampered: HashMap<String, Vec<u8>>,
truncated: HashSet<String>,
truncate_first: HashMap<String, usize>,
bearer: Option<String>,
statuses: HashMap<String, u16>,
queries: Vec<(String, String)>,
}
#[derive(Clone, Copy)]
pub enum Leaf {
Fixture,
OtherName,
Untrusted,
}
impl Leaf {
fn pem(self) -> (&'static [u8], &'static [u8]) {
match self {
Leaf::Fixture => (SERVER_CERT_PEM, SERVER_KEY_PEM),
Leaf::OtherName => (OTHERNAME_CERT_PEM, OTHERNAME_KEY_PEM),
Leaf::Untrusted => (UNTRUSTED_CERT_PEM, UNTRUSTED_KEY_PEM),
}
}
}
pub struct RepoServer {
addr: SocketAddr,
tls: bool,
seen: Arc<Mutex<Vec<String>>>,
answered: Arc<Mutex<Vec<(String, u16)>>>,
policy: Arc<Mutex<Policy>>,
peak: Arc<AtomicUsize>,
connections: Arc<AtomicUsize>,
h2_connections: Arc<AtomicUsize>,
}
impl RepoServer {
pub async fn start(root: &Path, tls: bool) -> RepoServer {
RepoServer::start_with_leaf(root, tls, Leaf::Fixture).await
}
pub async fn start_with_leaf(root: &Path, tls: bool, leaf: Leaf) -> RepoServer {
RepoServer::launch(root, tls, leaf, false).await
}
pub async fn start_demanding_client_certificate(root: &Path) -> RepoServer {
RepoServer::launch(root, true, Leaf::Fixture, true).await
}
async fn launch(root: &Path, tls: bool, leaf: Leaf, client_certificate: bool) -> RepoServer {
let root = root.to_path_buf();
let listener = TcpListener::bind("127.0.0.1:0".parse().unwrap())
.await
.unwrap();
let addr = listener.local_addr().unwrap();
let seen: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let answered: Arc<Mutex<Vec<(String, u16)>>> = Arc::new(Mutex::new(Vec::new()));
let policy: Arc<Mutex<Policy>> = Arc::new(Mutex::new(Policy::default()));
let peak = Arc::new(AtomicUsize::new(0));
let inflight = Arc::new(AtomicUsize::new(0));
let connections = Arc::new(AtomicUsize::new(0));
let h2_connections = Arc::new(AtomicUsize::new(0));
let acceptor = tls.then(|| {
futures_rustls::TlsAcceptor::from(Arc::new(server_config(
&["h2", "http/1.1"],
leaf,
client_certificate,
)))
});
let task = (
root,
seen.clone(),
answered.clone(),
policy.clone(),
peak.clone(),
inflight,
connections.clone(),
h2_connections.clone(),
);
drop(spawn(async move {
let (root, seen, answered, policy, peak, inflight, connections, h2_connections) = task;
loop {
let Ok((stream, _peer)) = listener.accept().await else {
return;
};
connections.fetch_add(1, Ordering::SeqCst);
let state = (
root.clone(),
seen.clone(),
answered.clone(),
policy.clone(),
peak.clone(),
inflight.clone(),
);
let acceptor = acceptor.clone();
let h2_connections = h2_connections.clone();
drop(spawn(async move {
match acceptor {
Some(acceptor) => {
let Ok(tls) = acceptor.accept(stream).await else {
return;
};
let h2 = tls.get_ref().1.alpn_protocol() == Some(b"h2");
if h2 {
h2_connections.fetch_add(1, Ordering::SeqCst);
}
serve(tls, h2, state).await;
}
None => serve(stream, false, state).await,
}
}));
}
}));
RepoServer {
addr,
tls,
seen,
answered,
policy,
peak,
connections,
h2_connections,
}
}
pub fn url(&self) -> String {
let scheme = if self.tls { "https" } else { "http" };
format!("{scheme}://localhost:{}", self.addr.port())
}
pub fn port(&self) -> u16 {
self.addr.port()
}
pub fn seen(&self) -> Vec<String> {
self.seen.lock().unwrap().clone()
}
pub fn seen_set(&self) -> HashSet<String> {
self.seen().into_iter().collect()
}
pub fn peak_inflight(&self) -> usize {
self.peak.load(Ordering::SeqCst)
}
pub fn connections(&self) -> usize {
self.connections.load(Ordering::SeqCst)
}
pub fn h2_connections(&self) -> usize {
self.h2_connections.load(Ordering::SeqCst)
}
pub fn require_bearer(&self, token: &str) {
self.policy.lock().unwrap().bearer = Some(token.to_owned());
}
pub fn answer_status(&self, path: &str, status: u16) {
self.policy
.lock()
.unwrap()
.statuses
.insert(path.to_owned(), status);
}
pub fn queries_for(&self, path: &str) -> Vec<String> {
self.policy
.lock()
.unwrap()
.queries
.iter()
.filter(|(seen, _)| seen == path)
.map(|(_, query)| query.clone())
.collect()
}
pub fn hide(&self, path: &str) {
self.policy.lock().unwrap().hidden.insert(path.to_owned());
}
pub fn tamper(&self, path: &str, bytes: Vec<u8>) {
self.policy
.lock()
.unwrap()
.tampered
.insert(path.to_owned(), bytes);
}
pub fn truncate(&self, path: &str) {
self.policy
.lock()
.unwrap()
.truncated
.insert(path.to_owned());
}
pub fn truncate_times(&self, path: &str, times: usize) {
self.policy
.lock()
.unwrap()
.truncate_first
.insert(path.to_owned(), times);
}
pub fn requests_for(&self, path: &str) -> usize {
self.seen().iter().filter(|seen| *seen == path).count()
}
pub fn statuses_for(&self, path: &str) -> Vec<u16> {
self.answered
.lock()
.unwrap()
.iter()
.filter(|(answered, _)| answered == path)
.map(|(_, status)| *status)
.collect()
}
pub fn forget(&self) {
self.seen.lock().unwrap().clear();
self.answered.lock().unwrap().clear();
self.policy.lock().unwrap().queries.clear();
}
}
pub type ServeState = (
PathBuf,
Arc<Mutex<Vec<String>>>,
Arc<Mutex<Vec<(String, u16)>>>,
Arc<Mutex<Policy>>,
Arc<AtomicUsize>,
Arc<AtomicUsize>,
);
pub async fn serve<S>(io: S, h2: bool, state: ServeState)
where
S: AsyncRead + AsyncWrite + Send + Unpin + 'static,
{
let io = TestIo {
inner: io,
scratch: Vec::new(),
};
let service = service_fn(move |request: Request<hyper::body::Incoming>| {
let (root, seen, answered, policy, peak, inflight) = state.clone();
async move {
let path = request.uri().path().trim_start_matches('/').to_owned();
let query = request.uri().query().unwrap_or_default().to_owned();
policy.lock().unwrap().queries.push((path.clone(), query));
let authorization = request
.headers()
.get(hyper::header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
seen.lock().unwrap().push(path.clone());
let now = inflight.fetch_add(1, Ordering::SeqCst) + 1;
peak.fetch_max(now, Ordering::SeqCst);
ostrya_rt::Timer::after(std::time::Duration::from_millis(5)).await;
let response = answer(&root, &path, authorization.as_deref(), &policy);
answered
.lock()
.unwrap()
.push((path, response.status().as_u16()));
inflight.fetch_sub(1, Ordering::SeqCst);
Ok::<_, Infallible>(response)
}
});
if h2 {
let _ = hyper::server::conn::http2::Builder::new(TestExecutor)
.serve_connection(io, service)
.await;
} else {
let _ = hyper::server::conn::http1::Builder::new()
.serve_connection(io, service)
.await;
}
}
pub fn answer(
root: &Path,
path: &str,
authorization: Option<&str>,
policy: &Mutex<Policy>,
) -> Response<FileBody> {
let (hidden, replacement, truncated) = {
let mut policy = policy.lock().unwrap();
if let Some(token) = &policy.bearer
&& authorization != Some(format!("Bearer {token}").as_str())
{
return status_only(StatusCode::UNAUTHORIZED);
}
if let Some(status) = policy.statuses.get(path) {
return status_only(StatusCode::from_u16(*status).unwrap());
}
let cut_once = match policy.truncate_first.get_mut(path) {
Some(left) if *left > 0 => {
*left -= 1;
true
}
_ => false,
};
(
policy.hidden.contains(path),
policy.tampered.get(path).cloned(),
cut_once || policy.truncated.contains(path),
)
};
if hidden {
return not_found();
}
let bytes = match replacement {
Some(bytes) => bytes,
None => match std::fs::read(root.join(path)) {
Ok(bytes) => bytes,
Err(_) => return not_found(),
},
};
if truncated {
return Response::builder()
.status(StatusCode::OK)
.body(FileBody {
chunks: vec![Bytes::copy_from_slice(&bytes[..bytes.len() / 2])],
declared: bytes.len() as u64,
})
.unwrap();
}
Response::builder()
.status(StatusCode::OK)
.body(FileBody {
declared: bytes.len() as u64,
chunks: vec![Bytes::from(bytes)],
})
.unwrap()
}
pub fn not_found() -> Response<FileBody> {
status_only(StatusCode::NOT_FOUND)
}
fn status_only(status: StatusCode) -> Response<FileBody> {
Response::builder()
.status(status)
.body(FileBody {
chunks: Vec::new(),
declared: 0,
})
.unwrap()
}
pub fn server_config(alpn: &[&str], leaf: Leaf, client_certificate: bool) -> rustls::ServerConfig {
let provider = Arc::new(rustls_graviola::default_provider());
let (cert_pem, key_pem) = leaf.pem();
let certs: Vec<_> = rustls_pemfile::certs(&mut io::BufReader::new(cert_pem))
.collect::<Result<_, _>>()
.unwrap();
let key = rustls_pemfile::private_key(&mut io::BufReader::new(key_pem))
.unwrap()
.unwrap();
let builder = rustls::ServerConfig::builder_with_provider(provider.clone())
.with_safe_default_protocol_versions()
.unwrap();
let builder = if client_certificate {
let mut roots = rustls::RootCertStore::empty();
for cert in rustls_pemfile::certs(&mut io::BufReader::new(CA_PEM)) {
roots.add(cert.unwrap()).unwrap();
}
let verifier =
rustls::server::WebPkiClientVerifier::builder_with_provider(roots.into(), provider)
.build()
.unwrap();
builder.with_client_cert_verifier(verifier)
} else {
builder.with_no_client_auth()
};
let mut config = builder.with_single_cert(certs, key).unwrap();
config.alpn_protocols = alpn.iter().map(|p| p.as_bytes().to_vec()).collect();
config
}
pub fn ostree(args: &[&str]) -> Vec<u8> {
let out = Command::new("ostree")
.args(args)
.output()
.expect("run ostree");
assert!(
out.status.success(),
"ostree {args:?} failed: {}",
String::from_utf8_lossy(&out.stderr)
);
out.stdout
}
pub fn build_tree(dir: &Path, marker: &[u8]) {
use std::os::unix::fs::PermissionsExt;
std::fs::create_dir_all(dir.join("subdir")).unwrap();
std::fs::write(dir.join("hello.txt"), marker).unwrap();
std::fs::write(dir.join("exec.sh"), b"#!/bin/sh\necho hi\n").unwrap();
std::fs::write(dir.join("subdir/nested.txt"), b"nested\n").unwrap();
symlink("hello.txt", dir.join("link")).unwrap();
std::fs::set_permissions(
dir.join("hello.txt"),
std::fs::Permissions::from_mode(0o644),
)
.unwrap();
std::fs::set_permissions(dir.join("exec.sh"), std::fs::Permissions::from_mode(0o755)).unwrap();
}
pub fn incompressible(len: usize) -> Vec<u8> {
let mut out = Vec::with_capacity(len + 8);
let mut state: u64 = 0x9e37_79b9_7f4a_7c15;
while out.len() < len {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
out.extend_from_slice(&state.to_le_bytes());
}
out.truncate(len);
out
}
pub fn largest_filez(repo: &Path) -> u64 {
let mut largest = 0;
for shard in std::fs::read_dir(repo.join("objects")).unwrap() {
for entry in std::fs::read_dir(shard.unwrap().path()).unwrap() {
let entry = entry.unwrap();
if entry.path().extension().is_some_and(|ext| ext == "filez") {
largest = largest.max(entry.metadata().unwrap().len());
}
}
}
largest
}
pub fn ref_binding(branch: &str) -> Value {
Value::Array(vec![Value::Tuple(vec![
Value::Str("ostree.ref-binding".to_owned()),
Value::Variant(Box::new((
Type::parse("as").unwrap(),
Value::Array(vec![Value::Str(branch.to_owned())]),
))),
])])
}
pub fn detached_dict() -> Value {
Value::Array(vec![Value::Tuple(vec![
Value::Str("test.detached".to_owned()),
Value::Variant(Box::new((
Type::parse("s").unwrap(),
Value::Str("present".to_owned()),
))),
])])
}
pub async fn commit_tree(
repo: &Repo,
base: &Path,
sub: &str,
branch: &str,
parent: Option<Checksum>,
timestamp: u64,
) -> Checksum {
commit_tree_with(
repo,
base,
sub,
branch,
parent,
timestamp,
CommitModifierFlags::SKIP_XATTRS | CommitModifierFlags::CANONICAL_PERMISSIONS,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn commit_tree_with(
repo: &Repo,
base: &Path,
sub: &str,
branch: &str,
parent: Option<Checksum>,
timestamp: u64,
flags: CommitModifierFlags,
) -> Checksum {
commit_tree_full(repo, base, sub, branch, parent, timestamp, flags, &[]).await
}
pub async fn commit_tree_related(
repo: &Repo,
base: &Path,
sub: &str,
branch: &str,
parent: Option<Checksum>,
related: &[(&str, Checksum)],
) -> Checksum {
commit_tree_full(
repo,
base,
sub,
branch,
parent,
FIXED_TS,
CommitModifierFlags::SKIP_XATTRS | CommitModifierFlags::CANONICAL_PERMISSIONS,
related,
)
.await
}
#[allow(clippy::too_many_arguments)]
async fn commit_tree_full(
repo: &Repo,
base: &Path,
sub: &str,
branch: &str,
parent: Option<Checksum>,
timestamp: u64,
flags: CommitModifierFlags,
related: &[(&str, Checksum)],
) -> Checksum {
let txn = repo.transaction().await.unwrap();
let mut mtree = MutableTree::new();
let mut modifier = CommitModifier::new(flags);
let dfd = std::fs::File::open(base).unwrap();
txn.write_dfd_to_mtree(dfd.as_fd(), Path::new(sub), &mut mtree, Some(&mut modifier))
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let commit = txn
.write_commit(
CommitOptions {
parent,
subject: Some(format!("{branch} {sub}")),
timestamp: Some(timestamp),
metadata: Some(ref_binding(branch)),
related: related
.iter()
.map(|(name, checksum)| ((*name).to_owned(), *checksum))
.collect(),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
txn.set_ref(&branch.parse::<Ref>().unwrap(), Some(&commit));
txn.commit().await.unwrap();
commit
}
pub const COMPOSEFS_DIGEST_KEY: &str = "ostree.composefs.digest.v0";
#[allow(clippy::too_many_arguments)]
pub async fn commit_tree_keyed(
repo: &Repo,
base: &Path,
sub: &str,
branch: &str,
parent: Option<Checksum>,
timestamp: u64,
related: &[(&str, Checksum)],
wrong: bool,
) -> Checksum {
let txn = repo.transaction().await.unwrap();
let mut mtree = MutableTree::new();
let mut modifier = CommitModifier::new(
CommitModifierFlags::SKIP_XATTRS | CommitModifierFlags::CANONICAL_PERMISSIONS,
);
let dfd = std::fs::File::open(base).unwrap();
txn.write_dfd_to_mtree(dfd.as_fd(), Path::new(sub), &mut mtree, Some(&mut modifier))
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let digest = if wrong {
[0x5a; 32]
} else {
txn.composefs_digest(&root).await.unwrap()
};
let Value::Array(mut metadata) = ref_binding(branch) else {
unreachable!("the ref binding is an a{{sv}} array")
};
metadata.push(Value::Tuple(vec![
Value::Str(COMPOSEFS_DIGEST_KEY.to_owned()),
Value::Variant(Box::new((
Type::parse("ay").unwrap(),
Value::Bytes(digest.to_vec()),
))),
]));
let commit = txn
.write_commit(
CommitOptions {
parent,
subject: Some(format!("{branch} {sub}")),
timestamp: Some(timestamp),
metadata: Some(Value::Array(metadata)),
related: related
.iter()
.map(|(name, checksum)| ((*name).to_owned(), *checksum))
.collect(),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
txn.set_ref(&Ref::local(branch), Some(&commit));
txn.commit().await.unwrap();
commit
}
pub async fn build_remote(dir: &Path) -> (Repo, Checksum) {
let src = dir.join("src");
build_tree(&src, b"hello\n");
let repo = Repo::create(&dir.join("remote"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let commit = commit_tree(&repo, dir, "src", "test/main", None, FIXED_TS).await;
repo.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
(repo, commit)
}
pub const REMOTE_ID: &str = "org.example.Remote";
pub const ID_X: &str = "org.example.X";
pub const ID_Y: &str = "org.example.Y";
pub async fn commit_bound(
repo: &Repo,
base: &Path,
sub: &str,
r: &Ref,
collection: Option<&str>,
) -> Checksum {
let binding = collection.map(|id| ("s", Value::Str(id.to_owned())));
commit_bound_value(repo, base, sub, r, binding).await
}
pub async fn commit_bound_value(
repo: &Repo,
base: &Path,
sub: &str,
r: &Ref,
binding: Option<(&str, Value)>,
) -> Checksum {
let txn = repo.transaction().await.unwrap();
let mut mtree = MutableTree::new();
let mut modifier = CommitModifier::new(
CommitModifierFlags::SKIP_XATTRS | CommitModifierFlags::CANONICAL_PERMISSIONS,
);
let dfd = std::fs::File::open(base).unwrap();
txn.write_dfd_to_mtree(dfd.as_fd(), Path::new(sub), &mut mtree, Some(&mut modifier))
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let Value::Array(mut metadata) = ref_binding(r.name()) else {
unreachable!("the ref binding is an a{{sv}} array")
};
if let Some((ty, value)) = binding {
metadata.push(Value::Tuple(vec![
Value::Str("ostree.collection-binding".to_owned()),
Value::Variant(Box::new((Type::parse(ty).unwrap(), value))),
]));
}
let commit = txn
.write_commit(
CommitOptions {
subject: Some(r.to_string()),
timestamp: Some(FIXED_TS),
metadata: Some(Value::Array(metadata)),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
txn.set_ref(r, Some(&commit));
txn.commit().await.unwrap();
commit
}
pub async fn build_collection_remote(dir: &Path) -> (Repo, [Checksum; 4]) {
build_tree(&dir.join("src"), b"hello\n");
let repo = Repo::create(
&dir.join("remote"),
CreateOptions::new(RepoMode::Archive).collection_id(REMOTE_ID),
)
.await
.unwrap();
let main = commit_bound(&repo, dir, "src", &Ref::local("main"), None).await;
let c = commit_bound(&repo, dir, "src", &Ref::local("c"), Some(REMOTE_ID)).await;
let a = commit_bound(&repo, dir, "src", &Ref::collection(ID_X, "a"), Some(ID_X)).await;
let b = commit_bound(&repo, dir, "src", &Ref::collection(ID_Y, "b"), Some(ID_Y)).await;
repo.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
(repo, [main, c, a, b])
}
pub async fn build_remote_two_refs(dir: &Path) -> (Repo, Checksum) {
let src = dir.join("src");
build_tree(&src, b"hello\n");
let repo = Repo::create(&dir.join("remote"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let commit = commit_tree(&repo, dir, "src", "test/main", None, FIXED_TS).await;
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("test/other"), Some(&commit));
txn.commit().await.unwrap();
repo.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
(repo, commit)
}
pub async fn build_dest(dir: &Path, mode: RepoMode, url: &str, extra: &str) -> Repo {
let path = dir.join("dest");
let repo = Repo::create(&path, CreateOptions::new(mode)).await.unwrap();
drop(repo);
let config = path.join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str(&format!(
"\n[remote \"origin\"]\nurl={url}\ngpg-verify=false\n{extra}"
));
std::fs::write(&config, text).unwrap();
Repo::open(&path).await.unwrap()
}
pub async fn reconfigure_dest(dir: &Path, url: &str, extra: &str) -> Repo {
let path = dir.join("dest");
let config = path.join("config");
let text = std::fs::read_to_string(&config).unwrap();
let core = text.split("\n[remote").next().unwrap().to_owned();
std::fs::write(
&config,
format!("{core}\n[remote \"origin\"]\nurl={url}\ngpg-verify=false\n{extra}"),
)
.unwrap();
Repo::open(&path).await.unwrap()
}
pub fn https_endpoint(server: &RepoServer) -> FetcherOptions {
let mut http = FetcherOptions::new(server.url());
http.tls.roots = TrustRoots::Pem(CA_PEM.to_vec());
http.proxy = Proxy::None;
http
}
pub fn filez_path(checksum: &str) -> String {
format!("objects/{}/{}.filez", &checksum[..2], &checksum[2..])
}
pub fn meta_path(checksum: &Checksum, ext: &str) -> String {
let hex = checksum.to_hex();
format!("objects/{}/{}.{ext}", &hex[..2], &hex[2..])
}
pub async fn assert_nothing_published(repo: &Repo) {
assert!(repo.list_refs(None).await.unwrap().is_empty());
assert!(
repo.list_refs(Some("refs/remotes"))
.await
.unwrap()
.is_empty()
);
}
pub enum ListRefusal {
InvalidInput(String),
}
pub fn listed_delta(from: Option<u8>, to: u8, digest: u8) -> AdvertisedDelta {
AdvertisedDelta {
from: from.map(|byte| Checksum::from_bytes([byte; 32])),
to: Checksum::from_bytes([to; 32]),
superblock: Checksum::from_bytes([digest; 32]),
}
}
pub fn static_delta_list_cases(
base: impl Fn() -> PullOptions,
) -> Vec<(&'static str, PullOptions, ListRefusal)> {
let (from, to) = (Checksum::from_bytes([1; 32]), Checksum::from_bytes([2; 32]));
let two_digests = format!(
"static delta {}-{} is listed with two superblock digests",
from.to_hex(),
to.to_hex()
);
vec![
(
"two digests",
PullOptions {
static_deltas: Some(vec![
listed_delta(None, 2, 5),
listed_delta(Some(1), 2, 3),
listed_delta(Some(1), 2, 4),
]),
..base()
},
ListRefusal::InvalidInput(two_digests),
),
(
"disable_static_deltas",
PullOptions {
static_deltas: Some(vec![listed_delta(Some(1), 2, 3)]),
disable_static_deltas: true,
..base()
},
ListRefusal::InvalidInput(
"a pull with static_deltas takes no disable_static_deltas option".to_owned(),
),
),
(
"subpaths",
PullOptions {
static_deltas: Some(Vec::new()),
subpaths: vec!["/".to_owned()],
..base()
},
ListRefusal::InvalidInput("a pull with static_deltas takes no subpath".to_owned()),
),
]
}
pub fn assert_list_refusal(tag: &str, err: &Error, expected: &ListRefusal) {
match (expected, err) {
(ListRefusal::InvalidInput(want), Error::InvalidInput(got)) => {
assert_eq!(got, want, "{tag}")
}
_ => panic!("{tag}: {err:?}"),
}
}
pub async fn content_checksums(repo: &Repo, commit: &Checksum) -> Vec<Checksum> {
let reachable = repo.traverse_commit(commit, -1).await.unwrap();
let mut out: Vec<Checksum> = reachable
.iter()
.filter(|name| name.ty == ostrya::ObjectType::File)
.map(|name| name.checksum)
.collect();
out.sort();
out
}