use std::collections::HashMap;
use std::io;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use futures_io::{AsyncRead, AsyncWrite};
use futures_lite::io::{AsyncWriteExt, Cursor};
use ostrya_core::filehdr::frame;
use ostrya_core::{Checksum, DeflateSink, FileHeader, ObjectName, ObjectType, Ref, Xattrs};
use ostrya_gvariant::{DictBuilder, Type, Value};
use ostrya_remote::proto::{
ErrorMessage, FrameReader, FrameWriter, HaveReply, HelloReply, MIN_FRAME_LIMIT, Message,
ObjectHeader, ObjectRead, ObjectsReply, ServerCommit,
};
use ostrya_remote::{
BoxFuture, Compression, DetachedMetadata, Encoding, Error, ErrorCode, Expected, ObjectData,
ObjectSource, PushPhase, PushProgress, PushProgressSnapshot, PushSession, RefOutcome, RefState,
RefUpdate, SessionOptions,
};
use ostrya_rt::block_on;
fn ck(n: u8) -> Checksum {
Checksum::from_bytes([n; 32])
}
fn file(n: u8) -> ObjectName {
ObjectName::new(ck(n), ObjectType::File)
}
fn meta_name(ty: ObjectType, n: u8) -> ObjectName {
ObjectName::new(ck(n), ty)
}
fn regular(mode: u32) -> FileHeader {
FileHeader {
uid: 0,
gid: 0,
mode: 0o100000 | mode,
symlink_target: String::new(),
xattrs: Xattrs::empty(),
}
}
fn symlink(target: &str) -> FileHeader {
FileHeader {
uid: 0,
gid: 0,
mode: 0o120777,
symlink_target: target.into(),
xattrs: Xattrs::empty(),
}
}
fn payload(len: usize, seed: u32) -> Vec<u8> {
let mut state = seed | 1;
let mut out = Vec::with_capacity(len);
while out.len() < len {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
if out.len() < len / 2 {
out.push(b'A' + (state & 3) as u8);
} else {
out.push((state >> 24) as u8);
}
}
out
}
fn sink_deflate(data: &[u8], level: u8) -> Vec<u8> {
block_on(async {
let mut sink = DeflateSink::new(Vec::new(), level);
sink.write_all(data).await.unwrap();
sink.close().await.unwrap();
sink.into_inner()
})
}
#[derive(Clone, Default)]
struct Capture {
bytes: Arc<Mutex<Vec<u8>>>,
writes: Arc<Mutex<Vec<usize>>>,
broken: Arc<AtomicBool>,
}
impl Capture {
fn bytes(&self) -> Vec<u8> {
self.bytes.lock().unwrap().clone()
}
fn writes(&self) -> Vec<usize> {
self.writes.lock().unwrap().clone()
}
fn break_writes(&self) {
self.broken.store(true, Ordering::SeqCst);
}
}
impl AsyncWrite for Capture {
fn poll_write(
self: Pin<&mut Self>,
_: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
if self.broken.load(Ordering::SeqCst) {
return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into()));
}
self.bytes.lock().unwrap().extend_from_slice(buf);
self.writes.lock().unwrap().push(buf.len());
Poll::Ready(Ok(buf.len()))
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}
fn encode(msgs: &[Message]) -> Vec<u8> {
let mut w = FrameWriter::new(Vec::new());
for msg in msgs {
block_on(w.write_message(msg)).unwrap();
}
w.into_inner()
}
fn hello_reply(refs: &[&str], encodings: &[Encoding], max_have: u32) -> Message {
Message::HelloReply(HelloReply {
version: 1,
mode: "archive".into(),
collection_id: None,
max_frame: MIN_FRAME_LIMIT,
max_have,
encodings: encodings.to_vec(),
parallel_uploads: 1,
refs: refs
.iter()
.map(|r| RefState {
name: r.to_string(),
commit: None,
})
.collect(),
})
}
const BOTH: &[Encoding] = &[Encoding::Raw, Encoding::Deflate];
fn objects_reply() -> Message {
Message::ObjectsReply(ObjectsReply {
objects: 0,
payload_bytes: 0,
})
}
fn error(code: ErrorCode) -> Message {
Message::Error(ErrorMessage {
code,
message: "refused".into(),
missing: Vec::new(),
current: None,
})
}
fn strings(refs: &[&str]) -> Vec<String> {
refs.iter().map(|r| r.to_string()).collect()
}
fn open_with(
input: Vec<u8>,
refs: &[&str],
opts: SessionOptions,
) -> (ostrya_remote::Result<PushSession>, Capture) {
let out = Capture::default();
let session = block_on(PushSession::over_stream(
Cursor::new(input),
out.clone(),
&strings(refs),
opts,
));
(session, out)
}
fn open(refs: &[&str], encodings: &[Encoding], replies: &[Message]) -> (PushSession, Capture) {
let mut msgs = vec![hello_reply(refs, encodings, 16_384)];
msgs.extend_from_slice(replies);
let (session, out) = open_with(encode(&msgs), refs, SessionOptions::default());
(session.unwrap(), out)
}
#[derive(Debug, PartialEq)]
enum Event {
Msg(Message),
Object {
header: ObjectHeader,
data: Vec<u8>,
abandoned: bool,
},
}
fn decode(bytes: &[u8]) -> Vec<Event> {
block_on(async {
let mut r = FrameReader::new(bytes);
let mut out = Vec::new();
let mut buf = vec![0u8; 8192];
while let Some(msg) = r.read_message().await.unwrap() {
let Message::ObjectHeader(header) = msg else {
out.push(Event::Msg(msg));
continue;
};
let mut data = Vec::new();
let abandoned = loop {
match r.read_object_data(&mut buf).await.unwrap() {
ObjectRead::Data(n) => data.extend_from_slice(&buf[..n]),
ObjectRead::End => break false,
ObjectRead::Abandoned => break true,
}
};
out.push(Event::Object {
header,
data,
abandoned,
});
if abandoned {
out.push(Event::Msg(Message::Abort));
}
}
out
})
}
fn after_hello(out: &Capture) -> Vec<Event> {
let mut events = decode(&out.bytes());
assert!(matches!(
events.first(),
Some(Event::Msg(Message::Hello(_)))
));
events.remove(0);
events
}
fn objects(events: &[Event]) -> Vec<(ObjectName, Encoding, Vec<u8>)> {
events
.iter()
.filter_map(|e| match e {
Event::Object { header, data, .. } => {
Some((header.name, header.encoding, data.clone()))
}
Event::Msg(_) => None,
})
.collect()
}
struct Failing {
data: Cursor<Vec<u8>>,
}
impl AsyncRead for Failing {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
match Pin::new(&mut self.data).poll_read(cx, buf) {
Poll::Ready(Ok(0)) => Poll::Ready(Err(io::Error::other("the file went away"))),
other => other,
}
}
}
#[derive(Clone)]
enum Item {
Content(FileHeader, Option<Vec<u8>>),
Encoded(Encoding, Vec<u8>),
Stored(Vec<u8>, Vec<u8>),
Failing(Vec<u8>),
Stalled,
}
#[derive(Default)]
struct Source {
items: HashMap<ObjectName, Item>,
meta: HashMap<Checksum, Value>,
encoded: HashMap<Checksum, Vec<u8>>,
opened: Mutex<Vec<(ObjectName, Encoding)>>,
asked: Mutex<Vec<Checksum>>,
sized: Mutex<Vec<Encoding>>,
}
impl Source {
fn with(mut self, name: ObjectName, item: Item) -> Source {
self.items.insert(name, item);
self
}
}
impl ObjectSource for Source {
fn objects<'a>(
&'a self,
_commit: &'a Checksum,
) -> BoxFuture<'a, ostrya_remote::Result<Vec<ObjectName>>> {
Box::pin(async move { Ok(self.items.keys().copied().collect()) })
}
fn open<'a>(
&'a self,
name: &'a ObjectName,
encoding: Encoding,
) -> BoxFuture<'a, ostrya_remote::Result<ObjectData>> {
self.opened.lock().unwrap().push((*name, encoding));
let item = self.items[name].clone();
Box::pin(async move {
Ok(match item {
Item::Content(header, payload) => ObjectData::Content {
size: payload.as_ref().map_or(0, |p| p.len() as u64),
header,
payload: payload.map(|p| Box::new(Cursor::new(p)) as _),
},
Item::Encoded(encoding, bytes) => ObjectData::Encoded {
encoding,
reader: Box::new(Cursor::new(bytes)),
},
Item::Stored(payload, _) if encoding == Encoding::Raw => ObjectData::Content {
header: regular(0o644),
size: payload.len() as u64,
payload: Some(Box::new(Cursor::new(payload))),
},
Item::Stored(_, stored) => ObjectData::Encoded {
encoding: Encoding::Deflate,
reader: Box::new(Cursor::new(stored)),
},
Item::Failing(bytes) => ObjectData::Content {
header: regular(0o644),
size: bytes.len() as u64 + 10,
payload: Some(Box::new(Failing {
data: Cursor::new(bytes),
})),
},
Item::Stalled => futures_lite::future::pending().await,
})
})
}
fn detached_metadata<'a>(
&'a self,
commit: &'a Checksum,
) -> BoxFuture<'a, ostrya_remote::Result<Option<Value>>> {
self.asked.lock().unwrap().push(*commit);
Box::pin(async move { Ok(self.meta.get(commit).cloned()) })
}
fn detached_metadata_encoded<'a>(
&'a self,
commit: &'a Checksum,
) -> BoxFuture<'a, ostrya_remote::Result<Option<DetachedMetadata>>> {
match self.encoded.get(commit) {
Some(bytes) => {
let bytes = bytes.clone();
Box::pin(async move { Ok(Some(DetachedMetadata::Encoded(bytes))) })
}
None => Box::pin(async move {
Ok(self
.detached_metadata(commit)
.await?
.map(DetachedMetadata::Dict))
}),
}
}
fn content_size<'a>(
&'a self,
names: &'a [ObjectName],
encoding: Encoding,
) -> BoxFuture<'a, ostrya_remote::Result<Option<u64>>> {
self.sized.lock().unwrap().push(encoding);
let total = names
.iter()
.filter(|n| n.ty == ObjectType::File)
.filter_map(|n| self.items.get(n))
.map(|item| match item {
Item::Content(_, payload) => payload.as_ref().map_or(0, |p| p.len() as u64),
Item::Encoded(_, bytes) => bytes.len() as u64,
Item::Stored(payload, stored) => match encoding {
Encoding::Raw => payload.len() as u64,
_ => stored.len() as u64,
},
Item::Failing(bytes) => bytes.len() as u64 + 10,
Item::Stalled => 0,
})
.sum();
Box::pin(async move { Ok(Some(total)) })
}
}
fn a_sv_bytes(dict: &Value) -> Vec<u8> {
ostrya_gvariant::to_bytes(&Type::parse("a{sv}").unwrap(), dict).unwrap()
}
fn assert_invalid<T: std::fmt::Debug>(r: ostrya_remote::Result<T>, text: &str) {
match r {
Err(Error::InvalidInput(m)) => assert!(m.contains(text), "{m}"),
other => panic!("expected InvalidInput with {text:?}, got {other:?}"),
}
}
fn update(name: &str) -> RefUpdate {
RefUpdate {
name: name.into(),
expected: Expected::Absent,
new: Some(ck(9)),
}
}
#[test]
fn hello_carries_the_version_the_agent_and_the_refs() {
let (_, out) = open(&["a", "b"], BOTH, &[]);
match &decode(&out.bytes())[..] {
[Event::Msg(Message::Hello(h))] => {
assert_eq!(h.version, 1);
assert_eq!(
h.agent.as_deref(),
Some(concat!("ostrya/", env!("CARGO_PKG_VERSION")))
);
assert_eq!(h.refs, strings(&["a", "b"]));
}
other => panic!("{other:?}"),
}
}
#[test]
fn hello_reply_refs_that_differ_are_protocol() {
for refs in [&["a", "c"][..], &["b", "a"], &["a"], &["a", "b", "c"]] {
let input = encode(&[hello_reply(refs, BOTH, 16)]);
let (r, _) = open_with(input, &["a", "b"], SessionOptions::default());
assert!(matches!(r, Err(Error::Protocol(_))), "{refs:?}");
}
}
#[test]
fn hello_reply_of_another_version_is_protocol() {
let mut reply = hello_reply(&["a"], BOTH, 16);
if let Message::HelloReply(r) = &mut reply {
r.version = 2;
}
let (r, _) = open_with(encode(&[reply]), &["a"], SessionOptions::default());
assert!(matches!(r, Err(Error::Protocol(_))));
}
#[test]
fn hello_names_a_collection_ref_as_text() {
let names = ["main", "@org.example.Os:a", "@org.example.C:b"];
let mut reply = hello_reply(&names, BOTH, 16);
if let Message::HelloReply(r) = &mut reply {
r.collection_id = Some("org.example.C".into());
}
let (r, out) = open_with(encode(&[reply]), &names, SessionOptions::default());
let session = r.unwrap();
let server = session.server();
assert_eq!(server.collection_id.as_deref(), Some("org.example.C"));
let canonical = |text: &str| server.canonical(&text.parse::<Ref>().unwrap());
assert_eq!(canonical("main"), Ref::local("main"));
assert_eq!(
canonical("@org.example.Os:a"),
Ref::collection("org.example.Os", "a")
);
assert_eq!(canonical("@org.example.C:b"), Ref::local("b"));
assert_eq!(canonical("origin:b"), Ref::remote("origin", "b"));
match &decode(&out.bytes())[..] {
[Event::Msg(Message::Hello(h)), ..] => assert_eq!(h.refs, names),
other => panic!("{other:?}"),
}
}
#[test]
fn error_at_hello_is_that_error() {
let input = encode(&[Message::Error(ErrorMessage {
code: ErrorCode::LockingDisabled,
message: "no locks".into(),
missing: Vec::new(),
current: None,
})]);
let (r, _) = open_with(input, &["a"], SessionOptions::default());
assert!(matches!(r, Err(Error::LockingDisabled(m)) if m == "no locks"));
let (r, _) = open_with(Vec::new(), &["a"], SessionOptions::default());
assert!(matches!(r, Err(Error::Io(e)) if e.kind() == io::ErrorKind::UnexpectedEof));
let (r, _) = open_with(
encode(&[objects_reply()]),
&["a"],
SessionOptions::default(),
);
assert!(matches!(r, Err(Error::Protocol(_))));
}
#[test]
fn missing_sends_batches_of_max_have() {
let names: Vec<ObjectName> = (1..=5).map(file).collect();
let replies = [
Message::HaveReply(HaveReply::from_missing([true, false])),
Message::HaveReply(HaveReply::from_missing([false, true])),
Message::HaveReply(HaveReply::from_missing([true])),
];
let mut msgs = vec![hello_reply(&["a"], BOTH, 2)];
msgs.extend(replies);
let (session, out) = open_with(encode(&msgs), &["a"], SessionOptions::default());
let session = session.unwrap();
let missing = block_on(session.missing(&names)).unwrap();
assert_eq!(missing, vec![file(1), file(4), file(5)]);
let haves: Vec<Vec<ObjectName>> = after_hello(&out)
.into_iter()
.map(|e| match e {
Event::Msg(Message::Have(names)) => names,
other => panic!("{other:?}"),
})
.collect();
assert_eq!(
haves,
vec![
names[..2].to_vec(),
names[2..4].to_vec(),
names[4..].to_vec()
]
);
}
const OFF_WIRE: [ObjectType; 5] = [
ObjectType::TombstoneCommit,
ObjectType::CommitMeta,
ObjectType::PayloadLink,
ObjectType::FileXattrs,
ObjectType::FileXattrsLink,
];
#[test]
fn missing_refuses_types_off_the_wire_and_a_bad_bitmap() {
let (session, out) = open(
&["a"],
BOTH,
&[Message::HaveReply(HaveReply::from_missing([true]))],
);
for ty in OFF_WIRE {
assert_invalid(
block_on(session.missing(&[file(1), meta_name(ty, 1)])),
"is not an object to offer or send",
);
}
assert!(after_hello(&out).is_empty(), "nothing sent");
assert_eq!(
block_on(session.missing(&[file(1)])).unwrap(),
vec![file(1)]
);
let (session, _) = open(
&["a"],
BOTH,
&[Message::HaveReply(HaveReply { bitmap: vec![0, 0] })],
);
assert!(matches!(
block_on(session.missing(&[file(1)])),
Err(Error::Protocol(_))
));
assert_invalid(
block_on(session.missing(&[file(1)])),
"the session is broken",
);
}
#[test]
fn missing_splits_a_batch_that_does_not_fit_the_frame_limit() {
let fit = |n: usize| {
let names = vec![file(1); n];
let mut w = FrameWriter::new(Vec::new());
block_on(w.write_message(&Message::Have(names))).is_ok()
};
let names: Vec<ObjectName> = (0..30_000u32)
.map(|i| {
let mut sum = [0u8; 32];
sum[..4].copy_from_slice(&i.to_be_bytes());
ObjectName::new(Checksum::from_bytes(sum), ObjectType::File)
})
.collect();
let counts: Vec<usize> = (1..=names.len()).collect();
let first = counts.partition_point(|n| fit(*n));
assert!(first < names.len(), "the names need two frames");
let msgs = [
hello_reply(&["a"], BOTH, u32::MAX),
Message::HaveReply(HaveReply::from_missing(vec![false; first])),
Message::HaveReply(HaveReply::from_missing(vec![true; names.len() - first])),
];
let (session, out) = open_with(encode(&msgs), &["a"], SessionOptions::default());
let missing = block_on(session.unwrap().missing(&names)).unwrap();
assert_eq!(missing, names[first..]);
let sizes: Vec<usize> = after_hello(&out)
.into_iter()
.map(|e| match e {
Event::Msg(Message::Have(batch)) => batch.len(),
other => panic!("{other:?}"),
})
.collect();
assert_eq!(sizes, vec![first, names.len() - first]);
}
#[test]
fn a_failed_request_write_gives_the_pending_error() {
let (session, out) = open(&["a"], BOTH, &[error(ErrorCode::Unauthorized)]);
out.break_writes();
assert!(matches!(
block_on(session.missing(&[file(1)])),
Err(Error::Unauthorized(_))
));
let source = Source::default()
.with(file(1), Item::Encoded(Encoding::Raw, b"x".to_vec()))
.with(
file(2),
Item::Content(regular(0o644), Some(payload(300_000, 7))),
);
let (session, out) = open(&["a"], BOTH, &[error(ErrorCode::ModeRefused)]);
out.break_writes();
assert!(matches!(
block_on(session.send(&source, &[file(1)], &[], Compression::None)),
Err(Error::ModeRefused(_))
));
for compression in [Compression::None, Compression::Deflate { level: 1 }] {
let (session, out) = open(&["a"], BOTH, &[error(ErrorCode::LimitExceeded)]);
out.break_writes();
assert!(matches!(
block_on(session.send(&source, &[file(2)], &[], compression)),
Err(Error::LimitExceeded(_))
));
}
}
#[test]
fn a_full_chunk_goes_out_with_its_length() {
let data = payload(5 * 65536 + 100, 8);
let source = Source::default().with(file(1), Item::Content(regular(0o644), Some(data)));
for compression in [Compression::None, Compression::Deflate { level: 1 }] {
let (session, out) = open(&["a"], BOTH, &[objects_reply()]);
let hello = out.writes().len();
block_on(session.send(&source, &[file(1)], &[], compression)).unwrap();
let writes = &out.writes()[hello..];
assert!(writes.len() > 3, "{compression:?}: {writes:?}");
assert!(
writes[..writes.len() - 1].iter().all(|n| *n >= 16),
"{compression:?}: {writes:?}"
);
}
}
#[test]
fn a_large_object_goes_out_in_writes_of_at_most_64_kib() {
let mut state = 0x9E37_79B9u32;
let data: Vec<u8> = (0..64 * 65536)
.map(|_| {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
(state >> 24) as u8
})
.collect();
let source = Source::default().with(file(1), Item::Content(regular(0o644), Some(data)));
for compression in [Compression::None, Compression::Deflate { level: 1 }] {
let (session, out) = open(&["a"], BOTH, &[objects_reply()]);
let hello = out.writes().len();
block_on(session.send(&source, &[file(1)], &[], compression)).unwrap();
let writes = &out.writes()[hello..];
assert!(writes.len() > 64, "{compression:?}: {writes:?}");
assert!(
writes.iter().all(|n| *n <= 65536 && *n != 4),
"{compression:?}: {writes:?}"
);
if compression == Compression::None {
assert!(
writes[1..writes.len() - 1].iter().all(|n| *n == 65536),
"{writes:?}"
);
}
}
}
#[test]
fn detached_metadata_over_the_frame_limit_goes_in_chunks() {
let big = vec![7u8; MIN_FRAME_LIMIT as usize * 3 / 2];
let mut dict = DictBuilder::new();
dict.insert_bytes("big", &big);
let dict = dict.build();
let mut source = Source::default();
source.meta.insert(ck(1), dict.clone());
let (session, out) = open(&["a"], BOTH, &[objects_reply()]);
block_on(session.send(&source, &[], &[ck(1)], Compression::None)).unwrap();
assert_eq!(
objects(&after_hello(&out)),
vec![(
meta_name(ObjectType::CommitMeta, 1),
Encoding::Raw,
a_sv_bytes(&dict)
)]
);
}
#[test]
fn raw_content_metadata_and_encoded_objects() {
let data = payload(100_000, 1);
let dirtree = b"dirtree bytes".to_vec();
let source = Source::default()
.with(file(1), Item::Content(regular(0o644), Some(data.clone())))
.with(file(2), Item::Content(symlink("target"), None))
.with(
meta_name(ObjectType::DirTree, 3),
Item::Encoded(Encoding::Raw, dirtree.clone()),
);
let (session, out) = open(&["a"], BOTH, &[objects_reply()]);
let names = [file(1), file(2), meta_name(ObjectType::DirTree, 3)];
block_on(session.send(&source, &names, &[], Compression::None)).unwrap();
let events = after_hello(&out);
assert_eq!(events.last(), Some(&Event::Msg(Message::ObjectsEnd)));
let mut want1 = frame(®ular(0o644).serialize().unwrap()).unwrap();
want1.extend_from_slice(&data);
let want2 = frame(&symlink("target").serialize().unwrap()).unwrap();
assert_eq!(
objects(&events),
vec![
(file(1), Encoding::Raw, want1),
(file(2), Encoding::Raw, want2),
(meta_name(ObjectType::DirTree, 3), Encoding::Raw, dirtree),
]
);
let opened = source.opened.lock().unwrap().clone();
assert!(opened.iter().all(|(_, e)| *e == Encoding::Raw));
}
#[test]
fn deflate_falls_back_to_raw_when_the_server_lists_raw_alone() {
let data = payload(5000, 2);
let source = Source::default().with(file(1), Item::Content(regular(0o644), Some(data.clone())));
let (session, out) = open(&["a"], &[Encoding::Raw], &[objects_reply()]);
block_on(session.send(&source, &[file(1)], &[], Compression::Deflate { level: 6 })).unwrap();
let mut want = frame(®ular(0o644).serialize().unwrap()).unwrap();
want.extend_from_slice(&data);
assert_eq!(
objects(&after_hello(&out)),
vec![(file(1), Encoding::Raw, want)]
);
assert_eq!(
source.opened.lock().unwrap()[0],
(file(1), Encoding::Raw),
"the source is asked for raw"
);
}
#[test]
fn deflated_content_equals_the_sink_output() {
let first = payload(3 * 65536 / 2, 3);
let second = payload(70_000, 4);
for level in 1..=9 {
let source = Source::default()
.with(file(1), Item::Content(regular(0o644), Some(first.clone())))
.with(file(2), Item::Content(regular(0o755), Some(second.clone())))
.with(file(3), Item::Content(symlink("t"), None))
.with(file(4), Item::Content(regular(0o600), Some(Vec::new())));
let (session, out) = open(&["a"], BOTH, &[objects_reply()]);
let names = [file(1), file(2), file(3), file(4)];
block_on(session.send(&source, &names, &[], Compression::Deflate { level })).unwrap();
let expect = |header: &FileHeader, data: Option<&[u8]>| {
let size = data.map_or(0, |d| d.len() as u64);
let mut bytes = frame(&header.serialize_archive(size).unwrap()).unwrap();
if let Some(d) = data {
bytes.extend(sink_deflate(d, level));
}
bytes
};
let got = objects(&after_hello(&out));
let want = vec![
(
file(1),
Encoding::Deflate,
expect(®ular(0o644), Some(&first)),
),
(
file(2),
Encoding::Deflate,
expect(®ular(0o755), Some(&second)),
),
(file(3), Encoding::Deflate, expect(&symlink("t"), None)),
(
file(4),
Encoding::Deflate,
expect(®ular(0o600), Some(&[])),
),
];
assert_eq!(got, want, "level {level}");
let symlink_header = frame(&symlink("t").serialize_archive(0).unwrap()).unwrap();
assert_eq!(got[2].2, symlink_header);
assert!(
got[3].2.len()
> frame(®ular(0o600).serialize_archive(0).unwrap())
.unwrap()
.len()
);
let opened = source.opened.lock().unwrap().clone();
assert!(opened.iter().all(|(_, e)| *e == Encoding::Deflate));
}
}
#[test]
fn encoded_objects_pass_through() {
let filez = b"stored filez bytes".to_vec();
let raw = b"raw content bytes".to_vec();
let source = Source::default()
.with(file(1), Item::Encoded(Encoding::Deflate, filez.clone()))
.with(file(2), Item::Encoded(Encoding::Raw, raw.clone()));
for compression in [Compression::None, Compression::Deflate { level: 1 }] {
let (session, out) = open(&["a"], BOTH, &[objects_reply()]);
block_on(session.send(&source, &[file(1), file(2)], &[], compression)).unwrap();
assert_eq!(
objects(&after_hello(&out)),
vec![
(file(1), Encoding::Deflate, filez.clone()),
(file(2), Encoding::Raw, raw.clone()),
],
"{compression:?}"
);
}
}
#[test]
fn deflated_bytes_the_session_cannot_send_are_refused() {
let cases = [
(&[Encoding::Raw][..], file(1)),
(BOTH, meta_name(ObjectType::DirMeta, 1)),
];
for (encodings, name) in cases {
let source = Source::default()
.with(file(9), Item::Encoded(Encoding::Raw, b"x".to_vec()))
.with(name, Item::Encoded(Encoding::Deflate, b"filez".to_vec()));
let (session, out) = open(&["a"], encodings, &[]);
assert_invalid(
block_on(session.send(&source, &[file(9), name], &[], Compression::None)),
"deflated",
);
let events = after_hello(&out);
assert_eq!(events.len(), 2, "{events:?}");
assert!(matches!(
events[0],
Event::Object {
abandoned: false,
..
}
));
assert_eq!(events[1], Event::Msg(Message::Abort));
assert_invalid(
block_on(session.send(&source, &[], &[], Compression::None)),
"the session is broken",
);
}
}
#[test]
fn content_data_that_does_not_fit_its_header_is_refused() {
let cases = [
(file(1), Item::Content(symlink("t"), Some(b"x".to_vec()))),
(file(1), Item::Content(regular(0o644), None)),
(
meta_name(ObjectType::Commit, 1),
Item::Content(regular(0o644), Some(Vec::new())),
),
];
for (name, item) in cases {
let source = Source::default().with(name, item);
let (session, out) = open(&["a"], BOTH, &[]);
assert!(matches!(
block_on(session.send(&source, &[name], &[], Compression::None)),
Err(Error::InvalidInput(_))
));
assert_eq!(after_hello(&out), vec![Event::Msg(Message::Abort)]);
}
}
#[test]
fn send_refusals_before_any_byte() {
let source = Source::default().with(file(1), Item::Encoded(Encoding::Raw, b"x".to_vec()));
let (session, out) = open(&["a"], BOTH, &[objects_reply()]);
for level in [0, 10] {
assert_invalid(
block_on(session.send(&source, &[file(1)], &[], Compression::Deflate { level })),
"level",
);
}
for ty in OFF_WIRE {
assert_invalid(
block_on(session.send(
&source,
&[file(1), meta_name(ty, 1)],
&[],
Compression::None,
)),
"is not an object to offer or send",
);
}
assert!(after_hello(&out).is_empty());
block_on(session.send(&source, &[], &[ck(5)], Compression::None)).unwrap();
assert!(after_hello(&out).is_empty());
block_on(session.send(&source, &[file(1)], &[], Compression::None)).unwrap();
assert_eq!(objects(&after_hello(&out)).len(), 1);
}
#[test]
fn detached_metadata_goes_once_per_commit() {
let mut dict = DictBuilder::new();
dict.insert_str("key", "value");
let dict = dict.build();
let mut source = Source::default().with(
meta_name(ObjectType::Commit, 1),
Item::Encoded(Encoding::Raw, b"commit".to_vec()),
);
source.meta.insert(ck(1), dict.clone());
source.meta.insert(ck(2), Value::Array(Vec::new()));
let (session, out) = open(&["a"], BOTH, &[objects_reply(), objects_reply()]);
block_on(session.send(
&source,
&[meta_name(ObjectType::Commit, 1)],
&[ck(1), ck(3), ck(1)],
Compression::None,
))
.unwrap();
block_on(session.send(&source, &[], &[ck(1), ck(2)], Compression::None)).unwrap();
block_on(session.send(&source, &[], &[ck(1), ck(2)], Compression::None)).unwrap();
let events = after_hello(&out);
let ends = events
.iter()
.filter(|e| **e == Event::Msg(Message::ObjectsEnd))
.count();
assert_eq!(ends, 2, "two object streams");
assert_eq!(
objects(&events),
vec![
(
meta_name(ObjectType::Commit, 1),
Encoding::Raw,
b"commit".to_vec()
),
(
meta_name(ObjectType::CommitMeta, 1),
Encoding::Raw,
a_sv_bytes(&dict)
),
(
meta_name(ObjectType::CommitMeta, 2),
Encoding::Raw,
a_sv_bytes(&Value::Array(Vec::new()))
),
]
);
}
#[test]
fn encoded_detached_metadata_goes_as_it_is() {
let mut dict = DictBuilder::new();
dict.insert_str("key", "value");
let dict = dict.build();
let mut source = Source::default();
source.meta.insert(ck(1), dict.clone());
source.encoded.insert(ck(2), b"encoded bytes".to_vec());
let (session, out) = open(&["a"], BOTH, &[objects_reply()]);
block_on(session.send(&source, &[], &[ck(1), ck(2)], Compression::None)).unwrap();
assert_eq!(*source.asked.lock().unwrap(), vec![ck(1)]);
assert_eq!(
objects(&after_hello(&out)),
vec![
(
meta_name(ObjectType::CommitMeta, 1),
Encoding::Raw,
a_sv_bytes(&dict)
),
(
meta_name(ObjectType::CommitMeta, 2),
Encoding::Raw,
b"encoded bytes".to_vec()
),
]
);
}
#[test]
fn a_failing_source_abandons_the_object_and_aborts() {
let source = Source::default()
.with(file(1), Item::Encoded(Encoding::Raw, b"ok".to_vec()))
.with(file(2), Item::Failing(payload(10_000, 5)));
for compression in [Compression::None, Compression::Deflate { level: 6 }] {
let (session, out) = open(&["a"], BOTH, &[]);
let r = block_on(session.send(&source, &[file(1), file(2)], &[], compression));
match &r {
Err(e @ Error::Source(_)) => {
let cause = std::error::Error::source(e).expect("the cause of the source error");
assert!(cause.to_string().contains("the file went away"), "{cause}");
}
other => panic!("{other:?}"),
}
let events = after_hello(&out);
assert_eq!(events.len(), 3, "{events:?}");
assert!(matches!(
events[0],
Event::Object {
abandoned: false,
..
}
));
assert!(matches!(
events[1],
Event::Object {
abandoned: true,
..
}
));
assert_eq!(events[2], Event::Msg(Message::Abort));
assert_invalid(block_on(session.missing(&[])), "the session is broken");
assert_invalid(block_on(session.abort()), "the session is broken");
}
}
#[test]
fn a_reply_other_than_objects_reply() {
let source = Source::default().with(file(1), Item::Encoded(Encoding::Raw, b"x".to_vec()));
let (session, _) = open(
&["a"],
BOTH,
&[Message::Error(ErrorMessage {
code: ErrorCode::ChecksumMismatch,
message: "bad".into(),
missing: Vec::new(),
current: None,
})],
);
assert!(matches!(
block_on(session.send(&source, &[file(1)], &[], Compression::None)),
Err(Error::ChecksumMismatch(_))
));
let (session, _) = open(
&["a"],
BOTH,
&[Message::HaveReply(HaveReply { bitmap: vec![] })],
);
assert!(matches!(
block_on(session.send(&source, &[file(1)], &[], Compression::None)),
Err(Error::Protocol(_))
));
}
#[test]
fn an_overlapping_call_fails_and_a_dropped_call_breaks_the_session() {
let source = Source::default().with(file(1), Item::Stalled);
let (session, _) = open(&["a"], BOTH, &[]);
block_on(async {
let names = [file(1)];
let mut call = Box::pin(session.send(&source, &names, &[], Compression::None));
assert!(futures_lite::future::poll_once(&mut call).await.is_none());
assert_invalid(session.missing(&[file(1)]).await, "a call is in progress");
assert_invalid(
session.send(&source, &[], &[], Compression::None).await,
"a call is in progress",
);
drop(call);
assert_invalid(session.missing(&[file(1)]).await, "the session is broken");
});
assert_invalid(
block_on(session.commit(&[update("a")], false)),
"the session is broken",
);
}
fn commit_reply(names: &[&str]) -> Message {
Message::CommitReply(
names
.iter()
.map(|n| RefOutcome {
name: n.to_string(),
old: None,
new: Some(ck(9)),
})
.collect(),
)
}
#[test]
fn commit_returns_the_outcomes() {
let (session, out) = open(&["a", "b"], BOTH, &[commit_reply(&["b", "a"])]);
let outcome = block_on(session.commit(&[update("b"), update("a")], true)).unwrap();
assert_eq!(outcome.commit, None);
assert_eq!(outcome.refs.len(), 2);
match &after_hello(&out)[..] {
[Event::Msg(Message::Commit(c))] => {
assert!(c.force);
assert_eq!(c.updates, vec![update("b"), update("a")]);
}
other => panic!("{other:?}"),
}
}
#[test]
fn commit_prechecks_send_nothing() {
let cases: [(&[RefUpdate], &str); 3] = [
(&[], "at least one"),
(&[update("c")], "not named"),
(&[update("a"), update("a")], "twice"),
];
for (updates, text) in cases {
let (session, out) = open(&["a", "b"], BOTH, &[commit_reply(&["a"])]);
assert_invalid(block_on(session.commit(updates, false)), text);
assert!(after_hello(&out).is_empty(), "{text}");
}
}
#[test]
fn a_break_after_commit_is_an_unknown_outcome() {
let reply = encode(&[commit_reply(&["a", "b"])]);
let truncated = reply[..reply.len() - 3].to_vec();
let others = encode(&[objects_reply()]);
for tail in [Vec::new(), truncated, others] {
let mut input = encode(&[hello_reply(&["a", "b"], BOTH, 16)]);
input.extend(tail);
let (session, out) = open_with(input, &["a", "b"], SessionOptions::default());
let r = block_on(session.unwrap().commit(&[update("a"), update("b")], false));
match r {
Err(Error::CommitOutcomeUnknown { refs, .. }) => assert_eq!(refs, strings(&["a", "b"])),
other => panic!("{other:?}"),
}
assert!(matches!(
&after_hello(&out)[..],
[Event::Msg(Message::Commit(_))]
));
}
}
#[test]
fn an_error_after_commit_is_that_error() {
let error = Message::Error(ErrorMessage {
code: ErrorCode::RefMismatch,
message: "moved".into(),
missing: Vec::new(),
current: Some(RefState {
name: "a".into(),
commit: Some(ck(4)),
}),
});
let (session, _) = open(&["a"], BOTH, &[error]);
match block_on(session.commit(&[update("a")], false)) {
Err(Error::RefMismatch { name, current, .. }) => {
assert_eq!(name, "a");
assert_eq!(current, Some(ck(4)));
}
other => panic!("{other:?}"),
}
}
fn assert_unknown<T: std::fmt::Debug>(r: ostrya_remote::Result<T>, refs: &[&str], text: &str) {
match r {
Err(Error::CommitOutcomeUnknown { refs: got, message }) => {
assert_eq!(got, strings(refs));
assert!(message.contains(text), "{message}");
}
other => panic!("expected CommitOutcomeUnknown with {text:?}, got {other:?}"),
}
}
#[test]
fn a_commit_reply_for_other_refs_is_an_unknown_outcome() {
for reply in [&["b", "a"][..], &["a"], &["a", "b", "c"]] {
let (session, _) = open(&["a", "b", "c"], BOTH, &[commit_reply(reply)]);
assert_unknown(
block_on(session.commit(&[update("a"), update("b")], false)),
&["a", "b"],
"other refs",
);
}
}
#[test]
fn a_failed_commit_write_reads_the_pending_reply() {
let (session, out) = open(&["a"], BOTH, &[commit_reply(&["a"])]);
out.break_writes();
let outcome = block_on(session.commit(&[update("a")], false)).unwrap();
assert_eq!(outcome.refs.len(), 1);
assert_eq!(outcome.refs[0].name, "a");
let (session, out) = open(&["a", "b"], BOTH, &[commit_reply(&["b"])]);
out.break_writes();
assert_unknown(
block_on(session.commit(&[update("a")], false)),
&["a"],
"other refs",
);
let (session, out) = open(&["a"], BOTH, &[error(ErrorCode::Unauthorized)]);
out.break_writes();
assert!(matches!(
block_on(session.commit(&[update("a")], false)),
Err(Error::Unauthorized(_))
));
let (session, out) = open(&["a"], BOTH, &[]);
out.break_writes();
assert_unknown(
block_on(session.commit(&[update("a")], false)),
&["a"],
"the write of Commit failed",
);
}
fn server_commit(branch: &str, tags: &[&str]) -> ServerCommit {
ServerCommit {
branch: branch.into(),
tags: strings(tags),
bind_refs: strings(&["bound"]),
root_dirtree: ck(1),
root_dirmeta: ck(2),
subject: "subject".into(),
body: "body".into(),
metadata: vec![(
"version".into(),
ostrya_gvariant::to_bytes(&Type::Variant, &Value::variant(Type::Str, "1".into()))
.unwrap(),
)],
related: Vec::new(),
timestamp: Some(1_700_000_000),
orphan: false,
}
}
fn server_commit_reply(
branch: &str,
tags: &[&str],
old: Option<Checksum>,
new: Checksum,
) -> Message {
Message::CommitReply(
std::iter::once(RefOutcome {
name: branch.into(),
old,
new: Some(new),
})
.chain(tags.iter().map(|t| RefOutcome {
name: t.to_string(),
old: None,
new: Some(new),
}))
.collect(),
)
}
#[test]
fn a_server_commit_sends_commit_with_the_server_commit_alone() {
let sc = server_commit("main", &["t1", "t2"]);
let reply = server_commit_reply("main", &["t1", "t2"], Some(ck(4)), ck(9));
let (session, out) = open(&["main", "t1", "t2"], BOTH, &[reply]);
session.check_server_commit(&sc).unwrap();
let outcome = block_on(session.server_commit(sc.clone())).unwrap();
assert_eq!(outcome.commit, Some(ck(9)));
assert_eq!(
outcome
.refs
.iter()
.map(|r| r.name.as_str())
.collect::<Vec<_>>(),
["main", "t1", "t2"]
);
assert_eq!(outcome.refs[0].old, Some(ck(4)));
match &after_hello(&out)[..] {
[Event::Msg(Message::Commit(c))] => {
assert!(c.updates.is_empty());
assert!(!c.force);
assert_eq!(c.server_commit.as_deref(), Some(&sc));
}
other => panic!("{other:?}"),
}
}
#[test]
fn server_commit_prechecks_send_nothing() {
let cases: [(ServerCommit, &str); 5] = [
(server_commit("other", &[]), "'other' was not named"),
(server_commit("main", &["t3"]), "'t3' was not named"),
(server_commit("main", &["t1", "t1"]), "'t1' is named twice"),
(
server_commit("main", &["t1", "t1", "t3"]),
"'t1' is named twice",
),
(
server_commit("main", &["t3", "t1", "t1"]),
"'t3' was not named",
),
];
for (sc, text) in cases {
let (session, out) = open(&["main", "t1"], BOTH, &[]);
assert_invalid(session.check_server_commit(&sc), text);
assert_invalid(block_on(session.server_commit(sc)), text);
assert!(after_hello(&out).is_empty(), "{text}");
}
}
#[test]
fn a_server_commit_to_the_own_id_and_64_hex_sends_nothing() {
let hex = "ab".repeat(32);
let own = format!("@org.example.C:{hex}");
let other = format!("@org.example.Os:{hex}");
let open_c = |names: &[&str]| {
let mut reply = hello_reply(names, BOTH, 16_384);
if let Message::HelloReply(r) = &mut reply {
r.collection_id = Some("org.example.C".into());
}
let (session, out) = open_with(encode(&[reply]), names, SessionOptions::default());
(session.unwrap(), out)
};
let cases = [
(server_commit(&own, &[]), vec![own.as_str()], "branch"),
(
server_commit("main", &[&own]),
vec!["main", own.as_str()],
"tag",
),
];
for (sc, names, what) in cases {
let text = format!("{what} '{own}' is 64 hex characters");
let (session, out) = open_c(&names);
assert_invalid(session.check_server_commit(&sc), &text);
assert_invalid(block_on(session.server_commit(sc)), &text);
assert!(after_hello(&out).is_empty(), "{text}");
}
let (session, _) = open_c(&[&other]);
session
.check_server_commit(&server_commit(&other, &[]))
.unwrap();
}
#[test]
fn a_server_commit_over_the_frame_limit_is_refused_before_it_is_sent() {
let mut sc = server_commit("main", &[]);
let big = Value::variant(
Type::parse("ay").unwrap(),
Value::Bytes(vec![7; MIN_FRAME_LIMIT as usize]),
);
sc.metadata.push((
"big".into(),
ostrya_gvariant::to_bytes(&Type::Variant, &big).unwrap(),
));
let (session, out) = open(&["main"], BOTH, &[]);
match session.check_server_commit(&sc) {
Err(Error::LimitExceeded(m)) => assert!(m.contains("over the limit"), "{m}"),
other => panic!("{other:?}"),
}
assert!(matches!(
block_on(session.server_commit(sc)),
Err(Error::LimitExceeded(_))
));
assert!(after_hello(&out).is_empty());
let mut sc = server_commit("main", &[]);
sc.metadata.push(("bad".into(), vec![1, 2, 3]));
let (session, out) = open(&["main"], BOTH, &[]);
assert!(matches!(
session.check_server_commit(&sc),
Err(Error::Protocol(_))
));
drop(session);
assert!(after_hello(&out).is_empty());
}
#[test]
fn a_server_commit_that_the_server_refuses_at_commit_is_refused_before_it_is_sent() {
let deep = |levels: usize| {
let ty = Type::parse(&format!("{}i", "a".repeat(levels))).unwrap();
let value = (0..levels).fold(Value::I32(1), |inner, _| Value::Array(vec![inner]));
let mut sc = server_commit("main", &[]);
sc.metadata.push((
"deep".into(),
ostrya_gvariant::to_bytes(&Type::Variant, &Value::variant(ty, value)).unwrap(),
));
sc
};
let (session, out) = open(&["main"], BOTH, &[]);
session.check_server_commit(&deep(125)).unwrap();
assert_invalid(session.check_server_commit(&deep(126)), "'deep'");
assert_invalid(block_on(session.server_commit(deep(126))), "'deep'");
assert!(after_hello(&out).is_empty());
let tags: Vec<String> = (0..23_000).map(|i| format!("t{i:05}")).collect();
let refs: Vec<&str> = std::iter::once("main")
.chain(tags.iter().map(String::as_str))
.collect();
let sc = ServerCommit {
tags: tags.clone(),
..server_commit("main", &[])
};
let (session, out) = open(&refs, BOTH, &[]);
match session.check_server_commit(&sc) {
Err(Error::LimitExceeded(m)) => assert!(m.contains("23000 tags"), "{m}"),
other => panic!("{other:?}"),
}
assert!(matches!(
block_on(session.server_commit(sc)),
Err(Error::LimitExceeded(_))
));
assert!(after_hello(&out).is_empty());
}
#[test]
fn a_server_commit_reply_that_does_not_name_one_commit_is_an_unknown_outcome() {
let names = ["main", "t1"];
let mut split = server_commit_reply("main", &["t1"], None, ck(9));
if let Message::CommitReply(refs) = &mut split {
refs[1].new = Some(ck(8));
}
let mut old_tag = server_commit_reply("main", &["t1"], None, ck(9));
if let Message::CommitReply(refs) = &mut old_tag {
refs[1].old = Some(ck(3));
}
let mut deleted = server_commit_reply("main", &["t1"], None, ck(9));
if let Message::CommitReply(refs) = &mut deleted {
refs[0].new = None;
refs[1].new = None;
}
for (reply, text) in [
(split, "one new commit"),
(old_tag, "one new commit"),
(deleted, "one new commit"),
(
server_commit_reply("t1", &["main"], None, ck(9)),
"other refs",
),
(server_commit_reply("main", &[], None, ck(9)), "other refs"),
] {
let (session, _) = open(&names, BOTH, &[reply]);
assert_unknown(
block_on(session.server_commit(server_commit("main", &["t1"]))),
&names,
text,
);
}
}
#[test]
fn an_error_after_a_server_commit_is_that_error() {
let (session, _) = open(&["main"], BOTH, &[error(ErrorCode::RefDenied)]);
assert!(matches!(
block_on(session.server_commit(server_commit("main", &[]))),
Err(Error::RefDenied(_))
));
}
#[test]
fn abort_sends_abort() {
let (session, out) = open(&["a"], BOTH, &[]);
block_on(session.abort()).unwrap();
assert_eq!(after_hello(&out), vec![Event::Msg(Message::Abort)]);
}
#[test]
fn progress_counts_and_phases() {
let progress = PushProgress::new();
assert_eq!(progress.snapshot().phase, PushPhase::Scanning);
let data = payload(10_000, 6);
let mut source = Source::default()
.with(file(1), Item::Content(regular(0o644), Some(data.clone())))
.with(file(2), Item::Encoded(Encoding::Raw, b"xyz".to_vec()));
source.meta.insert(ck(7), Value::Array(Vec::new()));
let msgs = [
hello_reply(&["a"], BOTH, 16),
Message::HaveReply(HaveReply::from_missing([true, true, false])),
objects_reply(),
commit_reply(&["a"]),
];
let opts = SessionOptions {
agent: Some("test/1".into()),
progress: Some(progress.clone()),
};
let (session, out) = open_with(encode(&msgs), &["a"], opts);
let session = session.unwrap();
assert_eq!(progress.snapshot().phase, PushPhase::Connecting);
assert_eq!(progress.snapshot().bytes_sent, out.bytes().len() as u64);
let needed = block_on(session.missing(&[file(1), file(2), file(3)])).unwrap();
let snap = progress.snapshot();
assert_eq!((snap.objects_total, snap.objects_needed), (3, 2));
block_on(session.send(&source, &needed, &[ck(7)], Compression::None)).unwrap();
let snap = progress.snapshot();
assert_eq!(snap.phase, PushPhase::Uploading);
assert_eq!(snap.objects_sent, 2, "the detached metadata does not count");
let header = frame(®ular(0o644).serialize().unwrap()).unwrap();
let meta = a_sv_bytes(&Value::Array(Vec::new()));
assert_eq!(
snap.payload_bytes,
(header.len() + data.len() + 3 + meta.len()) as u64
);
assert_eq!(snap.bytes_sent, out.bytes().len() as u64);
let outcome = block_on(session.commit(&[update("a")], false)).unwrap();
let snap = progress.snapshot();
assert_eq!(snap.phase, PushPhase::Committing);
let stats = outcome.stats;
assert_eq!(
(
stats.objects_total,
stats.objects_needed,
stats.objects_sent,
stats.payload_bytes
),
(3, 2, 2, snap.payload_bytes)
);
assert_eq!(stats.bytes_sent, out.bytes().len() as u64);
assert_eq!(snap.bytes_sent, stats.bytes_sent);
match &decode(&out.bytes())[0] {
Event::Msg(Message::Hello(h)) => assert_eq!(h.agent.as_deref(), Some("test/1")),
other => panic!("{other:?}"),
}
}
#[test]
fn the_progress_hook_runs_per_phase_per_object_and_per_100_kib() {
for compression in [Compression::None, Compression::Deflate { level: 6 }] {
let calls: Arc<Mutex<Vec<PushProgressSnapshot>>> = Arc::default();
let record = Arc::clone(&calls);
let progress = PushProgress::with_hook(Arc::new(move |snapshot| {
record.lock().unwrap().push(*snapshot)
}));
let data = payload(250_000, 3);
let source = Source::default()
.with(file(1), Item::Content(regular(0o644), Some(data)))
.with(file(2), Item::Content(symlink("target"), None))
.with(
meta_name(ObjectType::DirTree, 3),
Item::Encoded(Encoding::Raw, b"xyz".to_vec()),
);
let names = [file(1), file(2), meta_name(ObjectType::DirTree, 3)];
let msgs = [
hello_reply(&["a"], BOTH, 16),
Message::HaveReply(HaveReply::from_missing([true, true, true])),
objects_reply(),
commit_reply(&["a"]),
];
let opts = SessionOptions {
progress: Some(progress.clone()),
..SessionOptions::default()
};
let (session, _out) = open_with(encode(&msgs), &["a"], opts);
let session = session.unwrap();
let needed = block_on(session.missing(&names)).unwrap();
block_on(session.send(&source, &needed, &[], compression)).unwrap();
block_on(session.commit(&[update("a")], false)).unwrap();
let last = progress.snapshot();
assert_eq!(last.bytes_total, 250_000, "{compression:?}");
assert_eq!(last.content_bytes, last.bytes_total, "{compression:?}");
let calls = calls.lock().unwrap();
let mut phases: Vec<PushPhase> = calls.iter().map(|c| c.phase).collect();
phases.dedup();
assert_eq!(
phases,
[
PushPhase::Connecting,
PushPhase::Negotiating,
PushPhase::Uploading,
PushPhase::Committing
],
"{compression:?}"
);
let first_upload = calls
.iter()
.find(|c| c.phase == PushPhase::Uploading)
.unwrap();
assert_eq!(first_upload.bytes_total, 250_000, "{compression:?}");
assert_eq!(first_upload.content_bytes, 0, "{compression:?}");
assert_eq!(calls.len(), 4 + 3 + 2, "{compression:?}: {calls:?}");
let per_object: Vec<u64> = calls
.windows(2)
.filter(|w| w[1].objects_sent > w[0].objects_sent)
.map(|w| w[1].objects_sent)
.collect();
assert_eq!(per_object, [1, 2, 3], "{compression:?}");
let steps: Vec<u64> = calls
.windows(2)
.filter(|w| w[1].content_bytes / 102_400 > w[0].content_bytes / 102_400)
.map(|w| w[1].content_bytes / 102_400)
.collect();
assert_eq!(steps, [1, 2], "{compression:?}");
}
}
#[test]
fn the_byte_total_follows_the_encoding_the_server_takes() {
let data = payload(5000, 5);
let stored = b"stored deflate bytes".to_vec();
for (encodings, want_encoding, want_total) in [
(&[Encoding::Raw][..], Encoding::Raw, data.len() as u64),
(BOTH, Encoding::Deflate, stored.len() as u64),
] {
let progress = PushProgress::new();
let source = Source::default().with(file(1), Item::Stored(data.clone(), stored.clone()));
let msgs = [hello_reply(&["a"], encodings, 16), objects_reply()];
let opts = SessionOptions {
progress: Some(progress.clone()),
..SessionOptions::default()
};
let (session, _out) = open_with(encode(&msgs), &["a"], opts);
let session = session.unwrap();
block_on(session.send(&source, &[file(1)], &[], Compression::Deflate { level: 6 }))
.unwrap();
let last = progress.snapshot();
assert_eq!(last.bytes_total, want_total, "{want_encoding:?}");
assert_eq!(last.content_bytes, last.bytes_total, "{want_encoding:?}");
assert_eq!(*source.sized.lock().unwrap(), [want_encoding]);
assert_eq!(source.opened.lock().unwrap()[0], (file(1), want_encoding));
}
}