mod common;
use std::path::Path;
use common::{Field2Entry, TmpDir, file_inventory, store_with_field2};
use ostrya::{
Checksum, CommitModifier, CommitModifierFlags, CommitOptions, CommitRelations, CreateOptions,
DictBuilder, DummySigner, Error, LockKind, MutableTree, ObjectType, PullOptions, Ref,
RelationField, Repo, RepoMode, RepoTree, Transaction, Type, Value,
};
use ostrya_rt::block_on;
const FIXED_TS: u64 = 1_700_000_000;
const RELATED_KEY: &str = "ostrya.related";
fn write_tree(base: &Path, name: &str) {
let dir = base.join(name);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("payload.txt"), format!("{name}\n")).unwrap();
}
async fn repo_with_trees(base: &Path, names: &[&str]) -> Repo {
for name in names {
write_tree(base, name);
}
Repo::create(&base.join("repo"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap()
}
async fn stage_tree(txn: &Transaction, base: &Path, name: &str) -> RepoTree {
use std::os::fd::AsFd;
let mut mtree = MutableTree::new();
let mut modifier = CommitModifier::new(CommitModifierFlags::SKIP_XATTRS);
let dfd = std::fs::File::open(base).unwrap();
txn.write_dfd_to_mtree(
dfd.as_fd(),
Path::new(name),
&mut mtree,
Some(&mut modifier),
)
.await
.unwrap();
txn.write_mtree(&mut mtree).await.unwrap()
}
fn options(name: &str, related: &[(&str, Checksum)]) -> CommitOptions {
CommitOptions {
subject: Some(name.to_owned()),
timestamp: Some(FIXED_TS),
attachments: related
.iter()
.map(|(entry, checksum)| ((*entry).to_owned(), *checksum))
.collect(),
..CommitOptions::default()
}
}
async fn commit(repo: &Repo, base: &Path, name: &str, related: &[(&str, Checksum)]) -> Checksum {
let txn = repo.transaction().await.unwrap();
let root = stage_tree(&txn, base, name).await;
let commit = txn
.write_commit(options(name, related), &root)
.await
.unwrap();
txn.commit().await.unwrap();
commit
}
fn field2(entries: &[(&str, Checksum)]) -> Vec<(String, Vec<u8>)> {
entries
.iter()
.map(|(name, checksum)| ((*name).to_owned(), checksum.as_bytes().to_vec()))
.collect()
}
fn owned(entries: &[(&str, Checksum)]) -> Vec<(String, Checksum)> {
entries
.iter()
.map(|(name, checksum)| ((*name).to_owned(), *checksum))
.collect()
}
fn sources(entries: &[(&str, &[u8])]) -> (Type, Value) {
let elements = entries
.iter()
.map(|(name, bytes)| {
Value::Tuple(vec![
Value::Str((*name).to_owned()),
Value::Bytes(bytes.to_vec()),
])
})
.collect();
(Type::parse("a(say)").unwrap(), Value::Array(elements))
}
fn dict(entries: Vec<(&str, (Type, Value))>) -> Value {
let mut builder = DictBuilder::new();
for (key, (ty, value)) in entries {
builder.insert(key, ty, value);
}
builder.build()
}
fn related_error(err: Error) -> (Option<Checksum>, RelationField, String) {
match err {
Error::InvalidRelations {
commit,
field,
reason,
} => (commit, field, reason),
other => panic!("expected InvalidRelations, got {other:?}"),
}
}
fn write_raw_detached(repo: &Repo, commit: &Checksum, meta: &Value) {
let bytes = ostrya_core::to_bytes(&Type::parse("a{sv}").unwrap(), meta).unwrap();
let path = repo.path().join("objects").join(ostrya::loose_path(
commit,
ObjectType::CommitMeta,
repo.mode(),
));
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, bytes).unwrap();
}
async fn detached_keys(repo: &Repo, commit: &Checksum) -> Vec<String> {
let dict = repo
.read_commit_detached_metadata(commit)
.await
.unwrap()
.expect("the commit has detached metadata");
dict.as_array()
.unwrap()
.iter()
.map(|entry| entry.as_tuple().unwrap()[0].as_str().unwrap().to_owned())
.collect()
}
fn string(text: &str) -> (Type, Value) {
(Type::parse("s").unwrap(), Value::Str(text.to_owned()))
}
fn objects(repo: &Repo) -> Vec<(String, Vec<u8>)> {
file_inventory(repo.path(), "objects")
}
fn staged(repo: &Repo) -> Vec<(String, Vec<u8>)> {
file_inventory(repo.path(), "tmp")
}
fn refs(repo: &Repo) -> Vec<(String, Vec<u8>)> {
file_inventory(repo.path(), "refs")
}
#[test]
fn write_commit_sorts_the_attachments() {
let tmp = TmpDir::new("related-sort");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["fe", "uki", "head"]).await;
let fe = commit(&repo, tmp.path(), "fe", &[]).await;
let uki = commit(&repo, tmp.path(), "uki", &[]).await;
let head = commit(
&repo,
tmp.path(),
"head",
&[("container/fe", fe), ("boot/uki", uki), ("Boot/x", fe)],
)
.await;
let sorted = [("Boot/x", fe), ("boot/uki", uki), ("container/fe", fe)];
let (stored, _) = repo.load_commit(&head).await.unwrap();
assert_eq!(stored.related, field2(&sorted));
assert_eq!(
repo.read_commit_relations(&head).await.unwrap(),
CommitRelations {
attachments: owned(&sorted),
supplements: Vec::new(),
}
);
});
}
#[test]
fn one_set_of_attachments_gives_one_checksum() {
let tmp = TmpDir::new("related-stable");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["fe", "uki", "head"]).await;
let fe = commit(&repo, tmp.path(), "fe", &[]).await;
let uki = commit(&repo, tmp.path(), "uki", &[]).await;
let first = commit(
&repo,
tmp.path(),
"head",
&[("container/fe", fe), ("boot/uki", uki)],
)
.await;
let second = commit(
&repo,
tmp.path(),
"head",
&[("boot/uki", uki), ("container/fe", fe)],
)
.await;
assert_eq!(first, second);
let plain = commit(&repo, tmp.path(), "head", &[]).await;
assert_ne!(first, plain, "field 2 is in the commit checksum");
});
}
#[test]
fn write_commit_refuses_defective_or_incomplete_attachments() {
let tmp = TmpDir::new("related-refuse");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["dep", "partial", "head"]).await;
let att = commit(&repo, tmp.path(), "dep", &[]).await;
let partial = commit(&repo, tmp.path(), "partial", &[]).await;
let state = repo.path().join("state");
std::fs::create_dir_all(&state).unwrap();
std::fs::write(state.join(format!("{partial}.commitpartial")), b"").unwrap();
let absent = Checksum::from_ay(&[0x22; 32]).unwrap();
let cases = [
(
vec![("a/x", att), ("", att)],
"entry 1 has an empty name".to_owned(),
),
(
vec![("b/x", att), ("a/x", att), ("b/x", absent)],
"two entries have the name b/x".to_owned(),
),
(
vec![("a/x", att), ("b/x", absent)],
format!(
"attachment b/x names commit {absent}, which is in neither the repository \
nor the transaction"
),
),
(
vec![("a/x", partial)],
format!("attachment a/x names commit {partial}, which is partial"),
),
];
for (related, expected) in cases {
let objects_before = objects(&repo);
let refs_before = refs(&repo);
let txn = repo.transaction().await.unwrap();
let root = stage_tree(&txn, tmp.path(), "head").await;
let staged_before = staged(&repo);
let err = txn
.write_commit(options("head", &related), &root)
.await
.unwrap_err();
assert_eq!(
staged(&repo),
staged_before,
"the refused call stages nothing"
);
assert_eq!(
err.to_string(),
format!("related commits in field 2: {expected}")
);
assert_eq!(
related_error(err),
(None, RelationField::Attachments, expected)
);
let written = txn
.write_commit(options("head", &[("a/x", att)]), &root)
.await
.unwrap();
txn.set_ref(&Ref::local("main"), Some(&written));
txn.abort().await.unwrap();
assert_eq!(objects(&repo), objects_before, "no new object");
assert_eq!(refs(&repo), refs_before, "no new ref");
}
});
}
#[test]
fn check_attachments_runs_the_checks_of_write_commit() {
let tmp = TmpDir::new("related-check");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["dep", "partial", "c", "nested"]).await;
let att = commit(&repo, tmp.path(), "dep", &[]).await;
let partial = commit(&repo, tmp.path(), "partial", &[]).await;
let c = commit(&repo, tmp.path(), "c", &[]).await;
let nested = commit(&repo, tmp.path(), "nested", &[("lib/c", c)]).await;
let defective = store_with_field2(&repo, &att, &[("lib/c", &c.as_bytes()[..31])]).await;
let state = repo.path().join("state");
std::fs::create_dir_all(&state).unwrap();
std::fs::write(state.join(format!("{partial}.commitpartial")), b"").unwrap();
let absent = Checksum::from_ay(&[0x22; 32]).unwrap();
let txn = repo.transaction().await.unwrap();
let cases = [
(vec![("", att)], "entry 0 has an empty name".to_owned()),
(
vec![("a/x", att), ("a/x", att)],
"two entries have the name a/x".to_owned(),
),
(
vec![("a/x", absent)],
format!(
"attachment a/x names commit {absent}, which is in neither the repository \
nor the transaction"
),
),
(
vec![("a/x", partial)],
format!("attachment a/x names commit {partial}, which is partial"),
),
];
for (related, expected) in cases {
let staged_before = staged(&repo);
let err = txn.check_attachments(&owned(&related)).await.unwrap_err();
assert_eq!(
related_error(err),
(None, RelationField::Attachments, expected)
);
assert_eq!(staged(&repo), staged_before, "the call stages nothing");
}
let err = txn
.check_attachments(&owned(&[("b/x", partial), ("a/x", absent)]))
.await
.unwrap_err();
assert!(
related_error(err).2.starts_with("attachment a/x "),
"the first name in byte order"
);
let accepted = owned(&[
("b/x", att),
("a/x", c),
("c/x", nested),
("d/x", defective),
]);
let _ = txn.check_attachments(&accepted).await.unwrap();
assert_eq!(
accepted,
owned(&[
("b/x", att),
("a/x", c),
("c/x", nested),
("d/x", defective)
])
);
let _ = txn.check_attachments(&[]).await.unwrap();
txn.abort().await.unwrap();
});
}
#[test]
fn check_attachments_refuses_an_attachment_whose_field2_does_not_decode() {
let tmp = TmpDir::new("related-undecodable");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["dep", "source", "head"]).await;
let att = commit(&repo, tmp.path(), "dep", &[]).await;
let source = commit(&repo, tmp.path(), "source", &[("lib/undecodable", att)]).await;
let (stored, _) = repo.load_commit(&source).await.unwrap();
let mut bytes = stored.serialize().unwrap();
let name = b"lib/undecodable\0";
let at = bytes
.windows(name.len())
.position(|window| window == name)
.unwrap();
bytes[at + name.len() - 1] = b'!';
let txn = repo.transaction().await.unwrap();
let broken = txn
.write_metadata(ObjectType::Commit, None, &bytes)
.await
.unwrap();
txn.commit().await.unwrap();
let objects_before = objects(&repo);
let refs_before = refs(&repo);
let txn = repo.transaction().await.unwrap();
let err = txn
.check_attachments(&owned(&[("a/x", broken)]))
.await
.unwrap_err();
assert!(matches!(err, Error::Core(_)), "got {err:?}");
let root = stage_tree(&txn, tmp.path(), "head").await;
let err = txn
.write_commit(options("head", &[("a/x", broken)]), &root)
.await
.unwrap_err();
assert!(matches!(err, Error::Core(_)), "got {err:?}");
txn.abort().await.unwrap();
assert_eq!(objects(&repo), objects_before, "no new object");
assert_eq!(refs(&repo), refs_before, "no new ref");
});
}
#[test]
fn check_attachments_reads_no_object_of_a_partial_attachment() {
let tmp = TmpDir::new("related-partial-unreadable");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["partial"]).await;
let partial = commit(&repo, tmp.path(), "partial", &[]).await;
let state = repo.path().join("state");
std::fs::create_dir_all(&state).unwrap();
std::fs::write(state.join(format!("{partial}.commitpartial")), b"").unwrap();
let path = repo.path().join("objects").join(ostrya::loose_path(
&partial,
ObjectType::Commit,
RepoMode::Archive,
));
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
let txn = repo.transaction().await.unwrap();
let err = txn
.check_attachments(&owned(&[("a/x", partial)]))
.await
.unwrap_err();
assert_eq!(
related_error(err),
(
None,
RelationField::Attachments,
format!("attachment a/x names commit {partial}, which is partial")
)
);
txn.abort().await.unwrap();
});
}
#[test]
fn check_attachments_refuses_a_staged_attachment_with_a_partial_marker() {
let tmp = TmpDir::new("related-staged-partial");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["dep"]).await;
let txn = repo.transaction().await.unwrap();
let root = stage_tree(&txn, tmp.path(), "dep").await;
let att = txn.write_commit(options("dep", &[]), &root).await.unwrap();
let state = repo.path().join("state");
std::fs::create_dir_all(&state).unwrap();
std::fs::write(state.join(format!("{att}.commitpartial")), b"").unwrap();
let err = txn
.check_attachments(&owned(&[("a/x", att)]))
.await
.unwrap_err();
assert_eq!(
related_error(err),
(
None,
RelationField::Attachments,
format!("attachment a/x names commit {att}, which is partial")
)
);
txn.abort().await.unwrap();
});
}
fn mark_partial(repo: &Repo, commit: &Checksum) {
let state = repo.path().join("state");
std::fs::create_dir_all(&state).unwrap();
std::fs::write(state.join(format!("{commit}.commitpartial")), b"").unwrap();
}
fn invalid_input(err: Error) -> String {
match err {
Error::InvalidInput(text) => text,
other => panic!("expected InvalidInput, got {other:?}"),
}
}
#[test]
fn write_commit_checked_does_not_check_again() {
let tmp = TmpDir::new("related-checked-once");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["fe", "uki", "head"]).await;
let fe = commit(&repo, tmp.path(), "fe", &[]).await;
let uki = commit(&repo, tmp.path(), "uki", &[]).await;
let unsorted = owned(&[("container/fe", fe), ("boot/uki", uki)]);
let txn = repo.transaction().await.unwrap();
let checked = txn.check_attachments(&unsorted).await.unwrap();
mark_partial(&repo, &fe);
let root = stage_tree(&txn, tmp.path(), "head").await;
let head = txn
.write_commit_checked(options("head", &[]), checked, &root)
.await
.unwrap();
txn.commit().await.unwrap();
let (stored, _) = repo.load_commit(&head).await.unwrap();
assert_eq!(
stored.related,
field2(&[("boot/uki", uki), ("container/fe", fe)])
);
let txn = repo.transaction().await.unwrap();
let root = stage_tree(&txn, tmp.path(), "head").await;
let mut opts = options("head", &[]);
opts.attachments = unsorted;
let err = txn.write_commit(opts, &root).await.unwrap_err();
assert_eq!(
related_error(err),
(
None,
RelationField::Attachments,
format!("attachment container/fe names commit {fe}, which is partial")
)
);
txn.abort().await.unwrap();
});
}
#[test]
fn write_commit_checked_refuses_a_list_of_another_transaction() {
let tmp = TmpDir::new("related-checked-other");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["dep", "head"]).await;
let att = commit(&repo, tmp.path(), "dep", &[]).await;
let other = repo.transaction().await.unwrap();
let txn = repo.transaction().await.unwrap();
let root = stage_tree(&txn, tmp.path(), "head").await;
let checked = other
.check_attachments(&owned(&[("a/x", att)]))
.await
.unwrap();
let staged_before = staged(&repo);
let err = txn
.write_commit_checked(options("head", &[]), checked, &root)
.await
.unwrap_err();
assert_eq!(
invalid_input(err),
"the checked attachments come from another transaction"
);
assert_eq!(staged(&repo), staged_before, "the call stages nothing");
other.abort().await.unwrap();
let checked = txn
.check_attachments(&owned(&[("a/x", att)]))
.await
.unwrap();
let head = txn
.write_commit_checked(options("head", &[]), checked, &root)
.await
.unwrap();
txn.commit().await.unwrap();
assert_eq!(
repo.read_commit_relations(&head).await.unwrap().attachments,
owned(&[("a/x", att)])
);
});
}
#[test]
fn write_commit_checked_refuses_attachments_in_the_options() {
let tmp = TmpDir::new("related-checked-options");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["dep", "head"]).await;
let att = commit(&repo, tmp.path(), "dep", &[]).await;
let txn = repo.transaction().await.unwrap();
let root = stage_tree(&txn, tmp.path(), "head").await;
let checked = txn
.check_attachments(&owned(&[("a/x", att)]))
.await
.unwrap();
let staged_before = staged(&repo);
let err = txn
.write_commit_checked(options("head", &[("a/x", att)]), checked, &root)
.await
.unwrap_err();
assert_eq!(
invalid_input(err),
"the commit options name attachments; the checked attachments give them"
);
assert_eq!(staged(&repo), staged_before, "the call stages nothing");
let checked = txn
.check_attachments(&owned(&[("a/x", att)]))
.await
.unwrap();
let head = txn
.write_commit_checked(options("head", &[]), checked, &root)
.await
.unwrap();
txn.commit().await.unwrap();
assert_eq!(
repo.read_commit_relations(&head).await.unwrap().attachments,
owned(&[("a/x", att)])
);
});
}
#[test]
fn write_commit_checked_gives_the_commit_of_write_commit() {
let tmp = TmpDir::new("related-checked-same");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["fe", "uki", "head"]).await;
let fe = commit(&repo, tmp.path(), "fe", &[]).await;
let uki = commit(&repo, tmp.path(), "uki", &[]).await;
let unsorted = [("container/fe", fe), ("boot/uki", uki)];
let txn = repo.transaction().await.unwrap();
let root = stage_tree(&txn, tmp.path(), "head").await;
let checked = txn.check_attachments(&owned(&unsorted)).await.unwrap();
let through_list = txn
.write_commit_checked(options("head", &[]), checked, &root)
.await
.unwrap();
let direct = txn
.write_commit(options("head", &unsorted), &root)
.await
.unwrap();
assert_eq!(through_list, direct);
txn.commit().await.unwrap();
});
}
#[test]
fn write_commit_accepts_a_nested_attachment() {
let tmp = TmpDir::new("related-nested");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["c", "b", "a"]).await;
let c = commit(&repo, tmp.path(), "c", &[]).await;
let b = commit(&repo, tmp.path(), "b", &[("lib/c", c)]).await;
let a = commit(&repo, tmp.path(), "a", &[("lib/b", b)]).await;
assert_eq!(
repo.read_commit_relations(&a).await.unwrap().attachments,
owned(&[("lib/b", b)])
);
assert_eq!(
repo.read_commit_relations(&b).await.unwrap().attachments,
owned(&[("lib/c", c)])
);
});
}
#[test]
fn write_commit_writes_a_chain_of_attachments() {
let tmp = TmpDir::new("related-chain");
block_on(async {
let repo = Repo::create(
&tmp.path().join("repo"),
CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
let chain = common::write_chain(&repo, tmp.path(), "rootfs").await;
for (commit, expected) in [
(chain.r, owned(&[(common::CHAIN_C, chain.c)])),
(chain.c, owned(&[(common::CHAIN_D, chain.d)])),
(chain.d, Vec::new()),
] {
let (stored, _) = repo.load_commit(&commit).await.unwrap();
let expected_field2: Vec<(String, Vec<u8>)> = expected
.iter()
.map(|(name, checksum)| (name.clone(), checksum.as_bytes().to_vec()))
.collect();
assert_eq!(stored.related, expected_field2, "field 2 of {commit}");
assert_eq!(
repo.read_commit_relations(&commit)
.await
.unwrap()
.attachments,
expected
);
}
let txn = repo.transaction().await.unwrap();
let _ = txn
.check_attachments(&owned(&[("system/rootfs", chain.r)]))
.await
.unwrap();
txn.abort().await.unwrap();
});
}
#[test]
fn write_commit_writes_a_diamond_of_attachments() {
let tmp = TmpDir::new("related-diamond");
block_on(async {
let repo = Repo::create(
&tmp.path().join("repo"),
CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
let diamond = common::write_diamond(&repo, tmp.path(), "rootfs").await;
assert_ne!(diamond.a, diamond.b);
for (commit, expected) in [
(
diamond.r,
owned(&[
(common::DIAMOND_A, diamond.a),
(common::DIAMOND_B, diamond.b),
]),
),
(diamond.a, owned(&[(common::DIAMOND_D, diamond.d)])),
(diamond.b, owned(&[(common::DIAMOND_D, diamond.d)])),
(diamond.d, Vec::new()),
] {
assert_eq!(
repo.read_commit_relations(&commit)
.await
.unwrap()
.attachments,
expected,
"field 2 of {commit}"
);
}
let txn = repo.transaction().await.unwrap();
let _ = txn
.check_attachments(&owned(&[("system/rootfs", diamond.r)]))
.await
.unwrap();
txn.abort().await.unwrap();
});
}
#[test]
fn the_attachment_check_reads_no_attachment_of_an_attachment() {
let tmp = TmpDir::new("related-shallow");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["gone-top", "partial-top"]).await;
let gone = common::write_chain(&repo, tmp.path(), "gone").await;
std::fs::remove_file(repo.path().join("objects").join(ostrya::loose_path(
&gone.d,
ObjectType::Commit,
repo.mode(),
)))
.unwrap();
let partial = common::write_chain(&repo, tmp.path(), "partial").await;
mark_partial(&repo, &partial.d);
for (c, top) in [(gone.c, "gone-top"), (partial.c, "partial-top")] {
let txn = repo.transaction().await.unwrap();
let _ = txn
.check_attachments(&owned(&[(common::CHAIN_C, c)]))
.await
.unwrap();
txn.abort().await.unwrap();
let written = commit(&repo, tmp.path(), top, &[(common::CHAIN_C, c)]).await;
assert_eq!(
repo.read_commit_relations(&written)
.await
.unwrap()
.attachments,
owned(&[(common::CHAIN_C, c)])
);
}
});
}
#[test]
fn write_commit_accepts_an_attachment_of_the_same_transaction() {
let tmp = TmpDir::new("related-same-txn");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["dep", "head", "nested"]).await;
let txn = repo.transaction().await.unwrap();
let att_root = stage_tree(&txn, tmp.path(), "dep").await;
let att = txn
.write_commit(options("dep", &[]), &att_root)
.await
.unwrap();
let root = stage_tree(&txn, tmp.path(), "head").await;
let head = txn
.write_commit(options("head", &[("a/dep", att)]), &root)
.await
.unwrap();
let nested_root = stage_tree(&txn, tmp.path(), "nested").await;
let nested = txn
.write_commit(options("nested", &[("a/head", head)]), &nested_root)
.await
.unwrap();
txn.commit().await.unwrap();
assert_eq!(
repo.read_commit_relations(&head).await.unwrap().attachments,
owned(&[("a/dep", att)])
);
assert_eq!(
repo.read_commit_relations(&nested)
.await
.unwrap()
.attachments,
owned(&[("a/head", head)])
);
});
}
#[test]
fn composefs_metadata_keeps_the_attachments() {
let tmp = TmpDir::new("related-composefs-keep");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["dep", "head"]).await;
let att = commit(&repo, tmp.path(), "dep", &[]).await;
let head = commit(&repo, tmp.path(), "head", &[("a/dep", att)]).await;
let txn = repo.transaction().await.unwrap();
let rewritten = repo
.commit_add_composefs_metadata(&txn, &head)
.await
.unwrap();
txn.commit().await.unwrap();
let (stored, _) = repo.load_commit(&rewritten).await.unwrap();
assert_eq!(stored.related, field2(&[("a/dep", att)]));
});
}
#[test]
fn composefs_metadata_accepts_a_nested_attachment() {
let tmp = TmpDir::new("related-composefs-nested");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["c", "b", "head"]).await;
let c = commit(&repo, tmp.path(), "c", &[]).await;
let b = commit(&repo, tmp.path(), "b", &[("lib/c", c)]).await;
let head = commit(&repo, tmp.path(), "head", &[("lib/b", b)]).await;
let txn = repo.transaction().await.unwrap();
let rewritten = repo
.commit_add_composefs_metadata(&txn, &head)
.await
.unwrap();
txn.commit().await.unwrap();
let (stored, _) = repo.load_commit(&rewritten).await.unwrap();
assert_eq!(stored.related, field2(&[("lib/b", b)]));
});
}
#[test]
fn composefs_metadata_refuses_a_defective_source_field() {
let tmp = TmpDir::new("related-composefs-refuse");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["c", "head"]).await;
let c = commit(&repo, tmp.path(), "c", &[]).await;
let head = commit(&repo, tmp.path(), "head", &[]).await;
let c_bytes = c.as_bytes().as_slice();
let cases: [(&[Field2Entry], String); 4] = [
(
&[("lib/y", c_bytes), ("lib/x", c_bytes)],
"entries are not sorted by name: lib/x follows lib/y".to_owned(),
),
(
&[("lib/x", c_bytes), ("lib/x", c_bytes)],
"two entries have the name lib/x".to_owned(),
),
(
&[("lib/x", &c_bytes[..31])],
"entry 0 (lib/x) has a checksum of 31 bytes, not 32".to_owned(),
),
(
&[("lib/x", &[0x33; 32])],
format!(
"attachment lib/x names commit {}, which is in neither the repository nor \
the transaction",
Checksum::from_ay(&[0x33; 32]).unwrap()
),
),
];
for (related, expected) in cases {
let source = store_with_field2(&repo, &head, related).await;
let objects_before = objects(&repo);
let txn = repo.transaction().await.unwrap();
let err = repo
.commit_add_composefs_metadata(&txn, &source)
.await
.unwrap_err();
assert_eq!(
related_error(err),
(Some(source), RelationField::Attachments, expected)
);
txn.abort().await.unwrap();
assert_eq!(objects(&repo), objects_before, "no new object");
}
});
}
#[test]
fn read_commit_relations_gives_both_fields() {
let tmp = TmpDir::new("related-read-both");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["dep", "src", "head"]).await;
let att = commit(&repo, tmp.path(), "dep", &[]).await;
let src = commit(&repo, tmp.path(), "src", &[]).await;
let head = commit(&repo, tmp.path(), "head", &[("a/dep", att)]).await;
let absent = [0x44; 32];
let meta = dict(vec![(
RELATED_KEY,
sources(&[("source/src", src.as_bytes()), ("source/gone", &absent)]),
)]);
repo.write_commit_detached_metadata(&head, Some(&meta))
.await
.unwrap();
assert_eq!(
repo.read_commit_relations(&head).await.unwrap(),
CommitRelations {
attachments: owned(&[("a/dep", att)]),
supplements: owned(&[
("source/src", src),
("source/gone", Checksum::from_ay(&absent).unwrap()),
]),
}
);
assert_eq!(
repo.read_commit_relations(&att).await.unwrap(),
CommitRelations::default()
);
});
}
#[test]
fn read_commit_relations_takes_the_first_supplement_key() {
let tmp = TmpDir::new("related-read-first-key");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["src", "head"]).await;
let src = commit(&repo, tmp.path(), "src", &[]).await;
let head = commit(&repo, tmp.path(), "head", &[]).await;
let meta = dict(vec![
(RELATED_KEY, sources(&[("source/first", src.as_bytes())])),
(RELATED_KEY, sources(&[("source/second", src.as_bytes())])),
]);
repo.write_commit_detached_metadata(&head, Some(&meta))
.await
.unwrap();
assert_eq!(
repo.read_commit_relations(&head).await.unwrap().supplements,
owned(&[("source/first", src)])
);
});
}
#[test]
fn read_commit_relations_refuses_a_defective_supplement_value() {
let tmp = TmpDir::new("related-read-bad-sources");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["head"]).await;
let head = commit(&repo, tmp.path(), "head", &[]).await;
let strings = (
Type::parse("as").unwrap(),
Value::Array(vec![Value::Str("source/x".into())]),
);
let cases = [
(strings, "type is `as`, not `a(say)`"),
(
sources(&[("source/x", &[0x55; 20])]),
"entry 0 (source/x) has a checksum of 20 bytes, not 32",
),
(sources(&[("", &[0x55; 32])]), "entry 0 has an empty name"),
];
for (value, expected) in cases {
let meta = dict(vec![(RELATED_KEY, value)]);
write_raw_detached(&repo, &head, &meta);
let err = repo.read_commit_relations(&head).await.unwrap_err();
assert_eq!(
err.to_string(),
format!("related commits in ostrya.related of commit {head}: {expected}")
);
assert_eq!(
related_error(err),
(Some(head), RelationField::Supplements, expected.to_owned())
);
}
});
}
#[test]
fn read_commit_relations_checks_the_format_of_field2() {
let tmp = TmpDir::new("related-read-field2");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["dep", "head"]).await;
let att = commit(&repo, tmp.path(), "dep", &[]).await;
let head = commit(&repo, tmp.path(), "head", &[]).await;
let bytes = att.as_bytes().as_slice();
let short = store_with_field2(&repo, &head, &[("a/x", &bytes[..31])]).await;
assert_eq!(
related_error(repo.read_commit_relations(&short).await.unwrap_err()),
(
Some(short),
RelationField::Attachments,
"entry 0 (a/x) has a checksum of 31 bytes, not 32".to_owned()
)
);
let unnamed = store_with_field2(&repo, &head, &[("a/x", bytes), ("", bytes)]).await;
assert_eq!(
related_error(repo.read_commit_relations(&unnamed).await.unwrap_err()),
(
Some(unnamed),
RelationField::Attachments,
"entry 1 has an empty name".to_owned()
)
);
let absent = [0x66; 32];
let unsorted = store_with_field2(
&repo,
&head,
&[("b/x", bytes), ("a/x", &absent), ("b/x", bytes)],
)
.await;
let absent = Checksum::from_ay(&absent).unwrap();
assert_eq!(
repo.read_commit_relations(&unsorted)
.await
.unwrap()
.attachments,
owned(&[("b/x", att), ("a/x", absent), ("b/x", att)])
);
});
}
#[test]
fn read_commit_relations_of_an_absent_commit() {
let tmp = TmpDir::new("related-read-absent");
block_on(async {
let repo = repo_with_trees(tmp.path(), &[]).await;
let absent = Checksum::from_ay(&[0x77; 32]).unwrap();
let err = repo.read_commit_relations(&absent).await.unwrap_err();
assert!(matches!(err, Error::ObjectNotFound { .. }), "got {err:?}");
});
}
#[test]
fn add_supplement_replaces_by_name_and_keeps_the_sort() {
let tmp = TmpDir::new("related-add-sort");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["x", "y", "head"]).await;
let x = commit(&repo, tmp.path(), "x", &[]).await;
let y = commit(&repo, tmp.path(), "y", &[]).await;
let head = commit(&repo, tmp.path(), "head", &[]).await;
repo.write_commit_detached_metadata(&head, Some(&dict(vec![("test.note", string("n"))])))
.await
.unwrap();
repo.add_supplement(&head, "z/x", &x).await.unwrap();
repo.add_supplement(&head, "a/y", &y).await.unwrap();
assert_eq!(
repo.read_commit_relations(&head).await.unwrap().supplements,
owned(&[("a/y", y), ("z/x", x)])
);
repo.add_supplement(&head, "z/x", &y).await.unwrap();
assert_eq!(
repo.read_commit_relations(&head).await.unwrap().supplements,
owned(&[("a/y", y), ("z/x", y)])
);
assert_eq!(
detached_keys(&repo, &head).await,
["test.note", RELATED_KEY]
);
let absent = Checksum::from_ay(&[0x31; 32]).unwrap();
repo.add_supplement(&x, "layer/gone", &absent)
.await
.unwrap();
assert_eq!(
repo.read_commit_relations(&x).await.unwrap().supplements,
owned(&[("layer/gone", absent)])
);
assert_eq!(detached_keys(&repo, &x).await, [RELATED_KEY]);
});
}
#[test]
fn add_supplement_edits_the_first_key() {
let tmp = TmpDir::new("related-add-first-key");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["src", "head"]).await;
let src = commit(&repo, tmp.path(), "src", &[]).await;
let head = commit(&repo, tmp.path(), "head", &[]).await;
let second = sources(&[("source/second", src.as_bytes())]);
let meta = dict(vec![
(RELATED_KEY, sources(&[("source/first", src.as_bytes())])),
(RELATED_KEY, second.clone()),
]);
repo.write_commit_detached_metadata(&head, Some(&meta))
.await
.unwrap();
repo.add_supplement(&head, "source/added", &src)
.await
.unwrap();
let expected = dict(vec![
(
RELATED_KEY,
sources(&[
("source/added", src.as_bytes()),
("source/first", src.as_bytes()),
]),
),
(RELATED_KEY, second),
]);
assert_eq!(
repo.read_commit_detached_metadata(&head).await.unwrap(),
Some(expected)
);
});
}
#[test]
fn add_supplement_refuses_an_empty_name() {
let tmp = TmpDir::new("related-add-empty-name");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["src", "head"]).await;
let src = commit(&repo, tmp.path(), "src", &[]).await;
let head = commit(&repo, tmp.path(), "head", &[]).await;
repo.add_supplement(&head, "source/src", &src)
.await
.unwrap();
let before = objects(&repo);
let expected = (
Some(head),
RelationField::Supplements,
"the new entry has an empty name".to_owned(),
);
let err = repo.add_supplement(&head, "", &src).await.unwrap_err();
assert_eq!(related_error(err), expected);
assert_eq!(objects(&repo), before, "the refused add writes nothing");
let txn = repo.transaction().await.unwrap();
let err = txn.add_supplement(&head, "", &src).unwrap_err();
assert_eq!(related_error(err), expected);
txn.commit().await.unwrap();
assert_eq!(objects(&repo), before, "the refused add queues nothing");
});
}
#[test]
fn add_supplement_of_an_absent_commit() {
let tmp = TmpDir::new("related-add-absent");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["src"]).await;
let src = commit(&repo, tmp.path(), "src", &[]).await;
let absent = Checksum::from_ay(&[0x77; 32]).unwrap();
let before = objects(&repo);
let err = repo
.add_supplement(&absent, "source/src", &src)
.await
.unwrap_err();
assert!(
matches!(err, Error::ObjectNotFound { checksum, ty: ObjectType::Commit } if checksum == absent),
"got {err:?}"
);
assert_eq!(objects(&repo), before);
});
}
#[test]
fn add_supplement_refuses_a_defective_stored_value() {
let tmp = TmpDir::new("related-add-defective");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["src", "head"]).await;
let src = commit(&repo, tmp.path(), "src", &[]).await;
let head = commit(&repo, tmp.path(), "head", &[]).await;
let meta = dict(vec![(
RELATED_KEY,
sources(&[("source/short", &[0x55; 31])]),
)]);
write_raw_detached(&repo, &head, &meta);
let before = objects(&repo);
let expected = (
Some(head),
RelationField::Supplements,
"entry 0 (source/short) has a checksum of 31 bytes, not 32".to_owned(),
);
let err = repo
.add_supplement(&head, "source/src", &src)
.await
.unwrap_err();
assert_eq!(related_error(err), expected);
assert_eq!(objects(&repo), before, "the refused add writes nothing");
let refs_before = refs(&repo);
let txn = repo.transaction().await.unwrap();
txn.add_supplement(&head, "source/src", &src).unwrap();
txn.set_ref(&Ref::local("main"), Some(&head));
let err = txn.commit().await.unwrap_err();
assert_eq!(related_error(err), expected);
assert_eq!(objects(&repo), before);
assert_eq!(refs(&repo), refs_before, "the failed commit writes no ref");
});
}
#[test]
fn transaction_add_supplement_gives_the_result_of_the_repo_add() {
let tmp = TmpDir::new("related-add-txn");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["x", "y", "one", "two"]).await;
let x = commit(&repo, tmp.path(), "x", &[]).await;
let y = commit(&repo, tmp.path(), "y", &[]).await;
let one = commit(&repo, tmp.path(), "one", &[]).await;
let two = commit(&repo, tmp.path(), "two", &[]).await;
let adds = [("z/x", x), ("a/y", y), ("z/x", y)];
for (name, source) in adds {
repo.add_supplement(&one, name, &source).await.unwrap();
}
let txn = repo.transaction().await.unwrap();
for (name, source) in adds {
txn.add_supplement(&two, name, &source).unwrap();
}
txn.commit().await.unwrap();
assert_eq!(
repo.read_commit_detached_metadata(&two).await.unwrap(),
repo.read_commit_detached_metadata(&one).await.unwrap()
);
assert_eq!(
repo.read_commit_relations(&two).await.unwrap().supplements,
owned(&[("a/y", y), ("z/x", y)])
);
});
}
#[test]
fn transaction_adds_apply_after_the_queued_dict_and_before_the_signatures() {
let tmp = TmpDir::new("related-add-txn-order");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["src", "head"]).await;
let src = commit(&repo, tmp.path(), "src", &[]).await;
let head = commit(&repo, tmp.path(), "head", &[]).await;
let txn = repo.transaction().await.unwrap();
txn.set_commit_detached_metadata(&head, dict(vec![("test.note", string("n"))]));
txn.add_supplement(&head, "source/src", &src).unwrap();
txn.sign_commit(&head, &DummySigner::new("key"))
.await
.unwrap();
txn.commit().await.unwrap();
let keys = detached_keys(&repo, &head).await;
assert_eq!(keys.len(), 3, "got {keys:?}");
assert_eq!(keys[..2], ["test.note", RELATED_KEY]);
assert_eq!(
repo.read_commit_relations(&head).await.unwrap().supplements,
owned(&[("source/src", src)])
);
let txn = repo.transaction().await.unwrap();
txn.add_supplement(&head, "source/other", &src).unwrap();
txn.set_commit_detached_metadata(&head, dict(vec![("test.note", string("m"))]));
txn.commit().await.unwrap();
assert_eq!(detached_keys(&repo, &head).await, ["test.note"]);
assert!(
repo.read_commit_relations(&head)
.await
.unwrap()
.supplements
.is_empty()
);
});
}
#[test]
fn a_local_write_keeps_the_related_key_under_the_switch() {
let tmp = TmpDir::new("related-local-write-switch");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["src", "one", "two", "three", "four"]).await;
let config = repo.path().join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str("\n[ex-ostrya]\nkeep-detached-related=false\n");
std::fs::write(&config, text).unwrap();
let repo = Repo::open(repo.path()).await.unwrap();
assert!(!repo.config().keep_detached_related().unwrap());
let src = commit(&repo, tmp.path(), "src", &[]).await;
let [one, two, three, four] = [
commit(&repo, tmp.path(), "one", &[]).await,
commit(&repo, tmp.path(), "two", &[]).await,
commit(&repo, tmp.path(), "three", &[]).await,
commit(&repo, tmp.path(), "four", &[]).await,
];
let meta = dict(vec![
("test.note", string("n")),
(RELATED_KEY, sources(&[("source/src", src.as_bytes())])),
]);
repo.write_commit_detached_metadata(&one, Some(&meta))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_commit_detached_metadata(&two, meta.clone());
txn.commit().await.unwrap();
repo.add_supplement(&three, "source/src", &src)
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.add_supplement(&four, "source/src", &src).unwrap();
txn.commit().await.unwrap();
for head in [one, two, three, four] {
repo.sign_commit(&head, &DummySigner::new("key"))
.await
.unwrap();
assert!(
detached_keys(&repo, &head)
.await
.iter()
.any(|k| k == RELATED_KEY),
"{head}"
);
assert_eq!(
repo.read_commit_relations(&head).await.unwrap().supplements,
owned(&[("source/src", src)]),
"{head}"
);
}
});
}
fn defective_values() -> Vec<((Type, Value), &'static str)> {
let strings = (
Type::parse("as").unwrap(),
Value::Array(vec![Value::Str("source/x".into())]),
);
vec![
(strings, "type is `as`, not `a(say)`"),
(
sources(&[("source/ok", &[0x55; 32]), ("source/x", &[0x55; 31])]),
"entry 1 (source/x) has a checksum of 31 bytes, not 32",
),
(sources(&[("", &[0x55; 32])]), "entry 0 has an empty name"),
]
}
#[test]
fn write_commit_detached_metadata_checks_each_supplement_key() {
let tmp = TmpDir::new("related-write-check");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["head"]).await;
let head = commit(&repo, tmp.path(), "head", &[]).await;
let stored = dict(vec![("test.note", string("n"))]);
repo.write_commit_detached_metadata(&head, Some(&stored))
.await
.unwrap();
let before = objects(&repo);
let valid = sources(&[("source/ok", &[0x55; 32])]);
for (value, reason) in defective_values() {
for meta in [
dict(vec![(RELATED_KEY, value.clone())]),
dict(vec![
(RELATED_KEY, valid.clone()),
(RELATED_KEY, value.clone()),
]),
] {
let err = repo
.write_commit_detached_metadata(&head, Some(&meta))
.await
.unwrap_err();
assert_eq!(
err.to_string(),
format!("related commits in ostrya.related of commit {head}: {reason}")
);
assert_eq!(
related_error(err),
(Some(head), RelationField::Supplements, reason.to_owned())
);
assert_eq!(objects(&repo), before, "the refused write writes nothing");
}
}
let accepted = dict(vec![(
RELATED_KEY,
sources(&[
("source/b", &[0x55; 32]),
("source/a", &[0x56; 32]),
("source/b", &[0x57; 32]),
]),
)]);
repo.write_commit_detached_metadata(&head, Some(&accepted))
.await
.unwrap();
});
}
#[test]
fn write_commit_detached_metadata_checks_before_the_lock() {
let tmp = TmpDir::new("related-write-before-lock");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["head"]).await;
let head = commit(&repo, tmp.path(), "head", &[]).await;
let config = repo.path().join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str("lock-timeout-secs=0\n");
std::fs::write(&config, text).unwrap();
let writing = Repo::open(repo.path()).await.unwrap();
let held = repo
.transaction_with_lock(LockKind::Exclusive)
.await
.expect("take the exclusive hold");
let valid = dict(vec![(RELATED_KEY, sources(&[("source/ok", &[0x55; 32])]))]);
let err = writing
.write_commit_detached_metadata(&head, Some(&valid))
.await
.unwrap_err();
assert!(
matches!(err, Error::LockTimeout { secs: 0 }),
"the hold is live: {err:?}"
);
let before = objects(&repo);
let defective = dict(vec![(RELATED_KEY, sources(&[("", &[0x55; 32])]))]);
let err = writing
.write_commit_detached_metadata(&head, Some(&defective))
.await
.unwrap_err();
assert_eq!(
related_error(err),
(
Some(head),
RelationField::Supplements,
"entry 0 has an empty name".to_owned()
),
"the check comes before the lock"
);
held.abort().await.unwrap();
assert_eq!(objects(&repo), before, "the refused write writes nothing");
assert_eq!(
writing.read_commit_detached_metadata(&head).await.unwrap(),
None
);
});
}
#[test]
fn a_queued_defective_dict_fails_the_commit() {
let tmp = TmpDir::new("related-queued-check");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["head"]).await;
for (value, reason) in defective_values() {
let before = objects(&repo);
let refs_before = refs(&repo);
let txn = repo.transaction().await.unwrap();
let root = stage_tree(&txn, tmp.path(), "head").await;
let head = txn.write_commit(options("head", &[]), &root).await.unwrap();
txn.set_commit_detached_metadata(&head, dict(vec![(RELATED_KEY, value)]));
txn.set_ref(&Ref::local("main"), Some(&head));
let err = txn.commit().await.unwrap_err();
assert_eq!(
related_error(err),
(Some(head), RelationField::Supplements, reason.to_owned())
);
assert_eq!(
objects(&repo),
before,
"the refused commit publishes nothing"
);
assert_eq!(refs(&repo), refs_before, "the refused commit writes no ref");
assert!(staged(&repo).is_empty(), "the staging directory is removed");
}
});
}
#[test]
fn a_signature_over_a_defective_value_takes_no_check() {
let tmp = TmpDir::new("related-sign-no-check");
block_on(async {
let repo = repo_with_trees(tmp.path(), &["head"]).await;
let head = commit(&repo, tmp.path(), "head", &[]).await;
let meta = dict(vec![(
RELATED_KEY,
sources(&[("source/short", &[0x55; 31])]),
)]);
write_raw_detached(&repo, &head, &meta);
repo.sign_commit(&head, &DummySigner::new("key"))
.await
.unwrap();
assert_eq!(detached_keys(&repo, &head).await.len(), 2);
});
}
#[test]
fn a_local_pull_stores_a_defective_value() {
let tmp = TmpDir::new("related-pull-no-check");
block_on(async {
let src = repo_with_trees(tmp.path(), &["head"]).await;
let txn = src.transaction().await.unwrap();
let root = stage_tree(&txn, tmp.path(), "head").await;
let head = txn.write_commit(options("head", &[]), &root).await.unwrap();
txn.set_ref(&Ref::local("main"), Some(&head));
txn.commit().await.unwrap();
let meta = dict(vec![(
RELATED_KEY,
sources(&[("source/short", &[0x55; 31])]),
)]);
write_raw_detached(&src, &head, &meta);
let dst = Repo::create(
&tmp.path().join("dst"),
CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(head));
assert_eq!(
dst.read_commit_detached_metadata(&head).await.unwrap(),
Some(meta)
);
});
}