use std::any::Any;
use std::collections::HashMap;
use std::sync::{Arc, LazyLock};
use ostrya_core::{Checksum, ObjectType, Ref, Type, validate};
use super::finish::{
Checked, Named, check_anchor, check_ref_paths, commit_ref, missing_objects, protocol, publish,
report, sign_server_commit,
};
use super::hooks::{self, HookRefusal, ReceiveHooks, ReceiveServerCommit};
use super::policy::SessionPolicy;
use super::session::{Failure, ReceiveCommit, ReceiveRefOutcome};
use super::walk;
use crate::error::Error;
use crate::remote::proto::{CommitRequest, MAX_FRAME, Message, ServerCommit};
use crate::remote::{self, RefOutcome};
use crate::repo::Repo;
use crate::server_commit::{CommitFields, clock, commit_bytes};
use crate::summary::OSTREE_METADATA_REF;
use crate::transaction::Transaction;
static VALUE_IN_COMMIT: LazyLock<Type> =
LazyLock::new(|| Type::parse("((v))").expect("valid signature"));
pub(super) async fn finish(
repo: &Repo,
policy: &dyn SessionPolicy,
hooks: Option<&dyn ReceiveHooks>,
txn: Transaction,
named: Named<'_>,
commit_meta: HashMap<Checksum, Vec<u8>>,
request: CommitRequest,
) -> Checked<ReceiveCommit> {
let CommitRequest {
updates,
force,
server_commit,
} = request;
let Some(sc) = server_commit.map(|sc| *sc) else {
unreachable!("the commit of a session passes a request with a server commit")
};
let own = repo.config().collection_id();
let indices = check_names(own, &named, &sc, updates.len(), force)?;
let paths: Arc<[String]> = indices.iter().map(|&i| named.paths[i].clone()).collect();
check_metadata(&sc)?;
check_reply_fits(&sc)?;
check_session_objects(&txn, &commit_meta)?;
let ServerCommit {
branch: branch_text,
tags: tag_texts,
bind_refs,
root_dirtree,
root_dirmeta,
subject,
body,
metadata,
timestamp,
orphan,
} = sc;
let mut names = indices.iter().map(|&i| named.refs[i].clone());
let sc = ReceiveServerCommit {
branch: names.next().expect("a server commit names its branch"),
tags: names.collect(),
bind_refs,
root_dirtree,
root_dirmeta,
subject,
body,
metadata,
timestamp,
orphan,
};
drop(indices);
for name in std::iter::once(&sc.branch).chain(&sc.tags) {
check_anchor(own.is_some(), name)?;
}
let rule = policy.server_commit_rule(&sc.branch, &sc.tags)?;
let root = (sc.root_dirtree, sc.root_dirmeta);
let missing = walk::completeness(&txn, [root]).await?;
if missing.total > 0 {
return Err(missing_objects(
missing,
"the tree of the server commit reaches",
));
}
txn.sync_staged().await.map_err(Failure::Internal)?;
let carried: Option<Box<dyn Any + Send>> = match hooks {
None => None,
Some(hooks) => Some(
hooks
.before_server_commit(&sc)
.await
.map_err(HookRefusal::into_failure)?,
),
};
let held = repo.lock_update().await.map_err(Failure::Internal)?;
let anchor = policy.regenerates_summary() && repo.config().collection_id().is_some();
let (states, anchor_parent) = repo
.read_ref_states(Arc::clone(&paths), anchor.then_some(OSTREE_METADATA_REF))
.await
.map_err(Failure::Internal)?;
let written: Vec<(&str, &str, bool)> = std::iter::once(branch_text.as_str())
.chain(tag_texts.iter().map(String::as_str))
.zip(paths.iter())
.map(|(name, path)| (name, path.as_str(), true))
.collect();
let current = check_ref_paths(&written, &states)?;
drop(written);
let tip = current[0];
if let Some(tip) = tip
&& sc.orphan
&& !rule.allow_orphan_over_branch
{
return Err(Failure::Wire(remote::Error::NonFastForward(format!(
"ref '{branch_text}' is at {tip}, and the policy does not allow a commit with no \
parent on it"
))));
}
for (tag, current) in tag_texts.iter().zip(¤t[1..]) {
if let Some(commit) = current {
return Err(Failure::Wire(remote::Error::RefMismatch {
message: format!(
"ref '{tag}' is at {commit}, and a tag of a server commit creates its ref"
),
name: tag.clone(),
current: Some(*commit),
}));
}
}
let collection_id = match &sc.branch {
Ref::Collection { id, .. } => Some(id.as_str()),
_ => own,
};
let timestamp = match sc.timestamp {
Some(timestamp) => timestamp,
None => clock().map_err(Failure::Internal)?,
};
let fields = CommitFields {
refs: std::iter::once(&sc.branch)
.chain(&sc.tags)
.map(Ref::name)
.chain(sc.bind_refs.iter().map(String::as_str))
.collect(),
root_dirtree: sc.root_dirtree,
root_dirmeta: sc.root_dirmeta,
subject: &sc.subject,
body: &sc.body,
metadata: &sc.metadata,
orphan: sc.orphan,
};
let bytes = Arc::new(
commit_bytes(&fields, tip, timestamp, collection_id)
.map_err(|e| Failure::Internal(e.into()))?,
);
drop(fields);
let ReceiveServerCommit {
branch,
tags,
bind_refs,
subject,
body,
metadata,
..
} = sc;
drop((bind_refs, subject, body, metadata));
let commit = txn
.write_metadata(ObjectType::Commit, None, &bytes)
.await
.map_err(Failure::Internal)?;
sign_server_commit(repo, &txn, commit, &bytes, rule.signers).await?;
drop(bytes);
let moves = tip != Some(commit);
if moves {
txn.set_ref(&branch, Some(&commit));
}
for tag in &tags {
txn.set_ref(tag, Some(&commit));
}
let changed = moves || !tags.is_empty();
let (stats, warnings) = Box::pin(publish(
repo,
policy,
txn,
held,
changed,
anchor_parent,
vec![commit],
))
.await?;
drop((paths, states, current));
let refs = std::iter::once((branch, tip))
.chain(tags.into_iter().map(|tag| (tag, None)))
.map(|(name, old)| ReceiveRefOutcome {
name,
old,
new: Some(commit),
})
.collect();
let reply = outcomes(branch_text, tag_texts, tip, commit);
let report = report(policy, refs, stats, warnings);
if let (Some(hooks), Some(carried)) = (hooks, carried)
&& let Err(mut message) = hooks.after_update(&report, carried).await
{
hooks::cut(&mut message);
return Err(Failure::Wire(remote::Error::Internal(message)));
}
Ok(ReceiveCommit { report, reply })
}
fn refs(sc: &ServerCommit) -> impl Iterator<Item = &str> {
std::iter::once(sc.branch.as_str()).chain(sc.tags.iter().map(String::as_str))
}
fn outcomes(
branch: String,
tags: Vec<String>,
tip: Option<Checksum>,
commit: Checksum,
) -> Vec<RefOutcome> {
std::iter::once(RefOutcome {
name: branch,
old: tip,
new: Some(commit),
})
.chain(tags.into_iter().map(|name| RefOutcome {
name,
old: None,
new: Some(commit),
}))
.collect()
}
fn name_failure(e: Error, what: &str, name: &str) -> Failure {
match e {
Error::InvalidRefspec(_) => Failure::Wire(remote::Error::InvalidRef(format!(
"invalid {what} '{name}'"
))),
other => Failure::Internal(other),
}
}
fn check_names(
own: Option<&str>,
named: &Named<'_>,
sc: &ServerCommit,
updates: usize,
force: bool,
) -> Checked<Vec<usize>> {
for name in refs(sc) {
commit_ref(own, name, true)?;
}
for name in &sc.bind_refs {
crate::validate_refspec(name).map_err(|e| name_failure(e, "bound name", name))?;
if name.contains(':') {
return Err(Failure::Wire(remote::Error::InvalidRef(format!(
"invalid bound name '{name}'"
))));
}
}
if updates > 0 {
return Err(protocol(format!(
"the Commit message holds a server commit and {updates} ref updates"
)));
}
if force {
return Err(protocol(
"the Commit message holds a server commit and force".into(),
));
}
let found = Named::indices(&named.by_name(), refs(sc), "written")?;
let branch = &named.refs[found[0]];
for &i in &found[1..] {
let tag = &named.refs[i];
if !tag.same_namespace(branch) {
return Err(protocol(format!(
"tag '{tag}' is not in the namespace of the branch '{branch}' of the server \
commit"
)));
}
}
Ok(found)
}
fn check_metadata(sc: &ServerCommit) -> Checked<()> {
for (key, value) in &sc.metadata {
validate(&VALUE_IN_COMMIT, value).map_err(|e| {
protocol(format!(
"a commit cannot hold the metadata value under '{key}': {e}"
))
})?;
}
Ok(())
}
fn check_reply_fits(sc: &ServerCommit) -> Checked<()> {
let any_commit = Checksum::from_bytes([0; 32]);
let longest = Message::CommitReply(outcomes(
sc.branch.clone(),
sc.tags.clone(),
Some(any_commit),
any_commit,
));
let body = longest.encode_body().map_err(Failure::Wire)?;
let len = body.len() as u64 + 1;
if len > u64::from(MAX_FRAME) {
return Err(Failure::Wire(remote::Error::LimitExceeded(format!(
"the reply to the server commit with {} tags can need a frame of {len} bytes, over \
the limit {MAX_FRAME}",
sc.tags.len()
))));
}
Ok(())
}
fn check_session_objects(
txn: &Transaction,
commit_meta: &HashMap<Checksum, Vec<u8>>,
) -> Checked<()> {
if let Some(commit) = commit_meta.keys().min() {
return Err(protocol(format!(
"detached metadata for commit {commit} in a session with a server commit"
)));
}
if let Some(commit) = txn.staged_of_type(ObjectType::Commit).into_iter().min() {
return Err(protocol(format!(
"commit {commit} is staged in a session with a server commit"
)));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use ostrya_core::{Commit, Value, to_bytes};
fn entry(key: &str, value: Value) -> (String, Vec<u8>) {
(key.into(), to_bytes(&Type::Variant, &value).unwrap())
}
fn with_metadata(metadata: Vec<(String, Vec<u8>)>) -> ServerCommit {
ServerCommit {
branch: "main".into(),
tags: Vec::new(),
bind_refs: Vec::new(),
root_dirtree: Checksum::from_bytes([1; 32]),
root_dirmeta: Checksum::from_bytes([2; 32]),
subject: String::new(),
body: String::new(),
metadata,
timestamp: None,
orphan: false,
}
}
#[test]
fn the_metadata_check_follows_the_depth_of_a_commit() {
for levels in 123..=127 {
let ty = (0..levels).fold(Type::Byte, |ty, _| Type::maybe(ty));
let value = (0..levels).fold(Value::Byte(1), |value, _| {
Value::Maybe(Some(Box::new(value)))
});
let value = Value::variant(ty, value);
let commit = Commit {
metadata: Value::Array(vec![Value::Tuple(vec![
Value::Str("deep".into()),
value.clone(),
])]),
parent: None,
related: Vec::new(),
subject: String::new(),
body: String::new(),
timestamp: 0,
root_dirtree: Checksum::from_bytes([1; 32]),
root_dirmeta: Checksum::from_bytes([2; 32]),
};
let sc = with_metadata(vec![entry("deep", value)]);
let checked = check_metadata(&sc);
assert_eq!(checked.is_ok(), levels <= 125, "{levels} levels");
let bytes = commit.serialize();
assert_eq!(bytes.is_ok(), levels <= 125, "{levels} levels");
if let Ok(bytes) = bytes {
assert_eq!(Commit::parse(&bytes).unwrap(), commit, "{levels} levels");
}
if levels > 125 {
assert!(
matches!(checked, Err(Failure::Wire(remote::Error::Protocol(_)))),
"{levels} levels"
);
}
}
}
#[test]
fn the_reply_bound_of_a_server_commit_is_the_encoded_size() {
let commit = |count: usize| ServerCommit {
tags: (0..count).map(|i| format!("tag-{i:015}")).collect(),
..with_metadata(Vec::new())
};
let encoded = |count: usize| {
let sc = commit(count);
let any = Checksum::from_bytes([3; 32]);
Message::CommitReply(outcomes(sc.branch, sc.tags, Some(any), any))
.encode_body()
.unwrap()
.len()
+ 1
};
let (mut low, mut high) = (0, 30_000);
assert!(check_reply_fits(&commit(low)).is_ok());
assert!(check_reply_fits(&commit(high)).is_err());
while high - low > 1 {
let mid = (low + high) / 2;
if check_reply_fits(&commit(mid)).is_ok() {
low = mid;
} else {
high = mid;
}
}
assert!(encoded(low) <= MAX_FRAME as usize);
assert!(encoded(high) > MAX_FRAME as usize);
match check_reply_fits(&commit(high)) {
Err(Failure::Wire(remote::Error::LimitExceeded(m))) => {
assert!(m.contains(&format!("{high} tags")), "{m}")
}
_ => panic!("expected limit-exceeded"),
}
}
}