summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/http/routes/mutations.rs91
-rw-r--r--src/lib.rs1
-rw-r--r--src/main.rs141
-rw-r--r--src/usecase/bootstrap.rs58
-rw-r--r--src/usecase/builds.rs46
-rw-r--r--src/usecase/detect.rs41
-rw-r--r--src/usecase/maintenance.rs43
-rw-r--r--src/usecase/mod.rs35
-rw-r--r--src/usecase/reviews.rs122
-rw-r--r--src/usecase/subscriptions.rs50
-rw-r--r--tests/architecture-budget.json75
-rw-r--r--tests/architecture.rs21
12 files changed, 536 insertions, 188 deletions
diff --git a/src/http/routes/mutations.rs b/src/http/routes/mutations.rs
index 2af8b7f..ad11dfa 100644
--- a/src/http/routes/mutations.rs
+++ b/src/http/routes/mutations.rs
@@ -1,7 +1,6 @@
-use crate::db::{self, builds};
-use crate::review::{approve as ap, candidates};
-use crate::pipeline;
use crate::http::{Req, Res, State};
+use crate::review::candidates;
+use crate::usecase;
use super::*;
@@ -18,32 +17,29 @@ pub(crate) fn review_approve(state: &State, req: &Req, id: &str) -> Res {
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) => {
+ // The same workflow the CLI runs: record the decision, then queue what it
+ // authorises. Only the rendering differs from here down.
+ match usecase::approve(&state.cfg, db, actor(state, req), &c, &identity, &digest, note.as_deref()) {
+ Ok(usecase::Approval::Recorded(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;
- }
+ match a.queued {
+ Ok(bid) => page.flash = format!("approved {}; build {} queued", c.pkgbase, short(&bid)),
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)) => {
+ Err(e) => {
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)) => {
+ Ok(usecase::Approval::Refused(stale)) => {
let mut page = chrome(state, req, "Review changed", "nav_reviews");
page.flash = format!("refused: {stale}");
page.has_flash = true;
@@ -86,7 +82,7 @@ pub(crate) fn review_reject(state: &State, req: &Req, id: &str) -> Res {
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) {
+ match usecase::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");
@@ -134,7 +130,7 @@ pub(crate) fn reviews_bulk(state: &State, req: &Req) -> Res {
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) {
+ let decisions = match usecase::bulk(&state.cfg, db, actor(state, req), &items, &decision, &confirmed) {
Ok(outcomes) => outcomes,
Err(e) => {
let mut page = chrome(state, req, "Reviews", "nav_reviews");
@@ -146,16 +142,11 @@ pub(crate) fn reviews_bulk(state: &State, req: &Req) -> Res {
};
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())),
+ for d in decisions {
+ match d {
+ usecase::Decision::Approved { pkgbase, .. } => done.push(pkgbase),
+ usecase::Decision::Rejected { pkgbase } => done.push(pkgbase),
+ usecase::Decision::Refused { pkgbase, why } => refused.push(format!("{pkgbase}: {why}")),
}
}
let mut page = chrome(state, req, "Reviews", "nav_reviews");
@@ -175,12 +166,12 @@ pub(crate) fn sub_add(state: &State, req: &Req) -> Res {
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)
+ match usecase::subscribe(db, &name, None) {
+ Ok(s) => {
+ // A subscription nobody has checked yet looks identical to one that
+ // is simply up to date, so the first detection is part of adding it.
+ let _ = usecase::check(&state.cfg, db, &s.pkgbase);
+ flash_sub(state, req, &format!("subscribed {} and ran a first check", s.pkgbase), false)
}
Err(e) => flash_sub(state, req, &format!("could not subscribe: {e}"), true),
}
@@ -189,32 +180,31 @@ pub(crate) fn sub_add(state: &State, req: &Req) -> Res {
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);
- 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)
+ match usecase::toggle_pause(db, &name) {
+ Ok(usecase::Pause::Now(next)) => flash_sub(state, req, &format!("{name}: {next}"), false),
+ Ok(usecase::Pause::NotApplicable(other)) => {
+ flash_sub(state, req, &format!("{name} is {other}: nothing to pause"), true)
+ }
+ Ok(usecase::Pause::Unknown) | Err(_) => {
+ flash_sub(state, req, &format!("no subscription for {name}"), true)
+ }
+ }
}
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);
+ let _ = usecase::unsubscribe(&state.db, &name);
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);
+ let _ = usecase::acknowledge_notice(&state.db, id);
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) {
+ match usecase::manual_rebuild(&state.cfg, &state.db, name) {
Ok(id) => {
let mut page = chrome(state, req, "Builds", "nav_builds");
page.flash = format!(
@@ -235,7 +225,7 @@ pub(crate) fn package_rebuild(state: &State, req: &Req, name: &str) -> Res {
}
pub(crate) fn package_withdraw(state: &State, req: &Req, name: &str) -> Res {
- match pipeline::publish::withdraw_package(&state.cfg, &state.db, name) {
+ match usecase::withdraw_package(&state.cfg, &state.db, name) {
Ok(()) => Res::redirect("/packages"),
Err(e) => {
let mut page = chrome(state, req, "Index", "nav_packages");
@@ -248,7 +238,7 @@ pub(crate) fn package_withdraw(state: &State, req: &Req, name: &str) -> Res {
}
pub(crate) fn build_cancel(state: &State, req: &Req, id: &str) -> Res {
- let _ = builds::request_cancel(&state.db, id);
+ let _ = usecase::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;
@@ -256,11 +246,8 @@ pub(crate) fn build_cancel(state: &State, req: &Req, id: &str) -> Res {
}
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}"))
- }
+ match usecase::retry(&state.db, "web", id) {
+ Ok(()) => Res::redirect(&format!("/builds/{id}")),
Err(e) => {
let mut page = chrome(state, req, "Builds", "nav_builds");
page.flash = format!("could not retry: {e}");
diff --git a/src/lib.rs b/src/lib.rs
index db3f2d1..f10aa96 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -16,6 +16,7 @@ pub mod sandbox;
pub mod shims;
pub mod time;
pub mod urlutil;
+pub mod usecase;
pub mod watch;
pub use error::{Error, Result};
diff --git a/src/main.rs b/src/main.rs
index 1686680..118d06e 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -5,7 +5,8 @@ use clap::{Parser, Subcommand};
use aur_build::config::Config;
use aur_build::db::{self, builds, model::*};
use aur_build::pipeline;
-use aur_build::review::{approve as ap, candidates, diff};
+use aur_build::review::candidates;
+use aur_build::usecase;
#[derive(Parser)]
#[command(name = "aur-build", version, about = "AUR build server: nothing is published that a human did not approve")]
@@ -95,21 +96,10 @@ fn main() -> anyhow::Result<()> {
if let Some(b) = bind {
cfg.bind = b.clone();
}
- cfg.ensure_dirs()?;
- db::migrate(&cfg.db_path())?;
- let db = db::Db::open_migrated(&cfg.db_path())?;
- db::ensure_repo(
- &db.writer,
- &cfg.repo_name,
- &cfg.repo_arch_dir().display().to_string(),
- &cfg.arch,
- &cfg.signing_key_id,
- )?;
- let _ = pipeline::publish::reconcile(&cfg, &db);
- let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
- aur_build::watch::scheduler::spawn_scheduler(std::sync::Arc::new(cfg.clone()), db.clone(), stop.clone());
- let _server = aur_build::http::spawn(cfg.clone(), db.clone())?;
- let _pool = aur_build::pipeline::dispatch::Pool::spawn(std::sync::Arc::new(cfg.clone()), db.clone());
+ let db = usecase::serve(&cfg)?;
+ // Starting the UI is the composition root's job: nothing below it may
+ // know the UI exists.
+ let _server = aur_build::http::spawn(cfg.clone(), db)?;
println!("serving on http://{} — ctrl-c to stop", cfg.bind);
loop {
std::thread::sleep(std::time::Duration::from_secs(3600));
@@ -126,46 +116,26 @@ fn main() -> anyhow::Result<()> {
if let Some(k) = signing_key {
cfg.signing_key_id = k;
}
- cfg.save()?;
- cfg.ensure_dirs()?;
- db::migrate(&cfg.db_path())?;
- let db = db::Db::open_migrated(&cfg.db_path())?;
- let rid = db::ensure_repo(
- &db.writer,
- &cfg.repo_name,
- &cfg.repo_arch_dir().display().to_string(),
- &cfg.arch,
- &cfg.signing_key_id,
- )?;
+ let rid = usecase::init(&cfg)?;
println!("initialized {} (repo id {rid})", cfg.root.display());
println!("add to pacman.conf:\n [{}]\n Server = {}/$repo/os/$arch", cfg.repo_name, cfg.base_url);
Ok(())
}
Cmd::Subscribe { pkgbase, url } => {
- let rid = db::repo_id(&ctx.db)?;
- let url = url.unwrap_or_else(|| format!("https://aur.archlinux.org/{pkgbase}.git"));
- db::subscribe(&ctx.db.writer, rid, &pkgbase, &url)?;
- println!("subscribed {pkgbase} ({url})");
+ let s = usecase::subscribe(&ctx.db, &pkgbase, url)?;
+ println!("subscribed {} ({})", s.pkgbase, s.url);
Ok(())
}
Cmd::Unsubscribe { pkgbase } => {
- db::set_subscription_state(&ctx.db.writer, &pkgbase, SubscriptionState::Removed)?;
+ usecase::unsubscribe(&ctx.db, &pkgbase)?;
println!("unsubscribed {pkgbase}");
Ok(())
}
Cmd::Detect { pkgbase } => {
- let names: Vec<String> = match pkgbase {
- Some(n) => vec![n],
- None => db::list_subscriptions(&ctx.db)?
- .into_iter()
- .filter(|s| s.state == SubscriptionState::Active)
- .map(|s| s.pkgbase)
- .collect(),
- };
- for n in names {
- match aur_build::watch::detect::check_pkgbase(&cfg, &ctx.db, &n) {
- Ok(r) => println!("{n}: {:?}", r.outcome),
- Err(e) => eprintln!("{n}: {e}"),
+ for c in usecase::detect(&cfg, &ctx.db, pkgbase)? {
+ match c.outcome {
+ Ok(o) => println!("{}: {:?}", c.pkgbase, o),
+ Err(e) => eprintln!("{}: {e}", c.pkgbase),
}
}
Ok(())
@@ -193,60 +163,59 @@ fn main() -> anyhow::Result<()> {
Ok(())
}
Cmd::Show { candidate } => {
- let c = need_candidate(&ctx.db, candidate)?;
- let (text, digest) = diff::render_current(&ctx.db, &cfg, &c)?;
- candidates::set_diff_digest(&ctx.db, c.id, &digest)?;
- candidates::mark_viewed(&ctx.db, c.id)?;
- println!("{text}");
+ let Some(p) = usecase::view_review(&cfg, &ctx.db, candidate)? else {
+ return Err(anyhow::anyhow!("no candidate #{candidate}"));
+ };
+ println!("{}", p.text);
println!("---");
- println!("identity_hash: {}", c.identity_hash);
- println!("diff_digest: {digest}");
- println!("approve with: aur-build approve {} --yes", c.id);
+ println!("identity_hash: {}", p.candidate.identity_hash);
+ println!("diff_digest: {}", p.digest);
+ println!("approve with: aur-build approve {} --yes", p.candidate.id);
Ok(())
}
Cmd::Approve { candidate, yes, note, identity, diff: diff_arg } => {
- let c = need_candidate(&ctx.db, candidate)?;
- let (text, digest) = diff::render_current(&ctx.db, &cfg, &c)?;
- candidates::set_diff_digest(&ctx.db, c.id, &digest)?;
- let identity = identity.unwrap_or_else(|| c.identity_hash.clone());
- let diff_arg = diff_arg.unwrap_or(digest);
- println!("{text}");
+ let Some(p) = usecase::prepare_review(&cfg, &ctx.db, candidate)? else {
+ return Err(anyhow::anyhow!("no candidate #{candidate}"));
+ };
+ let identity = identity.unwrap_or_else(|| p.candidate.identity_hash.clone());
+ let diff_arg = diff_arg.unwrap_or(p.digest);
+ println!("{}", p.text);
println!("---");
if !yes {
println!("not approved: re-run with --yes to approve exactly this");
return Ok(());
}
let who = whoami();
- match ap::approve(&ctx.db, &who, c.id, &identity, &diff_arg, note.as_deref()) {
- Ok(a) => {
- println!("approved #{} (approval {})", c.id, a.id);
- let id = pipeline::enqueue_for_candidate(&cfg, &ctx.db, &c)?;
+ match usecase::approve(&cfg, &ctx.db, &who, &p.candidate, &identity, &diff_arg, note.as_deref())? {
+ usecase::Approval::Recorded(a) => {
+ println!("approved #{} (approval {})", p.candidate.id, a.approval.id);
+ let id = a.queued?;
println!("queued build {id}");
println!("run it with: aur-build run {id}");
Ok(())
}
- Err(ap::ApproveError::Stale(stale)) => {
+ usecase::Approval::Refused(stale) => {
eprintln!("refused: {stale}");
std::process::exit(2)
}
- Err(ap::ApproveError::System(e)) => Err(e.into()),
}
}
Cmd::Reject { candidate, note } => {
- let c = need_candidate(&ctx.db, candidate)?;
let who = whoami();
- ap::reject(&ctx.db, &who, c.id, &note)?;
- println!("rejected #{}", c.id);
+ usecase::reject(&ctx.db, &who, candidate, &note)?;
+ println!("rejected #{candidate}");
Ok(())
}
Cmd::Build { candidate } => {
- let c = need_candidate(&ctx.db, candidate)?;
- let id = pipeline::enqueue_for_candidate(&cfg, &ctx.db, &c)?;
+ let Some(c) = candidates::candidate_by_id(&ctx.db, candidate)? else {
+ return Err(anyhow::anyhow!("no candidate #{candidate}"));
+ };
+ let id = usecase::enqueue_candidate(&cfg, &ctx.db, &c)?;
println!("queued build {id}");
Ok(())
}
Cmd::Rebuild { pkgbase } => {
- let id = pipeline::enqueue_manual_rebuild(&cfg, &ctx.db, &pkgbase)?;
+ let id = usecase::manual_rebuild(&cfg, &ctx.db, &pkgbase)?;
println!("queued rebuild {id}");
Ok(())
}
@@ -297,21 +266,19 @@ fn main() -> anyhow::Result<()> {
Ok(())
}
Cmd::Gc { keep, dry_run } => {
- let keep = keep.unwrap_or(aur_build::ops::DEFAULT_KEEP);
if dry_run {
- let (kept, evict) = aur_build::ops::plan_retention(&ctx.db, keep)?;
- println!("retention: keep {keep} version(s) per pkgbase");
- println!(" {} release(s) keep their files", kept.len());
- for e in evict {
- let files = aur_build::ops::release_files(&cfg, &ctx.db, e.release_id)?;
- println!(" release {} would lose {} file(s)", e.release_id, files.len());
+ let plan = usecase::plan_gc(&cfg, &ctx.db, keep)?;
+ println!("retention: keep {} version(s) per pkgbase", plan.keep);
+ println!(" {} release(s) keep their files", plan.kept);
+ for (release_id, files) in plan.evicting {
+ println!(" release {} would lose {} file(s)", release_id, files.len());
for f in files {
println!(" {}", f.display());
}
}
return Ok(());
}
- let r = aur_build::ops::retention(&cfg, &ctx.db, Some(keep))?;
+ let r = usecase::run_gc(&cfg, &ctx.db, keep)?;
println!(
"kept {} release(s), evicted {}, removed {} file(s), freed {} bytes, swept {} staging dir(s)",
r.releases_kept, r.releases_evicted, r.files_removed, r.bytes_freed, r.staging_swept
@@ -319,7 +286,7 @@ fn main() -> anyhow::Result<()> {
Ok(())
}
Cmd::Backup { to } => {
- let path = aur_build::ops::backup(&ctx.db, &to)?;
+ let path = usecase::backup(&ctx.db, &to)?;
println!(
"wrote {} bytes to {} (VACUUM INTO, single file, no WAL)",
std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0),
@@ -336,17 +303,7 @@ struct Ctx {
impl Ctx {
fn open(cfg: &Config) -> anyhow::Result<Self> {
- cfg.ensure_dirs()?;
- db::migrate(&cfg.db_path())?;
- let db = db::Db::open_migrated(&cfg.db_path())?;
- db::ensure_repo(
- &db.writer,
- &cfg.repo_name,
- &cfg.repo_arch_dir().display().to_string(),
- &cfg.arch,
- &cfg.signing_key_id,
- )?;
- Ok(Self { db })
+ Ok(Self { db: usecase::open(cfg)? })
}
}
@@ -354,7 +311,3 @@ fn whoami() -> String {
std::env::var("USER").or_else(|_| std::env::var("USERNAME")).unwrap_or_else(|_| "cli".into())
}
-fn need_candidate(db: &db::Db, id: i64) -> anyhow::Result<CandidateRow> {
- candidates::candidate_by_id(db, id)?
- .ok_or_else(|| anyhow::anyhow!("no candidate #{id}"))
-}
diff --git a/src/usecase/bootstrap.rs b/src/usecase/bootstrap.rs
new file mode 100644
index 0000000..6793076
--- /dev/null
+++ b/src/usecase/bootstrap.rs
@@ -0,0 +1,58 @@
+//! Bringing a repository up, which every command does and every front end
+//! used to write out for itself.
+
+use std::sync::atomic::AtomicBool;
+use std::sync::Arc;
+
+use crate::config::Config;
+use crate::db::{self, Db};
+use crate::error::Result;
+use crate::pipeline;
+
+/// Directories exist, the schema is current, and the repo row is present.
+///
+/// Four calls in an order that matters — migrate before open, `ensure_repo`
+/// before anything reads `repo_id` — which is precisely the kind of sequence
+/// that quietly rots when it is copied.
+pub fn open(cfg: &Config) -> Result<Db> {
+ open_and_ensure(cfg).map(|(db, _)| db)
+}
+
+/// `open`, plus the id of the row named by `cfg.repo_name` — which is what
+/// `init` prints, and is not necessarily the lowest repo id if a root ever
+/// holds more than one repo.
+fn open_and_ensure(cfg: &Config) -> Result<(Db, i64)> {
+ cfg.ensure_dirs()?;
+ db::migrate(&cfg.db_path())?;
+ let db = Db::open_migrated(&cfg.db_path())?;
+ let rid = db::ensure_repo(
+ &db.writer,
+ &cfg.repo_name,
+ &cfg.repo_arch_dir().display().to_string(),
+ &cfg.arch,
+ &cfg.signing_key_id,
+ )?;
+ Ok((db, rid))
+}
+
+/// A first run: persist the config, bring the repository up, and hand back the
+/// repo id so the operator can paste it into `pacman.conf`.
+pub fn init(cfg: &Config) -> Result<i64> {
+ cfg.save()?;
+ open_and_ensure(cfg).map(|(_, rid)| rid)
+}
+
+/// Everything `serve` does before control passes to the UI: bring the
+/// repository up, finish anything a previous run left half-published, and start
+/// the two background loops.
+///
+/// The HTTP server is deliberately not started here. This module sits below the
+/// UI and must not be able to name it.
+pub fn serve(cfg: &Config) -> Result<Db> {
+ let db = open(cfg)?;
+ let _ = pipeline::publish::reconcile(cfg, &db);
+ let stop = Arc::new(AtomicBool::new(false));
+ crate::watch::scheduler::spawn_scheduler(Arc::new(cfg.clone()), db.clone(), stop.clone());
+ let _pool = pipeline::dispatch::Pool::spawn(Arc::new(cfg.clone()), db.clone());
+ Ok(db)
+}
diff --git a/src/usecase/builds.rs b/src/usecase/builds.rs
new file mode 100644
index 0000000..c947742
--- /dev/null
+++ b/src/usecase/builds.rs
@@ -0,0 +1,46 @@
+//! Getting a build queued, cancelled, retried, or unpublished.
+
+use crate::config::Config;
+use crate::db::{self, builds, CandidateRow, Db};
+use crate::error::Result;
+use crate::pipeline;
+
+/// Queue a build for an approved candidate.
+pub fn enqueue_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result<String> {
+ pipeline::enqueue_for_candidate(cfg, db, c)
+}
+
+/// Queue a rebuild of what is currently accepted — no new approval, because
+/// nothing about the source is changing.
+pub fn manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result<String> {
+ pipeline::enqueue_manual_rebuild(cfg, db, pkgbase)
+}
+
+/// Ask a running build to stop. It stops at the next step boundary; a build
+/// cannot be interrupted mid-step without leaving a half-written package.
+pub fn cancel(db: &Db, build_id: &str) -> Result<()> {
+ builds::request_cancel(db, build_id)
+}
+
+/// Retry a failed build, and record that someone asked.
+///
+/// The audit row is part of the workflow rather than the caller's homework: a
+/// retry changes what a build means, and a retry nobody asked for is exactly
+/// what the audit trail is there to rule out.
+pub fn retry(db: &Db, actor: &str, build_id: &str) -> Result<()> {
+ builds::retry(db, build_id)?;
+ db::audit(
+ &db.writer,
+ actor,
+ actor,
+ "build.retry",
+ "build",
+ build_id,
+ serde_json::json!({}),
+ )
+}
+
+/// Take a package out of the repository index.
+pub fn withdraw_package(cfg: &Config, db: &Db, name: &str) -> Result<()> {
+ pipeline::publish::withdraw_package(cfg, db, name)
+}
diff --git a/src/usecase/detect.rs b/src/usecase/detect.rs
new file mode 100644
index 0000000..67cc83c
--- /dev/null
+++ b/src/usecase/detect.rs
@@ -0,0 +1,41 @@
+//! Checking whether an upstream moved — one pkgbase, or every active one.
+
+use crate::config::Config;
+use crate::db::{self, Db, SubscriptionState};
+use crate::error::Result;
+use crate::watch::detect::{self, Outcome};
+
+/// One pkgbase's detection result.
+///
+/// Per-item failures are returned rather than raised: a sweep over every
+/// subscription should not stop at the first pkgbase whose mirror is
+/// unreachable, and the caller decides whether a failure is a line on stderr
+/// or a row in a table.
+pub struct Checked {
+ pub pkgbase: String,
+ pub outcome: Result<Outcome>,
+}
+
+/// Detect one pkgbase, or every active subscription if none was named.
+pub fn detect(cfg: &Config, db: &Db, pkgbase: Option<String>) -> Result<Vec<Checked>> {
+ let names: Vec<String> = match pkgbase {
+ Some(n) => vec![n],
+ None => db::list_subscriptions(db)?
+ .into_iter()
+ .filter(|s| s.state == SubscriptionState::Active)
+ .map(|s| s.pkgbase)
+ .collect(),
+ };
+ Ok(names
+ .into_iter()
+ .map(|n| {
+ let outcome = check(cfg, db, &n);
+ Checked { pkgbase: n, outcome }
+ })
+ .collect())
+}
+
+/// Detect a single pkgbase and discard the report beyond its outcome.
+pub fn check(cfg: &Config, db: &Db, pkgbase: &str) -> Result<Outcome> {
+ detect::check_pkgbase(cfg, db, pkgbase).map(|r| r.outcome)
+}
diff --git a/src/usecase/maintenance.rs b/src/usecase/maintenance.rs
new file mode 100644
index 0000000..4276016
--- /dev/null
+++ b/src/usecase/maintenance.rs
@@ -0,0 +1,43 @@
+//! Housekeeping: retention, backups, and clearing the attention list.
+
+use std::path::{Path, PathBuf};
+
+use crate::config::Config;
+use crate::db::{self, Db};
+use crate::error::Result;
+use crate::ops;
+
+/// What a garbage collection would do, before anything is deleted.
+pub struct GcPlan {
+ pub keep: usize,
+ /// Releases whose files survive.
+ pub kept: usize,
+ /// Releases whose files would go, with the files each one owns.
+ pub evicting: Vec<(i64, Vec<PathBuf>)>,
+}
+
+/// Work out what retention would remove, without removing it.
+pub fn plan_gc(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<GcPlan> {
+ let keep = keep.unwrap_or(ops::DEFAULT_KEEP);
+ let (kept, evict) = ops::plan_retention(db, keep)?;
+ let mut evicting = Vec::with_capacity(evict.len());
+ for e in evict {
+ evicting.push((e.release_id, ops::release_files(cfg, db, e.release_id)?));
+ }
+ Ok(GcPlan { keep, kept: kept.len(), evicting })
+}
+
+/// Delete what retention says should go.
+pub fn run_gc(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<ops::RetentionReport> {
+ ops::retention(cfg, db, Some(keep.unwrap_or(ops::DEFAULT_KEEP)))
+}
+
+/// Copy the database to a single file, WAL folded in.
+pub fn backup(db: &Db, dest: &Path) -> Result<PathBuf> {
+ ops::backup(db, dest)
+}
+
+/// Mark a notice as seen.
+pub fn acknowledge_notice(db: &Db, id: i64) -> Result<()> {
+ db::acknowledge_notice(&db.writer, id)
+}
diff --git a/src/usecase/mod.rs b/src/usecase/mod.rs
new file mode 100644
index 0000000..4a7a0a9
--- /dev/null
+++ b/src/usecase/mod.rs
@@ -0,0 +1,35 @@
+//! The workflows themselves — the thing between a front end and the modules.
+//!
+//! Before this module existed, a workflow had one implementation per front end.
+//! `main` opened the repository inline before its command match; `serve` opened
+//! it again; the web routes wrote subscriptions and retried builds with their
+//! own `db::` calls, so the CLI and the UI could drift and nothing would notice
+//! until a reviewer saw one behaviour in the browser and another in the
+//! terminal.
+//!
+//! A function here is a workflow only if more than one step has to happen in a
+//! particular order. `subscribe` is a workflow because the repo row has to be
+//! resolved first and a first detection may have to follow. `candidate_by_id`
+//! is not, and stays where it is.
+//!
+//! Nothing in here formats output or knows a terminal, a form or a status code
+//! exists. Results carry enough structure for each front end to say the same
+//! facts in its own voice — which is why `Approved` reports the queueing
+//! outcome rather than deciding whether a failed enqueue is fatal.
+
+mod bootstrap;
+mod builds;
+mod detect;
+mod maintenance;
+mod reviews;
+mod subscriptions;
+
+pub use bootstrap::{init, open, serve};
+pub use builds::{cancel, enqueue_candidate, manual_rebuild, retry, withdraw_package};
+pub use maintenance::{acknowledge_notice, backup, plan_gc, run_gc, GcPlan};
+pub use reviews::{
+ approve, bulk, prepare_review, reject, view_review, Approval, Approved, Decision,
+ Prepared,
+};
+pub use subscriptions::{subscribe, toggle_pause, unsubscribe, Pause, Subscribe};
+pub use detect::{check, detect, Checked};
diff --git a/src/usecase/reviews.rs b/src/usecase/reviews.rs
new file mode 100644
index 0000000..8cbb534
--- /dev/null
+++ b/src/usecase/reviews.rs
@@ -0,0 +1,122 @@
+//! Reviewing: look at a candidate, decide, and queue what the decision buys.
+
+use crate::config::Config;
+use crate::db::{CandidateRow, Db};
+use crate::error::Result;
+use crate::pipeline;
+use crate::review::{approve as ap, candidates, diff};
+
+/// The diff a reviewer is being asked to look at, already recorded.
+pub struct Prepared {
+ pub candidate: CandidateRow,
+ pub text: String,
+ pub digest: String,
+}
+
+/// Render the current diff and store its digest, so the approval that follows
+/// can be checked against exactly what was shown rather than whatever the tree
+/// looked like a moment later.
+///
+/// `Ok(None)` means there is no such candidate; each front end says so in its
+/// own words.
+pub fn prepare_review(cfg: &Config, db: &Db, candidate_id: i64) -> Result<Option<Prepared>> {
+ let Some(c) = candidates::candidate_by_id(db, candidate_id)? else {
+ return Ok(None);
+ };
+ let (text, digest) = diff::render_current(db, cfg, &c)?;
+ candidates::set_diff_digest(db, c.id, &digest)?;
+ Ok(Some(Prepared { candidate: c, text, digest }))
+}
+
+/// `prepare_review`, plus recording that a human actually looked at it.
+///
+/// The review queue uses "viewed" to stop surfacing candidates nobody is
+/// reading, so looking and approving are separate facts.
+pub fn view_review(cfg: &Config, db: &Db, candidate_id: i64) -> Result<Option<Prepared>> {
+ let Some(p) = prepare_review(cfg, db, candidate_id)? else {
+ return Ok(None);
+ };
+ candidates::mark_viewed(db, p.candidate.id)?;
+ Ok(Some(p))
+}
+
+/// An approval that was recorded, and whether a build came out of it.
+pub struct Approved {
+ pub approval: ap::Approval,
+ /// Queuing is fatal in the CLI — an approved candidate with no build is a
+ /// silent stall — and a soft failure in the UI, which has already committed
+ /// the decision and can retry from the package page. So the workflow
+ /// reports it rather than choosing for both.
+ pub queued: Result<String>,
+}
+
+pub enum Approval {
+ Recorded(Approved),
+ /// The review moved underneath the reviewer; the reason says how.
+ Refused(ap::Stale),
+}
+
+/// Record an approval and queue the build it authorises.
+///
+/// These are one workflow because an approval that never queues is the bug the
+/// whole review queue exists to prevent, and both front ends had to remember to
+/// pair them.
+pub fn approve(
+ cfg: &Config,
+ db: &Db,
+ actor: &str,
+ c: &CandidateRow,
+ identity: &str,
+ digest: &str,
+ note: Option<&str>,
+) -> Result<Approval> {
+ let approval = match ap::approve(db, actor, c.id, identity, digest, note) {
+ Ok(a) => a,
+ Err(ap::ApproveError::Stale(stale)) => return Ok(Approval::Refused(stale)),
+ Err(ap::ApproveError::System(e)) => return Err(e),
+ };
+ Ok(Approval::Recorded(Approved { approval, queued: pipeline::enqueue_for_candidate(cfg, db, c) }))
+}
+
+/// Record a rejection. A rejection always needs a reason; it is the only record
+/// of why a candidate was passed over.
+pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> {
+ ap::reject(db, actor, candidate_id, note)
+}
+
+/// One candidate's result from a bulk decision.
+pub enum Decision {
+ Approved { pkgbase: String, queued: Result<String> },
+ Rejected { pkgbase: String },
+ Refused { pkgbase: String, why: String },
+}
+
+/// Apply one decision to many candidates, queueing a build for each that
+/// passed. Items that were refused — high risk without a confirmation, say —
+/// come back with the reason rather than aborting the batch.
+pub fn bulk(
+ cfg: &Config,
+ db: &Db,
+ actor: &str,
+ items: &[(i64, String, String)],
+ decision: &str,
+ confirmed: &[i64],
+) -> Result<Vec<Decision>> {
+ let outcomes = ap::bulk(db, actor, items, decision, confirmed)?;
+ Ok(outcomes
+ .into_iter()
+ .map(|item| match &item.outcome {
+ ap::BulkOutcome::Approved(_) => match &item.candidate {
+ Some(c) => Decision::Approved {
+ pkgbase: c.pkgbase.clone(),
+ queued: pipeline::enqueue_for_candidate(cfg, db, c),
+ },
+ None => Decision::Rejected { pkgbase: item.pkgbase().to_string() },
+ },
+ ap::BulkOutcome::Rejected => Decision::Rejected { pkgbase: item.pkgbase().to_string() },
+ ap::BulkOutcome::Refused(r) => {
+ Decision::Refused { pkgbase: item.pkgbase().to_string(), why: r.to_string() }
+ }
+ })
+ .collect())
+}
diff --git a/src/usecase/subscriptions.rs b/src/usecase/subscriptions.rs
new file mode 100644
index 0000000..c504cfe
--- /dev/null
+++ b/src/usecase/subscriptions.rs
@@ -0,0 +1,50 @@
+//! What the server watches, and whether it is allowed to.
+
+use crate::db::{self, Db, SubscriptionState};
+use crate::error::Result;
+
+/// A subscription that now exists.
+pub struct Subscribe {
+ pub pkgbase: String,
+ pub url: String,
+}
+
+/// Start watching a pkgbase.
+///
+/// The repo row has to be resolved first, which is the step every front end
+/// previously open-coded — and the web layer got it wrong, falling back to repo
+/// id 1 rather than saying the repository was not initialised.
+pub fn subscribe(db: &Db, pkgbase: &str, url: Option<String>) -> Result<Subscribe> {
+ let rid = db::repo_id(db)?;
+ let url = url.unwrap_or_else(|| format!("https://aur.archlinux.org/{pkgbase}.git"));
+ db::subscribe(&db.writer, rid, pkgbase, &url)?;
+ Ok(Subscribe { pkgbase: pkgbase.to_string(), url })
+}
+
+pub enum Pause {
+ /// Paused, or resumed if it already was.
+ Now(SubscriptionState),
+ /// Some other state — removed, say — where pausing means nothing.
+ NotApplicable(SubscriptionState),
+ /// Nothing is subscribed under that name.
+ Unknown,
+}
+
+/// Pause a subscription, or resume it if it is already paused.
+pub fn toggle_pause(db: &Db, pkgbase: &str) -> Result<Pause> {
+ let Some(current) = db::get_subscription(db, pkgbase)? else {
+ return Ok(Pause::Unknown);
+ };
+ let next = match current.state {
+ SubscriptionState::Active => SubscriptionState::Paused,
+ SubscriptionState::Paused => SubscriptionState::Active,
+ other => return Ok(Pause::NotApplicable(other)),
+ };
+ db::set_subscription_state(&db.writer, pkgbase, next)?;
+ Ok(Pause::Now(next))
+}
+
+/// Stop watching a pkgbase. The row stays: history outlives subscriptions.
+pub fn unsubscribe(db: &Db, pkgbase: &str) -> Result<()> {
+ db::set_subscription_state(&db.writer, pkgbase, SubscriptionState::Removed)
+}
diff --git a/tests/architecture-budget.json b/tests/architecture-budget.json
index 4d0bf90..9d63943 100644
--- a/tests/architecture-budget.json
+++ b/tests/architecture-budget.json
@@ -94,7 +94,7 @@
"glob": 0,
"largest": 364,
"largest_file": "src/db/candidates.rs",
- "lines": 3731,
+ "lines": 3742,
"priv": 10,
"pub": 202,
"test": 13
@@ -103,9 +103,9 @@
"dead": 0,
"deadonly": 0,
"glob": 0,
- "largest": 124,
+ "largest": 430,
"largest_file": "src/error.rs",
- "lines": 124,
+ "lines": 430,
"priv": 0,
"pub": 21,
"test": 0
@@ -144,23 +144,23 @@
"test": 0
},
"http": {
- "dead": 54,
+ "dead": 53,
"deadonly": 43,
"glob": 2,
"largest": 565,
"largest_file": "src/http/routes/pages.rs",
- "lines": 1951,
+ "lines": 1938,
"priv": 32,
"pub": 68,
- "test": 11
+ "test": 10
},
"lib": {
"dead": 0,
"deadonly": 0,
"glob": 0,
- "largest": 22,
+ "largest": 23,
"largest_file": "src/lib.rs",
- "lines": 22,
+ "lines": 23,
"priv": 0,
"pub": 0,
"test": 0
@@ -169,16 +169,16 @@
"dead": 0,
"deadonly": 0,
"glob": 0,
- "largest": 361,
+ "largest": 314,
"largest_file": "src/main.rs",
- "lines": 361,
+ "lines": 314,
"priv": 0,
"pub": 0,
"test": 0
},
"ops": {
- "dead": 5,
- "deadonly": 2,
+ "dead": 4,
+ "deadonly": 1,
"glob": 0,
"largest": 415,
"largest_file": "src/ops.rs",
@@ -191,10 +191,10 @@
"dead": 6,
"deadonly": 0,
"glob": 0,
- "largest": 481,
+ "largest": 472,
"largest_file": "src/pipeline/steps.rs",
- "lines": 1339,
- "priv": 2,
+ "lines": 1330,
+ "priv": 11,
"pub": 21,
"test": 6
},
@@ -232,13 +232,13 @@
"test": 0
},
"review": {
- "dead": 11,
- "deadonly": 6,
+ "dead": 10,
+ "deadonly": 5,
"glob": 0,
"largest": 295,
"largest_file": "src/review/diff.rs",
- "lines": 792,
- "priv": 0,
+ "lines": 880,
+ "priv": 2,
"pub": 29,
"test": 5
},
@@ -246,10 +246,10 @@
"dead": 15,
"deadonly": 0,
"glob": 0,
- "largest": 347,
+ "largest": 350,
"largest_file": "src/sandbox/kata.rs",
- "lines": 1175,
- "priv": 3,
+ "lines": 1178,
+ "priv": 11,
"pub": 27,
"test": 15
},
@@ -286,28 +286,39 @@
"pub": 2,
"test": 0
},
+ "usecase": {
+ "dead": 3,
+ "deadonly": 3,
+ "glob": 0,
+ "largest": 123,
+ "largest_file": "src/usecase/reviews.rs",
+ "lines": 402,
+ "priv": 0,
+ "pub": 30,
+ "test": 0
+ },
"watch": {
"dead": 13,
"deadonly": 7,
"glob": 0,
- "largest": 317,
+ "largest": 270,
"largest_file": "src/watch/detect.rs",
- "lines": 969,
- "priv": 0,
+ "lines": 970,
+ "priv": 2,
"pub": 30,
"test": 6
}
},
"totals": {
- "dead": 194,
- "deadonly": 121,
- "edges": 80,
+ "dead": 180,
+ "deadonly": 105,
+ "edges": 87,
"glob": 2,
"largest": 603,
"largest_file": "src/shims/mod.rs",
- "lines": 13593,
- "priv": 47,
- "pub": 560,
- "test": 73
+ "lines": 14336,
+ "priv": 68,
+ "pub": 579,
+ "test": 75
}
}
diff --git a/tests/architecture.rs b/tests/architecture.rs
index e957f53..d3a4142 100644
--- a/tests/architecture.rs
+++ b/tests/architecture.rs
@@ -44,16 +44,17 @@ const RANKS: &[(&str, u8, &str)] = &[
("watch", 6, "detection: turns a moved upstream into a candidate, so it needs review"),
("pipeline", 7, "the step machine: orchestrates watch, review and sandbox"),
("ops", 8, "retention, metrics, backup: reads across the modules it reports on"),
- ("http", 9, "the UI: the top of the tree, everything is beneath it"),
- ("main", 10, "the CLI: composition root"),
- ("lib", 10, "the crate root: declares the modules and re-exports the error type"),
- ("bin/sandbox-agent", 10, "the sandbox agent: composition root on the far side of the wire"),
- ("bin/gpg", 10, "a shim binary: composition root for one tool"),
- ("bin/makepkg", 10, "a shim binary: composition root for one tool"),
- ("bin/makechrootpkg", 10, "a shim binary: composition root for one tool"),
- ("bin/mkarchroot", 10, "a shim binary: composition root for one tool"),
- ("bin/pacman", 10, "a shim binary: composition root for one tool"),
- ("bin/repo-add", 10, "a shim binary: composition root for one tool"),
+ ("usecase", 9, "the workflows both front ends run: orchestrates review, watch, pipeline and ops"),
+ ("http", 10, "the UI: renders use-case results, so only the composition roots are above it"),
+ ("main", 11, "the CLI: composition root"),
+ ("lib", 11, "the crate root: declares the modules and re-exports the error type"),
+ ("bin/sandbox-agent", 11, "the sandbox agent: composition root on the far side of the wire"),
+ ("bin/gpg", 11, "a shim binary: composition root for one tool"),
+ ("bin/makepkg", 11, "a shim binary: composition root for one tool"),
+ ("bin/makechrootpkg", 11, "a shim binary: composition root for one tool"),
+ ("bin/mkarchroot", 11, "a shim binary: composition root for one tool"),
+ ("bin/pacman", 11, "a shim binary: composition root for one tool"),
+ ("bin/repo-add", 11, "a shim binary: composition root for one tool"),
];
/// `pub use … ::*` a module is still allowed to keep, as `module -> count`.