use std::any::Any;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, LazyLock};
use ostrya_core::{Checksum, ObjectType, Ref, Type, validate};
use super::finish::{
Checked, Named, attachment_edits, check_anchor, check_attachment_states, check_ref_paths,
checked_link_attachments, commit_ref, missing_objects, parse_commit_links,
partial_attachment_failure, protocol, publish, queue_detached, 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::MAX_METADATA_SIZE;
use crate::error::Error;
use crate::related::{self, HeldAttachment, RelationField};
use crate::remote::proto::{CommitRequest, MAX_FRAME, Message, ServerCommit};
use crate::remote::{self, RefOutcome};
use crate::repo::Repo;
use crate::repo_fs::RepoDir;
use crate::server_commit::{CommitFields, clock, commit_bytes};
use crate::summary::OSTREE_METADATA_REF;
use crate::transaction::Transaction;
use crate::write::flat_name;
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<'_>,
mut commit_meta: HashMap<Checksum, Vec<u8>>,
request: CommitRequest,
) -> Checked<ReceiveCommit> {
let CommitRequest {
updates,
force,
server_commit,
} = request;
let Some(mut 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)?;
let related = std::mem::take(&mut sc.related);
let related = related::sorted_new(related).map_err(|e| protocol(e.to_string()))?;
check_reply_fits(&sc)?;
let staged_commits = txn.staged_of_type(ObjectType::Commit);
let set = attachment_set(&txn, &related, &staged_commits).await?;
check_session_objects(&staged_commits, &mut commit_meta, &set, &related)?;
drop(staged_commits);
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,
related,
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 Attachments {
staged,
below,
held,
} = set;
check_attachment_states(
&attachment_names(&sc.related, &below),
&held,
"the server commit and the attachments below it name as attachments",
)?;
drop((below, held));
let roots = staged.iter().map(|(_, root)| *root);
let root = (sc.root_dirtree, sc.root_dirmeta);
let missing = walk::completeness(&txn, std::iter::once(root).chain(roots)).await?;
if missing.total > 0 {
return Err(missing_objects(
missing,
"the trees of the server commit and of its staged attachments reach",
));
}
let staged: Vec<Checksum> = staged.into_iter().map(|(commit, _)| commit).collect();
let (synced, edits) =
futures_lite::future::zip(txn.sync_staged(), attachment_edits(repo, commit_meta)).await;
synced.map_err(Failure::Internal)?;
let edits = edits?;
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, queued) = futures_lite::future::zip(
repo.read_ref_states(Arc::clone(&paths), anchor.then_some(OSTREE_METADATA_REF)),
async {
if edits.is_empty() {
return Ok(());
}
queue_detached(repo, &txn, edits).await
},
)
.await;
let (states, anchor_parent) = states.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),
}));
}
}
queued?;
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,
related: &sc.related,
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,
related,
..
} = sc;
drop((bind_refs, subject, body, metadata, related));
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,
std::iter::once(commit).chain(staged).collect(),
))
.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(
staged: &[Checksum],
commit_meta: &mut HashMap<Checksum, Vec<u8>>,
set: &Attachments,
related: &[(String, Checksum)],
) -> Checked<()> {
let members: HashSet<&Checksum> = set.staged.iter().map(|(commit, _)| commit).collect();
let held = |commit: &Checksum| {
set.held
.get(commit)
.is_some_and(|state| *state != HeldAttachment::Absent)
};
let dict = commit_meta
.keys()
.filter(|commit| !members.contains(commit) && !held(commit))
.min();
let commit = staged
.iter()
.filter(|commit| !members.contains(commit))
.min();
if (dict.is_some() || commit.is_some())
&& set
.held
.values()
.any(|state| *state == HeldAttachment::Partial)
&& let Some(failure) =
partial_attachment_failure(&attachment_names(related, &set.below), &set.held)
{
return Err(failure);
}
if let Some(commit) = dict {
return Err(protocol(format!(
"detached metadata for commit {commit} in a session with a server commit: the \
commit is not a staged or held attachment of the server commit"
)));
}
if let Some(commit) = commit {
return Err(protocol(format!(
"commit {commit} is staged in a session with a server commit, and is not an \
attachment of the server commit"
)));
}
commit_meta.retain(|commit, _| members.contains(commit));
Ok(())
}
#[derive(Default)]
struct Attachments {
staged: Vec<(Checksum, (Checksum, Checksum))>,
below: Vec<(Checksum, Checksum, String)>,
held: HashMap<Checksum, HeldAttachment>,
}
fn attachment_names<'a>(
related: &'a [(String, Checksum)],
below: &'a [(Checksum, Checksum, String)],
) -> Vec<(Checksum, Option<Checksum>, Cow<'a, str>)> {
let mut known = HashSet::new();
related
.iter()
.filter(|(_, attachment)| known.insert(*attachment))
.map(|(name, attachment)| (*attachment, None, Cow::Borrowed(name.as_str())))
.chain(below.iter().map(|(attachment, naming, name)| {
(*attachment, Some(*naming), Cow::Borrowed(name.as_str()))
}))
.collect()
}
async fn attachment_set(
txn: &Transaction,
related: &[(String, Checksum)],
staged: &[Checksum],
) -> Checked<Attachments> {
if related.is_empty() {
return Ok(Attachments::default());
}
let repo = txn.repo().clone();
let staging = txn.staging_dir().clone();
let staged: HashSet<Checksum> = staged.iter().copied().collect();
let mut known = HashSet::new();
let first: Vec<Checksum> = related
.iter()
.map(|(_, attachment)| *attachment)
.filter(|attachment| known.insert(*attachment))
.collect();
ostrya_rt::unblock(move || attachment_levels_blocking(&repo, &staging, &staged, first)).await
}
fn attachment_levels_blocking(
repo: &Repo,
staging: &RepoDir,
staged: &HashSet<Checksum>,
first: Vec<Checksum>,
) -> Checked<Attachments> {
let mut set = Attachments::default();
let mut known: HashSet<Checksum> = first.iter().copied().collect();
let mut level = first;
while !level.is_empty() {
let mut next = Vec::new();
for attachment in level {
let entries = if staged.contains(&attachment) {
let flat = flat_name(&attachment, ObjectType::Commit, repo.mode());
let bytes = staging
.read_capped(&flat, MAX_METADATA_SIZE)
.map_err(|e| Failure::Internal(e.into()))?;
let unparsable = |e| protocol(format!("commit {attachment} does not parse: {e}"));
let links = parse_commit_links(&bytes).map_err(unparsable)?;
set.staged.push((attachment, links.root));
checked_link_attachments(&attachment, links.related).map_err(|e| match e {
Error::Core(e) => unparsable(e),
e => protocol(e.to_string()),
})?
} else {
let state =
related::held_attachment_blocking(repo, None, &attachment, |_, entries| {
related::checked_entries(
RelationField::Attachments,
Some(attachment),
entries,
)
})
.map_err(Failure::Internal)?;
let (state, entries) = match state {
HeldAttachment::Absent => (HeldAttachment::Absent, Vec::new()),
HeldAttachment::Partial => (HeldAttachment::Partial, Vec::new()),
HeldAttachment::Complete { value } => {
(HeldAttachment::Complete { value: () }, value)
}
};
set.held.insert(attachment, state);
entries
};
for (name, below) in entries {
if known.insert(below) {
next.push(below);
set.below.push((below, attachment, name));
}
}
}
level = next;
}
Ok(set)
}
#[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,
related: Vec::new(),
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"),
}
}
}