diff options
Diffstat (limited to 'src/usecase')
| -rw-r--r-- | src/usecase/bootstrap.rs | 58 | ||||
| -rw-r--r-- | src/usecase/builds.rs | 46 | ||||
| -rw-r--r-- | src/usecase/detect.rs | 41 | ||||
| -rw-r--r-- | src/usecase/maintenance.rs | 43 | ||||
| -rw-r--r-- | src/usecase/mod.rs | 35 | ||||
| -rw-r--r-- | src/usecase/reviews.rs | 122 | ||||
| -rw-r--r-- | src/usecase/subscriptions.rs | 50 |
7 files changed, 395 insertions, 0 deletions
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) +} |
