summaryrefslogtreecommitdiffstats
path: root/src/db/builds.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/db/builds.rs')
-rw-r--r--src/db/builds.rs62
1 files changed, 62 insertions, 0 deletions
diff --git a/src/db/builds.rs b/src/db/builds.rs
index d251566..0a7013c 100644
--- a/src/db/builds.rs
+++ b/src/db/builds.rs
@@ -422,3 +422,65 @@ pub fn current_state(c: &Connection, id: &str) -> Result<String> {
.optional()?
.unwrap_or_default())
}
+
+/// Claim up to `limit` queued builds in one `BEGIN IMMEDIATE` transaction and
+/// hand them to workers (§8.2). SQLite has no `SKIP LOCKED`, but with exactly one
+/// writer the claim cannot race: the SELECT and the UPDATE are the same
+/// transaction, so no other claimer can see a row in between.
+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.filter_map(|r| r.ok()).collect()
+ };
+ 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)
+ })
+}
+
+/// A newer approved release for the same pkgbase makes an in-flight build
+/// pointless (§8.2 cancellation). Workers notice at the next step boundary and
+/// stop; nothing is killed mid-step, which is what keeps the checkpoints honest.
+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)
+ })
+}
+
+/// Put a build back on the queue after a transient failure, keeping the attempt
+/// count so the retry cap can bite (§8.4).
+pub fn requeue_transient(db: &Db, id: &str) -> Result<()> {
+ let id = id.to_string();
+ let at = time::now();
+ db.writer.tx(move |tx| {
+ tx.execute(
+ "UPDATE build SET state='queued', lease_owner=NULL, lease_expires_at=NULL,
+ error=NULL, updated_at=?1 WHERE id=?2",
+ params![at, id],
+ )?;
+ Ok(())
+ })
+}