diff options
| author | dev <dev@localhost> | 2026-11-20 17:13:44 +0000 |
|---|---|---|
| committer | dev <dev@localhost> | 2026-11-20 17:13:44 +0000 |
| commit | 8cd32e5309b14f5264813e5f2ce6ecdb5aa41fb4 (patch) | |
| tree | 2ce6c30a688ef3fb15af5639e22cfc230f8f3627 /src/db/builds/steps.rs | |
| parent | b73bb60403c3f2e7fc55d5038831912e8371e3a6 (diff) | |
| download | aur-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/steps.rs')
| -rw-r--r-- | src/db/builds/steps.rs | 290 |
1 files changed, 290 insertions, 0 deletions
diff --git a/src/db/builds/steps.rs b/src/db/builds/steps.rs new file mode 100644 index 0000000..64d57c7 --- /dev/null +++ b/src/db/builds/steps.rs @@ -0,0 +1,290 @@ +use rusqlite::{params, Connection, OptionalExtension}; + +use super::transition_in_tx; +use crate::db::{BuildState, Db, StepState}; +use crate::error::{Error, Result}; +use crate::time; +// ------------------------------------------------------------- step rows -- + +#[derive(Debug, Clone)] +pub struct StepRow { + pub step: String, + pub status: StepState, + pub attempt: i64, + pub error: Option<String>, +} + +pub fn steps(db: &Db, id: &str) -> Result<Vec<StepRow>> { + let id = id.to_string(); + db.read(move |c| { + let mut stmt = c.prepare( + "SELECT step, status, attempt, error FROM build_step WHERE build_id=?1 ORDER BY rowid", + )?; + let rows = stmt.query_map(params![id], |r| { + Ok(StepRow { + step: r.get(0)?, + status: crate::db::state_col::<StepState>(1, &r.get::<_, String>(1)?)?, + attempt: r.get(2)?, + error: r.get(3)?, + }) + })?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +pub fn step_status(db: &Db, build_id: &str, step: &str) -> Result<Option<StepState>> { + let (b, s) = (build_id.to_string(), step.to_string()); + db.read(move |c| { + c.query_row( + "SELECT status FROM build_step WHERE build_id=?1 AND step=?2", + params![b, s], + |r| crate::db::state_col::<StepState>(0, &r.get::<_, String>(0)?), + ) + .optional() + .map_err(Into::into) + }) +} + +pub fn begin_step(db: &Db, build_id: &str, step: &str, attempt: i64) -> Result<()> { + let (b, s) = (build_id.to_string(), step.to_string()); + let at = time::now(); + db.writer.tx(move |tx| { + let n = tx.execute( + "INSERT INTO build_step (build_id, step, status, attempt, started_at) + VALUES (?1,?2,'running',?3,?4) + ON CONFLICT(build_id, step) DO UPDATE SET status='running', attempt=?3, started_at=?4, + error=NULL + WHERE build_step.status NOT IN ('succeeded','skipped')", + params![b, s, attempt, at], + )?; + if n == 0 { + return Err(Error::invalid(format!( + "step {s} of build {b} is already checkpointed as done and must not re-run" + ))); + } + tx.execute("UPDATE build SET current_step=?1 WHERE id=?2", params![s, b])?; + Ok(()) + }) +} + +pub fn finish_step( + db: &Db, + build_id: &str, + step: &str, + to: StepState, + output_digest: Option<&str>, + error: Option<&str>, +) -> Result<()> { + let (b, s) = (build_id.to_string(), step.to_string()); + let od = output_digest.map(|s| s.to_string()); + let err = error.map(|s| s.to_string()); + let at = time::now(); + let froms = StepState::predecessors(to); + let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(","); + let sql = format!( + "UPDATE build_step SET status=?1, output_digest=?2, error=?3, finished_at=?4 + WHERE build_id=?5 AND step=?6 AND status IN ({placeholders})" + ); + db.writer.tx(move |tx| { + let status = to.as_str(); + let mut args: Vec<&dyn rusqlite::ToSql> = vec![&status, &od, &err, &at, &b, &s]; + 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 status FROM build_step WHERE build_id=?1 AND step=?2", + params![b, s], + |r| r.get(0), + ) + .optional()?; + return Err(match was { + Some(w) => Error::invalid(format!( + "illegal step transition {w} → {to} for step {s} of build {b}" + )), + None => Error::invalid(format!("no checkpoint for step {s} of build {b}")), + }); + } + Ok(()) + }) +} + +pub fn in_flight(db: &Db) -> Result<usize> { + db.read(|c| { + Ok(c.query_row( + "SELECT count(*) FROM build WHERE state IN ('leased','running')", + [], + |r| r.get::<_, i64>(0), + )? as usize) + }) +} + +pub fn queue_depth(db: &Db) -> Result<usize> { + db.read(|c| { + Ok(c.query_row("SELECT count(*) FROM build WHERE state='queued'", [], |r| r.get::<_, i64>(0))? as usize) + }) +} + +pub fn blocked_builds(db: &Db) -> Result<Vec<(String, String, Vec<String>)>> { + db.read(|c| { + let mut stmt = c.prepare( + "SELECT b.id, p.name, b.blocked_on_json FROM build b + JOIN pkgbase p ON p.id = b.pkgbase_id WHERE b.state='blocked_missing_dep'", + )?; + let rows = stmt.query_map([], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)) + })?; + let mut out = Vec::new(); + for r in rows { + let (id, name, json) = r?; + let blocked: Vec<String> = serde_json::from_str(&json).unwrap_or_default(); + out.push((id, name, blocked)); + } + Ok(out) + }) +} + +pub fn touch(db: &Db, id: &str) -> Result<()> { + let id = id.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET updated_at=?1 WHERE id=?2", params![time::now(), id])?; + Ok(()) + }) +} + +pub fn set_release_in(tx: &rusqlite::Transaction<'_>, id: &str, release_id: i64) -> Result<()> { + tx.execute("UPDATE build SET release_id=?1 WHERE id=?2", params![release_id, id])?; + Ok(()) +} + +pub fn set_release(db: &Db, id: &str, release_id: i64) -> Result<()> { + let id = id.to_string(); + db.writer.tx(move |tx| set_release_in(tx, &id, release_id)) +} + +pub fn set_world(db: &Db, id: &str, world_id: i64) -> Result<()> { + let id = id.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET world_snapshot_id=?1 WHERE id=?2", params![world_id, id])?; + Ok(()) + }) +} + +pub fn set_candidate(db: &Db, id: &str, candidate_id: i64) -> Result<()> { + let id = id.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET candidate_id=?1 WHERE id=?2", params![candidate_id, id])?; + Ok(()) + }) +} + +pub fn set_pkgbase(db: &Db, id: &str, pkgbase_id: i64) -> Result<()> { + let id = id.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET pkgbase_id=?1 WHERE id=?2", params![pkgbase_id, id])?; + Ok(()) + }) +} + +pub fn set_profile(db: &Db, id: &str, profile: &str) -> Result<()> { + let (id, p) = (id.to_string(), profile.to_string()); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET build_profile=?1 WHERE id=?2", params![p, id])?; + Ok(()) + }) +} + +pub fn set_kind(db: &Db, id: &str, kind: &str) -> Result<()> { + let (id, k) = (id.to_string(), kind.to_string()); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET kind=?1 WHERE id=?2", params![k, id])?; + Ok(()) + }) +} + +pub fn set_blocked_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| { + tx.execute("UPDATE build SET blocked_on_json=?1 WHERE id=?2", params![json, id])?; + Ok(()) + }) +} + +pub fn current_state(c: &Connection, id: &str) -> Result<Option<BuildState>> { + let s: Option<String> = c + .query_row("SELECT state FROM build WHERE id=?1", params![id], |r| r.get(0)) + .optional()?; + match s { + None => Ok(None), + Some(text) => BuildState::parse(&text) + .map(Some) + .ok_or_else(|| Error::invalid(format!("build {id} has a state outside the state machine: {text:?}"))), + } +} + +pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Result<Vec<String>> { + if limit == 0 { + return Ok(Vec::new()); + } + let owner = owner.to_string(); + let exp = time::secs_ahead(lease_secs); + let at = time::now(); + db.writer.tx(move |tx| { + let ids: Vec<String> = { + let mut stmt = tx.prepare( + "SELECT id FROM build WHERE state='queued' + ORDER BY priority DESC, created_at LIMIT ?1", + )?; + let rows = stmt.query_map(params![limit as i64], |r| r.get::<_, String>(0))?; + rows.collect::<rusqlite::Result<Vec<String>>>()? + }; + for id in &ids { + 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='queued'", + params![owner, exp, at, id], + )?; + } + Ok(ids) + }) +} + +pub fn cancel_superseded(db: &Db) -> Result<usize> { + db.writer.tx(move |tx| { + let n = tx.execute( + "UPDATE build SET cancel_requested=1 + WHERE state IN ('queued','leased','running') + AND candidate_id IN (SELECT id FROM candidate WHERE state='superseded')", + [], + )?; + Ok(n) + }) +} + +pub fn requeue_transient(db: &Db, id: &str) -> Result<()> { + let id = id.to_string(); + db.writer + .tx(move |tx| transition_in_tx(tx, &id, BuildState::Queued, None)) +} + +pub fn retry(db: &Db, id: &str) -> Result<()> { + let id = id.to_string(); + db.writer.tx(move |tx| { + tx.execute( + "UPDATE build_step SET status='pending', error=NULL, started_at=NULL, finished_at=NULL + WHERE build_id=?1 AND status IN ('failed','interrupted')", + params![id], + )?; + transition_in_tx(tx, &id, BuildState::Queued, None)?; + tx.execute("UPDATE build SET cancel_requested=0 WHERE id=?1", params![id])?; + Ok(()) + }) +} |
