use crate::db::{self, approvals, candidates, CandidateState, *}; use crate::error::{Error, Result}; use crate::time; /// Why an approval was refused (§7.1a). Rendered as HTTP 409 with the current /// diff, plus a CLI message. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum Stale { #[error("review is no longer pending (state: {state})")] NotPending { state: String }, #[error("the candidate changed while you were looking: you were shown {expected}, it is now {actual}")] Identity { expected: String, actual: String }, #[error("the diff changed while you were looking (shown {expected}, now {actual})")] Diff { expected: String, actual: String }, /// The base moved: a newer version was accepted while the review was open. #[error("a newer version was accepted since this review was opened")] Base { expected: Option, actual: Option }, } #[derive(Debug, Clone)] pub struct Approval { pub id: i64, pub candidate_id: i64, pub base_release_id: Option, pub decision: String, pub diff_digest: String, pub identity_hash: String, } /// Why a decision did not happen (§7.1a, §6 M-3). /// /// Two families, and the difference is the whole point: `Stale` means the /// reviewer's screen no longer matches the database, so the answer is to look /// again; `System` means the database itself refused, and looking again changes /// nothing. #[derive(Debug, thiserror::Error)] pub enum ApproveError { /// What is stored is not what was displayed. #[error(transparent)] Stale(#[from] Stale), /// The write itself failed; nothing about the review is at fault. #[error("the decision could not be recorded: {0}")] System(#[from] Error), } /// Approve a candidate. Returns the approval row on success, or the reason the /// approval was refused. pub fn approve( db: &Db, actor: &str, candidate_id: i64, identity_hash: &str, diff_digest: &str, note: Option<&str>, ) -> std::result::Result { let actor = actor.to_string(); let ih = identity_hash.to_string(); let dd = diff_digest.to_string(); let note = note.map(|s| s.to_string()); let at = time::now(); db.writer.tx(move |tx| -> Result> { let subject = candidates::review_subject_in(tx, candidate_id)? .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?; let id = subject.id; let base = subject.base_release_id; let current_base = subject.current_base_release_id; if !subject.state.is_open() { return Ok(Err(ApproveError::Stale(Stale::NotPending { state: subject.state.to_string() }))); } if subject.identity_hash != ih { return Ok(Err(ApproveError::Stale(Stale::Identity { expected: ih.clone(), actual: subject.identity_hash }))); } if subject.diff_digest != dd { return Ok(Err(ApproveError::Stale(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest }))); } // Base is still the accepted release (I2, end to end). if base != current_base { return Ok(Err(ApproveError::Stale(Stale::Base { expected: base, actual: current_base }))); } let approval_id = approvals::record_in( tx, &approvals::Decision { candidate_id: id, base_release_id: base, at: &at, decision: "approved", risk_level: &subject.risk_level, diff_digest: &dd, identity_hash: &ih, note: note.as_deref(), }, )?; candidates::resolve_in(tx, id, CandidateState::Approved, &at)?; db::audit_in( tx, &db::AuditEntry::human( &at, &actor, "approve", "candidate", &id.to_string(), serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": subject.pkgbase_id}), ), )?; Ok(Ok(Approval { id: approval_id, candidate_id: id, base_release_id: base, decision: "approved".into(), diff_digest: dd, identity_hash: ih, })) }) // A failed transaction is a system failure, never a stale review. .map_err(ApproveError::System)? } /// Reject a candidate. Rejection is remembered per identity so the watcher stops /// nagging about the same version (§7.1), and can be re-opened later. pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> { let actor = actor.to_string(); let note = note.to_string(); let at = time::now(); db.writer.tx(move |tx| { let state = candidates::state_in(tx, candidate_id)? .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?; if !state.is_open() { return Err(Error::conflict(format!("candidate is {state}, not pending"))); } let identity = candidates::identity_in(tx, candidate_id)? .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?; approvals::record_rejection_in(tx, candidate_id, &at, &identity, ¬e)?; candidates::resolve_in(tx, candidate_id, CandidateState::Rejected, &at)?; db::audit_in( tx, &db::AuditEntry::human( &at, &actor, "reject", "candidate", &candidate_id.to_string(), serde_json::json!({"identity": identity, "note": note}), ), )?; Ok(()) }) } /// One item of a bulk decision, and what happened to it (§7.4). #[derive(Debug)] pub struct BulkItem { /// `None` when the id matched nothing — which a caller must be able to /// report, so the row cannot be the key. pub candidate: Option, pub outcome: BulkOutcome, } impl BulkItem { pub fn pkgbase(&self) -> &str { self.candidate.as_ref().map(|c| c.pkgbase.as_str()).unwrap_or("(gone)") } } /// What a bulk decision did with one item (§7.4). #[derive(Debug)] pub enum BulkOutcome { /// Approved; the approval row is here so the caller can queue the build. Approved(Approval), /// A rejection records no approval, so there is no row to hand back. Rejected, /// Not decided, and why. Refused(BulkRefusal), } /// Why a bulk decision skipped one of its items (§7.4). Each reason is its own /// variant because they are different answers to give a human. #[derive(Debug, thiserror::Error)] pub enum BulkRefusal { /// High-risk items need their own confirmation, per item (§7.4). #[error("high risk: confirm it individually")] HighRiskUnconfirmed, /// The form said neither approve nor reject. #[error("unknown decision `{0}`")] UnknownDecision(String), /// The review is gone — deleted, or never existed. #[error("no such review")] NotFound, /// The review no longer matches what was displayed. #[error(transparent)] Stale(Stale), /// The write itself failed. #[error("{0}")] System(Error), } /// §7.4 bulk decision. High-risk items are refused unless confirmed /// individually, and one refused item never rolls back the ones that were /// decided. `items` carries the identity and diff each review was displayed /// with, so the approval-echo rule applies to bulk exactly as to a single /// approval. pub fn bulk( db: &Db, actor: &str, items: &[(i64, String, String)], // (candidate_id, identity_hash, diff_digest) decision: &str, confirmed: &[i64], ) -> Result> { let mut out = Vec::new(); for (id, ih, dd) in items { let candidate = candidates::by_id(db, *id)?; let mut push = |candidate, outcome| out.push(BulkItem { candidate, outcome }); let Some(c) = &candidate else { push(None, BulkOutcome::Refused(BulkRefusal::NotFound)); continue; }; if decision == "approve" && c.risk_level == crate::review::risk::level::HIGH && !confirmed.contains(id) { push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::HighRiskUnconfirmed)); continue; } match decision { "approve" => match approve(db, actor, *id, ih, dd, Some("bulk")) { Ok(a) => push(Some(c.clone()), BulkOutcome::Approved(a)), Err(ApproveError::Stale(s)) => push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::Stale(s))), Err(ApproveError::System(e)) => push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::System(e))), }, "reject" => match reject(db, actor, *id, "bulk") { Ok(()) => push(Some(c.clone()), BulkOutcome::Rejected), Err(e) => push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::System(e))), }, other => push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::UnknownDecision(other.to_string()))), } } Ok(out) } pub fn approval_for(db: &Db, candidate_id: i64) -> Result> { approvals::for_candidate(db, candidate_id) } /// Withdraw a published release (§9 `repo-remove` path, decision 23: warns, /// does not block). pub fn withdraw(db: &Db, actor: &str, release_id: i64, reason: &str) -> Result<()> { let actor = actor.to_string(); let reason = reason.to_string(); let at = time::now(); db.writer.tx(move |tx| { db::withdraw_release_in(tx, release_id)?; db::audit_in( tx, &db::AuditEntry::human( &at, &actor, "withdraw", "release", &release_id.to_string(), serde_json::json!({"release": release_id, "reason": reason}), ), )?; Ok(()) }) } pub fn current_accepted(db: &Db, pkgbase: &str) -> Result> { db::accepted_release(db, pkgbase) }