summaryrefslogtreecommitdiffstats
path: root/src/db/builds/mod.rs
diff options
context:
space:
mode:
authordev <dev@localhost>2026-11-20 17:13:44 +0000
committerdev <dev@localhost>2026-11-20 17:13:44 +0000
commit8cd32e5309b14f5264813e5f2ce6ecdb5aa41fb4 (patch)
tree2ce6c30a688ef3fb15af5639e22cfc230f8f3627 /src/db/builds/mod.rs
parentb73bb60403c3f2e7fc55d5038831912e8371e3a6 (diff)
downloadaur-build-8cd32e5309b14f5264813e5f2ce6ecdb5aa41fb4.tar.gz
aur-build-8cd32e5309b14f5264813e5f2ce6ecdb5aa41fb4.zip
db: one module per aggregate, and an interface you can read
queries.rs was 1,501 lines holding 83 queries across seventeen aggregates, separated by comment banners that said "settings", "release", "notices" and then kept them in one file. The banners were the design; they just never got files. Each one has one now, verbatim — the split is provably content-only, the moved text being identical to the original as a sorted set of lines. model.rs and builds.rs were each two concerns deep, so they became directories. model.rs held what a row looks like and, separately, the state machines that say which moves are legal; builds.rs held the build machine and, below its own `step rows` banner, the step machine. The impl_state_enum! macro implements StateEnum for all five enums from one place, so it moved with its invocations rather than being exported across a boundary to chase them. They are directories rather than new sibling modules on purpose: `db::model::CandidateState` and `db::builds::steps` are used across the crate and by the integration tests, and renaming them would be a bigger change than the one being made. No call site and no test changed. db/mod.rs now lists its interface instead of spraying one. `pub use model::*` and `pub use queries::*` are gone, replaced by seventeen explicit exports, and the query modules are private — so a query that was not chosen for export is not reachable, and the width of the module is visible from its own text rather than only from a grep. The ratchet caught the win immediately: db.glob went 2 -> 0, which failed a_shrunk_interface_is_written_back until the budget was written back at the new value. db is off the glob allowlist now rather than holding a stale zero. 277 passed / 0 failed, clippy -D warnings clean, largest file in src/db 363 lines (candidates.rs, unchanged from before this work).
Diffstat (limited to 'src/db/builds/mod.rs')
-rw-r--r--src/db/builds/mod.rs312
1 files changed, 312 insertions, 0 deletions
diff --git a/src/db/builds/mod.rs b/src/db/builds/mod.rs
new file mode 100644
index 0000000..2e116bb
--- /dev/null
+++ b/src/db/builds/mod.rs
@@ -0,0 +1,312 @@
+use rusqlite::{params, OptionalExtension};
+
+use crate::db::{BuildState, Db};
+use crate::error::{Error, Result};
+use crate::time;
+
+#[derive(Debug, Clone)]
+pub struct BuildRow {
+ pub id: String,
+ pub pkgbase_id: i64,
+ pub candidate_id: Option<i64>,
+ pub release_id: Option<i64>,
+ pub kind: String,
+ pub world_snapshot_id: Option<i64>,
+ pub build_profile: String,
+ pub state: BuildState,
+ pub blocked_on_json: String,
+ pub current_step: Option<String>,
+ pub lease_owner: Option<String>,
+ pub lease_expires_at: Option<String>,
+ pub attempt: i64,
+ pub priority: i64,
+ pub cancel_requested: bool,
+ pub error: Option<String>,
+}
+
+const BUILD_COLS: &str = "id, pkgbase_id, candidate_id, release_id, kind, world_snapshot_id, \
+ build_profile, state, blocked_on_json, current_step, lease_owner, lease_expires_at, \
+ attempt, priority, cancel_requested, error";
+
+pub(crate) fn row_to_build(r: &rusqlite::Row<'_>) -> rusqlite::Result<BuildRow> {
+ let state = crate::db::state_col::<BuildState>(7, &r.get::<_, String>(7)?)?;
+ Ok(BuildRow {
+ id: r.get(0)?,
+ pkgbase_id: r.get(1)?,
+ candidate_id: r.get(2)?,
+ release_id: r.get(3)?,
+ kind: r.get(4)?,
+ world_snapshot_id: r.get(5)?,
+ build_profile: r.get(6)?,
+ state,
+ blocked_on_json: r.get(8)?,
+ current_step: r.get(9)?,
+ lease_owner: r.get(10)?,
+ lease_expires_at: r.get(11)?,
+ attempt: r.get(12)?,
+ priority: r.get(13)?,
+ cancel_requested: r.get::<_, i64>(14)? != 0,
+ error: r.get(15)?,
+ })
+}
+
+pub fn build_id(pkgbase: &str, identity_hash: &str, world_hash: &str, profile: &str) -> String {
+ crate::hash::hex_str(&format!("{pkgbase}|{identity_hash}|{world_hash}|{profile}"))
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn enqueue(
+ db: &Db,
+ id: &str,
+ pkgbase_id: i64,
+ candidate_id: Option<i64>,
+ kind: &str,
+ world_snapshot_id: Option<i64>,
+ profile: &str,
+ priority: i64,
+) -> Result<bool> {
+ let (id, kind, profile) = (id.to_string(), kind.to_string(), profile.to_string());
+ let at = time::now();
+ db.writer.tx(move |tx| {
+ let n = tx.execute(
+ "INSERT INTO build (id, pkgbase_id, candidate_id, kind, world_snapshot_id, build_profile,
+ state, created_at, updated_at, priority)
+ VALUES (?1,?2,?3,?4,?5,?6,'queued',?7,?7,?8)
+ ON CONFLICT(id) DO NOTHING",
+ params![id, pkgbase_id, candidate_id, kind, world_snapshot_id, profile, at, priority],
+ )?;
+ Ok(n == 1)
+ })
+}
+
+pub fn get(db: &Db, id: &str) -> Result<Option<BuildRow>> {
+ let id = id.to_string();
+ db.read(move |c| {
+ Ok(c.query_row(
+ &format!("SELECT {BUILD_COLS} FROM build WHERE id=?1"),
+ params![id],
+ row_to_build,
+ )
+ .optional()?)
+ })
+}
+
+pub fn list(db: &Db, states: &[BuildState], limit: i64) -> Result<Vec<BuildRow>> {
+ let states = states.iter().map(|s| s.as_str().to_string()).collect::<Vec<_>>();
+ db.read(move |c| {
+ let placeholders = states.iter().map(|_| "?").collect::<Vec<_>>().join(",");
+ let sql = format!(
+ "SELECT {BUILD_COLS} FROM build WHERE state IN ({placeholders})
+ ORDER BY priority DESC, created_at LIMIT ?{}",
+ states.len() + 1
+ );
+ let mut stmt = c.prepare(&sql)?;
+ let rows = stmt.query_map(
+ rusqlite::params_from_iter(states.iter().chain(std::iter::once(&limit.to_string())).map(|s| s as &dyn rusqlite::ToSql)),
+ row_to_build,
+ )?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+pub fn queued(db: &Db, limit: i64) -> Result<Vec<String>> {
+ db.read(|c| {
+ let mut stmt = c.prepare(
+ "SELECT id FROM build WHERE state='queued' ORDER BY priority DESC, created_at LIMIT ?1",
+ )?;
+ let rows = stmt.query_map(params![limit], |r| r.get::<_, String>(0))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+pub fn claim(db: &Db, owner: &str, id: &str, lease_secs: i64) -> Result<bool> {
+ let (owner, id) = (owner.to_string(), id.to_string());
+ let exp = time::secs_ahead(lease_secs);
+ let at = time::now();
+ db.writer.tx(move |tx| {
+ let n = tx.execute(
+ "UPDATE build SET state='leased', lease_owner=?1, lease_expires_at=?2,
+ attempt=attempt+1, updated_at=?3
+ WHERE id=?4 AND state IN ('queued','leased')",
+ params![owner, exp, at, id],
+ )?;
+ Ok(n == 1)
+ })
+}
+
+pub fn extend_lease(db: &Db, id: &str, lease_secs: i64) -> Result<()> {
+ let id = id.to_string();
+ let exp = time::secs_ahead(lease_secs);
+ db.writer.tx(move |tx| {
+ tx.execute(
+ "UPDATE build SET lease_expires_at=?1 WHERE id=?2",
+ params![exp, id],
+ )?;
+ Ok(())
+ })
+}
+
+pub fn reap_expired(db: &Db) -> Result<usize> {
+ let now = time::now();
+ db.writer.tx(move |tx| {
+ let ids: Vec<String> = {
+ let mut stmt = tx.prepare(
+ "SELECT id FROM build WHERE state IN ('leased','running')
+ AND lease_expires_at IS NOT NULL AND lease_expires_at < ?1",
+ )?;
+ let rows = stmt.query_map(params![now], |r| r.get::<_, String>(0))?;
+ rows.collect::<rusqlite::Result<Vec<String>>>()?
+ };
+ for id in &ids {
+ tx.execute(
+ "UPDATE build SET state='queued', lease_owner=NULL, lease_expires_at=NULL
+ WHERE id=?1",
+ params![id],
+ )?;
+ tx.execute(
+ "UPDATE build_step SET status='interrupted', finished_at=?2
+ WHERE build_id=?1 AND status='running'",
+ params![id, now],
+ )?;
+ }
+ Ok(ids.len())
+ })
+}
+
+fn transition_in_tx(
+ tx: &mut rusqlite::Transaction<'_>,
+ id: &str,
+ to: BuildState,
+ error: Option<&str>,
+) -> Result<()> {
+ let froms = BuildState::predecessors(to);
+ let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(",");
+ let sql = format!(
+ "UPDATE build SET state=?1, error=?2, updated_at=?3, lease_owner=NULL,
+ lease_expires_at=NULL WHERE id=?4 AND state IN ({placeholders})"
+ );
+ let at = time::now();
+ let state = to.as_str();
+ let mut args: Vec<&dyn rusqlite::ToSql> = vec![&state, &error, &at, &id];
+ for f in &froms {
+ args.push(f);
+ }
+ let n = tx.execute(&sql, rusqlite::params_from_iter(args))?;
+ if n == 0 {
+ let was: Option<String> = tx
+ .query_row("SELECT state FROM build WHERE id=?1", params![id], |r| r.get(0))
+ .optional()?;
+ return Err(match was {
+ Some(s) => Error::invalid(format!("illegal build transition {s} → {to} for build {id}")),
+ None => Error::invalid(format!("no build {id} to move to {to}")),
+ });
+ }
+ Ok(())
+}
+
+pub fn set_state(db: &Db, id: &str, to: BuildState, error: Option<&str>) -> Result<()> {
+ let id = id.to_string();
+ let error = error.map(|e| e.to_string());
+ db.writer
+ .tx(move |tx| transition_in_tx(tx, &id, to, error.as_deref()))
+}
+
+pub fn block_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> {
+ let id = id.to_string();
+ let json = serde_json::to_string(blocked_on)?;
+ db.writer.tx(move |tx| {
+ transition_in_tx(tx, &id, BuildState::BlockedMissingDep, None)?;
+ tx.execute("UPDATE build SET blocked_on_json=?1 WHERE id=?2", params![json, id])?;
+ Ok(())
+ })
+}
+
+pub fn requeue_blocked(db: &Db) -> Result<usize> {
+ let now = time::now();
+ db.writer.tx(move |tx| {
+ let rows: Vec<(String, String)> = {
+ let mut stmt = tx.prepare("SELECT id, blocked_on_json FROM build WHERE state='blocked_missing_dep'")?;
+ let out = stmt
+ .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?
+ .collect::<rusqlite::Result<Vec<(String, String)>>>()?;
+ out
+ };
+ let in_index: std::collections::HashSet<String> = {
+ let mut stmt = tx.prepare("SELECT name FROM package WHERE state='in_index'")?;
+ let names = stmt
+ .query_map([], |r| r.get::<_, String>(0))?
+ .collect::<rusqlite::Result<Vec<String>>>()?;
+ names.into_iter().collect()
+ };
+ let mut n = 0;
+ for (id, blocked_on) in rows {
+ let waiting: Vec<String> = serde_json::from_str(&blocked_on).unwrap_or_default();
+ let satisfied = waiting.iter().all(|name| in_index.contains(name));
+ if satisfied && !waiting.is_empty() {
+ tx.execute(
+ "UPDATE build SET state='queued', blocked_on_json='[]', updated_at=?1 WHERE id=?2",
+ params![now, id],
+ )?;
+ n += 1;
+ }
+ }
+ Ok(n)
+ })
+}
+
+pub fn request_cancel(db: &Db, id: &str) -> Result<()> {
+ let id = id.to_string();
+ db.writer.tx(move |tx| {
+ tx.execute("UPDATE build SET cancel_requested=1 WHERE id=?1", params![id])?;
+ Ok(())
+ })
+}
+
+pub fn cancel_requested(db: &Db, id: &str) -> Result<bool> {
+ let id = id.to_string();
+ db.read(move |c| {
+ Ok(c.query_row("SELECT cancel_requested FROM build WHERE id=?1", params![id], |r| {
+ Ok(r.get::<_, i64>(0)? != 0)
+ })
+ .optional()?
+ .unwrap_or(false))
+ })
+}
+
+
+// The step machine is its own concern: same build, one row per step, its own
+// legal moves.
+mod steps;
+
+pub use steps::{
+ StepRow,
+ begin_step,
+ blocked_builds,
+ cancel_superseded,
+ claim_batch,
+ current_state,
+ finish_step,
+ in_flight,
+ queue_depth,
+ requeue_transient,
+ retry,
+ set_blocked_on,
+ set_candidate,
+ set_kind,
+ set_pkgbase,
+ set_profile,
+ set_release,
+ set_release_in,
+ set_world,
+ step_status,
+ steps,
+ touch,
+};