use std::collections::HashSet;
use std::path::Path;
use futures_io::{AsyncRead, AsyncWrite};
use ostrya_core::{Checksum, MAX_COLLECTION_ID_LEN, Ref, Type, Value};
use crate::error::{Error, Result};
use crate::proto::ServerCommit;
use crate::session::{
Compression, PushOutcome, PushProgress, PushSession, ServerInfo, SessionOptions, deflate_level,
invalid,
};
use crate::transport::{Endpoint, PreparedSession};
use crate::tree::{EntryFilter, ScanOptions, TreeModel};
const BINDING_KEYS: [&str; 2] = ["ostree.ref-binding", "ostree.collection-binding"];
pub struct TreePushOptions {
pub onto: Ref,
pub tags: Vec<Ref>,
pub bind_refs: Vec<String>,
pub orphan: bool,
pub collection: Option<String>,
pub subject: Option<String>,
pub body: Option<String>,
pub metadata: Vec<(String, Value)>,
pub timestamp: Option<u64>,
pub compression: Compression,
pub entry_filter: Option<EntryFilter>,
pub hash_jobs: Option<usize>,
pub progress: Option<PushProgress>,
}
impl Default for TreePushOptions {
fn default() -> TreePushOptions {
TreePushOptions {
onto: Ref::local(String::new()),
tags: Vec::new(),
bind_refs: Vec::new(),
orphan: false,
collection: None,
subject: None,
body: None,
metadata: Vec::new(),
timestamp: None,
compression: Compression::default(),
entry_filter: None,
hash_jobs: None,
progress: None,
}
}
}
pub async fn push_tree(
endpoint: Endpoint,
root: &Path,
opts: TreePushOptions,
) -> Result<PushOutcome> {
let (scan, push) = Prepared::new(opts)?;
let transport = PushSession::prepare(endpoint).await?;
push.scan_and_run(transport, root, scan).await
}
pub async fn push_tree_prepared(
session: PreparedSession,
root: &Path,
opts: TreePushOptions,
) -> Result<PushOutcome> {
let (scan, push) = Prepared::new(opts)?;
push.scan_and_run(session, root, scan).await
}
pub async fn push_tree_over_stream<R, W>(
input: R,
output: W,
root: &Path,
opts: TreePushOptions,
) -> Result<PushOutcome>
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
let (scan, push) = Prepared::new(opts)?;
let model = push.scan(root, scan).await?;
let session =
PushSession::over_stream(input, output, &push.refs, push.session_options()).await?;
push.run(session, model).await
}
#[non_exhaustive]
pub struct ScannedTree {
pub model: TreeModel,
pub commit: ServerCommit,
pub branch: Ref,
pub tags: Vec<Ref>,
pub compression: Compression,
pub progress: Option<PushProgress>,
}
pub async fn scan_tree(root: &Path, opts: TreePushOptions) -> Result<ScannedTree> {
let (scan, push) = Prepared::new(opts)?;
crate::proto::check_server_commit_metadata(&push.commit)?;
let model = push.scan(root, scan).await?;
let Prepared {
mut commit,
branch,
tags,
compression,
progress,
..
} = push;
commit.root_dirtree = model.root_dirtree();
commit.root_dirmeta = model.root_dirmeta();
Ok(ScannedTree {
model,
commit,
branch,
tags,
compression,
progress,
})
}
struct Prepared {
refs: Vec<String>,
commit: ServerCommit,
branch: Ref,
tags: Vec<Ref>,
compression: Compression,
progress: Option<PushProgress>,
}
impl Prepared {
fn new(opts: TreePushOptions) -> Result<(ScanOptions, Prepared)> {
let TreePushOptions {
onto,
tags,
bind_refs,
orphan,
collection,
subject,
body,
metadata,
timestamp,
compression,
entry_filter,
hash_jobs,
progress,
} = opts;
if let Some(id) = &collection {
check_collection(id)?;
}
let (branch, tags) = check_names(onto, tags, &bind_refs, collection.as_deref())?;
deflate_level(compression)?;
let metadata = metadata_entries(metadata)?;
let scan = ScanOptions {
entry_filter,
hash_jobs,
};
let refs: Vec<String> = std::iter::once(&branch)
.chain(&tags)
.map(Ref::to_string)
.collect();
let unset = Checksum::from_bytes([0; 32]);
let push = Prepared {
commit: ServerCommit {
branch: refs[0].clone(),
tags: refs[1..].to_vec(),
bind_refs,
root_dirtree: unset,
root_dirmeta: unset,
subject: subject.unwrap_or_default(),
body: body.unwrap_or_default(),
metadata,
related: Vec::new(),
timestamp,
orphan,
},
refs,
branch,
tags,
compression,
progress,
};
Ok((scan, push))
}
async fn scan(&self, root: &Path, scan: ScanOptions) -> Result<TreeModel> {
TreeModel::scan_with(root, scan, self.progress.as_ref()).await
}
async fn scan_and_run(
self,
transport: PreparedSession,
root: &Path,
scan: ScanOptions,
) -> Result<PushOutcome> {
let model = self.scan(root, scan).await?;
let session = transport.open(&self.refs, self.session_options()).await?;
Box::pin(self.run(session, model)).await
}
fn session_options(&self) -> SessionOptions {
SessionOptions {
progress: self.progress.clone(),
..SessionOptions::default()
}
}
async fn run(self, session: PushSession, model: TreeModel) -> Result<PushOutcome> {
let mut commit = self.commit;
commit.root_dirtree = model.root_dirtree();
commit.root_dirmeta = model.root_dirmeta();
match upload(&session, &model, &commit, self.compression).await {
Ok(()) => {
drop(model);
session.server_commit(commit).await
}
Err(e) => {
let _ = session.abort().await;
Err(e)
}
}
}
}
async fn upload(
session: &PushSession,
model: &TreeModel,
commit: &ServerCommit,
compression: Compression,
) -> Result<()> {
check_tags_absent(session.server(), &commit.tags)?;
session.check_server_commit(commit)?;
let names = model.object_names();
let missing = session.missing(&names).await?;
drop(names);
session.send(model, &missing, &[], compression).await
}
fn check_tags_absent(server: &ServerInfo, tags: &[String]) -> Result<()> {
match tags
.iter()
.find_map(|tag| server.tip(tag).map(|tip| (tag, tip)))
{
Some((tag, current)) => Err(Error::RefMismatch {
message: format!("ref '{tag}' is at {current}"),
name: tag.clone(),
current: Some(current),
}),
None => Ok(()),
}
}
fn check_ref(r: &Ref, what: &str) -> Result<()> {
if let Ref::Remote { .. } = r {
return Err(invalid(format!(
"{what} '{r}' is a remote ref; a tree push writes no remote ref"
)));
}
if r.validate().is_err() {
return Err(invalid(format!("{what} '{r}' is not a valid ref name")));
}
if let Ref::Local { name } = r
&& ostrya_core::is_checksum_shaped(name)
{
return Err(invalid(format!(
"{what} '{r}' is 64 hex characters, which a revision reads as a commit checksum"
)));
}
Ok(())
}
fn in_collection(r: Ref, collection: Option<&str>, what: &str) -> Result<Ref> {
let Some(id) = collection else {
return Ok(r);
};
r.in_collection(id).map_err(|r| {
let Ref::Collection { id: other, .. } = &r else {
unreachable!("a refused ref is a collection ref");
};
invalid(format!(
"{what} '{r}' names the collection '{other}', and the push names the collection \
'{id}'"
))
})
}
fn check_names(
onto: Ref,
tags: Vec<Ref>,
bind_refs: &[String],
collection: Option<&str>,
) -> Result<(Ref, Vec<Ref>)> {
check_ref(&onto, "branch")?;
for tag in &tags {
check_ref(tag, "tag")?;
}
let onto = in_collection(onto, collection, "branch")?;
let tags = tags
.into_iter()
.map(|tag| in_collection(tag, collection, "tag"))
.collect::<Result<Vec<_>>>()?;
let mut seen = HashSet::new();
for tag in &tags {
if *tag == onto {
return Err(invalid(format!("the tag '{tag}' is also the branch")));
}
if !seen.insert(tag) {
return Err(invalid(format!("the tag '{tag}' is named twice")));
}
}
if let Some((other, r)) = Ref::collection_conflict(std::iter::once(&onto).chain(&tags)) {
return Err(invalid(format!(
"the refs '{other}' and '{r}' of the server commit are in two namespaces"
)));
}
for name in bind_refs {
if name.contains(':') || !ostrya_core::is_ref_name(name) {
return Err(invalid(format!(
"bound name '{name}' is not a valid ref name"
)));
}
}
Ok((onto, tags))
}
fn check_collection(id: &str) -> Result<()> {
if id.len() > MAX_COLLECTION_ID_LEN {
return Err(invalid(format!(
"the collection id of {} bytes is longer than {MAX_COLLECTION_ID_LEN} bytes",
id.len()
)));
}
if !ostrya_core::is_collection_id(id) {
return Err(invalid(format!("invalid collection id '{id}'")));
}
Ok(())
}
fn metadata_entries(entries: Vec<(String, Value)>) -> Result<Vec<(String, Vec<u8>)>> {
entries
.into_iter()
.map(|(key, value)| {
if key.is_empty() {
return Err(invalid("the metadata holds an empty key"));
}
if BINDING_KEYS.contains(&key.as_str()) {
return Err(invalid(format!(
"the metadata holds the key '{key}', which the server writes"
)));
}
let bytes = ostrya_core::to_bytes(&Type::Variant, &value).map_err(|e| {
invalid(format!(
"the metadata value under '{key}' is not a variant: {e}"
))
})?;
Ok((key, bytes))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn refused(opts: TreePushOptions) -> String {
match Prepared::new(opts) {
Err(Error::InvalidInput(m)) => m,
Err(e) => panic!("{e:?}"),
Ok(_) => panic!("accepted"),
}
}
fn onto(branch: &str) -> TreePushOptions {
TreePushOptions {
onto: Ref::local(branch),
timestamp: Some(1),
..Default::default()
}
}
fn strings(items: &[&str]) -> Vec<String> {
items.iter().map(|s| s.to_string()).collect()
}
fn refs(items: &[&str]) -> Vec<Ref> {
items.iter().map(|s| s.parse().unwrap()).collect()
}
const BAD_NAMES: [&str; 16] = [
"", "main^", "a^b", "^", "x/y^", "/a", "a/", "a//b", ".", "..", "a/../b", "a\0b", "a b",
"a*", "-a", "a/.b",
];
#[test]
fn the_branch_and_the_tags_are_checked_before_the_scan() {
let hex = "ab".repeat(32);
for (what, make) in [
(
"branch",
(|r: Ref| TreePushOptions {
onto: r,
..onto("main")
}) as fn(Ref) -> TreePushOptions,
),
("tag", |r: Ref| TreePushOptions {
tags: vec![r],
..onto("main")
}),
] {
let m = refused(make(Ref::remote("origin", "main")));
assert!(m.contains("is a remote ref"), "{what}: {m}");
for bad in BAD_NAMES {
let m = refused(make(Ref::local(bad)));
assert!(m.contains("not a valid ref name"), "{what} {bad:?}: {m}");
assert!(m.starts_with(what), "{what} {bad:?}: {m}");
}
let m = refused(make(Ref::collection("no-dot", "a")));
assert!(m.contains("not a valid ref name"), "{what}: {m}");
assert!(
refused(make(Ref::local(hex.as_str()))).contains("commit checksum"),
"{what}"
);
}
let m = refused(TreePushOptions {
tags: refs(&["t", "main"]),
..onto("main")
});
assert!(m.contains("'main' is also the branch"), "{m}");
let m = refused(TreePushOptions {
tags: refs(&["t", "u", "t"]),
..onto("main")
});
assert!(m.contains("'t' is named twice"), "{m}");
let upper = hex.to_uppercase();
let (_, push) = Prepared::new(TreePushOptions {
tags: refs(&["a/b", "x.y", &upper, &hex[1..], "@org.example.X:t"]),
..onto("main")
})
.unwrap();
assert_eq!(
push.refs,
["main", "a/b", "x.y", &upper, &hex[1..], "@org.example.X:t"]
);
Prepared::new(TreePushOptions {
onto: Ref::collection("org.example.X", hex.as_str()),
..onto("main")
})
.unwrap();
}
#[test]
fn the_collection_names_the_namespace_of_each_plain_ref() {
let x = || Some("org.example.X".to_owned());
let (_, push) = Prepared::new(TreePushOptions {
tags: refs(&["t", "@org.example.X:u"]),
bind_refs: strings(&["b"]),
collection: x(),
..onto("a")
})
.unwrap();
assert_eq!(
push.refs,
["@org.example.X:a", "@org.example.X:t", "@org.example.X:u"]
);
assert_eq!(push.commit.branch, "@org.example.X:a");
assert_eq!(push.commit.tags, ["@org.example.X:t", "@org.example.X:u"]);
assert_eq!(push.commit.bind_refs, ["b"]);
assert_eq!(push.branch, Ref::collection("org.example.X", "a"));
let (_, plain) = Prepared::new(TreePushOptions {
onto: Ref::collection("org.example.X", "a"),
..onto("a")
})
.unwrap();
assert_eq!(plain.refs, push.refs[..1]);
let m = refused(TreePushOptions {
onto: Ref::collection("org.example.Y", "a"),
collection: x(),
..onto("a")
});
assert!(
m.contains(
"names the collection 'org.example.Y', and the push names the collection \
'org.example.X'"
),
"{m}"
);
let m = refused(TreePushOptions {
tags: refs(&["@org.example.Y:t"]),
collection: x(),
..onto("a")
});
assert!(m.starts_with("tag '@org.example.Y:t'"), "{m}");
let m = refused(TreePushOptions {
tags: refs(&["@org.example.X:a"]),
collection: x(),
..onto("a")
});
assert!(m.contains("'@org.example.X:a' is also the branch"), "{m}");
let m = refused(TreePushOptions {
onto: Ref::collection("org.example.X", "a"),
tags: refs(&["t", "@org.example.Y:u"]),
..onto("a")
});
assert!(
m.contains("'@org.example.X:a' and '@org.example.Y:u'"),
"{m}"
);
Prepared::new(TreePushOptions {
tags: refs(&["@org.example.X:t"]),
..onto("main")
})
.unwrap();
}
#[test]
fn a_bound_name_passes_the_ref_name_rule_with_no_colon() {
for bad in BAD_NAMES.iter().copied().chain(["o:main"]) {
let m = refused(TreePushOptions {
bind_refs: strings(&[bad]),
..onto("main")
});
assert!(m.contains("bound name"), "{bad:?}: {m}");
}
let hex = "ab".repeat(32);
let (_, push) = Prepared::new(TreePushOptions {
bind_refs: strings(&["x", "x", "main", &hex]),
..onto("main")
})
.unwrap();
assert_eq!(push.commit.bind_refs, ["x", "x", "main", hex.as_str()]);
assert_eq!(push.refs, ["main"]);
let (_, push) = Prepared::new(TreePushOptions {
bind_refs: strings(&["x"]),
collection: Some("org.example.X".into()),
..onto("main")
})
.unwrap();
assert_eq!(push.commit.bind_refs, ["x"]);
}
#[test]
fn the_collection_is_checked_before_the_scan() {
let longest = format!("org.{}", "a".repeat(251));
let over = format!("org.{}", "a".repeat(252));
for (id, needle) in [("no-dot", "invalid collection id"), (&*over, "256 bytes")] {
let m = refused(TreePushOptions {
collection: Some(id.into()),
..onto("main")
});
assert!(m.contains(needle), "{m}");
}
let (_, push) = Prepared::new(TreePushOptions {
collection: Some(longest.clone()),
..onto("main")
})
.unwrap();
assert_eq!(push.branch, Ref::collection(longest, "main"));
}
#[test]
fn the_other_options_are_checked_before_the_scan() {
for level in [0, 10] {
let m = refused(TreePushOptions {
compression: Compression::Deflate { level },
..onto("main")
});
assert!(m.contains("compression level"), "{m}");
}
let variant = Value::variant(ostrya_core::Type::Str, Value::Str("v".into()));
let m = refused(TreePushOptions {
metadata: vec![(String::new(), variant.clone())],
..onto("main")
});
assert!(m.contains("metadata holds an empty key"), "{m}");
for key in BINDING_KEYS {
let m = refused(TreePushOptions {
metadata: vec![("k".into(), variant.clone()), (key.into(), variant.clone())],
..onto("main")
});
assert!(
m.contains(&format!("'{key}', which the server writes")),
"{m}"
);
}
let m = refused(TreePushOptions {
metadata: vec![("k".into(), Value::Str("bare".into()))],
..onto("main")
});
assert!(m.contains("not a variant"), "{m}");
}
#[test]
fn the_server_commit_carries_the_options() {
let string = |s: &str| Value::variant(ostrya_core::Type::Str, Value::Str(s.into()));
let (_, push) = Prepared::new(TreePushOptions {
tags: refs(&["t"]),
bind_refs: strings(&["b"]),
orphan: true,
subject: Some("s".into()),
body: Some("m".into()),
metadata: vec![("z".into(), string("1")), ("a".into(), string("2"))],
timestamp: Some(42),
..onto("main")
})
.unwrap();
let sc = push.commit;
assert_eq!(sc.branch, "main");
assert_eq!(sc.tags, ["t"]);
assert_eq!(sc.bind_refs, ["b"]);
assert!(sc.orphan);
assert_eq!((sc.subject.as_str(), sc.body.as_str()), ("s", "m"));
let v = |value: &Value| ostrya_core::to_bytes(&Type::Variant, value).unwrap();
assert_eq!(
sc.metadata,
[
("z".to_owned(), v(&string("1"))),
("a".to_owned(), v(&string("2")))
]
);
assert_eq!(sc.timestamp, Some(42));
let (_, push) = Prepared::new(TreePushOptions {
timestamp: None,
..onto("main")
})
.unwrap();
assert_eq!(push.commit.timestamp, None);
assert_eq!(push.commit.subject, "");
}
#[test]
fn a_tag_that_the_server_holds_is_ref_mismatch() {
use crate::proto::{Encoding, RefState};
let tip = Checksum::from_bytes([5; 32]);
let server = ServerInfo {
version: 1,
mode: "archive".into(),
collection_id: None,
max_frame: 1 << 20,
max_have: 16_384,
encodings: vec![Encoding::Raw],
parallel_uploads: 1,
refs: [("main", Some(tip)), ("a", None), ("b", Some(tip))]
.into_iter()
.map(|(name, commit)| RefState {
name: name.into(),
commit,
})
.collect(),
};
check_tags_absent(&server, &strings(&["a"])).unwrap();
match check_tags_absent(&server, &strings(&["a", "b"])) {
Err(Error::RefMismatch { name, current, .. }) => {
assert_eq!(name, "b");
assert_eq!(current, Some(tip));
}
other => panic!("{other:?}"),
}
}
#[test]
fn scan_tree_checks_the_depth_and_fills_the_roots() {
let root =
std::env::temp_dir().join(format!("ostrya-remote-scan-tree-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("dir")).unwrap();
std::fs::write(root.join("dir/file"), b"file").unwrap();
let deep = (0..126).fold(Value::Byte(1), |value, _| {
Value::Maybe(Some(Box::new(value)))
});
let ty = (0..126).fold(Type::Byte, |ty, _| Type::maybe(ty));
let absent = root.join("absent");
match ostrya_rt::block_on(scan_tree(
&absent,
TreePushOptions {
metadata: vec![("deep".into(), Value::variant(ty, deep))],
..onto("main")
},
)) {
Err(Error::InvalidInput(m)) => assert!(m.contains("cannot hold"), "{m}"),
other => panic!("{:?}", other.map(|_| ())),
}
let scanned = ostrya_rt::block_on(scan_tree(
&root,
TreePushOptions {
collection: Some("org.example.A".into()),
compression: Compression::Deflate { level: 3 },
..onto("main")
},
));
let _ = std::fs::remove_dir_all(&root);
let scanned = scanned.unwrap();
assert_eq!(scanned.commit.root_dirtree, scanned.model.root_dirtree());
assert_eq!(scanned.commit.root_dirmeta, scanned.model.root_dirmeta());
assert_eq!(scanned.commit.branch, "@org.example.A:main");
assert_eq!(scanned.commit.timestamp, Some(1));
assert_eq!(scanned.branch, Ref::collection("org.example.A", "main"));
assert!(scanned.tags.is_empty());
assert_eq!(scanned.compression, Compression::Deflate { level: 3 });
assert_eq!(scanned.model.object_names().len(), 4);
}
#[test]
fn the_scan_shows_scanning_during_the_walk_and_hashing_after_it() {
use std::sync::{Arc, Mutex};
use crate::PushPhase;
use crate::tree::EntryAction;
#[derive(Debug, PartialEq, Eq)]
enum Call {
Hook(PushPhase),
Filter,
}
let root =
std::env::temp_dir().join(format!("ostrya-remote-scan-phases-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("dir")).unwrap();
std::fs::write(root.join("dir/file"), b"file").unwrap();
let calls: Arc<Mutex<Vec<Call>>> = Arc::default();
let hook_calls = Arc::clone(&calls);
let progress = PushProgress::with_hook(Arc::new(move |snapshot| {
hook_calls.lock().unwrap().push(Call::Hook(snapshot.phase));
}));
progress.set_phase(PushPhase::Committing);
calls.lock().unwrap().clear();
let seen = Arc::new(Mutex::new(Vec::new()));
let record = (seen.clone(), progress.clone(), Arc::clone(&calls));
let filter: EntryFilter = Box::new(move |_path, _meta| {
record.0.lock().unwrap().push(record.1.snapshot().phase);
record.2.lock().unwrap().push(Call::Filter);
EntryAction::Keep
});
let scan = ScanOptions {
entry_filter: Some(filter),
hash_jobs: None,
};
let model = ostrya_rt::block_on(TreeModel::scan_with(&root, scan, Some(&progress)));
let _ = std::fs::remove_dir_all(&root);
model.unwrap();
let seen = seen.lock().unwrap();
assert_eq!(seen.len(), 3, "{seen:?}");
assert!(seen.iter().all(|p| *p == PushPhase::Scanning), "{seen:?}");
assert_eq!(progress.snapshot().phase, PushPhase::Hashing);
assert_eq!(
*calls.lock().unwrap(),
[
Call::Hook(PushPhase::Scanning),
Call::Filter,
Call::Filter,
Call::Filter,
Call::Hook(PushPhase::Hashing),
]
);
}
#[test]
fn a_new_handle_gets_a_scanning_call_before_the_walk_and_a_hashing_call_after_it() {
use std::sync::{Arc, Mutex};
use crate::PushPhase;
use crate::tree::EntryAction;
#[derive(Debug, PartialEq, Eq)]
enum Call {
Hook(PushPhase),
Filter,
}
let root =
std::env::temp_dir().join(format!("ostrya-remote-scan-hook-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("dir")).unwrap();
std::fs::write(root.join("dir/file"), b"file").unwrap();
let calls: Arc<Mutex<Vec<Call>>> = Arc::default();
let hook_calls = Arc::clone(&calls);
let progress = PushProgress::with_hook(Arc::new(move |snapshot| {
hook_calls.lock().unwrap().push(Call::Hook(snapshot.phase));
}));
let filter_calls = Arc::clone(&calls);
let filter: EntryFilter = Box::new(move |_path, _meta| {
filter_calls.lock().unwrap().push(Call::Filter);
EntryAction::Keep
});
let scan = ScanOptions {
entry_filter: Some(filter),
hash_jobs: None,
};
let model = ostrya_rt::block_on(TreeModel::scan_with(&root, scan, Some(&progress)));
let _ = std::fs::remove_dir_all(&root);
model.unwrap();
assert_eq!(
*calls.lock().unwrap(),
[
Call::Hook(PushPhase::Scanning),
Call::Filter,
Call::Filter,
Call::Filter,
Call::Hook(PushPhase::Hashing),
]
);
}
}