summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-18 18:41:27 +0000
committeraur-build <aur-build@localhost>2026-11-18 18:41:27 +0000
commit76a214ed4d82d8937a3ec38c27d4d59304b8fac3 (patch)
tree4a81e60b8f40fb3e9838c8e7f5ab7c361049dbeb /src
parent1abce8ba992353bca3d7b64b2633a15136e9303b (diff)
downloadaur-build-76a214ed4d82d8937a3ec38c27d4d59304b8fac3.tar.gz
aur-build-76a214ed4d82d8937a3ec38c27d4d59304b8fac3.zip
http: routes split by direction of travel
n-4. `routes.rs` was 1,065 lines with the routing table, twenty-odd page renderers, every mutating POST, and the size/date formatting helpers in one file, so finding where a form landed meant scrolling past everything that did not touch it. It is a module now: `routes/mod.rs` keeps the gate, the login handlers, the routing table and the helpers two files share (207 lines); `routes/pages.rs` holds the read side, which only ever goes through `db.read`; `routes/mutations.rs` holds the write side, which is where the audit writes and the flash messages live. The split is by *read versus write*, which is the distinction the crate actually cares about — the read path uses the thread-local read-only connection and must never reach the writer — so the file boundary now matches the invariant rather than being an arbitrary line count. Behaviour is unchanged: the handlers are the same functions, re-exported into `routes` so the routing table still reads as one flat list of endpoints.
Diffstat (limited to 'src')
-rw-r--r--src/http/routes.rs1065
-rw-r--r--src/http/routes/mod.rs207
-rw-r--r--src/http/routes/mutations.rs292
-rw-r--r--src/http/routes/pages.rs588
4 files changed, 1087 insertions, 1065 deletions
diff --git a/src/http/routes.rs b/src/http/routes.rs
deleted file mode 100644
index 4a988b2..0000000
--- a/src/http/routes.rs
+++ /dev/null
@@ -1,1065 +0,0 @@
-//! Route handlers (§12).
-//!
-//! Every handler reads through `db.read` — the thread-local read-only
-//! connection — and hands mutations to the writer actor. A slow client can
-//! therefore never hold the write lock, which is the whole point of the split.
-
-use crate::db::{self, builds, model::*, Db};
-use crate::review::{approve as ap, candidates, diff, risk};
-use crate::{ops, pipeline, time};
-
-use super::auth;
-use super::render::*;
-use super::{sse, Req, Res, State};
-
-/// Redirect an unauthenticated visitor to the login page. The session id is
-/// the credential: a cookie a client typed by hand proves nothing, only a sid
-/// this process minted and marked authenticated at a successful login does.
-pub fn gate(state: &State, req: &Req, sid: &str) -> Option<Res> {
- if !auth::auth_required(&state.cfg) {
- return None;
- }
- if auth::is_authenticated(sid) || req.path == "/login" {
- return None;
- }
- Some(Res::redirect("/login"))
-}
-
-pub fn login_form(state: &State, req: &Req) -> Res {
- let page = Page::new("Sign in", csrf(state, req));
- page_to_res(Login { page, error: String::new() }, 200)
-}
-
-/// Forget the session server-side and clear the cookie. The CSRF token is
-/// derived from the sid, so dropping the sid invalidates every form a browser
-/// still has open — which is exactly what logout should do.
-pub fn logout(req: &Req) -> Res {
- if let Some(sid) = req.cookie("sid") {
- auth::drop_session(&sid);
- }
- let mut res = Res::redirect("/login");
- res.header("Set-Cookie", "sid=; Path=/; Max-Age=0");
- res
-}
-
-pub fn login(state: &State, req: &Req) -> Res {
- let given = req.form_get("password").unwrap_or_default();
- let page = Page::new("Sign in", csrf(state, req));
- if auth::password_ok(&state.cfg, &given) {
- // Rotate rather than promote: the sid the visitor arrived with (if any)
- // is dropped, so the session that existed before the password was typed
- // is never the one that carries the privilege afterwards.
- if let Some(old) = req.cookie("sid") {
- auth::drop_session(&old);
- }
- let sid = match auth::new_session() {
- Some(sid) => sid,
- None => return page_to_res(Login { page, error: "server: no entropy for a session".into() }, 500),
- };
- auth::authenticate(&sid);
- let mut res = Res::redirect("/");
- // `serve` turns this into the `Set-Cookie: sid=…` header.
- res.header("X-New-Session", &sid);
- res
- } else {
- page_to_res(Login { page, error: "wrong password".into() }, 401)
- }
-}
-
-pub fn route(state: &State, req: &Req, seg: &[&str]) -> Res {
- match (req.method.as_str(), seg) {
- ("GET", []) => dashboard(state, req),
- ("GET", ["reviews"]) => reviews(state, req),
- ("GET", ["reviews", id]) => review_detail(state, req, id),
- ("POST", ["reviews", id, "approve"]) => review_approve(state, req, id),
- ("POST", ["reviews", id, "reject"]) => review_reject(state, req, id),
- ("POST", ["reviews", "bulk"]) => reviews_bulk(state, req),
- ("POST", ["logout"]) => logout(req),
- ("GET", ["subscriptions"]) => subscriptions(state, req),
- ("POST", ["subscriptions", "add"]) => sub_add(state, req),
- ("POST", ["subscriptions", "pause"]) => sub_pause(state, req),
- ("POST", ["subscriptions", "remove"]) => sub_remove(state, req),
- ("GET", ["attention"]) => attention(state, req),
- ("POST", ["attention", "ack"]) => notice_ack(state, req),
- ("GET", ["packages"]) => packages(state, req),
- ("GET", ["packages", name]) => package_detail(state, req, name),
- ("POST", ["packages", name, "rebuild"]) => package_rebuild(state, req, name),
- ("POST", ["packages", name, "withdraw"]) => package_withdraw(state, req, name),
- ("GET", ["builds"]) => builds_page(state, req),
- ("GET", ["builds", id]) => build_detail(state, req, id),
- ("GET", ["builds", id, "log.txt"]) => build_log(state, id),
- ("GET", ["builds", id, "log.stream"]) => build_log_stream(state, req, id),
- ("POST", ["builds", id, "cancel"]) => build_cancel(state, req, id),
- ("POST", ["builds", id, "requeue"]) => build_retry(state, req, id),
- ("GET", ["audit"]) => audit(state, req),
- ("GET", ["settings"]) => settings(state, req),
- _ => not_found(state, req),
- }
-}
-
-fn not_found(state: &State, req: &Req) -> Res {
- let page = chrome(state, req, "Not found", "nav_packages");
- page_to_res(
- ErrorPage {
- page,
- status: "404".into(),
- message: "no such page".into(),
- detail: String::new(),
- },
- 404,
- )
-}
-
-/// The shared chrome: counts for the nav badges and the active-tab marker.
-fn chrome(state: &State, req: &Req, title: &str, active: &str) -> Page {
- let db = &state.db;
- let mut page = Page::new(title, csrf(state, req));
- page.pending = candidates::pending_candidates(db).map(|v| v.len() as i64).unwrap_or(0);
- page.running = builds::in_flight(db).map(|v| v as i64).unwrap_or(0)
- + builds::queue_depth(db).map(|v| v as i64).unwrap_or(0);
- page.attention = db::list_notices(db, false).map(|v| v.len() as i64).unwrap_or(0)
- + builds::blocked_builds(db).map(|v| v.len() as i64).unwrap_or(0);
- page.nav_reviews = if active == "nav_reviews" { "on" } else { "" };
- page.nav_builds = if active == "nav_builds" { "on" } else { "" };
- page.nav_attention = if active == "nav_attention" { "on" } else { "" };
- page.nav_packages = if active == "nav_packages" { "on" } else { "" };
- page.nav_subscriptions = if active == "nav_subscriptions" { "on" } else { "" };
- page.nav_audit = if active == "nav_audit" { "on" } else { "" };
- page.nav_settings = if active == "nav_settings" { "on" } else { "" };
- page.gated = auth::auth_required(&state.cfg);
- page
-}
-
-fn csrf(_state: &State, req: &Req) -> String {
- req.cookie("sid").map(|s| auth::csrf_token(&s)).unwrap_or_default()
-}
-
-/// A byte count a human can read at a glance.
-fn human_size(bytes: i64) -> String {
- const UNITS: [&str; 4] = ["B", "KiB", "MiB", "GiB"];
- let mut v = bytes as f64;
- let mut i = 0;
- while v >= 1024.0 && i < UNITS.len() - 1 {
- v /= 1024.0;
- i += 1;
- }
- if i == 0 {
- format!("{bytes} {}", UNITS[0])
- } else {
- format!("{v:.1} {}", UNITS[i])
- }
-}
-
-fn short(id: &str) -> String {
- id.chars().take(10).collect()
-}
-
-fn age(detected_at: &str) -> String {
- let now = time::now();
- format!("{detected_at} → {now}")
-}
-
-// ------------------------------------------------------------- dashboard --
-
-fn dashboard(state: &State, req: &Req) -> Res {
- let db = &state.db;
- let page = chrome(state, req, "Dashboard", "");
- let publishes: Vec<PublishRow> = db::all_published_releases(db)
- .unwrap_or_default()
- .into_iter()
- .take(15)
- .filter_map(|r| {
- let pb = db::get_pkgbase_by_id(db, r.pkgbase_id).ok().flatten()?;
- Some(PublishRow {
- name: pb.name,
- version: r.version(),
- published_at: r.published_at.unwrap_or_else(|| r.state.to_string()),
- aur_commit: r.aur_commit.clone(),
- aur_commit_short: short(&r.aur_commit),
- })
- })
- .collect();
- page_to_res(
- Dashboard {
- page,
- subscriptions: db::list_subscriptions(db).map(|v| v.len() as i64).unwrap_or(0),
- index_count: db::index_packages(db).map(|v| v.len() as i64).unwrap_or(0),
- pending_reviews: candidates::pending_candidates(db).map(|v| v.len() as i64).unwrap_or(0),
- running_builds: builds::in_flight(db).map(|v| v as i64).unwrap_or(0),
- attention: db::list_notices(db, false).map(|v| v.len() as i64).unwrap_or(0),
- publishes,
- },
- 200,
- )
-}
-
-// ---------------------------------------------------------------- inbox --
-
-fn review_rows(db: &Db) -> Vec<ReviewRow> {
- let mut rows: Vec<ReviewRow> = candidates::pending_candidates(db)
- .unwrap_or_default()
- .into_iter()
- .map(|c| ReviewRow {
- id: c.id,
- pkgbase: c.pkgbase.clone(),
- version: full_version(&c),
- kind: c.kind.clone(),
- risk: c.risk_level.clone(),
- signals: c.risk_signals(),
- age: age(&c.detected_at),
- revision: c.revision,
- })
- .collect();
- // Risk first, then oldest — the scarcest resource gets the loudest rows.
- let rank = |r: &str| match r {
- risk::level::HIGH => 0,
- risk::level::MEDIUM => 1,
- _ => 2,
- };
- rows.sort_by_key(|r| (rank(&r.risk), r.age.clone(), r.id));
- rows
-}
-
-fn reviews(state: &State, req: &Req) -> Res {
- let page = chrome(state, req, "Reviews", "nav_reviews");
- page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 200)
-}
-
-fn full_version(c: &CandidateRow) -> String {
- crate::pkgver::full_version(&c.epoch, &c.pkgver, &c.pkgrel)
-}
-
-fn review_detail(state: &State, req: &Req, id: &str) -> Res {
- let db = &state.db;
- let Some(id) = id.parse::<i64>().ok() else {
- return not_found(state, req);
- };
- let Some(c) = candidates::candidate_by_id(db, id).unwrap_or(None) else {
- return not_found(state, req);
- };
- // Opening a review freezes it: a later detection now opens a fresh review
- // instead of silently changing what is on screen (§7.1).
- let _ = candidates::mark_viewed(db, id);
- let page = chrome(state, req, &format!("Review {}", c.pkgbase), "nav_reviews");
- let (head, panels, recipe, srcinfo, sources_resolved, deps_resolved) = review_body(state, &c);
- let base = panels_base(&c);
- page_to_res(
- ReviewDetail {
- page,
- c: head,
- base_version: base.0,
- has_base: base.1,
- panels,
- recipe,
- has_srcinfo: !srcinfo.is_empty(),
- srcinfo,
- sources_resolved,
- deps_resolved,
- },
- 200,
- )
-}
-
-fn panels_base(c: &CandidateRow) -> (String, bool) {
- match c.base_release_id {
- Some(_) => ("previous accepted release".into(), true),
- None => ("nothing accepted yet".into(), false),
- }
-}
-
-/// Build the review body: the panel set plus the first-introduction material.
-fn review_body(
- state: &State,
- c: &CandidateRow,
-) -> (ReviewHead, Vec<Panel>, String, String, String, String) {
- let db = &state.db;
- let base = match c.base_release_id {
- Some(id) => db::release_by_id(db, id).unwrap_or(None),
- None => None,
- };
- let panels = diff::panels(&state.cfg, db, c, base.as_ref()).unwrap_or_default();
- let rendered = diff::render_text(&panels);
- let _ = rendered;
- let snapshot = db::snapshot_by_id(db, c.snapshot_id).unwrap_or(None);
- let recipe_json = snapshot.as_ref().map(|s| s.srcinfo_json.clone()).unwrap_or_default();
- let parsed: Option<Recipe> = serde_json::from_str(&recipe_json).ok();
- let is_first = c.kind == candidate_kind::FIRST_INTRODUCTION;
-
- let head = ReviewHead {
- id: c.id,
- pkgbase: c.pkgbase.clone(),
- version: full_version(c),
- kind: c.kind.clone(),
- is_first,
- risk: c.risk_level.clone(),
- signals: c.risk_signals(),
- missing_deps: c.missing_deps(),
- dependents: crate::watch::staleness::dependents_of(db, &c.pkgbase).unwrap_or_default(),
- revision: c.revision,
- aur_commit: snapshot.as_ref().map(|s| s.aur_commit.clone()).unwrap_or_default(),
- aur_commit_short: snapshot
- .as_ref()
- .map(|s| short(&s.aur_commit))
- .unwrap_or_default(),
- identity_hash: c.identity_hash.clone(),
- diff_digest: c.diff_digest.clone(),
- };
- let shown: Vec<Panel> = panels
- .iter()
- .map(|p| Panel::new(p.title, p.body.clone()))
- .collect();
- let (recipe_text, srcinfo) = match &parsed {
- Some(r) => (r.pkgbuild.clone(), r.srcinfo.clone().unwrap_or_default()),
- None => (String::new(), String::new()),
- };
- let sources_resolved = serde_json::to_string_pretty(
- &serde_json::from_str::<serde_json::Value>(&c.source_digests_json)
- .unwrap_or_else(|_| serde_json::json!([])),
- )
- .unwrap_or_default();
- let deps_resolved = parsed
- .as_ref()
- .map(|r| {
- format!(
- "depends: {}\nmakedepends: {}\ncheckdepends: {}\noptdepends: {}",
- r.depends.join(", "),
- r.makedepends.join(", "),
- r.checkdepends.join(", "),
- r.optdepends.join(", ")
- )
- })
- .unwrap_or_default();
- (head, shown, recipe_text, srcinfo, sources_resolved, deps_resolved)
-}
-
-// -------------------------------------------------------------- approve --
-
-fn review_approve(state: &State, req: &Req, id: &str) -> Res {
- let db = &state.db;
- let Some(id) = id.parse::<i64>().ok() else {
- return not_found(state, req);
- };
- let Some(c) = candidates::candidate_by_id(db, id).unwrap_or(None) else {
- return not_found(state, req);
- };
- let identity = req.form_get("identity_hash").unwrap_or_default();
- let digest = req.form_get("diff_digest").unwrap_or_default();
- let note = req.form_get("note").filter(|s| !s.trim().is_empty());
- match ap::approve(db, actor(state, req), id, &identity, &digest, note.as_deref()) {
- Ok(a) => {
- let mut page = chrome(state, req, "Reviews", "nav_reviews");
- page.flash = format!("approved {} (approval {}); build queued", c.pkgbase, a.id);
- page.has_flash = true;
- match pipeline::enqueue_for_candidate(&state.cfg, db, &c) {
- Ok(bid) => {
- page.flash = format!("approved {}; build {} queued", c.pkgbase, short(&bid));
- page.has_flash = true;
- }
- Err(e) => {
- page.flash = format!("approved, but the build could not be queued: {e}");
- page.has_flash = true;
- page.flash_err = true;
- }
- }
- page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 200)
- }
- Err(ap::ApproveError::System(e)) => {
- // The database refused. Telling the reviewer their review went stale
- // would be a lie about the one thing they cannot check themselves.
- let mut page = chrome(state, req, "Review failed", "nav_reviews");
- page.flash = format!("the approval could not be recorded: {e}");
- page.has_flash = true;
- page.flash_err = true;
- page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 500)
- }
- Err(ap::ApproveError::Stale(stale)) => {
- // §7.1a: refuse, re-render what it is now, and say why. Never
- // silently retarget the approval onto the newer state.
- let mut page = chrome(state, req, "Review changed", "nav_reviews");
- page.flash = format!("refused: {stale}");
- page.has_flash = true;
- page.flash_err = true;
- // Show the review as it stands NOW — the frozen one the form came
- // from may have collapsed or been superseded while it was open.
- let current = candidates::pending_candidates(db)
- .unwrap_or_default()
- .into_iter()
- .find(|p| p.pkgbase_id == c.pkgbase_id)
- .unwrap_or_else(|| c.clone());
- let (head, panels, recipe, srcinfo, sources, deps) = review_body(state, &current);
- let base = panels_base(&current);
- page_to_res(
- ReviewDetail {
- page,
- c: head,
- base_version: base.0,
- has_base: base.1,
- panels,
- recipe,
- has_srcinfo: !srcinfo.is_empty(),
- srcinfo,
- sources_resolved: sources,
- deps_resolved: deps,
- },
- 409,
- )
- }
- }
-}
-
-fn review_reject(state: &State, req: &Req, id: &str) -> Res {
- let db = &state.db;
- let Some(id) = id.parse::<i64>().ok() else {
- return not_found(state, req);
- };
- let Some(note) = req.form_get("note").filter(|s| !s.trim().is_empty()) else {
- let mut page = chrome(state, req, "Review", "nav_reviews");
- page.flash = "a rejection needs a reason: it is the only record of why".into();
- page.has_flash = true;
- page.flash_err = true;
- return page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 400);
- };
- match ap::reject(db, actor(state, req), id, &note) {
- Ok(()) => {
- let mut page = chrome(state, req, "Reviews", "nav_reviews");
- page.flash = format!("rejected #{id}; it can be re-opened from the package page");
- page.has_flash = true;
- page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 200)
- }
- Err(e) => {
- let mut page = chrome(state, req, "Reviews", "nav_reviews");
- page.flash = format!("could not reject: {e}");
- page.has_flash = true;
- page.flash_err = true;
- page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 409)
- }
- }
-}
-
-/// Bulk approve/reject (§7.4): per-item, never "approve everything forever",
-/// and high-risk items are refused unless each was confirmed individually.
-fn reviews_bulk(state: &State, req: &Req) -> Res {
- let db = &state.db;
- let form = req.form();
- let ids: Vec<i64> = form
- .iter()
- .filter(|(k, _)| k == "ids")
- .filter_map(|(_, v)| v.parse().ok())
- .collect();
- let decision = form
- .iter()
- .find(|(k, _)| k == "decision")
- .map(|(_, v)| v.clone())
- .unwrap_or_default();
- let confirmed: Vec<i64> = form
- .iter()
- .filter(|(k, _)| k == "confirm")
- .filter_map(|(_, v)| v.parse().ok())
- .collect();
- if ids.is_empty() {
- let mut page = chrome(state, req, "Reviews", "nav_reviews");
- page.flash = "nothing selected".into();
- page.has_flash = true;
- page.flash_err = true;
- return page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 400);
- }
- // The rule itself lives in `review::approve::bulk`, so the page and the
- // library cannot disagree about what a bulk decision means (§7.4).
- let items: Vec<(i64, String, String)> = ids
- .iter()
- .filter_map(|id| {
- candidates::candidate_by_id(db, *id).ok().flatten().map(|c| (*id, c.identity_hash, c.diff_digest))
- })
- .collect();
- let outcomes = match ap::bulk(db, actor(state, req), &items, &decision, &confirmed) {
- Ok(outcomes) => outcomes,
- Err(e) => {
- let mut page = chrome(state, req, "Reviews", "nav_reviews");
- page.flash = format!("the decisions could not be recorded: {e}");
- page.has_flash = true;
- page.flash_err = true;
- return page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 500);
- }
- };
- let mut done = Vec::new();
- let mut refused = Vec::new();
- for item in outcomes {
- match &item.outcome {
- ap::BulkOutcome::Approved(_) => {
- if let Some(c) = &item.candidate {
- let _ = pipeline::enqueue_for_candidate(&state.cfg, db, c);
- done.push(c.pkgbase.clone());
- }
- }
- ap::BulkOutcome::Rejected => done.push(item.pkgbase().to_string()),
- ap::BulkOutcome::Refused(r) => refused.push(format!("{}: {r}", item.pkgbase())),
- }
- }
- let mut page = chrome(state, req, "Reviews", "nav_reviews");
- page.flash = format!(
- "{}: {}{}",
- if decision == "approve" { "approved" } else { "rejected" },
- done.join(", "),
- if refused.is_empty() { String::new() } else { format!(" — refused: {}", refused.join("; ")) }
- );
- page.has_flash = true;
- page.flash_err = !refused.is_empty();
- page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 200)
-}
-
-/// Who the audit trail says made a decision. With no password configured the
-/// UI is open on loopback and every session is the operator's; with one, only
-/// a session that passed the gate gets a name.
-fn actor(state: &State, req: &Req) -> &'static str {
- let sid = req.cookie("sid").unwrap_or_default();
- if !auth::auth_required(&state.cfg) || auth::is_authenticated(&sid) {
- "web"
- } else {
- "web-anon"
- }
-}
-
-// -------------------------------------------------------- subscriptions --
-
-fn subscriptions(state: &State, req: &Req) -> Res {
- let db = &state.db;
- let page = chrome(state, req, "Subscriptions", "nav_subscriptions");
- let pending = candidates::pending_candidates(db).unwrap_or_default();
- let rows = db::list_subscriptions(db)
- .unwrap_or_default()
- .into_iter()
- .map(|s| SubRow {
- pending: pending.iter().filter(|c| c.pkgbase == s.pkgbase).count() as i64,
- name: s.pkgbase.clone(),
- state: s.state.to_string(),
- maintainer: s.maintainer.unwrap_or_else(|| "unknown".into()),
- last_checked: s.last_checked_at.unwrap_or_else(|| "never".into()),
- next_check: s.next_check_at.unwrap_or_else(|| "soon".into()),
- last_error: s.last_error.clone().unwrap_or_default(),
- has_error: s.last_error.is_some(),
- pause_label: if s.state == SubscriptionState::Paused { "resume" } else { "pause" },
- })
- .collect();
- page_to_res(Subscriptions { page, rows }, 200)
-}
-
-fn sub_add(state: &State, req: &Req) -> Res {
- let db = &state.db;
- let Some(name) = req.form_get("pkgbase").map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) else {
- return flash_sub(state, req, "give a pkgbase name", true);
- };
- let rid = db::repo_id(db).unwrap_or(1);
- let url = format!("https://aur.archlinux.org/{name}.git");
- match db::subscribe(&db.writer, rid, &name, &url) {
- Ok(_) => {
- let _ = crate::watch::detect::check_pkgbase(&state.cfg, db, &name);
- flash_sub(state, req, &format!("subscribed {name} and ran a first check"), false)
- }
- Err(e) => flash_sub(state, req, &format!("could not subscribe: {e}"), true),
- }
-}
-
-fn sub_pause(state: &State, req: &Req) -> Res {
- let db = &state.db;
- let name = req.form_get("pkgbase").unwrap_or_default();
- let cur = db::get_subscription(db, &name).ok().flatten().map(|s| s.state);
- // Pause and resume are the only moves this page makes. A subscription that
- // is orphaned or removed is not the reviewer's to pause, and saying so beats
- // quietly rewriting its state.
- let next = match cur {
- Some(SubscriptionState::Active) => SubscriptionState::Paused,
- Some(SubscriptionState::Paused) => SubscriptionState::Active,
- Some(other) => return flash_sub(state, req, &format!("{name} is {other}: nothing to pause"), true),
- None => return flash_sub(state, req, &format!("no subscription for {name}"), true),
- };
- let _ = db::set_subscription_state(&db.writer, &name, next);
- flash_sub(state, req, &format!("{name}: {next}"), false)
-}
-
-fn sub_remove(state: &State, req: &Req) -> Res {
- let db = &state.db;
- let name = req.form_get("pkgbase").unwrap_or_default();
- let _ = db::set_subscription_state(&db.writer, &name, SubscriptionState::Removed);
- flash_sub(state, req, &format!("{name}: removed"), false)
-}
-
-fn flash_sub(state: &State, req: &Req, msg: &str, err: bool) -> Res {
- let page = chrome(state, req, "Subscriptions", "nav_subscriptions").flash(msg.into(), err);
- let pending = candidates::pending_candidates(&state.db).unwrap_or_default();
- let rows = db::list_subscriptions(&state.db)
- .unwrap_or_default()
- .into_iter()
- .map(|s| SubRow {
- pending: pending.iter().filter(|c| c.pkgbase == s.pkgbase).count() as i64,
- name: s.pkgbase.clone(),
- state: s.state.to_string(),
- maintainer: s.maintainer.unwrap_or_else(|| "unknown".into()),
- last_checked: s.last_checked_at.unwrap_or_else(|| "never".into()),
- next_check: s.next_check_at.unwrap_or_else(|| "soon".into()),
- last_error: s.last_error.clone().unwrap_or_default(),
- has_error: s.last_error.is_some(),
- pause_label: if s.state == SubscriptionState::Paused { "resume" } else { "pause" },
- })
- .collect();
- page_to_res(Subscriptions { page, rows }, 200)
-}
-
-// ------------------------------------------------------------ attention --
-
-fn attention(state: &State, req: &Req) -> Res {
- let db = &state.db;
- let page = chrome(state, req, "Attention", "nav_attention");
- let notices = db::list_notices(db, false)
- .unwrap_or_default()
- .into_iter()
- .map(|n| NoticeRow {
- id: n.id,
- pkgbase: n.pkgbase.clone(),
- kind: n.kind.clone(),
- severity: n.severity.clone(),
- detail: n.detail_json.clone(),
- created_at: n.created_at.clone(),
- })
- .collect::<Vec<NoticeRow>>();
- let blocked: Vec<BlockedRow> = builds::blocked_builds(db)
- .unwrap_or_default()
- .into_iter()
- .map(|(id, pkgbase, blocked_on)| BlockedRow { id_short: short(&id), id, pkgbase, blocked_on })
- .collect();
- // Staleness is computed on read (P4 fills the query in).
- let stale = crate::watch::staleness::stale_rows(db).unwrap_or_default();
- let outdated: Vec<StaleRow> = stale
- .iter()
- .filter(|s| s.kind == crate::watch::staleness::Kind::Outdated)
- .cloned()
- .map(|s| StaleRow { pkgbase: s.pkgbase, dependency: s.dependency, built_with: s.built_with, now: s.now })
- .collect();
- let missing: Vec<StaleRow> = stale
- .iter()
- .filter(|s| s.kind == crate::watch::staleness::Kind::Missing)
- .cloned()
- .map(|s| StaleRow { pkgbase: s.pkgbase, dependency: s.dependency, built_with: s.built_with, now: s.now })
- .collect();
- let downgrades: Vec<StaleRow> = crate::watch::staleness::downgrades(db)
- .unwrap_or_default()
- .into_iter()
- .map(|s| StaleRow { pkgbase: s.pkgbase, dependency: s.dependency, built_with: s.built_with, now: s.now })
- .collect();
- let unbuilt: Vec<UnbuiltRow> = db::approved_but_unbuilt(db)
- .unwrap_or_default()
- .into_iter()
- .map(|u| UnbuiltRow {
- pkgbase: u.pkgbase,
- approved: u.approved,
- serving: u.serving,
- error: u.error,
- build_id: u.build_id,
- })
- .collect();
- let empty = notices.is_empty()
- && unbuilt.is_empty()
- && outdated.is_empty()
- && missing.is_empty()
- && blocked.is_empty();
- page_to_res(
- Attention { page, empty, notices, unbuilt, outdated, missing, downgrades, blocked },
- 200,
- )
-}
-
-fn notice_ack(state: &State, req: &Req) -> Res {
- let id: i64 = req.form_get("id").and_then(|s| s.parse().ok()).unwrap_or(0);
- let _ = db::acknowledge_notice(&state.db.writer, id);
- // POST-redirect-GET: the notice vanishing from the list is its own
- // confirmation, and a refresh can no longer re-POST.
- Res::redirect("/attention")
-}
-
-// ------------------------------------------------------------- packages --
-
-fn packages(state: &State, req: &Req) -> Res {
- let db = &state.db;
- let page = chrome(state, req, "Index", "nav_packages");
- let rows: Vec<IndexRow> = db::index_packages(db)
- .unwrap_or_default()
- .into_iter()
- .map(|p| IndexRow {
- name: p.name.clone(),
- version: p.version.clone(),
- arch: p.arch.clone(),
- size: p.size.map(human_size).unwrap_or_else(|| "—".into()),
- published_at: p.published_at.clone().unwrap_or_else(|| "—".into()),
- })
- .collect();
- let snippet = format!(
- "[{}]\nServer = {}/$repo/os/$arch\nSigLevel = Required DatabaseOptional",
- state.cfg.repo_name, state.cfg.base_url
- );
- page_to_res(Packages { page, repo: state.cfg.repo_name.clone(), rows, snippet }, 200)
-}
-
-fn package_detail(state: &State, req: &Req, name: &str) -> Res {
- let db = &state.db;
- let page = chrome(state, req, name, "nav_packages");
- let Some(pb) = db::get_pkgbase(db, name).unwrap_or(None) else {
- return not_found(state, req);
- };
- let releases = db::releases_for_pkgbase(db, pb.id, 20).unwrap_or_default();
- let accepted = db::accepted_release(db, name).unwrap_or(None);
- let timeline: Vec<TimelineRow> = releases
- .into_iter()
- .map(|r| TimelineRow {
- version: r.version(),
- state: r.state.to_string(),
- aur_commit: r.aur_commit.clone(),
- aur_commit_short: short(&r.aur_commit),
- published_at: r.published_at.unwrap_or_else(|| "—".into()),
- approver: r
- .approval_id
- .and_then(|aid| db::approval_note(db, aid).ok().filter(|s| !s.is_empty()))
- .filter(|s| !s.is_empty())
- .unwrap_or_else(|| "—".into()),
- })
- .collect();
- let builds: Vec<BuildLite> = db::builds_for_pkgbase(db, pb.id, 10)
- .unwrap_or_default()
- .into_iter()
- .map(|b| BuildLite {
- id_short: short(&b.id),
- id: b.id,
- kind: b.kind,
- state: b.state.to_string(),
- step: b.current_step.unwrap_or_default(),
- })
- .collect();
- // Depends-on comes from the recipe we actually serve; needed-by comes from
- // the packages whose own recipes name this one (§10.3).
- let deps_in: Vec<String> = accepted
- .as_ref()
- .and_then(|r| db::accepted_recipe(db, r).ok().flatten())
- .map(|r| {
- let mut v = crate::pkgver::dep_names(&r.depends);
- v.sort();
- v.dedup();
- v
- })
- .unwrap_or_default();
- let deps_out: Vec<String> = crate::watch::staleness::dependents_of(db, name).unwrap_or_default();
- let stale: Vec<String> = crate::watch::staleness::stale_for(db, name)
- .unwrap_or_default()
- .into_iter()
- .map(|s| format!("{} was built against {} but the index has {}", s.pkgbase, s.built_with, s.now))
- .collect();
- let summary = match &accepted {
- Some(r) => format!("serving {} · approved from aur_commit {}", r.version(), short(&r.aur_commit)),
- None => "nothing published yet".into(),
- };
- let unbuilt: Vec<UnbuiltRow> = db::approved_but_unbuilt(db)
- .unwrap_or_default()
- .into_iter()
- .filter(|u| u.pkgbase == name)
- .map(|u| UnbuiltRow {
- pkgbase: u.pkgbase,
- approved: u.approved,
- serving: u.serving,
- error: u.error,
- build_id: u.build_id,
- })
- .collect();
- page_to_res(
- PackageDetail {
- page,
- name: name.to_string(),
- summary,
- can_withdraw: accepted.is_some(),
- unbuilt,
- stale,
- deps_in,
- deps_out,
- timeline,
- builds,
- },
- 200,
- )
-}
-
-fn package_rebuild(state: &State, req: &Req, name: &str) -> Res {
- match pipeline::enqueue_manual_rebuild(&state.cfg, &state.db, name) {
- Ok(id) => {
- let mut page = chrome(state, req, "Builds", "nav_builds");
- page.flash = format!(
- "queued a rebuild of the approved version of {name} (build {}, no new approval needed)",
- &id[..8.min(id.len())]
- );
- page.has_flash = true;
- builds_with(state, req, page)
- }
- Err(e) => {
- let mut page = chrome(state, req, "Index", "nav_packages");
- page.flash = format!("could not queue a rebuild: {e}");
- page.has_flash = true;
- page.flash_err = true;
- page_to_res(Packages { page, repo: state.cfg.repo_name.clone(), rows: vec![], snippet: String::new() }, 400)
- }
- }
-}
-
-fn package_withdraw(state: &State, req: &Req, name: &str) -> Res {
- match pipeline::publish::withdraw_package(&state.cfg, &state.db, name) {
- Ok(()) => Res::redirect("/packages"),
- Err(e) => {
- let mut page = chrome(state, req, "Index", "nav_packages");
- page.flash = format!("withdrawal failed: {e}");
- page.has_flash = true;
- page.flash_err = true;
- page_to_res(Packages { page, repo: state.cfg.repo_name.clone(), rows: vec![], snippet: String::new() }, 500)
- }
- }
-}
-
-// --------------------------------------------------------------- builds --
-
-/// The version a build is about. A build points at a candidate, or — for a
-/// manual rebuild of something already published — at a release.
-fn build_version(db: &Db, b: &builds::BuildRow) -> String {
- if let Some(cid) = b.candidate_id {
- if let Some(c) = candidates::candidate_by_id(db, cid).ok().flatten() {
- return c.version();
- }
- }
- if let Some(rid) = b.release_id {
- if let Some(r) = db::release_by_id(db, rid).ok().flatten() {
- return r.version();
- }
- }
- String::new()
-}
-
-fn build_rows(state: &State) -> Vec<BuildRow> {
- builds::list(
- &state.db,
- BuildState::active(),
- 100,
- )
- .unwrap_or_default()
- .into_iter()
- .map(|b| {
- let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id)
- .ok()
- .flatten()
- .map(|p| p.name)
- .unwrap_or_default();
- let version = build_version(&state.db, &b);
- BuildRow {
- id_short: short(&b.id),
- id: b.id,
- pkgbase,
- version,
- kind: b.kind,
- state: b.state.to_string(),
- step: b.current_step.unwrap_or_default(),
- lease: b.lease_expires_at.unwrap_or_else(|| "—".into()),
- cancel: b.cancel_requested,
- error: b.error.unwrap_or_default(),
- }
- })
- .collect()
-}
-
-fn builds_page(state: &State, req: &Req) -> Res {
- let page = chrome(state, req, "Builds", "nav_builds");
- // htmx asks for the fragment; a browser with JavaScript off never does and
- // gets the whole page either way (§13).
- if req.query_get("fragment").as_deref() == Some("1") {
- return page_to_res(
- BuildsTable { page, rows: build_rows(state), recent: recent_rows(state) },
- 200,
- );
- }
- builds_with(state, req, page)
-}
-
-fn recent_rows(state: &State) -> Vec<BuildRow> {
- builds::list(&state.db, &[BuildState::Failed, BuildState::Succeeded], 10)
- .unwrap_or_default()
- .into_iter()
- .map(|b| {
- let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id).ok().flatten().map(|p| p.name).unwrap_or_default();
- let version = build_version(&state.db, &b);
- BuildRow {
- id_short: short(&b.id),
- id: b.id,
- pkgbase,
- version,
- kind: b.kind,
- state: b.state.to_string(),
- step: b.current_step.unwrap_or_default(),
- lease: String::new(),
- cancel: b.cancel_requested,
- error: b.error.unwrap_or_default(),
- }
- })
- .collect()
-}
-
-fn builds_with(state: &State, _req: &Req, page: Page) -> Res {
- page_to_res(Builds { page, rows: build_rows(state), recent: recent_rows(state) }, 200)
-}
-
-fn build_detail(state: &State, req: &Req, id: &str) -> Res {
- let db = &state.db;
- let Some(b) = builds::get(db, id).unwrap_or(None) else {
- return not_found(state, req);
- };
- let page = chrome(state, req, "Build", "nav_builds");
- let steps: Vec<StepRow> = builds::steps(db, id)
- .unwrap_or_default()
- .into_iter()
- .map(|s| {
- let cls = if s.status == StepState::Failed { "risk-high" } else { "mut" }.to_string();
- StepRow {
- step: s.step,
- status: s.status.to_string(),
- attempt: s.attempt,
- digest: String::new(),
- cls,
- error: s.error.unwrap_or_default(),
- }
- })
- .collect();
- let log_path = state.cfg.build_log_path(id);
- let all = std::fs::read_to_string(&log_path).unwrap_or_default();
- let lines: Vec<&str> = all.lines().collect();
- let tail = lines[lines.len().saturating_sub(200)..].join("\n");
- let blocked_on: Vec<String> = serde_json::from_str(&b.blocked_on_json).unwrap_or_default();
- let pkgbase = db::get_pkgbase_by_id(db, b.pkgbase_id).ok().flatten().map(|p| p.name).unwrap_or_default();
- page_to_res(
- BuildDetail {
- page,
- id: id.to_string(),
- id_short: short(id),
- pkgbase,
- version: build_version(db, &b),
- kind: b.kind,
- state: b.state.to_string(),
- error: b.error.clone().unwrap_or_default(),
- blocked_on,
- steps,
- log: tail,
- log_lines: lines.len().min(200),
- log_truncated: lines.len() > 200,
- },
- 200,
- )
-}
-
-fn build_log(state: &State, id: &str) -> Res {
- let body = std::fs::read_to_string(state.cfg.build_log_path(id)).unwrap_or_default();
- Res::text(200, body)
-}
-
-/// The live tail (§13). Server-sent events from a blocking reader: the pipeline
-/// appends to a file and never learns this connection exists, so a viewer that
-/// hangs up, stalls or never shows up cannot slow a build.
-fn build_log_stream(state: &State, req: &Req, id: &str) -> Res {
- if builds::get(&state.db, id).unwrap_or(None).is_none() {
- return not_found(state, req);
- }
- let tail = sse::LogTail::new(&state.cfg, state.db.clone(), id);
- let mut res = Res::stream("text/event-stream", tail, None);
- // No caching, and no proxy buffering: a buffered event stream is a log tail
- // that arrives all at once, which is the thing we are trying to avoid.
- res.header("Cache-Control", "no-cache");
- res.header("X-Accel-Buffering", "no");
- res
-}
-
-fn build_cancel(state: &State, req: &Req, id: &str) -> Res {
- let _ = builds::request_cancel(&state.db, id);
- let mut page = chrome(state, req, "Builds", "nav_builds");
- page.flash = format!("cancellation requested for {}; it stops at the next step boundary", short(id));
- page.has_flash = true;
- builds_with(state, req, page)
-}
-
-/// Retrying a failed build is an explicit, audited decision (§8.4), not
-/// something the system does to itself.
-fn build_retry(state: &State, req: &Req, id: &str) -> Res {
- match builds::retry(&state.db, id) {
- Ok(()) => {
- let _ = db::audit(&state.db.writer, "web", "web", "build.retry", "build", id, serde_json::json!({}));
- Res::redirect(&format!("/builds/{id}"))
- }
- Err(e) => {
- let mut page = chrome(state, req, "Builds", "nav_builds");
- page.flash = format!("could not retry: {e}");
- page.has_flash = true;
- page.flash_err = true;
- builds_with(state, req, page)
- }
- }
-}
-
-// ----------------------------------------------------------- ops, config --
-
-fn audit(state: &State, req: &Req) -> Res {
- let page = chrome(state, req, "Ops", "nav_audit");
- let rows = db::list_audit(&state.db, 200)
- .unwrap_or_default()
- .into_iter()
- .map(|a| AuditRow {
- at: a.at,
- actor_kind: a.actor_kind,
- actor: a.actor,
- action: a.action,
- entity: a.entity,
- entity_id: a.entity_id,
- detail: a.detail_json,
- })
- .collect();
- page_to_res(Audit { page, rows }, 200)
-}
-
-/// `GET /metrics` in Prometheus text exposition format (§12, §15).
-///
-/// Everything here is computed from live state on every scrape. There are no
-/// counters incremented at event sites, because a counter that has to be
-/// maintained by every code path is a counter that quietly drifts the first time
-/// a path is added; a query cannot drift.
-pub fn metrics(state: &State) -> Res {
- match ops::metrics(&state.cfg, &state.db) {
- Ok(m) => {
- let mut res = Res::text(200, m.to_prometheus());
- res.content_type = "text/plain; version=0.0.4; charset=utf-8".into();
- res
- }
- Err(e) => Res::text(500, format!("metrics unavailable: {e}\n")),
- }
-}
-
-fn settings(state: &State, req: &Req) -> Res {
- let page = chrome(state, req, "Settings", "nav_settings");
- let rows = db::all_settings(&state.db)
- .unwrap_or_default()
- .into_iter()
- .map(|(key, value)| SettingRow { key, value })
- .collect();
- let repo = format!(
- "name: {}\narch: {}\npath: {}\nsigning key: {}\nbind: {}",
- state.cfg.repo_name,
- state.cfg.arch,
- state.cfg.repo_arch_dir().display(),
- if state.cfg.signing_key_id.is_empty() { "none (unsigned!)" } else { &state.cfg.signing_key_id },
- state.cfg.bind
- );
- page_to_res(Settings { page, rows, repo }, 200)
-}
-
-// ------------------------------------------------------------ rendering --
-
-fn page_to_res<T: askama::Template>(t: T, status: u16) -> Res {
- match askama::Template::render(&t) {
- Ok(body) => Res::html(status, body),
- Err(e) => Res::text(500, format!("template error: {e}")),
- }
-}
diff --git a/src/http/routes/mod.rs b/src/http/routes/mod.rs
new file mode 100644
index 0000000..e78cc74
--- /dev/null
+++ b/src/http/routes/mod.rs
@@ -0,0 +1,207 @@
+//! Route handlers (§12).
+//!
+//! Every handler reads through `db.read` — the thread-local read-only
+//! connection — and hands mutations to the writer actor. A slow client can
+//! therefore never hold the write lock, which is the whole point of the split.
+
+use crate::db::{self, builds, model::*};
+use crate::review::candidates;
+use crate::time;
+use super::auth;
+use super::render::*;
+use super::{Req, Res, State};
+
+mod mutations;
+mod pages;
+
+// The handlers live in two files by direction of travel — reads in `pages`,
+// writes in `mutations` — and are pulled back into scope here so the routing
+// table below still reads as one flat list of endpoints (n-4).
+pub(crate) use mutations::*;
+pub(crate) use pages::*;
+
+pub fn gate(state: &State, req: &Req, sid: &str) -> Option<Res> {
+ if !auth::auth_required(&state.cfg) {
+ return None;
+ }
+ if auth::is_authenticated(sid) || req.path == "/login" {
+ return None;
+ }
+ Some(Res::redirect("/login"))
+}
+
+pub fn login_form(state: &State, req: &Req) -> Res {
+ let page = Page::new("Sign in", csrf(state, req));
+ page_to_res(Login { page, error: String::new() }, 200)
+}
+
+/// Forget the session server-side and clear the cookie. The CSRF token is
+/// derived from the sid, so dropping the sid invalidates every form a browser
+/// still has open — which is exactly what logout should do.
+pub fn logout(req: &Req) -> Res {
+ if let Some(sid) = req.cookie("sid") {
+ auth::drop_session(&sid);
+ }
+ let mut res = Res::redirect("/login");
+ res.header("Set-Cookie", "sid=; Path=/; Max-Age=0");
+ res
+}
+
+pub fn login(state: &State, req: &Req) -> Res {
+ let given = req.form_get("password").unwrap_or_default();
+ let page = Page::new("Sign in", csrf(state, req));
+ if auth::password_ok(&state.cfg, &given) {
+ // Rotate rather than promote: the sid the visitor arrived with (if any)
+ // is dropped, so the session that existed before the password was typed
+ // is never the one that carries the privilege afterwards.
+ if let Some(old) = req.cookie("sid") {
+ auth::drop_session(&old);
+ }
+ let sid = match auth::new_session() {
+ Some(sid) => sid,
+ None => return page_to_res(Login { page, error: "server: no entropy for a session".into() }, 500),
+ };
+ auth::authenticate(&sid);
+ let mut res = Res::redirect("/");
+ // `serve` turns this into the `Set-Cookie: sid=…` header.
+ res.header("X-New-Session", &sid);
+ res
+ } else {
+ page_to_res(Login { page, error: "wrong password".into() }, 401)
+ }
+}
+
+pub fn route(state: &State, req: &Req, seg: &[&str]) -> Res {
+ match (req.method.as_str(), seg) {
+ ("GET", []) => dashboard(state, req),
+ ("GET", ["reviews"]) => reviews(state, req),
+ ("GET", ["reviews", id]) => review_detail(state, req, id),
+ ("POST", ["reviews", id, "approve"]) => review_approve(state, req, id),
+ ("POST", ["reviews", id, "reject"]) => review_reject(state, req, id),
+ ("POST", ["reviews", "bulk"]) => reviews_bulk(state, req),
+ ("POST", ["logout"]) => logout(req),
+ ("GET", ["subscriptions"]) => subscriptions(state, req),
+ ("POST", ["subscriptions", "add"]) => sub_add(state, req),
+ ("POST", ["subscriptions", "pause"]) => sub_pause(state, req),
+ ("POST", ["subscriptions", "remove"]) => sub_remove(state, req),
+ ("GET", ["attention"]) => attention(state, req),
+ ("POST", ["attention", "ack"]) => notice_ack(state, req),
+ ("GET", ["packages"]) => packages(state, req),
+ ("GET", ["packages", name]) => package_detail(state, req, name),
+ ("POST", ["packages", name, "rebuild"]) => package_rebuild(state, req, name),
+ ("POST", ["packages", name, "withdraw"]) => package_withdraw(state, req, name),
+ ("GET", ["builds"]) => builds_page(state, req),
+ ("GET", ["builds", id]) => build_detail(state, req, id),
+ ("GET", ["builds", id, "log.txt"]) => build_log(state, id),
+ ("GET", ["builds", id, "log.stream"]) => build_log_stream(state, req, id),
+ ("POST", ["builds", id, "cancel"]) => build_cancel(state, req, id),
+ ("POST", ["builds", id, "requeue"]) => build_retry(state, req, id),
+ ("GET", ["audit"]) => audit(state, req),
+ ("GET", ["settings"]) => settings(state, req),
+ _ => not_found(state, req),
+ }
+}
+
+fn not_found(state: &State, req: &Req) -> Res {
+ let page = chrome(state, req, "Not found", "nav_packages");
+ page_to_res(
+ ErrorPage {
+ page,
+ status: "404".into(),
+ message: "no such page".into(),
+ detail: String::new(),
+ },
+ 404,
+ )
+}
+
+/// The shared chrome: counts for the nav badges and the active-tab marker.
+fn chrome(state: &State, req: &Req, title: &str, active: &str) -> Page {
+ let db = &state.db;
+ let mut page = Page::new(title, csrf(state, req));
+ page.pending = candidates::pending_candidates(db).map(|v| v.len() as i64).unwrap_or(0);
+ page.running = builds::in_flight(db).map(|v| v as i64).unwrap_or(0)
+ + builds::queue_depth(db).map(|v| v as i64).unwrap_or(0);
+ page.attention = db::list_notices(db, false).map(|v| v.len() as i64).unwrap_or(0)
+ + builds::blocked_builds(db).map(|v| v.len() as i64).unwrap_or(0);
+ page.nav_reviews = if active == "nav_reviews" { "on" } else { "" };
+ page.nav_builds = if active == "nav_builds" { "on" } else { "" };
+ page.nav_attention = if active == "nav_attention" { "on" } else { "" };
+ page.nav_packages = if active == "nav_packages" { "on" } else { "" };
+ page.nav_subscriptions = if active == "nav_subscriptions" { "on" } else { "" };
+ page.nav_audit = if active == "nav_audit" { "on" } else { "" };
+ page.nav_settings = if active == "nav_settings" { "on" } else { "" };
+ page.gated = auth::auth_required(&state.cfg);
+ page
+}
+
+fn csrf(_state: &State, req: &Req) -> String {
+ req.cookie("sid").map(|s| auth::csrf_token(&s)).unwrap_or_default()
+}
+
+/// A byte count a human can read at a glance.
+fn human_size(bytes: i64) -> String {
+ const UNITS: [&str; 4] = ["B", "KiB", "MiB", "GiB"];
+ let mut v = bytes as f64;
+ let mut i = 0;
+ while v >= 1024.0 && i < UNITS.len() - 1 {
+ v /= 1024.0;
+ i += 1;
+ }
+ if i == 0 {
+ format!("{bytes} {}", UNITS[0])
+ } else {
+ format!("{v:.1} {}", UNITS[i])
+ }
+}
+
+fn short(id: &str) -> String {
+ id.chars().take(10).collect()
+}
+
+fn age(detected_at: &str) -> String {
+ let now = time::now();
+ format!("{detected_at} → {now}")
+}
+
+/// Who the audit trail says made a decision. With no password configured the
+/// UI is open on loopback and every session is the operator's; with one, only
+/// a session that passed the gate gets a name.
+fn actor(state: &State, req: &Req) -> &'static str {
+ let sid = req.cookie("sid").unwrap_or_default();
+ if !auth::auth_required(&state.cfg) || auth::is_authenticated(&sid) {
+ "web"
+ } else {
+ "web-anon"
+ }
+}
+
+fn flash_sub(state: &State, req: &Req, msg: &str, err: bool) -> Res {
+ let page = chrome(state, req, "Subscriptions", "nav_subscriptions").flash(msg.into(), err);
+ let pending = candidates::pending_candidates(&state.db).unwrap_or_default();
+ let rows = db::list_subscriptions(&state.db)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|s| SubRow {
+ pending: pending.iter().filter(|c| c.pkgbase == s.pkgbase).count() as i64,
+ name: s.pkgbase.clone(),
+ state: s.state.to_string(),
+ maintainer: s.maintainer.unwrap_or_else(|| "unknown".into()),
+ last_checked: s.last_checked_at.unwrap_or_else(|| "never".into()),
+ next_check: s.next_check_at.unwrap_or_else(|| "soon".into()),
+ last_error: s.last_error.clone().unwrap_or_default(),
+ has_error: s.last_error.is_some(),
+ pause_label: if s.state == SubscriptionState::Paused { "resume" } else { "pause" },
+ })
+ .collect();
+ page_to_res(Subscriptions { page, rows }, 200)
+}
+
+// ------------------------------------------------------------ rendering --
+
+fn page_to_res<T: askama::Template>(t: T, status: u16) -> Res {
+ match askama::Template::render(&t) {
+ Ok(body) => Res::html(status, body),
+ Err(e) => Res::text(500, format!("template error: {e}")),
+ }
+}
diff --git a/src/http/routes/mutations.rs b/src/http/routes/mutations.rs
new file mode 100644
index 0000000..133d491
--- /dev/null
+++ b/src/http/routes/mutations.rs
@@ -0,0 +1,292 @@
+//! The write side of the UI: every handler that changes something, and the flash
+//! it answers with.
+
+use crate::db::{self, builds};
+use crate::review::{approve as ap, candidates};
+use crate::pipeline;
+use crate::http::{Req, Res, State};
+
+use super::*;
+
+// -------------------------------------------------------------- approve --
+
+pub(crate) fn review_approve(state: &State, req: &Req, id: &str) -> Res {
+ let db = &state.db;
+ let Some(id) = id.parse::<i64>().ok() else {
+ return not_found(state, req);
+ };
+ let Some(c) = candidates::candidate_by_id(db, id).unwrap_or(None) else {
+ return not_found(state, req);
+ };
+ let identity = req.form_get("identity_hash").unwrap_or_default();
+ let digest = req.form_get("diff_digest").unwrap_or_default();
+ let note = req.form_get("note").filter(|s| !s.trim().is_empty());
+ match ap::approve(db, actor(state, req), id, &identity, &digest, note.as_deref()) {
+ Ok(a) => {
+ let mut page = chrome(state, req, "Reviews", "nav_reviews");
+ page.flash = format!("approved {} (approval {}); build queued", c.pkgbase, a.id);
+ page.has_flash = true;
+ match pipeline::enqueue_for_candidate(&state.cfg, db, &c) {
+ Ok(bid) => {
+ page.flash = format!("approved {}; build {} queued", c.pkgbase, short(&bid));
+ page.has_flash = true;
+ }
+ Err(e) => {
+ page.flash = format!("approved, but the build could not be queued: {e}");
+ page.has_flash = true;
+ page.flash_err = true;
+ }
+ }
+ page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 200)
+ }
+ Err(ap::ApproveError::System(e)) => {
+ // The database refused. Telling the reviewer their review went stale
+ // would be a lie about the one thing they cannot check themselves.
+ let mut page = chrome(state, req, "Review failed", "nav_reviews");
+ page.flash = format!("the approval could not be recorded: {e}");
+ page.has_flash = true;
+ page.flash_err = true;
+ page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 500)
+ }
+ Err(ap::ApproveError::Stale(stale)) => {
+ // §7.1a: refuse, re-render what it is now, and say why. Never
+ // silently retarget the approval onto the newer state.
+ let mut page = chrome(state, req, "Review changed", "nav_reviews");
+ page.flash = format!("refused: {stale}");
+ page.has_flash = true;
+ page.flash_err = true;
+ // Show the review as it stands NOW — the frozen one the form came
+ // from may have collapsed or been superseded while it was open.
+ let current = candidates::pending_candidates(db)
+ .unwrap_or_default()
+ .into_iter()
+ .find(|p| p.pkgbase_id == c.pkgbase_id)
+ .unwrap_or_else(|| c.clone());
+ let (head, panels, recipe, srcinfo, sources, deps) = review_body(state, &current);
+ let base = panels_base(&current);
+ page_to_res(
+ ReviewDetail {
+ page,
+ c: head,
+ base_version: base.0,
+ has_base: base.1,
+ panels,
+ recipe,
+ has_srcinfo: !srcinfo.is_empty(),
+ srcinfo,
+ sources_resolved: sources,
+ deps_resolved: deps,
+ },
+ 409,
+ )
+ }
+ }
+}
+
+pub(crate) fn review_reject(state: &State, req: &Req, id: &str) -> Res {
+ let db = &state.db;
+ let Some(id) = id.parse::<i64>().ok() else {
+ return not_found(state, req);
+ };
+ let Some(note) = req.form_get("note").filter(|s| !s.trim().is_empty()) else {
+ let mut page = chrome(state, req, "Review", "nav_reviews");
+ page.flash = "a rejection needs a reason: it is the only record of why".into();
+ page.has_flash = true;
+ page.flash_err = true;
+ return page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 400);
+ };
+ match ap::reject(db, actor(state, req), id, &note) {
+ Ok(()) => {
+ let mut page = chrome(state, req, "Reviews", "nav_reviews");
+ page.flash = format!("rejected #{id}; it can be re-opened from the package page");
+ page.has_flash = true;
+ page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 200)
+ }
+ Err(e) => {
+ let mut page = chrome(state, req, "Reviews", "nav_reviews");
+ page.flash = format!("could not reject: {e}");
+ page.has_flash = true;
+ page.flash_err = true;
+ page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 409)
+ }
+ }
+}
+
+/// Bulk approve/reject (§7.4): per-item, never "approve everything forever",
+/// and high-risk items are refused unless each was confirmed individually.
+pub(crate) fn reviews_bulk(state: &State, req: &Req) -> Res {
+ let db = &state.db;
+ let form = req.form();
+ let ids: Vec<i64> = form
+ .iter()
+ .filter(|(k, _)| k == "ids")
+ .filter_map(|(_, v)| v.parse().ok())
+ .collect();
+ let decision = form
+ .iter()
+ .find(|(k, _)| k == "decision")
+ .map(|(_, v)| v.clone())
+ .unwrap_or_default();
+ let confirmed: Vec<i64> = form
+ .iter()
+ .filter(|(k, _)| k == "confirm")
+ .filter_map(|(_, v)| v.parse().ok())
+ .collect();
+ if ids.is_empty() {
+ let mut page = chrome(state, req, "Reviews", "nav_reviews");
+ page.flash = "nothing selected".into();
+ page.has_flash = true;
+ page.flash_err = true;
+ return page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 400);
+ }
+ // The rule itself lives in `review::approve::bulk`, so the page and the
+ // library cannot disagree about what a bulk decision means (§7.4).
+ let items: Vec<(i64, String, String)> = ids
+ .iter()
+ .filter_map(|id| {
+ candidates::candidate_by_id(db, *id).ok().flatten().map(|c| (*id, c.identity_hash, c.diff_digest))
+ })
+ .collect();
+ let outcomes = match ap::bulk(db, actor(state, req), &items, &decision, &confirmed) {
+ Ok(outcomes) => outcomes,
+ Err(e) => {
+ let mut page = chrome(state, req, "Reviews", "nav_reviews");
+ page.flash = format!("the decisions could not be recorded: {e}");
+ page.has_flash = true;
+ page.flash_err = true;
+ return page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 500);
+ }
+ };
+ let mut done = Vec::new();
+ let mut refused = Vec::new();
+ for item in outcomes {
+ match &item.outcome {
+ ap::BulkOutcome::Approved(_) => {
+ if let Some(c) = &item.candidate {
+ let _ = pipeline::enqueue_for_candidate(&state.cfg, db, c);
+ done.push(c.pkgbase.clone());
+ }
+ }
+ ap::BulkOutcome::Rejected => done.push(item.pkgbase().to_string()),
+ ap::BulkOutcome::Refused(r) => refused.push(format!("{}: {r}", item.pkgbase())),
+ }
+ }
+ let mut page = chrome(state, req, "Reviews", "nav_reviews");
+ page.flash = format!(
+ "{}: {}{}",
+ if decision == "approve" { "approved" } else { "rejected" },
+ done.join(", "),
+ if refused.is_empty() { String::new() } else { format!(" — refused: {}", refused.join("; ")) }
+ );
+ page.has_flash = true;
+ page.flash_err = !refused.is_empty();
+ page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 200)
+}
+
+pub(crate) fn sub_add(state: &State, req: &Req) -> Res {
+ let db = &state.db;
+ let Some(name) = req.form_get("pkgbase").map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) else {
+ return flash_sub(state, req, "give a pkgbase name", true);
+ };
+ let rid = db::repo_id(db).unwrap_or(1);
+ let url = format!("https://aur.archlinux.org/{name}.git");
+ match db::subscribe(&db.writer, rid, &name, &url) {
+ Ok(_) => {
+ let _ = crate::watch::detect::check_pkgbase(&state.cfg, db, &name);
+ flash_sub(state, req, &format!("subscribed {name} and ran a first check"), false)
+ }
+ Err(e) => flash_sub(state, req, &format!("could not subscribe: {e}"), true),
+ }
+}
+
+pub(crate) fn sub_pause(state: &State, req: &Req) -> Res {
+ let db = &state.db;
+ let name = req.form_get("pkgbase").unwrap_or_default();
+ let cur = db::get_subscription(db, &name).ok().flatten().map(|s| s.state);
+ // Pause and resume are the only moves this page makes. A subscription that
+ // is orphaned or removed is not the reviewer's to pause, and saying so beats
+ // quietly rewriting its state.
+ let next = match cur {
+ Some(SubscriptionState::Active) => SubscriptionState::Paused,
+ Some(SubscriptionState::Paused) => SubscriptionState::Active,
+ Some(other) => return flash_sub(state, req, &format!("{name} is {other}: nothing to pause"), true),
+ None => return flash_sub(state, req, &format!("no subscription for {name}"), true),
+ };
+ let _ = db::set_subscription_state(&db.writer, &name, next);
+ flash_sub(state, req, &format!("{name}: {next}"), false)
+}
+
+pub(crate) fn sub_remove(state: &State, req: &Req) -> Res {
+ let db = &state.db;
+ let name = req.form_get("pkgbase").unwrap_or_default();
+ let _ = db::set_subscription_state(&db.writer, &name, SubscriptionState::Removed);
+ flash_sub(state, req, &format!("{name}: removed"), false)
+}
+
+pub(crate) fn notice_ack(state: &State, req: &Req) -> Res {
+ let id: i64 = req.form_get("id").and_then(|s| s.parse().ok()).unwrap_or(0);
+ let _ = db::acknowledge_notice(&state.db.writer, id);
+ // POST-redirect-GET: the notice vanishing from the list is its own
+ // confirmation, and a refresh can no longer re-POST.
+ Res::redirect("/attention")
+}
+
+pub(crate) fn package_rebuild(state: &State, req: &Req, name: &str) -> Res {
+ match pipeline::enqueue_manual_rebuild(&state.cfg, &state.db, name) {
+ Ok(id) => {
+ let mut page = chrome(state, req, "Builds", "nav_builds");
+ page.flash = format!(
+ "queued a rebuild of the approved version of {name} (build {}, no new approval needed)",
+ &id[..8.min(id.len())]
+ );
+ page.has_flash = true;
+ builds_with(state, req, page)
+ }
+ Err(e) => {
+ let mut page = chrome(state, req, "Index", "nav_packages");
+ page.flash = format!("could not queue a rebuild: {e}");
+ page.has_flash = true;
+ page.flash_err = true;
+ page_to_res(Packages { page, repo: state.cfg.repo_name.clone(), rows: vec![], snippet: String::new() }, 400)
+ }
+ }
+}
+
+pub(crate) fn package_withdraw(state: &State, req: &Req, name: &str) -> Res {
+ match pipeline::publish::withdraw_package(&state.cfg, &state.db, name) {
+ Ok(()) => Res::redirect("/packages"),
+ Err(e) => {
+ let mut page = chrome(state, req, "Index", "nav_packages");
+ page.flash = format!("withdrawal failed: {e}");
+ page.has_flash = true;
+ page.flash_err = true;
+ page_to_res(Packages { page, repo: state.cfg.repo_name.clone(), rows: vec![], snippet: String::new() }, 500)
+ }
+ }
+}
+
+pub(crate) fn build_cancel(state: &State, req: &Req, id: &str) -> Res {
+ let _ = builds::request_cancel(&state.db, id);
+ let mut page = chrome(state, req, "Builds", "nav_builds");
+ page.flash = format!("cancellation requested for {}; it stops at the next step boundary", short(id));
+ page.has_flash = true;
+ builds_with(state, req, page)
+}
+
+/// Retrying a failed build is an explicit, audited decision (§8.4), not
+/// something the system does to itself.
+pub(crate) fn build_retry(state: &State, req: &Req, id: &str) -> Res {
+ match builds::retry(&state.db, id) {
+ Ok(()) => {
+ let _ = db::audit(&state.db.writer, "web", "web", "build.retry", "build", id, serde_json::json!({}));
+ Res::redirect(&format!("/builds/{id}"))
+ }
+ Err(e) => {
+ let mut page = chrome(state, req, "Builds", "nav_builds");
+ page.flash = format!("could not retry: {e}");
+ page.has_flash = true;
+ page.flash_err = true;
+ builds_with(state, req, page)
+ }
+ }
+}
diff --git a/src/http/routes/pages.rs b/src/http/routes/pages.rs
new file mode 100644
index 0000000..dea7de0
--- /dev/null
+++ b/src/http/routes/pages.rs
@@ -0,0 +1,588 @@
+//! The read side of the UI: pages that only ever go through `db.read`.
+
+use crate::db::{self, builds, Db};
+use crate::review::{candidates, diff, risk};
+use crate::ops;
+use crate::http::{sse, Req, Res, State};
+
+use super::*;
+
+// ------------------------------------------------------------- dashboard --
+
+pub(crate) fn dashboard(state: &State, req: &Req) -> Res {
+ let db = &state.db;
+ let page = chrome(state, req, "Dashboard", "");
+ let publishes: Vec<PublishRow> = db::all_published_releases(db)
+ .unwrap_or_default()
+ .into_iter()
+ .take(15)
+ .filter_map(|r| {
+ let pb = db::get_pkgbase_by_id(db, r.pkgbase_id).ok().flatten()?;
+ Some(PublishRow {
+ name: pb.name,
+ version: r.version(),
+ published_at: r.published_at.unwrap_or_else(|| r.state.to_string()),
+ aur_commit: r.aur_commit.clone(),
+ aur_commit_short: short(&r.aur_commit),
+ })
+ })
+ .collect();
+ page_to_res(
+ Dashboard {
+ page,
+ subscriptions: db::list_subscriptions(db).map(|v| v.len() as i64).unwrap_or(0),
+ index_count: db::index_packages(db).map(|v| v.len() as i64).unwrap_or(0),
+ pending_reviews: candidates::pending_candidates(db).map(|v| v.len() as i64).unwrap_or(0),
+ running_builds: builds::in_flight(db).map(|v| v as i64).unwrap_or(0),
+ attention: db::list_notices(db, false).map(|v| v.len() as i64).unwrap_or(0),
+ publishes,
+ },
+ 200,
+ )
+}
+
+// ---------------------------------------------------------------- inbox --
+
+pub(crate) fn review_rows(db: &Db) -> Vec<ReviewRow> {
+ let mut rows: Vec<ReviewRow> = candidates::pending_candidates(db)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|c| ReviewRow {
+ id: c.id,
+ pkgbase: c.pkgbase.clone(),
+ version: full_version(&c),
+ kind: c.kind.clone(),
+ risk: c.risk_level.clone(),
+ signals: c.risk_signals(),
+ age: age(&c.detected_at),
+ revision: c.revision,
+ })
+ .collect();
+ // Risk first, then oldest — the scarcest resource gets the loudest rows.
+ let rank = |r: &str| match r {
+ risk::level::HIGH => 0,
+ risk::level::MEDIUM => 1,
+ _ => 2,
+ };
+ rows.sort_by_key(|r| (rank(&r.risk), r.age.clone(), r.id));
+ rows
+}
+
+pub(crate) fn reviews(state: &State, req: &Req) -> Res {
+ let page = chrome(state, req, "Reviews", "nav_reviews");
+ page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 200)
+}
+
+pub(crate) fn full_version(c: &CandidateRow) -> String {
+ crate::pkgver::full_version(&c.epoch, &c.pkgver, &c.pkgrel)
+}
+
+pub(crate) fn review_detail(state: &State, req: &Req, id: &str) -> Res {
+ let db = &state.db;
+ let Some(id) = id.parse::<i64>().ok() else {
+ return not_found(state, req);
+ };
+ let Some(c) = candidates::candidate_by_id(db, id).unwrap_or(None) else {
+ return not_found(state, req);
+ };
+ // Opening a review freezes it: a later detection now opens a fresh review
+ // instead of silently changing what is on screen (§7.1).
+ let _ = candidates::mark_viewed(db, id);
+ let page = chrome(state, req, &format!("Review {}", c.pkgbase), "nav_reviews");
+ let (head, panels, recipe, srcinfo, sources_resolved, deps_resolved) = review_body(state, &c);
+ let base = panels_base(&c);
+ page_to_res(
+ ReviewDetail {
+ page,
+ c: head,
+ base_version: base.0,
+ has_base: base.1,
+ panels,
+ recipe,
+ has_srcinfo: !srcinfo.is_empty(),
+ srcinfo,
+ sources_resolved,
+ deps_resolved,
+ },
+ 200,
+ )
+}
+
+pub(crate) fn panels_base(c: &CandidateRow) -> (String, bool) {
+ match c.base_release_id {
+ Some(_) => ("previous accepted release".into(), true),
+ None => ("nothing accepted yet".into(), false),
+ }
+}
+
+/// Build the review body: the panel set plus the first-introduction material.
+pub(crate) fn review_body(
+ state: &State,
+ c: &CandidateRow,
+) -> (ReviewHead, Vec<Panel>, String, String, String, String) {
+ let db = &state.db;
+ let base = match c.base_release_id {
+ Some(id) => db::release_by_id(db, id).unwrap_or(None),
+ None => None,
+ };
+ let panels = diff::panels(&state.cfg, db, c, base.as_ref()).unwrap_or_default();
+ let rendered = diff::render_text(&panels);
+ let _ = rendered;
+ let snapshot = db::snapshot_by_id(db, c.snapshot_id).unwrap_or(None);
+ let recipe_json = snapshot.as_ref().map(|s| s.srcinfo_json.clone()).unwrap_or_default();
+ let parsed: Option<Recipe> = serde_json::from_str(&recipe_json).ok();
+ let is_first = c.kind == candidate_kind::FIRST_INTRODUCTION;
+
+ let head = ReviewHead {
+ id: c.id,
+ pkgbase: c.pkgbase.clone(),
+ version: full_version(c),
+ kind: c.kind.clone(),
+ is_first,
+ risk: c.risk_level.clone(),
+ signals: c.risk_signals(),
+ missing_deps: c.missing_deps(),
+ dependents: crate::watch::staleness::dependents_of(db, &c.pkgbase).unwrap_or_default(),
+ revision: c.revision,
+ aur_commit: snapshot.as_ref().map(|s| s.aur_commit.clone()).unwrap_or_default(),
+ aur_commit_short: snapshot
+ .as_ref()
+ .map(|s| short(&s.aur_commit))
+ .unwrap_or_default(),
+ identity_hash: c.identity_hash.clone(),
+ diff_digest: c.diff_digest.clone(),
+ };
+ let shown: Vec<Panel> = panels
+ .iter()
+ .map(|p| Panel::new(p.title, p.body.clone()))
+ .collect();
+ let (recipe_text, srcinfo) = match &parsed {
+ Some(r) => (r.pkgbuild.clone(), r.srcinfo.clone().unwrap_or_default()),
+ None => (String::new(), String::new()),
+ };
+ let sources_resolved = serde_json::to_string_pretty(
+ &serde_json::from_str::<serde_json::Value>(&c.source_digests_json)
+ .unwrap_or_else(|_| serde_json::json!([])),
+ )
+ .unwrap_or_default();
+ let deps_resolved = parsed
+ .as_ref()
+ .map(|r| {
+ format!(
+ "depends: {}\nmakedepends: {}\ncheckdepends: {}\noptdepends: {}",
+ r.depends.join(", "),
+ r.makedepends.join(", "),
+ r.checkdepends.join(", "),
+ r.optdepends.join(", ")
+ )
+ })
+ .unwrap_or_default();
+ (head, shown, recipe_text, srcinfo, sources_resolved, deps_resolved)
+}
+
+// -------------------------------------------------------- subscriptions --
+
+pub(crate) fn subscriptions(state: &State, req: &Req) -> Res {
+ let db = &state.db;
+ let page = chrome(state, req, "Subscriptions", "nav_subscriptions");
+ let pending = candidates::pending_candidates(db).unwrap_or_default();
+ let rows = db::list_subscriptions(db)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|s| SubRow {
+ pending: pending.iter().filter(|c| c.pkgbase == s.pkgbase).count() as i64,
+ name: s.pkgbase.clone(),
+ state: s.state.to_string(),
+ maintainer: s.maintainer.unwrap_or_else(|| "unknown".into()),
+ last_checked: s.last_checked_at.unwrap_or_else(|| "never".into()),
+ next_check: s.next_check_at.unwrap_or_else(|| "soon".into()),
+ last_error: s.last_error.clone().unwrap_or_default(),
+ has_error: s.last_error.is_some(),
+ pause_label: if s.state == SubscriptionState::Paused { "resume" } else { "pause" },
+ })
+ .collect();
+ page_to_res(Subscriptions { page, rows }, 200)
+}
+
+// ------------------------------------------------------------ attention --
+
+pub(crate) fn attention(state: &State, req: &Req) -> Res {
+ let db = &state.db;
+ let page = chrome(state, req, "Attention", "nav_attention");
+ let notices = db::list_notices(db, false)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|n| NoticeRow {
+ id: n.id,
+ pkgbase: n.pkgbase.clone(),
+ kind: n.kind.clone(),
+ severity: n.severity.clone(),
+ detail: n.detail_json.clone(),
+ created_at: n.created_at.clone(),
+ })
+ .collect::<Vec<NoticeRow>>();
+ let blocked: Vec<BlockedRow> = builds::blocked_builds(db)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|(id, pkgbase, blocked_on)| BlockedRow { id_short: short(&id), id, pkgbase, blocked_on })
+ .collect();
+ // Staleness is computed on read (P4 fills the query in).
+ let stale = crate::watch::staleness::stale_rows(db).unwrap_or_default();
+ let outdated: Vec<StaleRow> = stale
+ .iter()
+ .filter(|s| s.kind == crate::watch::staleness::Kind::Outdated)
+ .cloned()
+ .map(|s| StaleRow { pkgbase: s.pkgbase, dependency: s.dependency, built_with: s.built_with, now: s.now })
+ .collect();
+ let missing: Vec<StaleRow> = stale
+ .iter()
+ .filter(|s| s.kind == crate::watch::staleness::Kind::Missing)
+ .cloned()
+ .map(|s| StaleRow { pkgbase: s.pkgbase, dependency: s.dependency, built_with: s.built_with, now: s.now })
+ .collect();
+ let downgrades: Vec<StaleRow> = crate::watch::staleness::downgrades(db)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|s| StaleRow { pkgbase: s.pkgbase, dependency: s.dependency, built_with: s.built_with, now: s.now })
+ .collect();
+ let unbuilt: Vec<UnbuiltRow> = db::approved_but_unbuilt(db)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|u| UnbuiltRow {
+ pkgbase: u.pkgbase,
+ approved: u.approved,
+ serving: u.serving,
+ error: u.error,
+ build_id: u.build_id,
+ })
+ .collect();
+ let empty = notices.is_empty()
+ && unbuilt.is_empty()
+ && outdated.is_empty()
+ && missing.is_empty()
+ && blocked.is_empty();
+ page_to_res(
+ Attention { page, empty, notices, unbuilt, outdated, missing, downgrades, blocked },
+ 200,
+ )
+}
+
+// ------------------------------------------------------------- packages --
+
+pub(crate) fn packages(state: &State, req: &Req) -> Res {
+ let db = &state.db;
+ let page = chrome(state, req, "Index", "nav_packages");
+ let rows: Vec<IndexRow> = db::index_packages(db)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|p| IndexRow {
+ name: p.name.clone(),
+ version: p.version.clone(),
+ arch: p.arch.clone(),
+ size: p.size.map(human_size).unwrap_or_else(|| "—".into()),
+ published_at: p.published_at.clone().unwrap_or_else(|| "—".into()),
+ })
+ .collect();
+ let snippet = format!(
+ "[{}]\nServer = {}/$repo/os/$arch\nSigLevel = Required DatabaseOptional",
+ state.cfg.repo_name, state.cfg.base_url
+ );
+ page_to_res(Packages { page, repo: state.cfg.repo_name.clone(), rows, snippet }, 200)
+}
+
+pub(crate) fn package_detail(state: &State, req: &Req, name: &str) -> Res {
+ let db = &state.db;
+ let page = chrome(state, req, name, "nav_packages");
+ let Some(pb) = db::get_pkgbase(db, name).unwrap_or(None) else {
+ return not_found(state, req);
+ };
+ let releases = db::releases_for_pkgbase(db, pb.id, 20).unwrap_or_default();
+ let accepted = db::accepted_release(db, name).unwrap_or(None);
+ let timeline: Vec<TimelineRow> = releases
+ .into_iter()
+ .map(|r| TimelineRow {
+ version: r.version(),
+ state: r.state.to_string(),
+ aur_commit: r.aur_commit.clone(),
+ aur_commit_short: short(&r.aur_commit),
+ published_at: r.published_at.unwrap_or_else(|| "—".into()),
+ approver: r
+ .approval_id
+ .and_then(|aid| db::approval_note(db, aid).ok().filter(|s| !s.is_empty()))
+ .filter(|s| !s.is_empty())
+ .unwrap_or_else(|| "—".into()),
+ })
+ .collect();
+ let builds: Vec<BuildLite> = db::builds_for_pkgbase(db, pb.id, 10)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|b| BuildLite {
+ id_short: short(&b.id),
+ id: b.id,
+ kind: b.kind,
+ state: b.state.to_string(),
+ step: b.current_step.unwrap_or_default(),
+ })
+ .collect();
+ // Depends-on comes from the recipe we actually serve; needed-by comes from
+ // the packages whose own recipes name this one (§10.3).
+ let deps_in: Vec<String> = accepted
+ .as_ref()
+ .and_then(|r| db::accepted_recipe(db, r).ok().flatten())
+ .map(|r| {
+ let mut v = crate::pkgver::dep_names(&r.depends);
+ v.sort();
+ v.dedup();
+ v
+ })
+ .unwrap_or_default();
+ let deps_out: Vec<String> = crate::watch::staleness::dependents_of(db, name).unwrap_or_default();
+ let stale: Vec<String> = crate::watch::staleness::stale_for(db, name)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|s| format!("{} was built against {} but the index has {}", s.pkgbase, s.built_with, s.now))
+ .collect();
+ let summary = match &accepted {
+ Some(r) => format!("serving {} · approved from aur_commit {}", r.version(), short(&r.aur_commit)),
+ None => "nothing published yet".into(),
+ };
+ let unbuilt: Vec<UnbuiltRow> = db::approved_but_unbuilt(db)
+ .unwrap_or_default()
+ .into_iter()
+ .filter(|u| u.pkgbase == name)
+ .map(|u| UnbuiltRow {
+ pkgbase: u.pkgbase,
+ approved: u.approved,
+ serving: u.serving,
+ error: u.error,
+ build_id: u.build_id,
+ })
+ .collect();
+ page_to_res(
+ PackageDetail {
+ page,
+ name: name.to_string(),
+ summary,
+ can_withdraw: accepted.is_some(),
+ unbuilt,
+ stale,
+ deps_in,
+ deps_out,
+ timeline,
+ builds,
+ },
+ 200,
+ )
+}
+
+// --------------------------------------------------------------- builds --
+
+/// The version a build is about. A build points at a candidate, or — for a
+/// manual rebuild of something already published — at a release.
+pub(crate) fn build_version(db: &Db, b: &builds::BuildRow) -> String {
+ if let Some(cid) = b.candidate_id {
+ if let Some(c) = candidates::candidate_by_id(db, cid).ok().flatten() {
+ return c.version();
+ }
+ }
+ if let Some(rid) = b.release_id {
+ if let Some(r) = db::release_by_id(db, rid).ok().flatten() {
+ return r.version();
+ }
+ }
+ String::new()
+}
+
+pub(crate) fn build_rows(state: &State) -> Vec<BuildRow> {
+ builds::list(
+ &state.db,
+ BuildState::active(),
+ 100,
+ )
+ .unwrap_or_default()
+ .into_iter()
+ .map(|b| {
+ let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id)
+ .ok()
+ .flatten()
+ .map(|p| p.name)
+ .unwrap_or_default();
+ let version = build_version(&state.db, &b);
+ BuildRow {
+ id_short: short(&b.id),
+ id: b.id,
+ pkgbase,
+ version,
+ kind: b.kind,
+ state: b.state.to_string(),
+ step: b.current_step.unwrap_or_default(),
+ lease: b.lease_expires_at.unwrap_or_else(|| "—".into()),
+ cancel: b.cancel_requested,
+ error: b.error.unwrap_or_default(),
+ }
+ })
+ .collect()
+}
+
+pub(crate) fn builds_page(state: &State, req: &Req) -> Res {
+ let page = chrome(state, req, "Builds", "nav_builds");
+ // htmx asks for the fragment; a browser with JavaScript off never does and
+ // gets the whole page either way (§13).
+ if req.query_get("fragment").as_deref() == Some("1") {
+ return page_to_res(
+ BuildsTable { page, rows: build_rows(state), recent: recent_rows(state) },
+ 200,
+ );
+ }
+ builds_with(state, req, page)
+}
+
+pub(crate) fn recent_rows(state: &State) -> Vec<BuildRow> {
+ builds::list(&state.db, &[BuildState::Failed, BuildState::Succeeded], 10)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|b| {
+ let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id).ok().flatten().map(|p| p.name).unwrap_or_default();
+ let version = build_version(&state.db, &b);
+ BuildRow {
+ id_short: short(&b.id),
+ id: b.id,
+ pkgbase,
+ version,
+ kind: b.kind,
+ state: b.state.to_string(),
+ step: b.current_step.unwrap_or_default(),
+ lease: String::new(),
+ cancel: b.cancel_requested,
+ error: b.error.unwrap_or_default(),
+ }
+ })
+ .collect()
+}
+
+pub(crate) fn builds_with(state: &State, _req: &Req, page: Page) -> Res {
+ page_to_res(Builds { page, rows: build_rows(state), recent: recent_rows(state) }, 200)
+}
+
+pub(crate) fn build_detail(state: &State, req: &Req, id: &str) -> Res {
+ let db = &state.db;
+ let Some(b) = builds::get(db, id).unwrap_or(None) else {
+ return not_found(state, req);
+ };
+ let page = chrome(state, req, "Build", "nav_builds");
+ let steps: Vec<StepRow> = builds::steps(db, id)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|s| {
+ let cls = if s.status == StepState::Failed { "risk-high" } else { "mut" }.to_string();
+ StepRow {
+ step: s.step,
+ status: s.status.to_string(),
+ attempt: s.attempt,
+ digest: String::new(),
+ cls,
+ error: s.error.unwrap_or_default(),
+ }
+ })
+ .collect();
+ let log_path = state.cfg.build_log_path(id);
+ let all = std::fs::read_to_string(&log_path).unwrap_or_default();
+ let lines: Vec<&str> = all.lines().collect();
+ let tail = lines[lines.len().saturating_sub(200)..].join("\n");
+ let blocked_on: Vec<String> = serde_json::from_str(&b.blocked_on_json).unwrap_or_default();
+ let pkgbase = db::get_pkgbase_by_id(db, b.pkgbase_id).ok().flatten().map(|p| p.name).unwrap_or_default();
+ page_to_res(
+ BuildDetail {
+ page,
+ id: id.to_string(),
+ id_short: short(id),
+ pkgbase,
+ version: build_version(db, &b),
+ kind: b.kind,
+ state: b.state.to_string(),
+ error: b.error.clone().unwrap_or_default(),
+ blocked_on,
+ steps,
+ log: tail,
+ log_lines: lines.len().min(200),
+ log_truncated: lines.len() > 200,
+ },
+ 200,
+ )
+}
+
+pub(crate) fn build_log(state: &State, id: &str) -> Res {
+ let body = std::fs::read_to_string(state.cfg.build_log_path(id)).unwrap_or_default();
+ Res::text(200, body)
+}
+
+/// The live tail (§13). Server-sent events from a blocking reader: the pipeline
+/// appends to a file and never learns this connection exists, so a viewer that
+/// hangs up, stalls or never shows up cannot slow a build.
+pub(crate) fn build_log_stream(state: &State, req: &Req, id: &str) -> Res {
+ if builds::get(&state.db, id).unwrap_or(None).is_none() {
+ return not_found(state, req);
+ }
+ let tail = sse::LogTail::new(&state.cfg, state.db.clone(), id);
+ let mut res = Res::stream("text/event-stream", tail, None);
+ // No caching, and no proxy buffering: a buffered event stream is a log tail
+ // that arrives all at once, which is the thing we are trying to avoid.
+ res.header("Cache-Control", "no-cache");
+ res.header("X-Accel-Buffering", "no");
+ res
+}
+
+// ----------------------------------------------------------- ops, config --
+
+pub(crate) fn audit(state: &State, req: &Req) -> Res {
+ let page = chrome(state, req, "Ops", "nav_audit");
+ let rows = db::list_audit(&state.db, 200)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|a| AuditRow {
+ at: a.at,
+ actor_kind: a.actor_kind,
+ actor: a.actor,
+ action: a.action,
+ entity: a.entity,
+ entity_id: a.entity_id,
+ detail: a.detail_json,
+ })
+ .collect();
+ page_to_res(Audit { page, rows }, 200)
+}
+
+/// `GET /metrics` in Prometheus text exposition format (§12, §15).
+///
+/// Everything here is computed from live state on every scrape. There are no
+/// counters incremented at event sites, because a counter that has to be
+/// maintained by every code path is a counter that quietly drifts the first time
+/// a path is added; a query cannot drift.
+pub fn metrics(state: &State) -> Res {
+ match ops::metrics(&state.cfg, &state.db) {
+ Ok(m) => {
+ let mut res = Res::text(200, m.to_prometheus());
+ res.content_type = "text/plain; version=0.0.4; charset=utf-8".into();
+ res
+ }
+ Err(e) => Res::text(500, format!("metrics unavailable: {e}\n")),
+ }
+}
+
+pub(crate) fn settings(state: &State, req: &Req) -> Res {
+ let page = chrome(state, req, "Settings", "nav_settings");
+ let rows = db::all_settings(&state.db)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|(key, value)| SettingRow { key, value })
+ .collect();
+ let repo = format!(
+ "name: {}\narch: {}\npath: {}\nsigning key: {}\nbind: {}",
+ state.cfg.repo_name,
+ state.cfg.arch,
+ state.cfg.repo_arch_dir().display(),
+ if state.cfg.signing_key_id.is_empty() { "none (unsigned!)" } else { &state.cfg.signing_key_id },
+ state.cfg.bind
+ );
+ page_to_res(Settings { page, rows, repo }, 200)
+}