summaryrefslogtreecommitdiffstats
path: root/src/review
diff options
context:
space:
mode:
Diffstat (limited to 'src/review')
-rw-r--r--src/review/approve.rs177
-rw-r--r--src/review/candidates.rs273
-rw-r--r--src/review/diff.rs13
3 files changed, 88 insertions, 375 deletions
diff --git a/src/review/approve.rs b/src/review/approve.rs
index 0fdf2b2..704166c 100644
--- a/src/review/approve.rs
+++ b/src/review/approve.rs
@@ -5,9 +5,7 @@
//! rendered; if either has moved under the reviewer, the approval is refused
//! with a conflict (HTTP 409) and a re-render, never silently retargeted.
-use rusqlite::OptionalExtension;
-
-use crate::db::{self, *};
+use crate::db::{self, approvals, candidate_state, candidates, *};
use crate::error::{Error, Result};
use crate::time;
@@ -68,78 +66,54 @@ pub fn approve(
let at = time::now();
db.writer.tx(move |tx| -> Result<std::result::Result<Approval, Stale>> {
- type CandidateState = (i64, String, String, Option<i64>, Option<i64>, String, String);
- let row: Option<CandidateState> = tx
- .query_row(
- "SELECT c.id, c.state, c.identity_hash, c.base_release_id, p.current_accepted_release_id,
- c.risk_level, p.name
- FROM candidate c JOIN pkgbase p ON p.id = c.pkgbase_id
- WHERE c.id = ?1",
- rusqlite::params![candidate_id],
- |r| {
- Ok((
- r.get(0)?,
- r.get(1)?,
- r.get(2)?,
- r.get(3)?,
- r.get(4)?,
- r.get(5)?,
- r.get(6)?,
- ))
- },
- )
- .optional()?;
- let (id, state, actual_identity, base, current_base, risk, _pkgbase) =
- row.ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?;
+ 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;
// 1. still open
- if state != candidate_state::PENDING {
- return Ok(Err(Stale::NotPending { state }));
+ if subject.state != candidate_state::PENDING {
+ return Ok(Err(Stale::NotPending { state: subject.state }));
}
// 2. same candidate bytes
- if actual_identity != ih {
- return Ok(Err(Stale::Identity { expected: ih.clone(), actual: actual_identity }));
+ if subject.identity_hash != ih {
+ return Ok(Err(Stale::Identity { expected: ih.clone(), actual: subject.identity_hash }));
}
// 3. same rendered diff
- let stored_diff: String = tx.query_row(
- "SELECT diff_digest FROM candidate WHERE id=?1",
- rusqlite::params![id],
- |r| r.get(0),
- )?;
- if stored_diff != dd {
- return Ok(Err(Stale::Diff { expected: dd.clone(), actual: stored_diff }));
+ if subject.diff_digest != dd {
+ return Ok(Err(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest }));
}
// 4. base is still the accepted release (I2, end to end)
if base != current_base {
return Ok(Err(Stale::Base { expected: base, actual: current_base }));
}
- tx.execute(
- "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level,
- diff_digest, identity_hash, note)
- VALUES (?1,?2,?3,'approved',?4,?5,?6,?7)",
- rusqlite::params![id, base, at, risk, dd, ih, note],
- )?;
- let approval_id = tx.last_insert_rowid();
- tx.execute(
- "UPDATE candidate SET state='approved', resolved_at=?1 WHERE id=?2",
- rusqlite::params![at, id],
- )?;
- let pkgbase_id: i64 = tx.query_row(
- "SELECT pkgbase_id FROM candidate WHERE id=?1",
- rusqlite::params![id],
- |r| r.get(0),
+ 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(),
+ },
)?;
- tx.execute(
- "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json)
- VALUES (?1,'human',?2,'approve','candidate',?3,?4)",
- rusqlite::params![
- at,
- actor,
- id.to_string(),
- serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": pkgbase_id})
- .to_string()
- ],
+ candidates::resolve_in(tx, id, candidate_state::APPROVED, &at)?;
+ db::audit_in(
+ tx,
+ &db::AuditEntry {
+ at: &at,
+ actor_kind: "human",
+ actor: &actor,
+ action: "approve",
+ entity: "candidate",
+ entity_id: &id.to_string(),
+ detail: serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": subject.pkgbase_id}),
+ },
)?;
Ok(Ok(Approval {
id: approval_id,
@@ -160,33 +134,26 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()>
let note = note.to_string();
let at = time::now();
db.writer.tx(move |tx| {
- let state: String = tx
- .query_row("SELECT state FROM candidate WHERE id=?1", rusqlite::params![candidate_id], |r| r.get(0))
- .optional()?
+ let state = candidates::state_in(tx, candidate_id)?
.ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?;
if state != candidate_state::PENDING {
return Err(Error::conflict(format!("candidate is {state}, not pending")));
}
- let identity: String = tx.query_row(
- "SELECT identity_hash FROM candidate WHERE id=?1",
- rusqlite::params![candidate_id],
- |r| r.get(0),
- )?;
- tx.execute(
- "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level,
- diff_digest, identity_hash, note)
- SELECT id, base_release_id, ?1, 'rejected', risk_level, diff_digest, ?2, ?3
- FROM candidate WHERE id=?4",
- rusqlite::params![at, identity, note, candidate_id],
- )?;
- tx.execute(
- "UPDATE candidate SET state='rejected', resolved_at=?1 WHERE id=?2",
- rusqlite::params![at, candidate_id],
- )?;
- tx.execute(
- "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json)
- VALUES (?1,'human',?2,'reject','candidate',?3,?4)",
- rusqlite::params![at, actor, candidate_id.to_string(), serde_json::json!({"note": note}).to_string()],
+ 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, &note)?;
+ candidates::resolve_in(tx, candidate_id, candidate_state::REJECTED, &at)?;
+ db::audit_in(
+ tx,
+ &db::AuditEntry {
+ at: &at,
+ actor_kind: "human",
+ actor: &actor,
+ action: "reject",
+ entity: "candidate",
+ entity_id: &candidate_id.to_string(),
+ detail: serde_json::json!({"note": note}),
+ },
)?;
Ok(())
})
@@ -202,15 +169,7 @@ pub fn bulk(
) -> Result<Vec<std::result::Result<Approval, Stale>>> {
let mut out = Vec::new();
for (id, ih, dd) in items {
- let risk: String = db.read(|c| {
- Ok(c.query_row(
- "SELECT risk_level FROM candidate WHERE id=?1",
- rusqlite::params![id],
- |r| r.get(0),
- )
- .optional()?)
- })?
- .unwrap_or_default();
+ let risk = candidates::risk_level(db, *id)?.unwrap_or_default();
if decision == "approve" && risk == "high" && !confirm_high_risk {
out.push(Err(Stale::NotPending {
state: "high-risk: needs individual confirmation".into(),
@@ -230,14 +189,7 @@ pub fn bulk(
/// The approval behind a candidate, if any.
pub fn approval_for(db: &Db, candidate_id: i64) -> Result<Option<(i64, String)>> {
- db.read(|c| {
- Ok(c.query_row(
- "SELECT id, decision FROM approval WHERE candidate_id=?1",
- rusqlite::params![candidate_id],
- |r| Ok((r.get(0)?, r.get(1)?)),
- )
- .optional()?)
- })
+ approvals::for_candidate(db, candidate_id)
}
/// Withdraw a published release (§9 `repo-remove` path, decision 23: warns,
@@ -247,15 +199,18 @@ pub fn withdraw(db: &Db, actor: &str, release_id: i64, reason: &str) -> Result<(
let reason = reason.to_string();
let at = time::now();
db.writer.tx(move |tx| {
- tx.execute("UPDATE release SET state='withdrawn' WHERE id=?1", rusqlite::params![release_id])?;
- tx.execute(
- "UPDATE package SET state='removed' WHERE release_id=?1",
- rusqlite::params![release_id],
- )?;
- tx.execute(
- "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json)
- VALUES (?1,'human',?2,'withdraw','release',?3,?4)",
- rusqlite::params![at, actor, release_id.to_string(), serde_json::json!({"reason": reason}).to_string()],
+ db::withdraw_release_in(tx, release_id)?;
+ db::audit_in(
+ tx,
+ &db::AuditEntry {
+ at: &at,
+ actor_kind: "human",
+ actor: &actor,
+ action: "withdraw",
+ entity: "release",
+ entity_id: &release_id.to_string(),
+ detail: serde_json::json!({"reason": reason}),
+ },
)?;
Ok(())
})
diff --git a/src/review/candidates.rs b/src/review/candidates.rs
index 566434b..7cedf4b 100644
--- a/src/review/candidates.rs
+++ b/src/review/candidates.rs
@@ -5,23 +5,18 @@
//! fixed at creation to the pkgbase's `current_accepted_release` — that is what
//! makes "diff against the last accepted version, never the last seen one" (I2)
//! true no matter how many detections arrive while nobody is looking.
+//!
+//! This module is the *rule*, not the SQL: every statement it needs lives in
+//! `db::candidates` and is called through the transaction handle, so the whole
+//! decision is atomic and the schema still has one owner.
-use rusqlite::OptionalExtension;
-
-use crate::db::{self, *};
+use crate::db::{self, candidates as sql, Db, Pkgbase, ReleaseRow};
use crate::error::Result;
-use crate::time;
-#[derive(Debug, Clone)]
-pub struct NewCandidate {
- pub snapshot_id: i64,
- pub epoch: String,
- pub pkgver: String,
- pub pkgrel: String,
- pub upstream_pins_json: String,
- pub source_digests_json: String,
- pub identity_hash: String,
-}
+pub use crate::db::candidates::{
+ all as all_candidates, by_id as candidate_by_id, mark_viewed, open_reviews_for, pending as pending_candidates,
+ reopen_rejected, set_diff_digest, set_missing_deps, set_risk, NewCandidate,
+};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Upsert {
@@ -43,267 +38,41 @@ pub enum Upsert {
/// `accepted` is the pkgbase's current accepted release, or `None` when this is
/// a first introduction (§7.1b).
pub fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc: &NewCandidate) -> Result<Upsert> {
- let kind = if accepted.is_some() { candidate_kind::NEW_VERSION } else { candidate_kind::FIRST_INTRODUCTION };
+ let kind = if accepted.is_some() { db::candidate_kind::NEW_VERSION } else { db::candidate_kind::FIRST_INTRODUCTION };
let base = accepted.map(|a| a.id);
let pkgbase_id = pb.id;
let nc = nc.clone();
db.writer.tx(move |tx| {
- let existing: Option<(i64, String, Option<String>, i64)> = tx
- .query_row(
- "SELECT id, identity_hash, viewed_at, revision FROM candidate
- WHERE pkgbase_id=?1 AND state='pending_review'",
- rusqlite::params![pkgbase_id],
- |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
- )
- .optional()?;
-
- if let Some((id, identity, viewed, revision)) = existing {
- if identity == nc.identity_hash {
+ if let Some(open) = sql::open_in(tx, pkgbase_id)? {
+ if open.identity_hash == nc.identity_hash {
return Ok(Upsert::Unchanged);
}
- if viewed.is_none() {
+ if !open.viewed() {
// Collapse in place: same base, no new row, revision bumped.
- tx.execute(
- "UPDATE candidate SET snapshot_id=?1, epoch=?2, pkgver=?3, pkgrel=?4,
- upstream_pins_json=?5, source_digests_json=?6, identity_hash=?7,
- revision=?8, detected_at=?9, diff_digest=''
- WHERE id=?10",
- rusqlite::params![
- nc.snapshot_id, nc.epoch, nc.pkgver, nc.pkgrel,
- nc.upstream_pins_json, nc.source_digests_json, nc.identity_hash,
- revision + 1, time::now(), id
- ],
- )?;
- return Ok(Upsert::Collapsed { id, revision: revision + 1 });
+ let revision = sql::collapse_in(tx, &open, &nc)?;
+ return Ok(Upsert::Collapsed { id: open.id, revision });
}
// A human saw the old diff: freeze it for the audit trail and open a
// fresh review against the same base.
- tx.execute(
- "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2",
- rusqlite::params![time::now(), id],
- )?;
- let new_id = insert(tx, pkgbase_id, base, kind, &nc)?;
- return Ok(Upsert::Superseded { old: id, new: new_id });
+ sql::supersede_in(tx, open.id)?;
+ let new_id = sql::insert_in(tx, pkgbase_id, base, kind, &nc)?;
+ return Ok(Upsert::Superseded { old: open.id, new: new_id });
}
// No open review. A previously rejected identity must not be re-raised.
- let rejected: Option<i64> = tx
- .query_row(
- "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 AND state='rejected'
- ORDER BY id DESC LIMIT 1",
- rusqlite::params![pkgbase_id, nc.identity_hash],
- |r| r.get(0),
- )
- .optional()?;
- if rejected.is_some() {
+ if sql::rejected_before_in(tx, pkgbase_id, &nc.identity_hash)? {
return Ok(Upsert::PreviouslyRejected);
}
// Same identity already approved/recorded: nothing to do.
- let same: Option<i64> = tx
- .query_row(
- "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2
- ORDER BY id DESC LIMIT 1",
- rusqlite::params![pkgbase_id, nc.identity_hash],
- |r| r.get(0),
- )
- .optional()?;
- if same.is_some() {
+ if sql::recorded_before_in(tx, pkgbase_id, &nc.identity_hash)? {
return Ok(Upsert::Unchanged);
}
- let id = insert(tx, pkgbase_id, base, kind, &nc)?;
+ let id = sql::insert_in(tx, pkgbase_id, base, kind, &nc)?;
Ok(Upsert::Created { id, kind: kind.to_string() })
})
}
-fn insert(
- tx: &mut rusqlite::Transaction<'_>,
- pkgbase_id: i64,
- base: Option<i64>,
- kind: &str,
- nc: &NewCandidate,
-) -> Result<i64> {
- tx.execute(
- "INSERT INTO candidate (pkgbase_id, base_release_id, kind, snapshot_id, epoch, pkgver, pkgrel,
- upstream_pins_json, source_digests_json, identity_hash, state, detected_at)
- VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'pending_review',?11)",
- rusqlite::params![
- pkgbase_id, base, kind, nc.snapshot_id, nc.epoch, nc.pkgver, nc.pkgrel,
- nc.upstream_pins_json, nc.source_digests_json, nc.identity_hash, time::now()
- ],
- )?;
- Ok(tx.last_insert_rowid())
-}
-
-impl NewCandidate {
- /// The `epoch:pkgver-pkgrel` this candidate would publish.
- pub fn version(&self) -> String {
- crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel)
- }
-}
-
-/// Every candidate regardless of state, newest first (`aur-build reviews --all`).
-pub fn all_candidates(db: &Db) -> Result<Vec<CandidateRow>> {
- db.read(|c| {
- let mut stmt = c.prepare(
- "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver,
- c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash,
- c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json,
- c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name
- FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id
- ORDER BY c.detected_at DESC LIMIT 500",
- )?;
- let rows = stmt.query_map([], row_to_candidate)?;
- let mut out = Vec::new();
- for r in rows {
- out.push(r?);
- }
- Ok(out)
- })
-}
-
-/// Mark a candidate `viewed` the first time a human opens it. That timestamp is
-/// what decides whether a later detection collapses or supersedes (§7.1).
-pub fn mark_viewed(db: &Db, id: i64) -> Result<()> {
- let at = time::now();
- db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE candidate SET viewed_at=?1 WHERE id=?2 AND viewed_at IS NULL",
- rusqlite::params![at, id],
- )?;
- Ok(())
- })
-}
-
-pub fn pending_candidates(db: &Db) -> Result<Vec<CandidateRow>> {
- db.read(|c| {
- let mut stmt = c.prepare(
- "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver,
- c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash,
- c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json,
- c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name
- FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id
- WHERE c.state='pending_review'
- ORDER BY (c.risk_level='high') DESC, c.detected_at",
- )?;
- let rows = stmt.query_map([], row_to_candidate)?;
- let mut out = Vec::new();
- for r in rows {
- out.push(r?);
- }
- Ok(out)
- })
-}
-
-pub fn candidate_by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> {
- db.read(|c| {
- Ok(c.query_row(
- "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver,
- c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash,
- c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json,
- c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name
- FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?1",
- rusqlite::params![id],
- row_to_candidate,
- )
- .optional()?)
- })
-}
-
-fn row_to_candidate(r: &rusqlite::Row<'_>) -> rusqlite::Result<CandidateRow> {
- Ok(CandidateRow {
- id: r.get(0)?,
- pkgbase_id: r.get(1)?,
- base_release_id: r.get(2)?,
- kind: r.get(3)?,
- snapshot_id: r.get(4)?,
- epoch: r.get(5)?,
- pkgver: r.get(6)?,
- pkgrel: r.get(7)?,
- upstream_pins_json: r.get(8)?,
- source_digests_json: r.get(9)?,
- identity_hash: r.get(10)?,
- diff_digest: r.get(11)?,
- revision: r.get(12)?,
- viewed_at: r.get(13)?,
- risk_level: r.get(14)?,
- risk_signals_json: r.get(15)?,
- missing_deps_json: r.get(16)?,
- state: r.get(17)?,
- detected_at: r.get(18)?,
- resolved_at: r.get(19)?,
- pkgbase: r.get(20)?,
- })
-}
-
-/// Open reviews for a pkgbase (usually zero or one, by I7).
-pub fn open_reviews_for(db: &Db, pkgbase_id: i64) -> Result<Vec<CandidateRow>> {
- db.read(|c| {
- let mut stmt = c.prepare(
- "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver,
- c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash,
- c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json,
- c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name
- FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id
- WHERE c.pkgbase_id=?1 AND c.state='pending_review'",
- )?;
- let rows = stmt.query_map(rusqlite::params![pkgbase_id], row_to_candidate)?;
- let mut out = Vec::new();
- for r in rows {
- out.push(r?);
- }
- Ok(out)
- })
-}
-
-/// §7.1: a rejection can be re-opened. We retire the rejected row so it stops
-/// suppressing the identity, and the next detection opens a fresh review.
-pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> {
- let at = time::now();
- db.writer.tx(move |tx| {
- let n = tx.execute(
- "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2 AND state='rejected'",
- rusqlite::params![at, id],
- )?;
- if n == 0 {
- return Err(crate::error::Error::conflict("candidate is not rejected"));
- }
- Ok(())
- })
-}
-
-/// Record the risk assessment computed at review time.
-pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()> {
- let lvl = level.to_string();
- let sig = serde_json::to_string(signals)?;
- db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE candidate SET risk_level=?1, risk_signals_json=?2 WHERE id=?3",
- rusqlite::params![lvl, sig, id],
- )?;
- Ok(())
- })
-}
-
-pub fn set_missing_deps(db: &Db, id: i64, missing: &[String]) -> Result<()> {
- let m = serde_json::to_string(missing)?;
- db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE candidate SET missing_deps_json=?1 WHERE id=?2",
- rusqlite::params![m, id],
- )?;
- Ok(())
- })
-}
-
-pub fn set_diff_digest(db: &Db, id: i64, digest: &str) -> Result<()> {
- let d = digest.to_string();
- db.writer.tx(move |tx| {
- tx.execute("UPDATE candidate SET diff_digest=?1 WHERE id=?2", rusqlite::params![d, id])?;
- Ok(())
- })
-}
-
/// Convenience used by the watcher: the accepted release of a pkgbase row.
pub fn accepted_for(db: &Db, pb: &Pkgbase) -> Result<Option<ReleaseRow>> {
match pb.current_accepted_release_id {
diff --git a/src/review/diff.rs b/src/review/diff.rs
index 5af6f5a..1196406 100644
--- a/src/review/diff.rs
+++ b/src/review/diff.rs
@@ -72,18 +72,7 @@ fn recipe_of(db: &Db, snapshot_id: Option<i64>) -> Option<Recipe> {
}
fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Option<i64> {
- db.read(|c| {
- use rusqlite::OptionalExtension;
- c.query_row(
- "SELECT snapshot_id FROM candidate WHERE id=?1",
- rusqlite::params![candidate_id],
- |r| r.get::<_, i64>(0),
- )
- .optional()
- .map_err(Into::into)
- })
- .ok()
- .flatten()
+ db::candidate_snapshot_id(db, candidate_id).ok().flatten()
}
/// `source=()` entries added, removed, or moved to a different host (§6). A new