diff options
Diffstat (limited to 'src')
68 files changed, 1109 insertions, 1642 deletions
diff --git a/src/bin/sandbox-agent.rs b/src/bin/sandbox-agent.rs index ce34d50..078b67c 100644 --- a/src/bin/sandbox-agent.rs +++ b/src/bin/sandbox-agent.rs @@ -28,12 +28,9 @@ fn main() { } i += 1; } - let (hub, token) = match (hub, token) { - (Some(h), Some(t)) => (h, t), - _ => { - eprintln!("usage: sandbox-agent --hub HOST:PORT --token T [--profile P] [--ttl SECS]"); - std::process::exit(2); - } + let (Some(hub), Some(token)) = (hub, token) else { + eprintln!("usage: sandbox-agent --hub HOST:PORT --token T [--profile P] [--ttl SECS]"); + std::process::exit(2); }; let opts = aur_build::sandbox::agent::AgentOptions { hub, diff --git a/src/config.rs b/src/config.rs index 7818e4b..1b9f26a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -204,10 +204,7 @@ impl Default for Config { impl Config { pub fn sandbox_image(&self) -> String { - self.sandbox - .image() - .unwrap_or(DEFAULT_SANDBOX_IMAGE) - .to_string() + self.sandbox.image().unwrap_or(DEFAULT_SANDBOX_IMAGE).to_string() } pub fn validate(&self) -> crate::error::Result<()> { @@ -259,10 +256,7 @@ impl Config { let dir = absolute(root)?; let p = dir.join("config.json"); if !p.exists() { - return Err(crate::error::Error::not_found(format!( - "no config at {}; run `aur-build init`", - p.display() - ))); + return Err(crate::error::Error::not_found(format!("no config at {}; run `aur-build init`", p.display()))); } let s = std::fs::read_to_string(&p)?; let v: serde_json::Value = serde_json::from_str(&s)?; @@ -276,10 +270,7 @@ impl Config { std::fs::create_dir_all(&self.root)?; let mut out = self.clone(); out.root = absolute(&self.root)?; - std::fs::write( - self.root.join("config.json"), - serde_json::to_string_pretty(&out)? + "\n", - )?; + std::fs::write(self.root.join("config.json"), serde_json::to_string_pretty(&out)? + "\n")?; Ok(()) } @@ -396,10 +387,7 @@ impl Config { self.root.join("repo") } pub fn repo_arch_dir(&self) -> PathBuf { - self.repo_dir() - .join(&self.repo_name) - .join("os") - .join(&self.arch) + self.repo_dir().join(&self.repo_name).join("os").join(&self.arch) } pub fn repo_db_name(&self) -> String { format!("{}.db", self.repo_name) @@ -419,12 +407,12 @@ fn check_retired_sandbox_keys(v: &serde_json::Value) -> crate::error::Result<()> let named: Vec<String> = RETIRED .iter() .filter(|k| { - let key: &str = k; - match v.get(key) { - None => false, - Some(serde_json::Value::String(s)) => !retired_key_is_inert(key, s), - Some(_) => true, - } + let key: &str = k; + match v.get(key) { + None => false, + Some(serde_json::Value::String(s)) => !retired_key_is_inert(key, s), + Some(_) => true, + } }) .map(|k| format!("\"{k}\"")) .collect(); @@ -437,10 +425,7 @@ fn check_retired_sandbox_keys(v: &serde_json::Value) -> crate::error::Result<()> "{\"kind\":\"remote\",\"listen\":…,\"token\":…}, or ", "{\"kind\":\"agent-sandbox\",\"api\":…,\"namespace\":…,\"bearer\":…,\"image\":…,\"listen\":…,\"token\":…}" ); - Err(crate::error::Error::invalid(format!( - "{} are retired sandbox keys; {example}", - named.join(", ") - ))) + Err(crate::error::Error::invalid(format!("{} are retired sandbox keys; {example}", named.join(", ")))) } fn absolute(p: &Path) -> crate::error::Result<PathBuf> { @@ -449,13 +434,7 @@ fn absolute(p: &Path) -> crate::error::Result<PathBuf> { fn slug(url: &str) -> String { url.chars() - .map(|c| { - if c.is_ascii_alphanumeric() { - c.to_ascii_lowercase() - } else { - '-' - } - }) + .map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }) .collect::<String>() .trim_matches('-') .chars() @@ -472,11 +451,7 @@ mod tests { // fixture corpus, or a subprocess. fn load_sandbox(sandbox: &str) -> Result<Config, String> { let tmp = tempfile::tempdir().unwrap(); - std::fs::write( - tmp.path().join("config.json"), - format!("{{\n \"sandbox\": {sandbox}\n}}\n"), - ) - .unwrap(); + std::fs::write(tmp.path().join("config.json"), format!("{{\n \"sandbox\": {sandbox}\n}}\n")).unwrap(); Config::load(tmp.path()).map_err(|e| e.to_string()) } @@ -496,10 +471,7 @@ mod tests { other => panic!("expected loopback, got {other:?}"), } - let remote = load_sandbox( - r#"{"kind":"remote","listen":"127.0.0.1:8787","token":"s3cr3t"}"#, - ) - .unwrap(); + let remote = load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:8787","token":"s3cr3t"}"#).unwrap(); match &remote.sandbox { Sandbox::Remote { listen, token, shared_workspace } => { assert_eq!(listen, "127.0.0.1:8787"); @@ -545,8 +517,7 @@ mod tests { r#""token":"t""#.to_string(), ]; fields.retain(|f| !f.starts_with(&format!("\"{missing}\""))); - let err = load_sandbox(&format!("{{\"kind\":\"agent-sandbox\",{}}}", fields.join(","))) - .unwrap_err(); + let err = load_sandbox(&format!("{{\"kind\":\"agent-sandbox\",{}}}", fields.join(","))).unwrap_err(); assert!(err.contains(missing), "dropping {missing} must name it: {err}"); } } @@ -637,13 +608,12 @@ mod tests { #[test] fn a_field_that_is_present_but_empty_is_refused() { - let cfg = load_sandbox(r#"{"kind":"remote","listen":"","token":"t","shared_workspace":true}"#) - .unwrap(); + let cfg = load_sandbox(r#"{"kind":"remote","listen":"","token":"t","shared_workspace":true}"#).unwrap(); let err = cfg.validate().unwrap_err().to_string(); assert!(err.contains("listen"), "must name the empty field: {err}"); - let cfg = load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:1","token":" ","shared_workspace":true}"#) - .unwrap(); + let cfg = + load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:1","token":" ","shared_workspace":true}"#).unwrap(); let err = cfg.validate().unwrap_err().to_string(); assert!(err.contains("token"), "whitespace is not a token: {err}"); @@ -657,8 +627,7 @@ mod tests { ("token", "t"), ]); fields.insert(blank, ""); - let body: Vec<String> = - fields.iter().map(|(k, v)| format!("\"{k}\":\"{v}\"")).collect(); + let body: Vec<String> = fields.iter().map(|(k, v)| format!("\"{k}\":\"{v}\"")).collect(); let cfg = load_sandbox(&format!("{{\"kind\":\"agent-sandbox\",{}}}", body.join(","))).unwrap(); let err = cfg.validate().unwrap_err().to_string(); assert!(err.contains(blank), "blank {blank} must be named: {err}"); @@ -682,12 +651,10 @@ mod tests { assert!(err.contains("shared_workspace"), "{err}"); assert!(err.contains("agent-sandbox"), "{err}"); - assert!(load_sandbox( - r#"{"kind":"remote","listen":"127.0.0.1:1","token":"t","shared_workspace":true}"# - ) - .unwrap() - .validate() - .is_ok()); + assert!(load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:1","token":"t","shared_workspace":true}"#) + .unwrap() + .validate() + .is_ok()); } #[test] diff --git a/src/db/approvals.rs b/src/db/approvals.rs index ececc32..0c4a117 100644 --- a/src/db/approvals.rs +++ b/src/db/approvals.rs @@ -33,7 +33,13 @@ pub fn record_in(tx: &mut Transaction<'_>, d: &Decision<'_>) -> Result<i64> { Ok(tx.last_insert_rowid()) } -pub fn record_rejection_in(tx: &mut Transaction<'_>, candidate_id: i64, at: &str, identity_hash: &str, note: &str) -> Result<()> { +pub fn record_rejection_in( + tx: &mut Transaction<'_>, + candidate_id: i64, + at: &str, + identity_hash: &str, + note: &str, +) -> Result<()> { tx.execute( "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level, diff_digest, identity_hash, note) @@ -46,11 +52,9 @@ pub fn record_rejection_in(tx: &mut Transaction<'_>, candidate_id: i64, at: &str pub fn for_candidate(db: &Db, candidate_id: i64) -> Result<Option<(i64, String)>> { db.read(|c| { - Ok(c.query_row( - "SELECT id, decision FROM approval WHERE candidate_id=?1", - params![candidate_id], - |r| Ok((r.get(0)?, r.get(1)?)), - ) + Ok(c.query_row("SELECT id, decision FROM approval WHERE candidate_id=?1", params![candidate_id], |r| { + Ok((r.get(0)?, r.get(1)?)) + }) .optional()?) }) } diff --git a/src/db/audit.rs b/src/db/audit.rs index 45a3b46..23b20bb 100644 --- a/src/db/audit.rs +++ b/src/db/audit.rs @@ -1,6 +1,6 @@ use rusqlite::params; -use crate::db::*; +use crate::db::{Db, Writer}; use crate::error::Result; use crate::time; @@ -59,7 +59,6 @@ impl<'a> AuditEntry<'a> { ) -> Self { Self { at, actor_kind: "human", actor, action, entity, entity_id, detail } } - } pub fn audit_in(tx: &rusqlite::Transaction<'_>, e: &AuditEntry<'_>) -> Result<()> { @@ -71,7 +70,13 @@ pub fn audit_in(tx: &rusqlite::Transaction<'_>, e: &AuditEntry<'_>) -> Result<() Ok(()) } -pub fn audit_system(writer: &Writer, action: &str, entity: &str, entity_id: &str, detail: serde_json::Value) -> Result<()> { +pub fn audit_system( + writer: &Writer, + action: &str, + entity: &str, + entity_id: &str, + detail: serde_json::Value, +) -> Result<()> { audit(writer, "system", "", action, entity, entity_id, detail) } @@ -114,4 +119,3 @@ pub fn list_audit(db: &Db, limit: i64) -> Result<Vec<AuditRow>> { Ok(out) }) } - diff --git a/src/db/builds/mod.rs b/src/db/builds/mod.rs index 83566ad..e31543e 100644 --- a/src/db/builds/mod.rs +++ b/src/db/builds/mod.rs @@ -78,12 +78,7 @@ pub fn enqueue( 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()?) + Ok(c.query_row(&format!("SELECT {BUILD_COLS} FROM build WHERE id=?1"), params![id], row_to_build).optional()?) }) } @@ -98,7 +93,9 @@ pub fn list(db: &Db, states: &[BuildState], limit: i64) -> Result<Vec<BuildRow>> ); 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)), + 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(); @@ -111,9 +108,8 @@ pub fn list(db: &Db, states: &[BuildState], limit: i64) -> Result<Vec<BuildRow>> 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 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 { @@ -150,10 +146,7 @@ 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], - )?; + tx.execute("UPDATE build SET lease_expires_at=?1 WHERE id=?2", params![exp, id])?; Ok(()) }) } @@ -185,12 +178,7 @@ pub fn reap_expired(db: &Db) -> Result<usize> { }) } -fn transition_in_tx( - tx: &mut rusqlite::Transaction<'_>, - id: &str, - to: BuildState, - error: Option<&str>, -) -> Result<()> { +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!( @@ -205,9 +193,8 @@ fn transition_in_tx( } 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()?; + 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}")), @@ -218,9 +205,8 @@ fn transition_in_tx( 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())) + let error = error.map(std::string::ToString::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<()> { @@ -245,9 +231,7 @@ pub fn requeue_blocked(db: &Db) -> Result<usize> { }; 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>>>()?; + let names = stmt.query_map([], |r| r.get::<_, String>(0))?.collect::<rusqlite::Result<Vec<String>>>()?; names.into_iter().collect() }; let mut n = 0; @@ -277,23 +261,17 @@ pub fn request_cancel(db: &Db, id: &str) -> Result<()> { 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)) + 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::{ - begin_step, blocked_builds, cancel_superseded, claim_batch, - finish_step, in_flight, queue_depth, requeue_transient, - retry, set_blocked_on, set_release_in, set_world, - step_status, steps, + begin_step, blocked_builds, cancel_superseded, claim_batch, finish_step, in_flight, queue_depth, requeue_transient, + retry, set_blocked_on, set_release_in, set_world, step_status, steps, }; diff --git a/src/db/builds/steps.rs b/src/db/builds/steps.rs index 4ffff36..01faa03 100644 --- a/src/db/builds/steps.rs +++ b/src/db/builds/steps.rs @@ -17,9 +17,8 @@ pub struct StepRow { 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 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)?, @@ -39,11 +38,9 @@ pub fn steps(db: &Db, id: &str) -> Result<Vec<StepRow>> { 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)?), - ) + 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) }) @@ -80,8 +77,8 @@ pub fn finish_step( 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 od = output_digest.map(std::string::ToString::to_string); + let err = error.map(std::string::ToString::to_string); let at = time::now(); let froms = StepState::predecessors(to); let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(","); @@ -98,16 +95,10 @@ pub fn finish_step( 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), - ) + .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}" - )), + 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}")), }); } @@ -117,18 +108,15 @@ pub fn finish_step( 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) + 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) - }) + 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>)>> { @@ -137,9 +125,8 @@ pub fn blocked_builds(db: &Db) -> Result<Vec<(String, String, Vec<String>)>> { "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 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?; @@ -154,7 +141,6 @@ pub fn set_release_in(tx: &rusqlite::Transaction<'_>, id: &str, release_id: i64) Ok(()) } - pub fn set_world(db: &Db, id: &str, world_id: i64) -> Result<()> { let id = id.to_string(); db.writer.tx(move |tx| { @@ -163,10 +149,6 @@ pub fn set_world(db: &Db, id: &str, world_id: i64) -> Result<()> { }) } - - - - 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)?; @@ -176,7 +158,6 @@ pub fn set_blocked_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> { }) } - pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Result<Vec<String>> { if limit == 0 { return Ok(Vec::new()); @@ -219,8 +200,7 @@ pub fn cancel_superseded(db: &Db) -> Result<usize> { 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)) + db.writer.tx(move |tx| transition_in_tx(tx, &id, BuildState::Queued, None)) } pub fn retry(db: &Db, id: &str) -> Result<()> { diff --git a/src/db/candidates.rs b/src/db/candidates.rs index 411d60b..2aca851 100644 --- a/src/db/candidates.rs +++ b/src/db/candidates.rs @@ -107,9 +107,7 @@ pub(crate) fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Resu pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) -> Result<()> { let froms = CandidateState::predecessors(to); let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(","); - let sql = format!( - "UPDATE candidate SET state=?1, resolved_at=?2 WHERE id=?3 AND state IN ({placeholders})" - ); + let sql = format!("UPDATE candidate SET state=?1, resolved_at=?2 WHERE id=?3 AND state IN ({placeholders})"); let state = to.as_str(); let mut args: Vec<&dyn rusqlite::ToSql> = vec![&state, &at, &id]; for f in &froms { @@ -117,11 +115,15 @@ pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) - } let n = tx.execute(&sql, rusqlite::params_from_iter(args))?; if n == 0 { - let was: Option<String> = tx - .query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| r.get(0)) - .optional()?; + let was: Option<String> = + tx.query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| r.get(0)).optional()?; return Err(match was { - Some(w) => Error::conflict(Refused::IllegalTransition { entity: "candidate", id: id.to_string(), from: w, to: to.to_string() }), + Some(w) => Error::conflict(Refused::IllegalTransition { + entity: "candidate", + id: id.to_string(), + from: w, + to: to.to_string(), + }), None => Error::not_found(Missing::Candidate(id)), }); } @@ -155,14 +157,7 @@ pub(crate) fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result<Option<Op "SELECT id, identity_hash, viewed_at, revision FROM candidate WHERE pkgbase_id=?1 AND state='pending_review'", params![pkgbase_id], - |r| { - Ok(OpenReview { - id: r.get(0)?, - identity_hash: r.get(1)?, - viewed_at: r.get(2)?, - revision: r.get(3)?, - }) - }, + |r| Ok(OpenReview { id: r.get(0)?, identity_hash: r.get(1)?, viewed_at: r.get(2)?, revision: r.get(3)? }), ) .optional()?) } @@ -280,10 +275,7 @@ pub fn pending(db: &Db) -> Result<Vec<CandidateRow>> { pub fn by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> { let sql = format!("SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?1"); - db.read(move |c| { - Ok(c.query_row(&sql, params![id], row_to_candidate) - .optional()?) - }) + db.read(move |c| Ok(c.query_row(&sql, params![id], row_to_candidate).optional()?)) } // ---------------------------------------------------------------- writes -- @@ -291,10 +283,7 @@ pub fn by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> { pub fn mark_viewed(db: &Db, id: i64) -> Result<()> { let at = time::now(); db.writer.tx(move |tx| { - tx.execute( - "UPDATE candidate SET viewed_at=?1 WHERE id=?2 AND viewed_at IS NULL", - params![at, id], - )?; + tx.execute("UPDATE candidate SET viewed_at=?1 WHERE id=?2 AND viewed_at IS NULL", params![at, id])?; Ok(()) }) } @@ -303,10 +292,7 @@ pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()> let lvl = level.to_string(); let sig = serde_json::to_string(signals)?; db.writer.tx(move |tx| { - tx.execute( - "UPDATE candidate SET risk_level=?1, risk_signals_json=?2 WHERE id=?3", - params![lvl, sig, id], - )?; + tx.execute("UPDATE candidate SET risk_level=?1, risk_signals_json=?2 WHERE id=?3", params![lvl, sig, id])?; Ok(()) }) } @@ -314,10 +300,7 @@ pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()> pub fn set_missing_deps(db: &Db, id: i64, missing: &[String]) -> Result<()> { let m = serde_json::to_string(missing)?; db.writer.tx(move |tx| { - tx.execute( - "UPDATE candidate SET missing_deps_json=?1 WHERE id=?2", - params![m, id], - )?; + tx.execute("UPDATE candidate SET missing_deps_json=?1 WHERE id=?2", params![m, id])?; Ok(()) }) } diff --git a/src/db/invariants.rs b/src/db/invariants.rs index e9e133f..964b03c 100644 --- a/src/db/invariants.rs +++ b/src/db/invariants.rs @@ -1,5 +1,4 @@ - -use crate::db::*; +use crate::db::Db; use crate::error::Result; // ------------------------------------------------------- invariant helpers -- @@ -29,7 +28,6 @@ pub fn unapproved_index_entries(db: &Db) -> Result<Vec<String>> { }) } - #[derive(Debug, Clone)] // Unbuilt stays `pub`: the attention row `approved_but_unbuilt` returns to the web UI and to tests/crash.rs. pub struct Unbuilt { @@ -76,21 +74,14 @@ pub fn approved_but_unbuilt(db: &Db) -> Result<Vec<Unbuilt>> { let mut out = Vec::new(); for r in rows { let (pkgbase, ae, av, ar, se, sv, sr, error, build_id) = r?; - let (pkgbase, av, ar) = match (pkgbase, av, ar) { - (Some(p), Some(v), Some(rel)) => (p, v, rel), - _ => { - return Err(crate::error::Error::Db( - "failed build row without a candidate version".into(), - )) - } + let (Some(pkgbase), Some(av), Some(ar)) = (pkgbase, av, ar) else { + return Err(crate::error::Error::Db("failed build row without a candidate version".into())); }; out.push(Unbuilt { pkgbase, approved: crate::pkgver::full_version(&ae.unwrap_or_default(), &av, &ar), serving: match (sv, sr) { - (Some(v), Some(rel)) => { - crate::pkgver::full_version(&se.unwrap_or_default(), &v, &rel) - } + (Some(v), Some(rel)) => crate::pkgver::full_version(&se.unwrap_or_default(), &v, &rel), _ => String::new(), }, error, diff --git a/src/db/metrics.rs b/src/db/metrics.rs index 39a6b10..6c4c519 100644 --- a/src/db/metrics.rs +++ b/src/db/metrics.rs @@ -1,6 +1,6 @@ use rusqlite::params; -use crate::db::*; +use crate::db::Db; use crate::error::{Error, Result}; use crate::time; @@ -8,10 +8,7 @@ use crate::time; fn count_rows(db: &Db, sql: &str) -> Result<i64> { let sql = sql.to_string(); - db.read(move |c| { - c.query_row(&sql, [], |r| r.get::<_, i64>(0)) - .map_err(|e| Error::db(e.to_string())) - }) + db.read(move |c| c.query_row(&sql, [], |r| r.get::<_, i64>(0)).map_err(|e| Error::db(e.to_string()))) } pub fn build_state_counts(db: &Db) -> Result<Vec<(String, i64)>> { @@ -45,7 +42,8 @@ pub fn count_pending_reviews(db: &Db) -> Result<i64> { pub fn pending_review_ages_secs(db: &Db, now: &str) -> Result<Vec<i64>> { db.read(|c| { - let mut st = c.prepare("SELECT julianday(?1) - julianday(detected_at) FROM candidate WHERE state='pending_review'")?; + let mut st = + c.prepare("SELECT julianday(?1) - julianday(detected_at) FROM candidate WHERE state='pending_review'")?; let rows = st.query_map(params![now], |r| r.get::<_, Option<f64>>(0))?; let mut out = Vec::new(); for r in rows { @@ -73,13 +71,9 @@ pub fn count_unacknowledged_notices(db: &Db) -> Result<i64> { pub fn artifact_bytes_served(db: &Db) -> Result<u64> { db.read(|c| { - c.query_row( - "SELECT COALESCE(sum(size),0) FROM artifact WHERE purged_at IS NULL", - [], - |r| r.get::<_, i64>(0), - ) - .map(|v| v.max(0) as u64) - .map_err(|e| Error::db(e.to_string())) + c.query_row("SELECT COALESCE(sum(size),0) FROM artifact WHERE purged_at IS NULL", [], |r| r.get::<_, i64>(0)) + .map(|v| v.max(0) as u64) + .map_err(|e| Error::db(e.to_string())) }) } @@ -98,4 +92,3 @@ pub fn last_poll_age_secs(db: &Db, now: &str) -> Result<Option<i64>> { })?; Ok(at.and_then(|t| time::delta_secs(now, &t))) } - diff --git a/src/db/migrations.rs b/src/db/migrations.rs index 7adc69c..2e552f2 100644 --- a/src/db/migrations.rs +++ b/src/db/migrations.rs @@ -5,7 +5,7 @@ pub struct Migration { pub sql: &'static str, } -const M_0001_CORE: &str = r#" +const M_0001_CORE: &str = r" -- The single repo we publish. Exactly one row. CREATE TABLE repo ( id INTEGER PRIMARY KEY, @@ -170,9 +170,9 @@ CREATE TABLE package ( state TEXT NOT NULL DEFAULT 'in_index' -- in_index | removed ); CREATE INDEX package_by_name ON package (repo_id, name, state); -"#; +"; -const M_0002_BUILD: &str = r#" +const M_0002_BUILD: &str = r" CREATE TABLE build ( id TEXT PRIMARY KEY, -- deterministic intent hash pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), @@ -209,7 +209,7 @@ CREATE TABLE build_step ( finished_at TEXT, PRIMARY KEY (build_id, step) ); -"#; +"; const M_0003_NOTICES: &str = r#" -- "something changed but nothing is publishable". @@ -253,7 +253,7 @@ CREATE TABLE dep_edge ( ); "#; -const M_0004_TRIGGERS: &str = r#" +const M_0004_TRIGGERS: &str = r" -- The audit log is append-only. CREATE TRIGGER audit_no_update BEFORE UPDATE ON audit @@ -266,14 +266,14 @@ BEFORE DELETE ON audit BEGIN SELECT RAISE(ABORT, 'audit log is append-only: deletes are forbidden'); END; -"#; +"; -const M_0005_ARTIFACT_BUILD: &str = r#" +const M_0005_ARTIFACT_BUILD: &str = r" ALTER TABLE artifact ADD COLUMN build_id TEXT; CREATE INDEX artifact_by_build ON artifact (build_id); -"#; +"; -const M_0006_APPROVAL_IMMUTABLE: &str = r#" +const M_0006_APPROVAL_IMMUTABLE: &str = r" CREATE TRIGGER approval_no_update BEFORE UPDATE ON approval BEGIN @@ -285,9 +285,9 @@ BEFORE DELETE ON approval BEGIN SELECT RAISE(ABORT, 'approval records are immutable'); END; -"#; +"; -const M_0007_STAGE_B_CACHE: &str = r#" +const M_0007_STAGE_B_CACHE: &str = r" CREATE TABLE stage_b_cache ( pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), recipe_hash TEXT NOT NULL, @@ -301,7 +301,7 @@ CREATE TABLE stage_b_cache ( ); CREATE INDEX stage_b_cache_by_pkgbase ON stage_b_cache (pkgbase_id, resolved_at); -"#; +"; const M_0008_RETENTION: &str = r#" ALTER TABLE artifact ADD COLUMN purged_at TEXT; diff --git a/src/db/mod.rs b/src/db/mod.rs index 4379a5f..27d1bfb 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -29,17 +29,19 @@ mod world; /// no crate-internal alias to keep in a production build. #[cfg(feature = "test-support")] pub use migrations::MIGRATIONS; -pub(crate) use model::StateEnum; /// Its only caller is the test-tier `world_members`, so it is gated with it. #[cfg(feature = "test-support")] pub(crate) use model::json_or; +pub(crate) use model::StateEnum; -pub use model::{ - BUILD_STEPS, BuildState, CandidateRow, CandidateState, - Identity, Recipe, ReleaseRow, - SourceDigest, SourceEntry, StageBCacheRow, StepState, - SubscriptionState, UpstreamPin, WorldMember, candidate_kind, - notice_kind, +pub use audit::{audit, audit_in, audit_system, list_audit, AuditEntry}; +pub use invariants::approved_but_unbuilt; +#[cfg(feature = "test-support")] +pub use invariants::unapproved_index_entries; +pub use metrics::{ + artifact_bytes_served, build_state_counts, count_index_packages, count_pending_reviews, count_published_releases, + count_subscriptions, count_unacknowledged_notices, last_gc_age_secs, last_poll_age_secs, oldest_queued_age_secs, + pending_review_ages_secs, }; /// `ReleaseState` is a column type on the release row. Nothing outside `db` /// names it, so the alias out of `db` exists only for the test tier. @@ -47,53 +49,42 @@ pub use model::{ pub use model::ReleaseState; #[cfg(not(feature = "test-support"))] pub(crate) use model::ReleaseState; -pub use audit::{AuditEntry, audit, audit_in, audit_system, list_audit}; -pub use invariants::approved_but_unbuilt; -#[cfg(feature = "test-support")] -pub use invariants::unapproved_index_entries; -pub use metrics::{ - artifact_bytes_served, build_state_counts, count_index_packages, count_pending_reviews, - count_published_releases, count_subscriptions, count_unacknowledged_notices, last_gc_age_secs, - last_poll_age_secs, oldest_queued_age_secs, pending_review_ages_secs, +pub use model::{ + candidate_kind, notice_kind, BuildState, CandidateRow, CandidateState, Identity, Recipe, ReleaseRow, SourceDigest, + SourceEntry, StageBCacheRow, StepState, SubscriptionState, UpstreamPin, WorldMember, BUILD_STEPS, }; pub use notices::{acknowledge_notice, list_notices, put_notice_once}; pub use packages::{ - accepted_recipe, builds_for_pkgbase, index_artifact, index_packages, - index_version, our_package_names, -}; -pub use pkgbases::{ - Pkgbase, accepted_release_for, get_pkgbase, get_pkgbase_by_id, set_aur_head, + accepted_recipe, builds_for_pkgbase, index_artifact, index_packages, index_version, our_package_names, }; #[cfg(feature = "test-support")] pub use pkgbases::cas_accepted_release; +pub use pkgbases::{accepted_release_for, get_pkgbase, get_pkgbase_by_id, set_aur_head, Pkgbase}; pub use publish_writes::{ - NewRelease, accepted_pointer_in, artifact_path, cas_accepted_release_in, - insert_package_in, insert_release_in, remove_index_packages_in, remove_package_by_name_in, + accepted_pointer_in, artifact_path, cas_accepted_release_in, insert_package_in, insert_release_in, + remove_index_packages_in, remove_package_by_name_in, NewRelease, }; pub use releases::{ - accepted_release, all_published_releases, release_by_id, releases_for_pkgbase, - withdraw_release_in, + accepted_release, all_published_releases, release_by_id, releases_for_pkgbase, withdraw_release_in, }; pub use repos::{ensure_repo, repo_id}; pub use retention::{ - mark_release_purged, pkgbase_release_pointers, published_release_ids, record_gc_run, - release_artifact_paths, serving_release_ids, + mark_release_purged, pkgbase_release_pointers, published_release_ids, record_gc_run, release_artifact_paths, + serving_release_ids, }; -pub use settings::{all_settings, setting, setting_i64}; #[cfg(feature = "test-support")] pub use settings::set_setting; -pub use snapshots::{SnapshotRow, put_snapshot, snapshot_by_id}; +pub use settings::{all_settings, setting, setting_i64}; #[cfg(feature = "test-support")] pub use snapshots::snapshot_by_commit; +pub use snapshots::{put_snapshot, snapshot_by_id, SnapshotRow}; pub use stage_b::{stage_b_cache_get, stage_b_cache_put, stage_b_recent}; pub use staleness::{ - NewArtifact, approval_note, candidate_snapshot_id, index_recipes, - insert_artifact_in, published_world_members, put_source_cache, served_vs_offered_pkgvers, - source_cache_path, + approval_note, candidate_snapshot_id, index_recipes, insert_artifact_in, published_world_members, put_source_cache, + served_vs_offered_pkgvers, source_cache_path, NewArtifact, }; pub use subscriptions::{ - due_subscriptions, get_subscription, list_subscriptions, note_check, - set_subscription_state, subscribe, + due_subscriptions, get_subscription, list_subscriptions, note_check, set_subscription_state, subscribe, }; pub use world::put_world_snapshot; #[cfg(feature = "test-support")] @@ -138,12 +129,11 @@ fn open(path: &Path, read_only: bool) -> Result<Connection> { fn configure(conn: &Connection, read_only: bool) -> Result<()> { conn.pragma_update(None, "journal_mode", "WAL") - .and_then(|_| conn.pragma_update(None, "busy_timeout", 5000)) - .and_then(|_| conn.pragma_update(None, "foreign_keys", "ON")) + .and_then(|()| conn.pragma_update(None, "busy_timeout", 5000)) + .and_then(|()| conn.pragma_update(None, "foreign_keys", "ON")) .map_err(|e| Error::db(e.to_string()))?; if !read_only { - conn.pragma_update(None, "synchronous", "FULL") - .map_err(|e| Error::db(e.to_string()))?; + conn.pragma_update(None, "synchronous", "FULL").map_err(|e| Error::db(e.to_string()))?; } Ok(()) } @@ -151,18 +141,13 @@ fn configure(conn: &Connection, read_only: bool) -> Result<()> { pub fn migrate(path: &Path) -> Result<u32> { let mut conn = open(path, false)?; let mut applied = 0u32; - let current: u32 = conn - .pragma_query_value(None, "user_version", |r| r.get(0)) - .map_err(|e| Error::db(e.to_string()))?; + let current: u32 = + conn.pragma_query_value(None, "user_version", |r| r.get(0)).map_err(|e| Error::db(e.to_string()))?; for m in migrations::MIGRATIONS { if m.version > current { - let tx = conn - .transaction() - .map_err(|e| Error::db(e.to_string()))?; - tx.execute_batch(m.sql) - .map_err(|e| Error::db(format!("migration {} ({}): {e}", m.version, m.name)))?; - tx.pragma_update(None, "user_version", m.version) - .map_err(|e| Error::db(e.to_string()))?; + let tx = conn.transaction().map_err(|e| Error::db(e.to_string()))?; + tx.execute_batch(m.sql).map_err(|e| Error::db(format!("migration {} ({}): {e}", m.version, m.name)))?; + tx.pragma_update(None, "user_version", m.version).map_err(|e| Error::db(e.to_string()))?; tx.commit().map_err(|e| Error::db(e.to_string()))?; applied += 1; } @@ -195,7 +180,7 @@ pub struct Writer { } impl Writer { -/// Only `Writer::open` in this module starts a writer. + /// Only `Writer::open` in this module starts a writer. fn start(path: &Path) -> Result<Self> { let conn = open(path, false)?; let (tx, rx) = unbounded::<Msg>(); @@ -207,7 +192,7 @@ impl Writer { .spawn(move || { let mut conn = conn; alive_thread.store(true, Ordering::SeqCst); - for msg in rx.iter() { + for msg in &rx { match msg { Msg::Call(f) => f(&mut conn), #[cfg(feature = "test-support")] @@ -237,9 +222,7 @@ impl Writer { self.send(Box::new(move |conn| { let _ = reply_tx.send(f(conn)); }))?; - reply_rx - .recv() - .map_err(|_| Error::db("writer actor gone"))? + reply_rx.recv().map_err(|_| Error::db("writer actor gone"))? } pub(crate) fn tx<T>( @@ -263,9 +246,7 @@ impl Writer { if !self.is_alive() { return Err(Error::db("writer actor gone")); } - self.tx - .send(Msg::Call(f)) - .map_err(|_| Error::db("writer actor gone")) + self.tx.send(Msg::Call(f)).map_err(|_| Error::db("writer actor gone")) } /// Stop the writer actor. @@ -273,7 +254,7 @@ impl Writer { /// Test-tier only: the server runs until the process ends and never /// quiesces the writer deliberately. Tests use it to prove a worker /// that dies mid-write leaves the database consistent. -#[cfg(feature = "test-support")] + #[cfg(feature = "test-support")] pub fn shutdown(&self) { let _ = self.tx.send(Msg::Shutdown); } @@ -312,10 +293,7 @@ impl Readers { if pool.iter().position(|(p, _)| p == &path).is_none() { pool.push((path.clone(), open(&path, true)?)); } - let idx = pool - .iter() - .position(|(p, _)| p == &path) - .ok_or_else(|| Error::db("reader pool lost entry"))?; + let idx = pool.iter().position(|(p, _)| p == &path).ok_or_else(|| Error::db("reader pool lost entry"))?; // We only ever use one connection at a time per thread, and `f` // receives &Connection rather than &Readers, so it cannot re-enter. let conn = &pool[idx].1; @@ -338,10 +316,7 @@ impl Db { } pub fn open_migrated(path: &Path) -> Result<Self> { - Ok(Self { - writer: Arc::new(Writer::start(path)?), - readers: Arc::new(Readers::new(path)), - }) + Ok(Self { writer: Arc::new(Writer::start(path)?), readers: Arc::new(Readers::new(path)) }) } pub fn read<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> { @@ -352,16 +327,14 @@ impl Db { pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> { let dest_s = dest.display().to_string(); writer.call(move |conn| { - conn.execute("VACUUM INTO ?1", rusqlite::params![dest_s]) - .map_err(|e| Error::db(e.to_string()))?; + conn.execute("VACUUM INTO ?1", rusqlite::params![dest_s]).map_err(|e| Error::db(e.to_string()))?; Ok(()) }) } pub fn schema_version(path: &Path) -> Result<i64> { - let conn = rusqlite::Connection::open(path) - .map_err(|e| Error::db(format!("{} does not open: {e}", path.display())))?; + let conn = + rusqlite::Connection::open(path).map_err(|e| Error::db(format!("{} does not open: {e}", path.display())))?; conn.query_row("PRAGMA user_version", [], |r| r.get(0)) .map_err(|e| Error::db(format!("{} has no schema version: {e}", path.display()))) } - diff --git a/src/db/model/build_state.rs b/src/db/model/build_state.rs index 37eee79..478f93a 100644 --- a/src/db/model/build_state.rs +++ b/src/db/model/build_state.rs @@ -1,6 +1,5 @@ use serde::{Deserialize, Serialize}; - #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum BuildState { Queued, @@ -42,17 +41,14 @@ impl BuildState { } pub fn is_terminal(&self) -> bool { - matches!( - self, - BuildState::Succeeded | BuildState::Failed | BuildState::Cancelled - ) + matches!(self, BuildState::Succeeded | BuildState::Failed | BuildState::Cancelled) } /// The transition table itself. `predecessors` is how production /// enforces it; nothing outside this module asks the question directly. - fn can_transition(&self, to: BuildState) -> bool { - use BuildState::*; - if *self == to { + fn can_transition(self, to: BuildState) -> bool { + use BuildState::{BlockedMissingDep, Cancelled, Failed, Leased, Queued, Running, Succeeded}; + if self == to { return true; } match self { @@ -67,20 +63,11 @@ impl BuildState { } pub(crate) fn predecessors(to: BuildState) -> Vec<&'static str> { - BuildState::ALL - .iter() - .filter(|from| from.can_transition(to)) - .map(|from| from.as_str()) - .collect() + BuildState::ALL.iter().filter(|from| from.can_transition(to)).map(BuildState::as_str).collect() } pub fn active() -> &'static [BuildState] { - &[ - BuildState::Queued, - BuildState::Running, - BuildState::Leased, - BuildState::BlockedMissingDep, - ] + &[BuildState::Queued, BuildState::Running, BuildState::Leased, BuildState::BlockedMissingDep] } } @@ -130,9 +117,9 @@ impl StepState { matches!(self, StepState::Succeeded | StepState::Skipped) } - fn can_transition(&self, to: StepState) -> bool { - use StepState::*; - if *self == to { + fn can_transition(self, to: StepState) -> bool { + use StepState::{Failed, Interrupted, Pending, Running, Skipped, Succeeded}; + if self == to { return true; } match self { @@ -144,11 +131,7 @@ impl StepState { } pub(crate) fn predecessors(to: StepState) -> Vec<&'static str> { - StepState::ALL - .iter() - .filter(|from| from.can_transition(to)) - .map(|from| from.as_str()) - .collect() + StepState::ALL.iter().filter(|from| from.can_transition(to)).map(StepState::as_str).collect() } } @@ -158,18 +141,8 @@ impl std::fmt::Display for StepState { } } -pub const BUILD_STEPS: &[&str] = &[ - "materialize", - "plan", - "chroot", - "sources", - "pkgver", - "build", - "collect", - "verify", - "ingest", - "publish", -]; +pub const BUILD_STEPS: &[&str] = + &["materialize", "plan", "chroot", "sources", "pkgver", "build", "collect", "verify", "ingest", "publish"]; #[cfg(test)] mod tests { @@ -192,11 +165,7 @@ mod tests { #[test] fn the_transition_table_is_the_machine_the_code_actually_uses() { let reachable = |from: BuildState| -> Vec<&'static str> { - BuildState::ALL - .iter() - .filter(|to| from.can_transition(**to)) - .map(|to| to.as_str()) - .collect() + BuildState::ALL.iter().filter(|to| from.can_transition(**to)).map(super::BuildState::as_str).collect() }; assert_eq!(reachable(BuildState::Queued), ["queued", "leased", "running", "blocked_missing_dep", "cancelled"]); assert_eq!( diff --git a/src/db/model/mod.rs b/src/db/model/mod.rs index aef6a47..df861da 100644 --- a/src/db/model/mod.rs +++ b/src/db/model/mod.rs @@ -209,12 +209,12 @@ mod state; pub(crate) use state::StateEnum; -pub use build_state::{BUILD_STEPS, BuildState, StepState}; -pub use state::{CandidateState, SubscriptionState, candidate_kind, notice_kind}; +pub use build_state::{BuildState, StepState, BUILD_STEPS}; #[cfg(feature = "test-support")] pub use state::ReleaseState; #[cfg(not(feature = "test-support"))] pub(crate) use state::ReleaseState; +pub use state::{candidate_kind, notice_kind, CandidateState, SubscriptionState}; #[cfg(test)] mod tests { diff --git a/src/db/model/state.rs b/src/db/model/state.rs index 18860ff..4057652 100644 --- a/src/db/model/state.rs +++ b/src/db/model/state.rs @@ -1,6 +1,5 @@ use serde::{Deserialize, Serialize}; - use crate::db::model::build_state::{BuildState, StepState}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -40,9 +39,9 @@ impl CandidateState { *self == CandidateState::PendingReview } - fn can_transition(&self, to: CandidateState) -> bool { - use CandidateState::*; - if *self == to { + fn can_transition(self, to: CandidateState) -> bool { + use CandidateState::{Approved, Blocked, PendingReview, Rejected, Superseded}; + if self == to { return true; } match self { @@ -54,11 +53,7 @@ impl CandidateState { } pub(crate) fn predecessors(to: CandidateState) -> Vec<&'static str> { - CandidateState::ALL - .iter() - .filter(|from| from.can_transition(to)) - .map(|from| from.as_str()) - .collect() + CandidateState::ALL.iter().filter(|from| from.can_transition(to)).map(CandidateState::as_str).collect() } } @@ -78,7 +73,7 @@ pub mod candidate_kind { /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod release_state { - use super::*; + use super::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -101,11 +96,8 @@ pub use release_state::ReleaseState; pub(crate) use release_state::ReleaseState; impl ReleaseState { - const ALL: &'static [ReleaseState] = &[ - ReleaseState::Published, - ReleaseState::Withdrawn, - ReleaseState::FailedUnbuilt, - ]; + const ALL: &'static [ReleaseState] = + &[ReleaseState::Published, ReleaseState::Withdrawn, ReleaseState::FailedUnbuilt]; pub fn as_str(&self) -> &'static str { match self { diff --git a/src/db/notices.rs b/src/db/notices.rs index 36263a4..795f736 100644 --- a/src/db/notices.rs +++ b/src/db/notices.rs @@ -1,18 +1,17 @@ use rusqlite::{params, OptionalExtension}; -use crate::db::*; +use crate::db::{Db, Writer}; use crate::error::Result; use crate::time; // ----------------------------------------------------------------- notice -- - pub fn put_notice_once( writer: &Writer, pkgbase_id: i64, kind: &str, severity: &str, - detail: serde_json::Value, + detail: &serde_json::Value, ) -> Result<Option<i64>> { let (k, s, d) = (kind.to_string(), severity.to_string(), detail.to_string()); let at = time::now(); @@ -54,11 +53,7 @@ pub fn list_notices(db: &Db, include_acknowledged: bool) -> Result<Vec<NoticeRow "SELECT n.id, b.name, n.kind, n.severity, n.detail_json, n.created_at, n.acknowledged_at FROM notice n JOIN pkgbase b ON b.id = n.pkgbase_id {} ORDER BY (n.severity='high') DESC, n.created_at DESC LIMIT 500", - if include_acknowledged { - "" - } else { - "WHERE n.acknowledged_at IS NULL" - } + if include_acknowledged { "" } else { "WHERE n.acknowledged_at IS NULL" } ); let mut stmt = c.prepare(&sql)?; let rows = stmt.query_map([], |r| { @@ -83,11 +78,7 @@ pub fn list_notices(db: &Db, include_acknowledged: bool) -> Result<Vec<NoticeRow pub fn acknowledge_notice(writer: &Writer, id: i64) -> Result<()> { let at = time::now(); writer.tx(move |tx| { - tx.execute( - "UPDATE notice SET acknowledged_at=?1 WHERE id=?2", - params![at, id], - )?; + tx.execute("UPDATE notice SET acknowledged_at=?1 WHERE id=?2", params![at, id])?; Ok(()) }) } - diff --git a/src/db/packages.rs b/src/db/packages.rs index 247c328..3f1f96e 100644 --- a/src/db/packages.rs +++ b/src/db/packages.rs @@ -1,6 +1,6 @@ use rusqlite::{params, OptionalExtension}; -use crate::db::*; +use crate::db::{Db, Recipe, ReleaseRow}; use crate::error::Result; // ---------------------------------------------------------------- package -- @@ -79,7 +79,6 @@ pub fn index_artifact(db: &Db, name: &str) -> Result<Option<(String, String)>> { }) } - pub fn our_package_names(db: &Db) -> Result<std::collections::BTreeSet<String>> { db.read(|c| { let mut stmt = c.prepare("SELECT DISTINCT name FROM package WHERE state='in_index'")?; @@ -93,10 +92,7 @@ pub fn our_package_names(db: &Db) -> Result<std::collections::BTreeSet<String>> } pub fn accepted_recipe(db: &Db, release: &ReleaseRow) -> Result<Option<Recipe>> { - let cid = match release.candidate_id { - Some(c) => c, - None => return Ok(None), - }; + let Some(cid) = release.candidate_id else { return Ok(None) }; db.read(move |c| { use rusqlite::OptionalExtension; Ok(c.query_row( @@ -123,4 +119,3 @@ pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<cr rows.collect::<::rusqlite::Result<Vec<_>>>().map_err(Into::into) }) } - diff --git a/src/db/pkgbases.rs b/src/db/pkgbases.rs index 743aa43..909291f 100644 --- a/src/db/pkgbases.rs +++ b/src/db/pkgbases.rs @@ -1,6 +1,6 @@ use rusqlite::{params, OptionalExtension, Row}; -use crate::db::*; +use crate::db::{release_by_id, Db, ReleaseRow, Writer}; use crate::error::Result; // ---------------------------------------------------------------- pkgbase -- @@ -33,25 +33,17 @@ const PKGBASE_COLS: &str = "id, name, aur_url, mirror_path, aur_head, \ pub fn get_pkgbase(db: &Db, name: &str) -> Result<Option<Pkgbase>> { db.read(|c| { - c.query_row( - &format!("SELECT {PKGBASE_COLS} FROM pkgbase WHERE name = ?1"), - params![name], - row_to_pkgbase, - ) - .optional() - .map_err(Into::into) + c.query_row(&format!("SELECT {PKGBASE_COLS} FROM pkgbase WHERE name = ?1"), params![name], row_to_pkgbase) + .optional() + .map_err(Into::into) }) } pub fn get_pkgbase_by_id(db: &Db, id: i64) -> Result<Option<Pkgbase>> { db.read(|c| { - c.query_row( - &format!("SELECT {PKGBASE_COLS} FROM pkgbase WHERE id = ?1"), - params![id], - row_to_pkgbase, - ) - .optional() - .map_err(Into::into) + c.query_row(&format!("SELECT {PKGBASE_COLS} FROM pkgbase WHERE id = ?1"), params![id], row_to_pkgbase) + .optional() + .map_err(Into::into) }) } @@ -66,19 +58,14 @@ pub fn accepted_release_for(db: &Db, pb: &Pkgbase) -> Result<Option<ReleaseRow>> } } - pub fn set_aur_head(writer: &Writer, pkgbase_id: i64, head: &str, mirror: &str) -> Result<()> { let (h, m) = (head.to_string(), mirror.to_string()); writer.tx(move |tx| { - tx.execute( - "UPDATE pkgbase SET aur_head=?1, mirror_path=?2 WHERE id=?3", - params![h, m, pkgbase_id], - )?; + tx.execute("UPDATE pkgbase SET aur_head=?1, mirror_path=?2 WHERE id=?3", params![h, m, pkgbase_id])?; Ok(()) }) } - /// Compare-and-set the accepted-release pointer. /// /// Test-tier only, and the reason is worth keeping next to it: production @@ -89,12 +76,7 @@ pub fn set_aur_head(writer: &Writer, pkgbase_id: i64, head: &str, mirror: &str) /// names differ by three characters, which is exactly how a name-match census /// once credited this function with a production caller it never had. #[cfg(feature = "test-support")] -pub fn cas_accepted_release( - writer: &Writer, - pkgbase_id: i64, - expected: Option<i64>, - new_id: i64, -) -> Result<bool> { +pub fn cas_accepted_release(writer: &Writer, pkgbase_id: i64, expected: Option<i64>, new_id: i64) -> Result<bool> { writer.tx(move |tx| { let n = tx.execute( "UPDATE pkgbase SET current_accepted_release_id=?1 @@ -104,4 +86,3 @@ pub fn cas_accepted_release( Ok(n == 1) }) } - diff --git a/src/db/publish_writes.rs b/src/db/publish_writes.rs index e5ce73f..11679cf 100644 --- a/src/db/publish_writes.rs +++ b/src/db/publish_writes.rs @@ -1,29 +1,24 @@ use rusqlite::{params, params_from_iter, OptionalExtension}; -use crate::db::*; +use crate::db::Db; use crate::error::Result; // ------------------------------------------------------------ publish writes -- pub fn artifact_path(db: &Db, id: i64) -> Result<Option<String>> { db.read(|c| { - Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", params![id], |r| r.get::<_, String>(0)) - .optional()?) + Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", params![id], |r| r.get::<_, String>(0)).optional()?) }) } fn artifact_id_by_digest_in(tx: &rusqlite::Transaction<'_>, digest: &str) -> Result<Option<i64>> { - Ok(tx - .query_row("SELECT id FROM artifact WHERE digest=?1", params![digest], |r| r.get::<_, i64>(0)) - .optional()?) + Ok(tx.query_row("SELECT id FROM artifact WHERE digest=?1", params![digest], |r| r.get::<_, i64>(0)).optional()?) } pub fn accepted_pointer_in(tx: &rusqlite::Transaction<'_>, pkgbase_id: i64) -> Result<Option<i64>> { - tx.query_row( - "SELECT current_accepted_release_id FROM pkgbase WHERE id=?1", - params![pkgbase_id], - |r| r.get::<_, Option<i64>>(0), - ) + tx.query_row("SELECT current_accepted_release_id FROM pkgbase WHERE id=?1", params![pkgbase_id], |r| { + r.get::<_, Option<i64>>(0) + }) .optional() .map(Option::flatten) .map_err(Into::into) @@ -54,10 +49,7 @@ pub fn remove_index_packages_in(tx: &rusqlite::Transaction<'_>, names: &[String] } pub fn remove_package_by_name_in(tx: &rusqlite::Transaction<'_>, repo_id: i64, name: &str) -> Result<()> { - tx.execute( - "UPDATE package SET state='removed' WHERE repo_id=?1 AND name=?2", - params![repo_id, name], - )?; + tx.execute("UPDATE package SET state='removed' WHERE repo_id=?1 AND name=?2", params![repo_id, name])?; Ok(()) } @@ -118,4 +110,3 @@ pub fn insert_package_in( )?; Ok(()) } - diff --git a/src/db/releases.rs b/src/db/releases.rs index cff31c1..78215cc 100644 --- a/src/db/releases.rs +++ b/src/db/releases.rs @@ -1,6 +1,6 @@ use rusqlite::{params, OptionalExtension, Row}; -use crate::db::*; +use crate::db::{Db, ReleaseRow, ReleaseState}; use crate::error::{Error, Missing, Refused, Result}; // ---------------------------------------------------------------- release -- @@ -32,17 +32,19 @@ const RELEASE_COLS_R: &str = "r.id, r.pkgbase_id, r.candidate_id, r.approval_id, r.world_snapshot_id, r.state, r.published_at"; pub fn withdraw_release_in(tx: &rusqlite::Transaction<'_>, release_id: i64) -> Result<()> { - let n = tx.execute( - "UPDATE release SET state='withdrawn' WHERE id=?1 AND state='published'", - params![release_id], - )?; + let n = + tx.execute("UPDATE release SET state='withdrawn' WHERE id=?1 AND state='published'", params![release_id])?; if n == 0 { - let state: Option<String> = tx - .query_row("SELECT state FROM release WHERE id=?1", params![release_id], |r| r.get(0)) - .optional()?; + let state: Option<String> = + tx.query_row("SELECT state FROM release WHERE id=?1", params![release_id], |r| r.get(0)).optional()?; return Err(match state.as_deref().map(ReleaseState::parse) { None => Error::not_found(Missing::Release(release_id)), - Some(Some(s)) => Error::conflict(Refused::WrongState { entity: "release", id: release_id.to_string(), found: s.to_string(), expected: "published" }), + Some(Some(s)) => Error::conflict(Refused::WrongState { + entity: "release", + id: release_id.to_string(), + found: s.to_string(), + expected: "published", + }), Some(None) => Error::invalid(format!( "release {release_id} has a state outside the state machine: {:?}", state.unwrap_or_default() @@ -55,13 +57,9 @@ pub fn withdraw_release_in(tx: &rusqlite::Transaction<'_>, release_id: i64) -> R pub fn release_by_id(db: &Db, id: i64) -> Result<Option<ReleaseRow>> { db.read(|c| { - c.query_row( - &format!("SELECT {RELEASE_COLS} FROM release WHERE id = ?1"), - params![id], - row_to_release, - ) - .optional() - .map_err(Into::into) + c.query_row(&format!("SELECT {RELEASE_COLS} FROM release WHERE id = ?1"), params![id], row_to_release) + .optional() + .map_err(Into::into) }) } @@ -71,7 +69,8 @@ pub fn accepted_release(db: &Db, pkgbase: &str) -> Result<Option<ReleaseRow>> { &format!( "SELECT {RELEASE_COLS_R} FROM release r JOIN pkgbase p ON p.current_accepted_release_id = r.id - WHERE p.name = ?1 AND r.state = 'published'"), + WHERE p.name = ?1 AND r.state = 'published'" + ), params![pkgbase], row_to_release, ) @@ -82,9 +81,7 @@ pub fn accepted_release(db: &Db, pkgbase: &str) -> Result<Option<ReleaseRow>> { pub fn releases_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<ReleaseRow>> { db.read(|c| { - let sql = format!( - "SELECT {RELEASE_COLS} FROM release WHERE pkgbase_id=?1 ORDER BY id DESC LIMIT ?2" - ); + let sql = format!("SELECT {RELEASE_COLS} FROM release WHERE pkgbase_id=?1 ORDER BY id DESC LIMIT ?2"); let mut stmt = c.prepare(&sql)?; let rows = stmt.query_map(params![pkgbase_id, limit], row_to_release)?; let mut out = Vec::new(); @@ -97,9 +94,7 @@ pub fn releases_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec< pub fn all_published_releases(db: &Db) -> Result<Vec<ReleaseRow>> { db.read(|c| { - let sql = format!( - "SELECT {RELEASE_COLS} FROM release WHERE state='published' ORDER BY pkgbase_id, id DESC" - ); + let sql = format!("SELECT {RELEASE_COLS} FROM release WHERE state='published' ORDER BY pkgbase_id, id DESC"); let mut stmt = c.prepare(&sql)?; let rows = stmt.query_map([], row_to_release)?; let mut out = Vec::new(); @@ -109,4 +104,3 @@ pub fn all_published_releases(db: &Db) -> Result<Vec<ReleaseRow>> { Ok(out) }) } - diff --git a/src/db/repos.rs b/src/db/repos.rs index 1906610..1423bdc 100644 --- a/src/db/repos.rs +++ b/src/db/repos.rs @@ -1,6 +1,6 @@ use rusqlite::{params, OptionalExtension}; -use crate::db::*; +use crate::db::{Db, Writer}; use crate::error::{Error, Missing, Result}; // -------------------------------------------------------------------- repo -- @@ -26,4 +26,3 @@ pub fn repo_id(db: &Db) -> Result<i64> { .ok_or_else(|| Error::not_found(Missing::RepoRow)) }) } - diff --git a/src/db/retention.rs b/src/db/retention.rs index 3e6f22f..75d9c29 100644 --- a/src/db/retention.rs +++ b/src/db/retention.rs @@ -1,6 +1,6 @@ use rusqlite::params; -use crate::db::*; +use crate::db::{Db, Writer}; use crate::error::Result; use crate::time; @@ -77,7 +77,15 @@ pub fn mark_release_purged(writer: &Writer, release_id: i64) -> Result<()> { }) } -pub fn record_gc_run(writer: &Writer, at: &str, kept: i64, evicted: i64, files_removed: i64, bytes_freed: i64, staging_swept: i64) -> Result<()> { +pub fn record_gc_run( + writer: &Writer, + at: &str, + kept: i64, + evicted: i64, + files_removed: i64, + bytes_freed: i64, + staging_swept: i64, +) -> Result<()> { let at = at.to_string(); writer.tx(move |tx| { tx.execute( @@ -88,4 +96,3 @@ pub fn record_gc_run(writer: &Writer, at: &str, kept: i64, evicted: i64, files_r Ok(()) }) } - diff --git a/src/db/settings.rs b/src/db/settings.rs index d42bb52..a8104a7 100644 --- a/src/db/settings.rs +++ b/src/db/settings.rs @@ -1,6 +1,6 @@ use rusqlite::{params, OptionalExtension}; -use crate::db::*; +use crate::db::{Db, Writer}; use crate::error::Result; // ---------------------------------------------------------------- settings -- @@ -53,4 +53,3 @@ pub fn set_setting(writer: &Writer, key: &str, value: &str) -> Result<()> { Ok(()) }) } - diff --git a/src/db/snapshots.rs b/src/db/snapshots.rs index 7966c8b..144cb0d 100644 --- a/src/db/snapshots.rs +++ b/src/db/snapshots.rs @@ -1,6 +1,6 @@ use rusqlite::{params, OptionalExtension}; -use crate::db::*; +use crate::db::{Db, Writer}; use crate::error::Result; use crate::time; @@ -15,12 +15,8 @@ pub fn put_snapshot( srcinfo_json: &str, files_json: &str, ) -> Result<i64> { - let (c, rh, si, fj) = ( - aur_commit.to_string(), - recipe_hash.to_string(), - srcinfo_json.to_string(), - files_json.to_string(), - ); + let (c, rh, si, fj) = + (aur_commit.to_string(), recipe_hash.to_string(), srcinfo_json.to_string(), files_json.to_string()); let at = time::now(); writer.tx(move |tx| { tx.execute( @@ -29,11 +25,9 @@ pub fn put_snapshot( ON CONFLICT(pkgbase_id, aur_commit) DO NOTHING", params![pkgbase_id, c, rh, si, fj, at], )?; - tx.query_row( - "SELECT id FROM snapshot WHERE pkgbase_id=?1 AND aur_commit=?2", - params![pkgbase_id, c], - |r| r.get(0), - ) + tx.query_row("SELECT id FROM snapshot WHERE pkgbase_id=?1 AND aur_commit=?2", params![pkgbase_id, c], |r| { + r.get(0) + }) .map_err(Into::into) }) } @@ -73,20 +67,10 @@ pub fn snapshot_by_commit(db: &Db, pkgbase_id: i64, commit: &str) -> Result<Opti pub fn snapshot_by_id(db: &Db, id: i64) -> Result<Option<SnapshotRow>> { db.read(|c| { - c.query_row( - "SELECT id, aur_commit, recipe_hash, srcinfo_json FROM snapshot WHERE id=?1", - params![id], - |r| { - Ok(SnapshotRow { - id: r.get(0)?, - aur_commit: r.get(1)?, - recipe_hash: r.get(2)?, - srcinfo_json: r.get(3)?, - }) - }, - ) + c.query_row("SELECT id, aur_commit, recipe_hash, srcinfo_json FROM snapshot WHERE id=?1", params![id], |r| { + Ok(SnapshotRow { id: r.get(0)?, aur_commit: r.get(1)?, recipe_hash: r.get(2)?, srcinfo_json: r.get(3)? }) + }) .optional() .map_err(Into::into) }) } - diff --git a/src/db/stage_b.rs b/src/db/stage_b.rs index bdcd836..7dd1129 100644 --- a/src/db/stage_b.rs +++ b/src/db/stage_b.rs @@ -1,11 +1,16 @@ use rusqlite::params; -use crate::db::*; +use crate::db::{Db, StageBCacheRow}; use crate::error::Result; // --------------------------------------------------------- stage B cache -- -pub fn stage_b_cache_get(db: &Db, pkgbase_id: i64, recipe_hash: &str, tip_hash: &str) -> Result<Option<StageBCacheRow>> { +pub fn stage_b_cache_get( + db: &Db, + pkgbase_id: i64, + recipe_hash: &str, + tip_hash: &str, +) -> Result<Option<StageBCacheRow>> { let (rh, th) = (recipe_hash.to_string(), tip_hash.to_string()); db.read(move |c| { use rusqlite::OptionalExtension; @@ -13,14 +18,7 @@ pub fn stage_b_cache_get(db: &Db, pkgbase_id: i64, recipe_hash: &str, tip_hash: "SELECT epoch, pkgver, pkgrel, pins_json FROM stage_b_cache WHERE pkgbase_id=?1 AND recipe_hash=?2 AND tip_hash=?3", params![pkgbase_id, rh, th], - |r| { - Ok(( - r.get::<_, String>(0)?, - r.get::<_, String>(1)?, - r.get::<_, String>(2)?, - r.get::<_, String>(3)?, - )) - }, + |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?)), ) .optional()? .map(|(epoch, pkgver, pkgrel, pins_json)| StageBCacheRow { @@ -41,14 +39,7 @@ pub fn stage_b_recent(db: &Db, pkgbase_id: i64, cooldown_secs: i64) -> Result<Op WHERE pkgbase_id=?1 AND resolved_at > ?2 ORDER BY resolved_at DESC LIMIT 1", params![pkgbase_id, cutoff], - |r| { - Ok(( - r.get::<_, String>(0)?, - r.get::<_, String>(1)?, - r.get::<_, String>(2)?, - r.get::<_, String>(3)?, - )) - }, + |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?)), ) .optional()? .map(|(epoch, pkgver, pkgrel, pins_json)| StageBCacheRow { @@ -83,4 +74,3 @@ pub fn stage_b_cache_put( Ok(()) }) } - diff --git a/src/db/staleness.rs b/src/db/staleness.rs index 59fccee..58be227 100644 --- a/src/db/staleness.rs +++ b/src/db/staleness.rs @@ -1,6 +1,6 @@ use rusqlite::{params, OptionalExtension}; -use crate::db::*; +use crate::db::{Db, Writer}; use crate::error::Result; use crate::time; @@ -33,11 +33,7 @@ pub fn served_vs_offered_pkgvers(db: &Db) -> Result<Vec<(String, String, String) WHERE r.state = 'published'", )?; let rows = st.query_map([], |r| { - Ok(( - r.get::<_, String>(0)?, - r.get::<_, String>(1)?, - r.get::<_, Option<String>>(2)?.unwrap_or_default(), - )) + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option<String>>(2)?.unwrap_or_default())) })?; Ok(rows.collect::<::rusqlite::Result<Vec<_>>>()?) }) @@ -63,10 +59,12 @@ pub fn index_recipes(db: &Db) -> Result<Vec<(String, String)>> { pub fn approval_note(db: &Db, approval_id: i64) -> Result<String> { db.read(|c| { - c.query_row("SELECT COALESCE(note,'') FROM approval WHERE id=?1", params![approval_id], |r| r.get::<_, String>(0)) - .optional() - .map(|o| o.unwrap_or_default()) - .map_err(Into::into) + c.query_row("SELECT COALESCE(note,'') FROM approval WHERE id=?1", params![approval_id], |r| { + r.get::<_, String>(0) + }) + .optional() + .map(std::option::Option::unwrap_or_default) + .map_err(Into::into) }) } @@ -77,7 +75,6 @@ pub fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Result<Option<i64>> }) } - pub fn put_source_cache(writer: &Writer, url: &str, digest: &str, size: u64, path: &str) -> Result<()> { let (u, d, p) = (url.to_string(), digest.to_string(), path.to_string()); let at = time::now(); @@ -93,11 +90,9 @@ pub fn put_source_cache(writer: &Writer, url: &str, digest: &str, size: u64, pat pub fn source_cache_path(db: &Db, url: &str, digest: &str) -> Result<Option<String>> { db.read(|c| { - Ok(c.query_row( - "SELECT path FROM source_cache WHERE url=?1 AND digest=?2", - params![url, digest], - |r| r.get::<_, String>(0), - ) + Ok(c.query_row("SELECT path FROM source_cache WHERE url=?1 AND digest=?2", params![url, digest], |r| { + r.get::<_, String>(0) + }) .optional()?) }) } @@ -121,4 +116,3 @@ pub fn insert_artifact_in(tx: &rusqlite::Transaction<'_>, a: &NewArtifact<'_>) - )?; Ok(()) } - diff --git a/src/db/subscriptions.rs b/src/db/subscriptions.rs index fc17de3..5b31f48 100644 --- a/src/db/subscriptions.rs +++ b/src/db/subscriptions.rs @@ -1,6 +1,6 @@ use rusqlite::{params, OptionalExtension, Row}; -use crate::db::*; +use crate::db::{Db, SubscriptionState, Writer}; use crate::error::Result; use crate::time; @@ -51,13 +51,9 @@ pub fn list_subscriptions(db: &Db) -> Result<Vec<Subscription>> { pub fn get_subscription(db: &Db, pkgbase: &str) -> Result<Option<Subscription>> { db.read(|c| { - c.query_row( - &format!("SELECT {SUB_COLS} FROM subscription WHERE pkgbase = ?1"), - params![pkgbase], - row_to_sub, - ) - .optional() - .map_err(Into::into) + c.query_row(&format!("SELECT {SUB_COLS} FROM subscription WHERE pkgbase = ?1"), params![pkgbase], row_to_sub) + .optional() + .map_err(Into::into) }) } @@ -83,17 +79,14 @@ pub fn subscribe(writer: &Writer, repo_id: i64, pkgbase: &str, aur_url: &str) -> pub fn set_subscription_state(writer: &Writer, pkgbase: &str, state: SubscriptionState) -> Result<()> { let (p, s) = (pkgbase.to_string(), state.to_string()); writer.tx(move |tx| { - tx.execute( - "UPDATE subscription SET state=?1 WHERE pkgbase=?2", - params![s, p], - )?; + tx.execute("UPDATE subscription SET state=?1 WHERE pkgbase=?2", params![s, p])?; Ok(()) }) } pub fn note_check(writer: &Writer, pkgbase: &str, next_check_at: &str, err: Option<&str>) -> Result<()> { let (p, n) = (pkgbase.to_string(), next_check_at.to_string()); - let e = err.map(|s| s.to_string()); + let e = err.map(std::string::ToString::to_string); let at = time::now(); writer.tx(move |tx| { tx.execute( @@ -120,4 +113,3 @@ pub fn due_subscriptions(db: &Db, now: &str) -> Result<Vec<Subscription>> { Ok(out) }) } - diff --git a/src/db/world.rs b/src/db/world.rs index 73e327f..19a28f1 100644 --- a/src/db/world.rs +++ b/src/db/world.rs @@ -1,6 +1,6 @@ use rusqlite::params; -use crate::db::*; +use crate::db::{json_or, Db, WorldMember, Writer}; use crate::error::Result; use crate::time; @@ -19,8 +19,7 @@ pub fn put_world_snapshot(writer: &Writer, members: &[WorldMember]) -> Result<i6 ON CONFLICT(hash) DO NOTHING", params![hash, json, at], )?; - tx.query_row("SELECT id FROM world_snapshot WHERE hash=?1", params![hash], |r| r.get(0)) - .map_err(Into::into) + tx.query_row("SELECT id FROM world_snapshot WHERE hash=?1", params![hash], |r| r.get(0)).map_err(Into::into) }) } @@ -31,12 +30,8 @@ pub fn put_world_snapshot(writer: &Writer, members: &[WorldMember]) -> Result<i6 #[cfg(feature = "test-support")] pub fn world_members(db: &Db, id: i64) -> Result<Vec<WorldMember>> { db.read(|c| { - let s: String = c.query_row( - "SELECT members_json FROM world_snapshot WHERE id=?1", - params![id], - |r| r.get(0), - )?; + let s: String = + c.query_row("SELECT members_json FROM world_snapshot WHERE id=?1", params![id], |r| r.get(0))?; Ok(json_or(&s, Vec::new())) }) } - diff --git a/src/error.rs b/src/error.rs index 2159d46..737dce1 100644 --- a/src/error.rs +++ b/src/error.rs @@ -63,10 +63,9 @@ impl fmt::Display for Refused { Refused::WrongState { entity, id, found, expected } => { write!(f, "{entity} {id} is {found}, not {expected}") } - Refused::PointerMoved { pkgbase } => write!( - f, - "accepted pointer moved while this build was running; refusing to publish ({pkgbase})" - ), + Refused::PointerMoved { pkgbase } => { + write!(f, "accepted pointer moved while this build was running; refusing to publish ({pkgbase})") + } Refused::Other(s) => write!(f, "{s}"), } } @@ -115,7 +114,9 @@ pub enum WorldGap { impl fmt::Display for WorldGap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - WorldGap::MissingPin { package } => write!(f, "sandbox world is missing {package} after installing the lease set"), + WorldGap::MissingPin { package } => { + write!(f, "sandbox world is missing {package} after installing the lease set") + } WorldGap::Other(s) => write!(f, "{s}"), } } @@ -419,9 +420,10 @@ mod tests { // The `From<&str>` arms exist so typing is incremental: a guard that is // genuinely just a sentence lands in Invariant/Other rather than // blocking the refactor. - assert!(matches!(Error::fail_closed("no aur_commit on the source identity"), - Error::FailClosed(Guard::Invariant(_)))); - assert!(matches!(Error::not_found("snapshot for build"), - Error::NotFound(Missing::Other(_)))); + assert!(matches!( + Error::fail_closed("no aur_commit on the source identity"), + Error::FailClosed(Guard::Invariant(_)) + )); + assert!(matches!(Error::not_found("snapshot for build"), Error::NotFound(Missing::Other(_)))); } } diff --git a/src/fetch.rs b/src/fetch.rs index 98876bc..d9689aa 100644 --- a/src/fetch.rs +++ b/src/fetch.rs @@ -31,9 +31,7 @@ fn open(url: &str) -> Result<(Body, Option<u64>)> { .timeout(std::time::Duration::from_secs(300)) .call() .map_err(|e| Error::Http(format!("{url}: {e}")))?; - let len = resp - .header("content-length") - .and_then(|v| v.parse::<u64>().ok()); + let len = resp.header("content-length").and_then(|v| v.parse::<u64>().ok()); return Ok((Body::Http(resp.into_reader()), len)); } Err(Error::invalid(format!("unsupported url scheme: {url}"))) @@ -14,10 +14,10 @@ pub fn git(cwd: Option<&Path>, args: &[&str]) -> Result<String> { cmd.env("GIT_CONFIG_NOSYSTEM", "1"); cmd.env("LC_ALL", "C"); let out = cmd.output().map_err(|e| Error::git(format!("git {args:?}: {e}")))?; - ok(out, args) + ok(&out, args) } -fn ok(out: Output, args: &[&str]) -> Result<String> { +fn ok(out: &Output, args: &[&str]) -> Result<String> { if !out.status.success() { return Err(Error::git(format!( "git {args:?} exited {}: {}", @@ -35,11 +35,7 @@ fn git_ok(cwd: Option<&Path>, args: &[&str]) -> bool { pub fn ls_remote_head(url: &str) -> Result<Option<String>> { match git(None, &["ls-remote", url, "HEAD"]) { Ok(out) => { - let sha = out - .split_whitespace() - .next() - .filter(|s| s.len() >= 7) - .map(|s| s.to_string()); + let sha = out.split_whitespace().next().filter(|s| s.len() >= 7).map(std::string::ToString::to_string); Ok(sha) } Err(e) if is_missing_remote(&e) => Ok(None), @@ -49,11 +45,9 @@ pub fn ls_remote_head(url: &str) -> Result<Option<String>> { pub fn ls_remote_ref(url: &str, refname: &str) -> Result<Option<String>> { match git(None, &["ls-remote", url, refname]) { - Ok(out) => Ok(out - .lines() - .next() - .and_then(|l| l.split_whitespace().next()) - .map(|s| s.to_string())), + Ok(out) => { + Ok(out.lines().next().and_then(|l| l.split_whitespace().next()).map(std::string::ToString::to_string)) + } Err(e) if is_missing_remote(&e) => Ok(None), Err(e) => Err(e), } @@ -85,10 +79,7 @@ pub fn clone_bare(url: &str, dest: &Path) -> Result<()> { if let Some(parent) = dest.parent() { std::fs::create_dir_all(parent)?; } - git( - None, - &["clone", "--quiet", "--bare", url, &dest.display().to_string()], - )?; + git(None, &["clone", "--quiet", "--bare", url, &dest.display().to_string()])?; Ok(()) } @@ -180,12 +171,7 @@ pub fn cat_file_batch(mirror: &Path, oids: &[String]) -> Result<BTreeMap<String, stdout.read_exact(&mut newline)?; out.insert(id, body); } - _ => { - return Err(Error::git(format!( - "unreadable cat-file header {:?}", - header.trim_end() - ))) - } + _ => return Err(Error::git(format!("unreadable cat-file header {:?}", header.trim_end()))), } } @@ -215,15 +201,11 @@ pub fn materialize(mirror: &Path, commit: &str, dest: &Path) -> Result<()> { .output() .map_err(|e| Error::git(e.to_string()))?; if !out.status.success() { - return Err(Error::git(format!( - "git archive {commit}: {}", - String::from_utf8_lossy(&out.stderr).trim() - ))); + return Err(Error::git(format!("git archive {commit}: {}", String::from_utf8_lossy(&out.stderr).trim()))); } let mut ar = tar::Archive::new(std::io::Cursor::new(&out.stdout)); ar.set_preserve_permissions(true); - ar.unpack(dest) - .map_err(|e| Error::git(format!("unpack {commit}: {e}")))?; + ar.unpack(dest).map_err(|e| Error::git(format!("unpack {commit}: {e}")))?; Ok(()) } diff --git a/src/http/auth.rs b/src/http/auth.rs index 0f174ef..9c7a733 100644 --- a/src/http/auth.rs +++ b/src/http/auth.rs @@ -15,10 +15,7 @@ fn random_hex() -> Option<String> { let mut buf = [0u8; 32]; let mut f = std::fs::File::open("/dev/urandom").ok()?; f.read_exact(&mut buf).ok()?; - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); let salt = format!("{:?}", (buf, nanos, std::process::id(), counter())); Some(hash::hex(salt.as_bytes())) } @@ -37,7 +34,7 @@ pub(crate) fn new_session() -> Option<String> { } pub(crate) fn is_valid_session(sid: &str) -> bool { - sessions().lock().map(|s| s.contains_key(sid)).unwrap_or(false) + sessions().lock().is_ok_and(|s| s.contains_key(sid)) } pub(crate) fn authenticate(sid: &str) { @@ -49,7 +46,7 @@ pub(crate) fn authenticate(sid: &str) { } pub(crate) fn is_authenticated(sid: &str) -> bool { - sessions().lock().map(|s| s.get(sid).copied().unwrap_or(false)).unwrap_or(false) + sessions().lock().is_ok_and(|s| s.get(sid).copied().unwrap_or(false)) } pub(crate) fn drop_session(sid: &str) { diff --git a/src/http/forms.rs b/src/http/forms.rs index 579b931..802855b 100644 --- a/src/http/forms.rs +++ b/src/http/forms.rs @@ -9,15 +9,12 @@ pub fn decode(s: &str) -> String { i += 1; } b'%' if i + 2 < bytes.len() => { - match u8::from_str_radix(&s[i + 1..i + 3], 16) { - Ok(v) => { - out.push(v); - i += 3; - } - Err(_) => { - out.push(bytes[i]); - i += 1; - } + if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) { + out.push(v); + i += 3; + } else { + out.push(bytes[i]); + i += 1; } } c => { diff --git a/src/http/mod.rs b/src/http/mod.rs index f10d4e2..a437978 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -24,7 +24,7 @@ struct Req { } impl Req { -/// Read by the route handlers, which are in this module; the word `form` in a test is a local parameter. + /// Read by the route handlers, which are in this module; the word `form` in a test is a local parameter. fn form(&self) -> &[(String, String)] { &self.form_pairs } @@ -65,10 +65,24 @@ struct Res { impl Res { /// `pub(crate)`, not `pub`: the census counted it as test-only because the word appears in `tests/http.rs`, but only inside a string — a route path, a content type, the word "redirect" in an assertion message. Nothing in the test tier calls it. fn html(status: u16, body: String) -> Self { - Self { status, content_type: "text/html; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new(), stream: None, stream_len: None } + Self { + status, + content_type: "text/html; charset=utf-8".into(), + body: body.into_bytes(), + headers: Vec::new(), + stream: None, + stream_len: None, + } } pub fn text(status: u16, body: String) -> Self { - Self { status, content_type: "text/plain; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new(), stream: None, stream_len: None } + Self { + status, + content_type: "text/plain; charset=utf-8".into(), + body: body.into_bytes(), + headers: Vec::new(), + stream: None, + stream_len: None, + } } pub fn stream(content_type: &str, reader: impl std::io::Read + Send + 'static, known_len: Option<usize>) -> Self { Self { @@ -118,32 +132,29 @@ pub use server::Server; pub(crate) use server::Server; pub fn spawn(cfg: Config, db: Db) -> std::io::Result<Server> { - let server = tiny_http::Server::http(&cfg.bind) - .map_err(|e| std::io::Error::other(e.to_string()))?; - let addr = server.server_addr().to_ip().map(|a| a.to_string()).unwrap_or_else(|| cfg.bind.clone()); + let server = tiny_http::Server::http(&cfg.bind).map_err(|e| std::io::Error::other(e.to_string()))?; + let addr = server.server_addr().to_ip().map_or_else(|| cfg.bind.clone(), |a| a.to_string()); let state = Arc::new(State { cfg, db }); eprintln!("aur-build listening on http://{addr}"); // Detached on purpose: the accept loop owns the listener and runs until the // process ends, and nothing joins it, so the handle would be stored unread. - std::thread::Builder::new() - .name("http-accept".into()) - .spawn(crate::time::inherit(move || { - for request in server.incoming_requests() { - let state = state.clone(); - std::thread::Builder::new() - .name("http-conn".into()) - .spawn(crate::time::inherit(move || { - if let Err(e) = serve(state, request) { - eprintln!("http: {e}"); - } - })) - .ok(); - } - }))?; + std::thread::Builder::new().name("http-accept".into()).spawn(crate::time::inherit(move || { + for request in server.incoming_requests() { + let state = state.clone(); + std::thread::Builder::new() + .name("http-conn".into()) + .spawn(crate::time::inherit(move || { + if let Err(e) = serve(&state, request) { + eprintln!("http: {e}"); + } + })) + .ok(); + } + }))?; Ok(Server { addr }) } -fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<()> { +fn serve(state: &State, mut request: tiny_http::Request) -> std::io::Result<()> { let url = request.url().to_string(); let (path, query) = match url.split_once('?') { Some((p, q)) => (p.to_string(), q.to_string()), @@ -155,14 +166,12 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result< .headers() .iter() .find(|h| h.field.equiv("Cookie")) - .map(|h| auth::parse_cookies(h.value.as_str())) - .unwrap_or_default(); + .map_or_default(|h| auth::parse_cookies(h.value.as_str())); let accept_gzip = request .headers() .iter() .find(|h| h.field.equiv("Accept-Encoding")) - .map(|h| h.value.as_str().contains("gzip")) - .unwrap_or(false); + .is_some_and(|h| h.value.as_str().contains("gzip")); let form_pairs = forms::parse(&body); let req = Req { method: request.method().as_str().to_string(), @@ -173,7 +182,7 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result< accept_gzip, }; - let mut res = dispatch(&state, &req); + let mut res = dispatch(state, &req); if let Some(sid) = res.headers.iter().find(|(k, _)| k == "X-New-Session").map(|(_, v)| v.clone()) { res.headers.retain(|(k, _)| k != "X-New-Session"); res.header("Set-Cookie", &format!("sid={sid}; Path=/; HttpOnly; SameSite=Strict")); @@ -188,13 +197,8 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result< } } if let Some(reader) = res.stream.take() { - let mut resp = tiny_http::Response::new( - tiny_http::StatusCode(res.status), - headers, - reader, - res.stream_len, - None, - ); + let mut resp = + tiny_http::Response::new(tiny_http::StatusCode(res.status), headers, reader, res.stream_len, None); if res.stream_len.is_some() { resp = resp.with_chunked_threshold(usize::MAX); } diff --git a/src/http/render.rs b/src/http/render.rs index 6e1083b..316988a 100644 --- a/src/http/render.rs +++ b/src/http/render.rs @@ -185,12 +185,7 @@ pub(crate) use panel::Panel; impl Panel { /// Built by the route handlers, which are in this module. pub(crate) fn new(title: &str, body: String) -> Self { - Self { - title: title.into(), - empty: body.trim().is_empty(), - empty_note: "no change".into(), - body, - } + Self { title: title.into(), empty: body.trim().is_empty(), empty_note: "no change".into(), body } } } @@ -419,21 +414,13 @@ pub(crate) fn static_asset(name: &str, accept_gzip: bool) -> crate::http::Res { "htmx.min.js" => { if accept_gzip { let gz: &[u8] = std::include_bytes!("../../static/htmx.min.js.gz"); - let mut r = Res::stream( - "text/javascript", - std::io::Cursor::new(gz.to_vec()), - Some(gz.len()), - ); + let mut r = Res::stream("text/javascript", std::io::Cursor::new(gz.to_vec()), Some(gz.len())); r.header("Content-Encoding", "gzip"); r.header("Cache-Control", "public, max-age=86400"); return r; } let raw: &[u8] = std::include_bytes!("../../static/htmx.min.js"); - let mut r = Res::stream( - "text/javascript", - std::io::Cursor::new(raw.to_vec()), - Some(raw.len()), - ); + let mut r = Res::stream("text/javascript", std::io::Cursor::new(raw.to_vec()), Some(raw.len())); r.header("Cache-Control", "public, max-age=86400"); r } diff --git a/src/http/routes/mod.rs b/src/http/routes/mod.rs index 2b9ebb9..1affabf 100644 --- a/src/http/routes/mod.rs +++ b/src/http/routes/mod.rs @@ -1,21 +1,27 @@ -use crate::db::{self, builds, model::*}; -use crate::review::candidates; -use crate::time; use super::auth; -use super::render::*; +use super::render::{ + Attention, Audit, AuditRow, BlockedRow, BuildDetail, BuildLite, BuildRow, Builds, BuildsTable, Dashboard, + ErrorPage, IndexRow, Login, NoticeRow, PackageDetail, Packages, Page, Panel, PublishRow, ReviewDetail, ReviewHead, + ReviewRow, ReviewsPage, SettingRow, Settings, StaleRow, StepRow, SubRow, Subscriptions, TimelineRow, UnbuiltRow, +}; use super::{Req, Res, State}; +use crate::db::{ + self, builds, + model::{candidate_kind, BuildState, CandidateRow, Recipe, StepState, SubscriptionState}, +}; +use crate::review::candidates; +use crate::time; mod mutations; mod pages; pub(crate) use mutations::{ - build_cancel, build_retry, notice_ack, package_rebuild, package_withdraw, review_approve, - review_reject, reviews_bulk, sub_add, sub_pause, sub_remove, + build_cancel, build_retry, notice_ack, package_rebuild, package_withdraw, review_approve, review_reject, + reviews_bulk, sub_add, sub_pause, sub_remove, }; pub(crate) use pages::{ - attention, audit, build_detail, build_log, build_log_stream, builds_page, builds_with, - dashboard, metrics, package_detail, packages, panels_base, review_body, review_detail, - review_rows, reviews, settings, subscriptions, + attention, audit, build_detail, build_log, build_log_stream, builds_page, builds_with, dashboard, metrics, + package_detail, packages, panels_base, review_body, review_detail, review_rows, reviews, settings, subscriptions, }; pub(crate) fn gate(state: &State, req: &Req, sid: &str) -> Option<Res> { @@ -64,9 +70,8 @@ fn login_impl(state: &State, req: &Req) -> Res { if let Some(old) = req.cookie("sid") { auth::drop_session(&old); } - let sid = match auth::new_session() { - Some(sid) => sid, - None => return page_to_res(Login { page, error: "server: no entropy for a session".into() }, 500), + let Some(sid) = auth::new_session() else { + return page_to_res(Login { page, error: "server: no entropy for a session".into() }, 500); }; auth::authenticate(&sid); let mut res = Res::redirect("/"); @@ -111,25 +116,16 @@ pub(crate) fn route(state: &State, req: &Req, seg: &[&str]) -> Res { fn not_found(state: &State, req: &Req) -> Res { let page = chrome(state, req, "Not found", "nav_packages"); - page_to_res( - ErrorPage { - page, - status: "404".into(), - message: "no such page".into(), - detail: String::new(), - }, - 404, - ) + page_to_res(ErrorPage { page, status: "404".into(), message: "no such page".into(), detail: String::new() }, 404) } fn chrome(state: &State, req: &Req, title: &str, active: &str) -> Page { let db = &state.db; let mut page = Page::new(title, csrf(state, req)); - page.pending = candidates::pending_candidates(db).map(|v| v.len() as i64).unwrap_or(0); - page.running = builds::in_flight(db).map(|v| v as i64).unwrap_or(0) - + builds::queue_depth(db).map(|v| v as i64).unwrap_or(0); - page.attention = db::list_notices(db, false).map(|v| v.len() as i64).unwrap_or(0) - + builds::blocked_builds(db).map(|v| v.len() as i64).unwrap_or(0); + page.pending = candidates::pending_candidates(db).map_or(0, |v| v.len() as i64); + page.running = builds::in_flight(db).map_or(0, |v| v as i64) + builds::queue_depth(db).map_or(0, |v| v as i64); + page.attention = db::list_notices(db, false).map_or(0, |v| v.len() as i64) + + builds::blocked_builds(db).map_or(0, |v| v.len() as i64); page.nav_reviews = if active == "nav_reviews" { "on" } else { "" }; page.nav_builds = if active == "nav_builds" { "on" } else { "" }; page.nav_attention = if active == "nav_attention" { "on" } else { "" }; @@ -142,7 +138,7 @@ fn chrome(state: &State, req: &Req, title: &str, active: &str) -> Page { } fn csrf(_state: &State, req: &Req) -> String { - req.cookie("sid").map(|s| auth::csrf_token(&s)).unwrap_or_default() + req.cookie("sid").map_or_default(|s| auth::csrf_token(&s)) } fn human_size(bytes: i64) -> String { diff --git a/src/http/routes/mutations.rs b/src/http/routes/mutations.rs index ad11dfa..0d3b188 100644 --- a/src/http/routes/mutations.rs +++ b/src/http/routes/mutations.rs @@ -2,7 +2,10 @@ use crate::http::{Req, Res, State}; use crate::review::candidates; use crate::usecase; -use super::*; +use super::{ + actor, builds_with, chrome, flash_sub, not_found, page_to_res, panels_base, review_body, review_rows, short, + Packages, ReviewDetail, ReviewsPage, +}; // -------------------------------------------------------------- approve -- @@ -102,21 +105,9 @@ pub(crate) fn review_reject(state: &State, req: &Req, id: &str) -> Res { pub(crate) fn reviews_bulk(state: &State, req: &Req) -> Res { let db = &state.db; let form = req.form(); - let ids: Vec<i64> = form - .iter() - .filter(|(k, _)| k == "ids") - .filter_map(|(_, v)| v.parse().ok()) - .collect(); - let decision = form - .iter() - .find(|(k, _)| k == "decision") - .map(|(_, v)| v.clone()) - .unwrap_or_default(); - let confirmed: Vec<i64> = form - .iter() - .filter(|(k, _)| k == "confirm") - .filter_map(|(_, v)| v.parse().ok()) - .collect(); + let ids: Vec<i64> = form.iter().filter(|(k, _)| k == "ids").filter_map(|(_, v)| v.parse().ok()).collect(); + let decision = form.iter().find(|(k, _)| k == "decision").map_or_default(|(_, v)| v.clone()); + let confirmed: Vec<i64> = form.iter().filter(|(k, _)| k == "confirm").filter_map(|(_, v)| v.parse().ok()).collect(); if ids.is_empty() { let mut page = chrome(state, req, "Reviews", "nav_reviews"); page.flash = "nothing selected".into(); @@ -185,9 +176,7 @@ pub(crate) fn sub_pause(state: &State, req: &Req) -> Res { 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) - } + Ok(usecase::Pause::Unknown) | Err(_) => flash_sub(state, req, &format!("no subscription for {name}"), true), } } diff --git a/src/http/routes/pages.rs b/src/http/routes/pages.rs index e8590b0..9081180 100644 --- a/src/http/routes/pages.rs +++ b/src/http/routes/pages.rs @@ -1,9 +1,15 @@ use crate::db::{self, builds, Db}; -use crate::review::{candidates, diff, risk}; -use crate::ops; use crate::http::{sse, Req, Res, State}; +use crate::ops; +use crate::review::{candidates, diff, risk}; -use super::*; +use super::{ + age, candidate_kind, chrome, human_size, not_found, page_to_res, short, Attention, Audit, AuditRow, BlockedRow, + BuildDetail, BuildLite, BuildRow, BuildState, Builds, BuildsTable, CandidateRow, Dashboard, IndexRow, NoticeRow, + PackageDetail, Packages, Page, Panel, PublishRow, Recipe, ReviewDetail, ReviewHead, ReviewRow, ReviewsPage, + SettingRow, Settings, StaleRow, StepRow, StepState, SubRow, SubscriptionState, Subscriptions, TimelineRow, + UnbuiltRow, +}; // ------------------------------------------------------------- dashboard -- @@ -28,11 +34,11 @@ pub(crate) fn dashboard(state: &State, req: &Req) -> Res { page_to_res( Dashboard { page, - subscriptions: db::list_subscriptions(db).map(|v| v.len() as i64).unwrap_or(0), - index_count: db::index_packages(db).map(|v| v.len() as i64).unwrap_or(0), - pending_reviews: candidates::pending_candidates(db).map(|v| v.len() as i64).unwrap_or(0), - running_builds: builds::in_flight(db).map(|v| v as i64).unwrap_or(0), - attention: db::list_notices(db, false).map(|v| v.len() as i64).unwrap_or(0), + subscriptions: db::list_subscriptions(db).map_or(0, |v| v.len() as i64), + index_count: db::index_packages(db).map_or(0, |v| v.len() as i64), + pending_reviews: candidates::pending_candidates(db).map_or(0, |v| v.len() as i64), + running_builds: builds::in_flight(db).map_or(0, |v| v as i64), + attention: db::list_notices(db, false).map_or(0, |v| v.len() as i64), publishes, }, 200, @@ -110,10 +116,7 @@ pub(crate) fn panels_base(c: &CandidateRow) -> (String, bool) { } } -pub(crate) fn review_body( - state: &State, - c: &CandidateRow, -) -> (ReviewHead, Vec<Panel>, String, String, String, String) { +pub(crate) fn review_body(state: &State, c: &CandidateRow) -> (ReviewHead, Vec<Panel>, String, String, String, String) { let db = &state.db; let base = match c.base_release_id { Some(id) => db::release_by_id(db, id).unwrap_or(None), @@ -123,7 +126,7 @@ pub(crate) fn review_body( let rendered = diff::render_text(&panels); let _ = rendered; let snapshot = db::snapshot_by_id(db, c.snapshot_id).unwrap_or(None); - let recipe_json = snapshot.as_ref().map(|s| s.srcinfo_json.clone()).unwrap_or_default(); + let recipe_json = snapshot.as_ref().map_or_default(|s| s.srcinfo_json.clone()); let parsed: Option<Recipe> = serde_json::from_str(&recipe_json).ok(); let is_first = c.kind == candidate_kind::FIRST_INTRODUCTION; @@ -138,39 +141,29 @@ pub(crate) fn review_body( missing_deps: c.missing_deps(), dependents: crate::watch::staleness::dependents_of(db, &c.pkgbase).unwrap_or_default(), revision: c.revision, - aur_commit: snapshot.as_ref().map(|s| s.aur_commit.clone()).unwrap_or_default(), - aur_commit_short: snapshot - .as_ref() - .map(|s| short(&s.aur_commit)) - .unwrap_or_default(), + aur_commit: snapshot.as_ref().map_or_default(|s| s.aur_commit.clone()), + aur_commit_short: snapshot.as_ref().map_or_default(|s| short(&s.aur_commit)), identity_hash: c.identity_hash.clone(), diff_digest: c.diff_digest.clone(), }; - let shown: Vec<Panel> = panels - .iter() - .map(|p| Panel::new(p.title, p.body.clone())) - .collect(); + let shown: Vec<Panel> = panels.iter().map(|p| Panel::new(p.title, p.body.clone())).collect(); let (recipe_text, srcinfo) = match &parsed { Some(r) => (r.pkgbuild.clone(), r.srcinfo.clone().unwrap_or_default()), None => (String::new(), String::new()), }; let sources_resolved = serde_json::to_string_pretty( - &serde_json::from_str::<serde_json::Value>(&c.source_digests_json) - .unwrap_or_else(|_| serde_json::json!([])), + &serde_json::from_str::<serde_json::Value>(&c.source_digests_json).unwrap_or_else(|_| serde_json::json!([])), ) .unwrap_or_default(); - let deps_resolved = parsed - .as_ref() - .map(|r| { - format!( - "depends: {}\nmakedepends: {}\ncheckdepends: {}\noptdepends: {}", - r.depends.join(", "), - r.makedepends.join(", "), - r.checkdepends.join(", "), - r.optdepends.join(", ") - ) - }) - .unwrap_or_default(); + let deps_resolved = parsed.as_ref().map_or_default(|r| { + format!( + "depends: {}\nmakedepends: {}\ncheckdepends: {}\noptdepends: {}", + r.depends.join(", "), + r.makedepends.join(", "), + r.checkdepends.join(", "), + r.optdepends.join(", ") + ) + }); (head, shown, recipe_text, srcinfo, sources_resolved, deps_resolved) } @@ -249,15 +242,9 @@ pub(crate) fn attention(state: &State, req: &Req) -> Res { build_id: u.build_id, }) .collect(); - let empty = notices.is_empty() - && unbuilt.is_empty() - && outdated.is_empty() - && missing.is_empty() - && blocked.is_empty(); - page_to_res( - Attention { page, empty, notices, unbuilt, outdated, missing, downgrades, blocked }, - 200, - ) + let empty = + notices.is_empty() && unbuilt.is_empty() && outdated.is_empty() && missing.is_empty() && blocked.is_empty(); + page_to_res(Attention { page, empty, notices, unbuilt, outdated, missing, downgrades, blocked }, 200) } // ------------------------------------------------------------- packages -- @@ -272,7 +259,7 @@ pub(crate) fn packages(state: &State, req: &Req) -> Res { name: p.name.clone(), version: p.version.clone(), arch: p.arch.clone(), - size: p.size.map(human_size).unwrap_or_else(|| "—".into()), + size: p.size.map_or_else(|| "—".into(), human_size), published_at: p.published_at.clone().unwrap_or_else(|| "—".into()), }) .collect(); @@ -317,16 +304,13 @@ pub(crate) fn package_detail(state: &State, req: &Req, name: &str) -> Res { step: b.current_step.unwrap_or_default(), }) .collect(); - let deps_in: Vec<String> = accepted - .as_ref() - .and_then(|r| db::accepted_recipe(db, r).ok().flatten()) - .map(|r| { + let deps_in: Vec<String> = + accepted.as_ref().and_then(|r| db::accepted_recipe(db, r).ok().flatten()).map_or_default(|r| { let mut v = crate::pkgver::dep_names(&r.depends); v.sort(); v.dedup(); v - }) - .unwrap_or_default(); + }); let deps_out: Vec<String> = crate::watch::staleness::dependents_of(db, name).unwrap_or_default(); let stale: Vec<String> = crate::watch::staleness::stale_for(db, name) .unwrap_or_default() @@ -383,43 +367,32 @@ fn build_version(db: &Db, b: &builds::BuildRow) -> String { } fn build_rows(state: &State) -> Vec<BuildRow> { - builds::list( - &state.db, - BuildState::active(), - 100, - ) - .unwrap_or_default() - .into_iter() - .map(|b| { - let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id) - .ok() - .flatten() - .map(|p| p.name) - .unwrap_or_default(); - let version = build_version(&state.db, &b); - BuildRow { - id_short: short(&b.id), - id: b.id, - pkgbase, - version, - kind: b.kind, - state: b.state.to_string(), - step: b.current_step.unwrap_or_default(), - lease: b.lease_expires_at.unwrap_or_else(|| "—".into()), - cancel: b.cancel_requested, - error: b.error.unwrap_or_default(), - } - }) - .collect() + builds::list(&state.db, BuildState::active(), 100) + .unwrap_or_default() + .into_iter() + .map(|b| { + let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id).ok().flatten().map_or_default(|p| p.name); + let version = build_version(&state.db, &b); + BuildRow { + id_short: short(&b.id), + id: b.id, + pkgbase, + version, + kind: b.kind, + state: b.state.to_string(), + step: b.current_step.unwrap_or_default(), + lease: b.lease_expires_at.unwrap_or_else(|| "—".into()), + cancel: b.cancel_requested, + error: b.error.unwrap_or_default(), + } + }) + .collect() } pub(crate) fn builds_page(state: &State, req: &Req) -> Res { let page = chrome(state, req, "Builds", "nav_builds"); if req.query_get("fragment").as_deref() == Some("1") { - return page_to_res( - BuildsTable { page, rows: build_rows(state), recent: recent_rows(state) }, - 200, - ); + return page_to_res(BuildsTable { page, rows: build_rows(state), recent: recent_rows(state) }, 200); } builds_with(state, req, page) } @@ -429,7 +402,7 @@ fn recent_rows(state: &State) -> Vec<BuildRow> { .unwrap_or_default() .into_iter() .map(|b| { - let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id).ok().flatten().map(|p| p.name).unwrap_or_default(); + let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id).ok().flatten().map_or_default(|p| p.name); let version = build_version(&state.db, &b); BuildRow { id_short: short(&b.id), @@ -477,7 +450,7 @@ pub(crate) fn build_detail(state: &State, req: &Req, id: &str) -> Res { let lines: Vec<&str> = all.lines().collect(); let tail = lines[lines.len().saturating_sub(200)..].join("\n"); let blocked_on: Vec<String> = serde_json::from_str(&b.blocked_on_json).unwrap_or_default(); - let pkgbase = db::get_pkgbase_by_id(db, b.pkgbase_id).ok().flatten().map(|p| p.name).unwrap_or_default(); + let pkgbase = db::get_pkgbase_by_id(db, b.pkgbase_id).ok().flatten().map_or_default(|p| p.name); page_to_res( BuildDetail { page, diff --git a/src/http/sse.rs b/src/http/sse.rs index 03e09ff..36a9d42 100644 --- a/src/http/sse.rs +++ b/src/http/sse.rs @@ -13,7 +13,7 @@ const POLL: Duration = Duration::from_millis(200); /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod log_tail { - use super::*; + use super::{builds, io, read_from, Duration, Instant, PathBuf, Read, KEEPALIVE, MAX_LIFETIME, POLL}; pub struct LogTail { path: PathBuf, @@ -120,13 +120,8 @@ pub use log_tail::LogTail; #[cfg(not(feature = "test-support"))] pub(crate) use log_tail::LogTail; - - fn read_from(path: &Path, offset: u64) -> (Vec<u8>, bool) { - let mut f = match std::fs::File::open(path) { - Ok(f) => f, - Err(_) => return (Vec::new(), false), - }; + let Ok(mut f) = std::fs::File::open(path) else { return (Vec::new(), false) }; use std::io::Seek; if f.seek(std::io::SeekFrom::Start(offset)).is_err() { return (Vec::new(), false); diff --git a/src/main.rs b/src/main.rs index 118d06e..5881102 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,7 @@ use std::path::PathBuf; use clap::{Parser, Subcommand}; use aur_build::config::Config; -use aur_build::db::{self, builds, model::*}; +use aur_build::db::{self, builds, model::BuildState}; use aur_build::pipeline; use aur_build::review::candidates; use aur_build::usecase; @@ -30,13 +30,19 @@ enum Cmd { #[arg(long)] url: Option<String>, }, - Unsubscribe { pkgbase: String }, - Detect { pkgbase: Option<String> }, + Unsubscribe { + pkgbase: String, + }, + Detect { + pkgbase: Option<String>, + }, Reviews { #[arg(long)] all: bool, }, - Show { candidate: i64 }, + Show { + candidate: i64, + }, Approve { candidate: i64, #[arg(long)] @@ -53,11 +59,19 @@ enum Cmd { #[arg(long)] note: String, }, - Build { candidate: i64 }, - Rebuild { pkgbase: String }, - Run { build: String }, + Build { + candidate: i64, + }, + Rebuild { + pkgbase: String, + }, + Run { + build: String, + }, Builds, - Status { build: String }, + Status { + build: String, + }, Packages, Serve { #[arg(long)] @@ -83,10 +97,7 @@ fn main() -> anyhow::Result<()> { let cli = Cli::parse(); let root = cli.root.clone().unwrap_or_else(|| Config::default().root); let cfg = if matches!(cli.cmd, Cmd::Init { .. }) { - Config::load(&root).unwrap_or_else(|_| Config { - root: root.clone(), - ..Config::default() - }) + Config::load(&root).unwrap_or_else(|_| Config { root: root.clone(), ..Config::default() }) } else { Config::load(&root)? }; @@ -141,11 +152,8 @@ fn main() -> anyhow::Result<()> { Ok(()) } Cmd::Reviews { all } => { - let rows = if all { - candidates::all_candidates(&ctx.db)? - } else { - candidates::pending_candidates(&ctx.db)? - }; + let rows = + if all { candidates::all_candidates(&ctx.db)? } else { candidates::pending_candidates(&ctx.db)? }; if rows.is_empty() { println!("nothing pending"); } @@ -289,7 +297,7 @@ fn main() -> anyhow::Result<()> { 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), + std::fs::metadata(&path).map_or(0, |m| m.len()), path.display() ); Ok(()) @@ -310,4 +318,3 @@ impl Ctx { fn whoami() -> String { std::env::var("USER").or_else(|_| std::env::var("USERNAME")).unwrap_or_else(|_| "cli".into()) } - @@ -65,89 +65,90 @@ impl Metrics { } pub fn to_prometheus(&self) -> String { + use std::fmt::Write as _; let mut o = String::new(); - o.push_str("# HELP aurbuild_up Always 1: the process answered the scrape.\n# TYPE aurbuild_up gauge\naurbuild_up 1\n"); - o.push_str(&header("aurbuild_queue_depth", "Builds waiting to run.")); - o.push_str(&format!("aurbuild_queue_depth {}\n", self.queue_depth)); - o.push_str(&header("aurbuild_oldest_queued_age_seconds", "How long the oldest queued build has waited.")); - o.push_str(&format!("aurbuild_oldest_queued_age_seconds {}\n", self.oldest_queued_age_secs)); + gauge(&mut o, "aurbuild_up", "Always 1: the process answered the scrape.", 1); + gauge(&mut o, "aurbuild_queue_depth", "Builds waiting to run.", self.queue_depth); + gauge( + &mut o, + "aurbuild_oldest_queued_age_seconds", + "How long the oldest queued build has waited.", + self.oldest_queued_age_secs, + ); o.push_str("# HELP aurbuild_builds_total Builds by state.\n# TYPE aurbuild_builds_total gauge\n"); for (state, n) in &self.builds { - o.push_str(&format!("aurbuild_builds_total{{state=\"{state}\"}} {n}\n")); + let _ = writeln!(o, "aurbuild_builds_total{{state=\"{state}\"}} {n}"); } - o.push_str(&header("aurbuild_pending_review_candidates", "Reviews waiting on a human — the review debt.")); - o.push_str(&format!("aurbuild_pending_review_candidates {}\n", self.pending_review)); + gauge( + &mut o, + "aurbuild_pending_review_candidates", + "Reviews waiting on a human — the review debt.", + self.pending_review, + ); o.push_str("# HELP aurbuild_pending_review_age_seconds Histogram of how long pending reviews have waited.\n# TYPE aurbuild_pending_review_age_seconds histogram\n"); for le in [3600i64, 21600, 86400, 259200, 604800] { let n = self.review_ages.iter().filter(|a| **a <= le).count(); - o.push_str(&format!("aurbuild_pending_review_age_seconds_bucket{{le=\"{le}\"}} {n}\n")); + let _ = writeln!(o, "aurbuild_pending_review_age_seconds_bucket{{le=\"{le}\"}} {n}"); } - o.push_str(&format!( - "aurbuild_pending_review_age_seconds_bucket{{le=\"+Inf\"}} {}\n", - self.review_ages.len() - )); let sum: i64 = self.review_ages.iter().sum(); - o.push_str(&format!("aurbuild_pending_review_age_seconds_sum {sum}\n")); - o.push_str(&format!("aurbuild_pending_review_age_seconds_count {}\n", self.review_ages.len())); - - o.push_str(&header("aurbuild_builds_succeeded_total", "Builds that published.")); - o.push_str(&format!("aurbuild_builds_succeeded_total {}\n", self.succeeded)); - o.push_str(&header("aurbuild_builds_failed_total", "Builds that failed.")); - o.push_str(&format!("aurbuild_builds_failed_total {}\n", self.failed)); - let rate = self.build_success_rate(); - o.push_str(&header("aurbuild_build_success_rate", "Share of recorded builds that succeeded.")); - o.push_str(&format!("aurbuild_build_success_rate {rate:.4}\n")); - - o.push_str(&header("aurbuild_blocked_missing_dep", "Builds blocked on a package we have not published.")); - o.push_str(&format!("aurbuild_blocked_missing_dep {}\n", self.blocked_missing_dep)); - o.push_str(&header("aurbuild_index_packages", "Packages in the served index.")); - o.push_str(&format!("aurbuild_index_packages {}\n", self.index_packages)); - o.push_str(&header("aurbuild_releases", "Published releases on record.")); - o.push_str(&format!("aurbuild_releases {}\n", self.releases)); - o.push_str(&header("aurbuild_subscriptions", "Subscribed pkgbases.")); - o.push_str(&format!("aurbuild_subscriptions {}\n", self.subscriptions)); - o.push_str(&header("aurbuild_notices_unseen", "Notices no human has looked at.")); - o.push_str(&format!("aurbuild_notices_unseen {}\n", self.notices_unseen)); + let _ = writeln!(o, "aurbuild_pending_review_age_seconds_bucket{{le=\"+Inf\"}} {}", self.review_ages.len()); + let _ = writeln!(o, "aurbuild_pending_review_age_seconds_sum {sum}"); + let _ = writeln!(o, "aurbuild_pending_review_age_seconds_count {}", self.review_ages.len()); + + gauge(&mut o, "aurbuild_builds_succeeded_total", "Builds that published.", self.succeeded); + gauge(&mut o, "aurbuild_builds_failed_total", "Builds that failed.", self.failed); + gauge( + &mut o, + "aurbuild_build_success_rate", + "Share of recorded builds that succeeded.", + format_args!("{:.4}", self.build_success_rate()), + ); + + gauge( + &mut o, + "aurbuild_blocked_missing_dep", + "Builds blocked on a package we have not published.", + self.blocked_missing_dep, + ); + gauge(&mut o, "aurbuild_index_packages", "Packages in the served index.", self.index_packages); + gauge(&mut o, "aurbuild_releases", "Published releases on record.", self.releases); + gauge(&mut o, "aurbuild_subscriptions", "Subscribed pkgbases.", self.subscriptions); + gauge(&mut o, "aurbuild_notices_unseen", "Notices no human has looked at.", self.notices_unseen); o.push_str("# HELP aurbuild_stale_releases Releases whose recorded world no longer matches the index, by reason.\n# TYPE aurbuild_stale_releases gauge\n"); - o.push_str(&format!("aurbuild_stale_releases{{reason=\"outdated\"}} {}\n", self.stale_outdated)); - o.push_str(&format!("aurbuild_stale_releases{{reason=\"missing\"}} {}\n", self.stale_missing)); - o.push_str(&header("aurbuild_downgrades", "Subscriptions where AUR offers a lower version than we serve.")); - o.push_str(&format!("aurbuild_downgrades {}\n", self.downgrades)); - - o.push_str(&header("aurbuild_sqlite_size_bytes", "Main database file size.")); - o.push_str(&format!("aurbuild_sqlite_size_bytes {}\n", self.db_bytes)); - o.push_str(&header("aurbuild_sqlite_wal_size_bytes", "Write-ahead log size — large means nobody is checkpointing.")); - o.push_str(&format!("aurbuild_sqlite_wal_size_bytes {}\n", self.wal_bytes)); - o.push_str(&header("aurbuild_artifact_bytes", "Bytes held in the content-addressed store.")); - o.push_str(&format!("aurbuild_artifact_bytes {}\n", self.artifact_bytes)); - o.push_str(&header("aurbuild_staging_bytes", "Bytes in disposable staging directories.")); - o.push_str(&format!("aurbuild_staging_bytes {}\n", self.staging_bytes)); - o.push_str(&format!("# TYPE aurbuild_staging_dirs gauge\naurbuild_staging_dirs {}\n", self.staging_dirs)); - + let _ = writeln!(o, "aurbuild_stale_releases{{reason=\"outdated\"}} {}", self.stale_outdated); + let _ = writeln!(o, "aurbuild_stale_releases{{reason=\"missing\"}} {}", self.stale_missing); + gauge( + &mut o, + "aurbuild_downgrades", + "Subscriptions where AUR offers a lower version than we serve.", + self.downgrades, + ); + + gauge(&mut o, "aurbuild_sqlite_size_bytes", "Main database file size.", self.db_bytes); + gauge( + &mut o, + "aurbuild_sqlite_wal_size_bytes", + "Write-ahead log size — large means nobody is checkpointing.", + self.wal_bytes, + ); + gauge(&mut o, "aurbuild_artifact_bytes", "Bytes held in the content-addressed store.", self.artifact_bytes); + gauge(&mut o, "aurbuild_staging_bytes", "Bytes in disposable staging directories.", self.staging_bytes); + let _ = writeln!(o, "# TYPE aurbuild_staging_dirs gauge\naurbuild_staging_dirs {}", self.staging_dirs); + + let help = "Seconds since the last successful poll of any source."; match self.poll_lag_age_secs { - Some(a) => { - o.push_str(&header("aurbuild_poll_lag_seconds", "Seconds since the last successful poll of any source.")); - o.push_str(&format!("aurbuild_poll_lag_seconds {a}\n")); - } - None => { - o.push_str(&header("aurbuild_poll_lag_seconds", "Seconds since the last successful poll of any source.")); - o.push_str("aurbuild_poll_lag_seconds nan\n"); - } + Some(a) => gauge(&mut o, "aurbuild_poll_lag_seconds", help, a), + None => gauge(&mut o, "aurbuild_poll_lag_seconds", help, "nan"), } + let help = "Seconds since the last retention run."; match self.last_gc_age_secs { - Some(a) => { - o.push_str(&header("aurbuild_last_gc_age_seconds", "Seconds since the last retention run.")); - o.push_str(&format!("aurbuild_last_gc_age_seconds {a}\n")); - } - None => { - o.push_str(&header("aurbuild_last_gc_age_seconds", "Seconds since the last retention run.")); - o.push_str("aurbuild_last_gc_age_seconds nan\n"); - } + Some(a) => gauge(&mut o, "aurbuild_last_gc_age_seconds", help, a), + None => gauge(&mut o, "aurbuild_last_gc_age_seconds", help, "nan"), } o } @@ -158,9 +159,7 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> { let now = time::now(); m.builds = db::build_state_counts(db)?; - let count = |state: &str| -> i64 { - m.builds.iter().find(|(s, _)| s == state).map(|(_, n)| *n).unwrap_or(0) - }; + let count = |state: &str| -> i64 { m.builds.iter().find(|(s, _)| s == state).map_or(0, |(_, n)| *n) }; m.queue_depth = count("queued"); m.succeeded = count("succeeded"); m.failed = count("failed"); @@ -170,7 +169,7 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> { m.pending_review = db::count_pending_reviews(db)?; m.review_ages = db::pending_review_ages_secs(db, &now)?; - m.review_ages.sort(); + m.review_ages.sort_unstable(); m.index_packages = db::count_index_packages(db)?; m.releases = db::count_published_releases(db)?; @@ -195,12 +194,14 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> { Ok(m) } -fn header(name: &str, help: &str) -> String { - format!("# HELP {name} {help}\n# TYPE {name} gauge\n") +/// One Prometheus gauge: its `# HELP`, its `# TYPE`, and its value. +fn gauge(o: &mut String, name: &str, help: &str, value: impl std::fmt::Display) { + use std::fmt::Write as _; + let _ = write!(o, "# HELP {name} {help}\n# TYPE {name} gauge\n{name} {value}\n"); } fn file_len(p: &Path) -> u64 { - std::fs::metadata(p).map(|m| m.len()).unwrap_or(0) + std::fs::metadata(p).map_or(0, |m| m.len()) } fn staging_usage(root: &Path) -> (usize, u64) { @@ -342,9 +343,7 @@ pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathB out.push(PathBuf::from(p)); } } - let digests = db::release_by_id(db, release_id)? - .map(|r| r.source_digests_json) - .unwrap_or_else(|| "[]".into()); + let digests = db::release_by_id(db, release_id)?.map_or_else(|| "[]".into(), |r| r.source_digests_json); if let Ok(list) = serde_json::from_str::<Vec<db::SourceDigest>>(&digests) { for d in list { if !d.digest.is_empty() { @@ -438,8 +437,7 @@ pub fn backup(db: &Db, dest: &Path) -> Result<PathBuf> { } } db::backup_to(&db.writer, &dest)?; - let version = db::schema_version(&dest) - .map_err(|e| crate::error::Error::db(format!("backup unreadable: {e}")))?; + let version = db::schema_version(&dest).map_err(|e| crate::error::Error::db(format!("backup unreadable: {e}")))?; if version <= 0 { return Err(crate::error::Error::db("backup does not contain a migrated database")); } diff --git a/src/pipeline/dispatch.rs b/src/pipeline/dispatch.rs index 8e35f0a..b2d3933 100644 --- a/src/pipeline/dispatch.rs +++ b/src/pipeline/dispatch.rs @@ -26,26 +26,24 @@ impl Pool { let mut handles = Vec::new(); for n in 0..workers { - let cfg = cfg.clone(); + let cfg = Arc::clone(&cfg); let db = db.clone(); - let stop = stop.clone(); + let stop = Arc::clone(&stop); let rx = rx.clone(); handles.push( std::thread::Builder::new() .name(format!("worker-{n}")) - .spawn(crate::time::inherit(move || worker(cfg, db, rx, stop))) + .spawn(crate::time::inherit(move || worker(&cfg, &db, &rx, &stop))) .expect("spawn worker"), ); } drop(rx); - let cfg2 = cfg.clone(); - let db2 = db.clone(); - let stop2 = stop.clone(); + let dispatcher_stop = Arc::clone(&stop); handles.push( std::thread::Builder::new() .name("dispatcher".into()) - .spawn(crate::time::inherit(move || dispatcher(cfg2, db2, stop2, tx))) + .spawn(crate::time::inherit(move || dispatcher(&cfg, &db, &dispatcher_stop, &tx))) .expect("spawn dispatcher"), ); @@ -66,13 +64,13 @@ impl Pool { } } -fn dispatcher(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>, tx: Sender<String>) { +fn dispatcher(cfg: &Config, db: &Db, stop: &AtomicBool, tx: &Sender<String>) { while !stop.load(Ordering::SeqCst) { - dispatch_once(&cfg, &db, &tx); + dispatch_once(cfg, db, tx); if !crate::time::wait( std::time::Duration::from_secs(cfg.dispatch_tick_secs), std::time::Duration::from_millis(200), - &stop, + stop, ) { break; } @@ -96,14 +94,7 @@ fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String> { fn dispatch_once_impl(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String> { let reaped = builds::reap_expired(db).unwrap_or(0); if reaped > 0 { - db::audit_system( - &db.writer, - "build.reaped", - "build", - "*", - serde_json::json!({"requeued": reaped}), - ) - .ok(); + db::audit_system(&db.writer, "build.reaped", "build", "*", serde_json::json!({"requeued": reaped})).ok(); } let _ = builds::requeue_blocked(db); let _ = builds::cancel_superseded(db); @@ -165,10 +156,7 @@ fn free_disk_mb(path: &std::path::Path) -> u64 { fn free_disk_mb_impl(path: &std::path::Path) -> u64 { use std::ffi::CString; - let c = match CString::new(path.as_os_str().to_string_lossy().as_bytes()) { - Ok(c) => c, - Err(_) => return u64::MAX, - }; + let Ok(c) = CString::new(path.as_os_str().to_string_lossy().as_bytes()) else { return u64::MAX }; let mut stat: libc::statvfs = unsafe { std::mem::zeroed() }; let rc = unsafe { libc::statvfs(c.as_ptr(), &mut stat) }; if rc != 0 { @@ -179,17 +167,17 @@ fn free_disk_mb_impl(path: &std::path::Path) -> u64 { avail * bsize / (1024 * 1024) } -fn worker(cfg: Arc<Config>, db: Db, rx: crossbeam_channel::Receiver<String>, stop: Arc<AtomicBool>) { - for id in rx.iter() { +fn worker(cfg: &Config, db: &Db, rx: &crossbeam_channel::Receiver<String>, stop: &AtomicBool) { + for id in rx { if stop.load(Ordering::SeqCst) { - let _ = builds::requeue_transient(&db, &id); + let _ = builds::requeue_transient(db, &id); continue; } - let attempt = builds::get(&db, &id).ok().flatten().map(|b| b.attempt).unwrap_or(1); - match pipeline::run(&cfg, &db, &id) { + let attempt = builds::get(db, &id).ok().flatten().map_or(1, |b| b.attempt); + match pipeline::run(cfg, db, &id) { Ok(Outcome::Failed { transient, .. }) => { if transient && attempt < cfg.max_transient_attempts { - let _ = builds::requeue_transient(&db, &id); + let _ = builds::requeue_transient(db, &id); db::audit_system( &db.writer, "build.retry", @@ -201,7 +189,7 @@ fn worker(cfg: Arc<Config>, db: Db, rx: crossbeam_channel::Receiver<String>, sto } } Ok(Outcome::Cancelled) => {} - Ok(Outcome::Blocked { .. }) | Ok(Outcome::Succeeded { .. }) | Err(_) => {} + Ok(Outcome::Blocked { .. } | Outcome::Succeeded { .. }) | Err(_) => {} } if stop.load(Ordering::SeqCst) { break; diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs index 3e63a69..5bc7cdb 100644 --- a/src/pipeline/mod.rs +++ b/src/pipeline/mod.rs @@ -1,5 +1,5 @@ -pub mod publish; pub mod dispatch; +pub mod publish; mod steps; use std::path::PathBuf; @@ -7,9 +7,9 @@ use std::sync::Arc; use std::time::Duration; use crate::config::Config; -use crate::db::{self, builds, Db, Pkgbase}; -use crate::db::model::*; +use crate::db::model::{BuildState, CandidateRow, ReleaseRow, StepState}; use crate::db::SnapshotRow; +use crate::db::{self, builds, Db, Pkgbase}; use crate::error::{Error, Missing, Result}; use crate::sandbox::{Sandbox, SandboxBackend}; @@ -103,26 +103,17 @@ pub struct Ctx { impl Ctx { pub fn new(cfg: &Config, db: &Db, build_id: &str) -> Result<Self> { - let build = builds::get(db, build_id)? - .ok_or_else(|| Error::not_found(Missing::Build(build_id.to_string())))?; - let pb = db::get_pkgbase_by_id(db, build.pkgbase_id)? - .ok_or_else(|| Error::not_found("pkgbase for build"))?; - let src = match build.candidate_id { - Some(cid) => { - let c = crate::review::reads::candidate(db, cid)? - .ok_or_else(|| Error::not_found("candidate for build"))?; - let snap = db::snapshot_by_id(db, c.snapshot_id)? - .ok_or_else(|| Error::not_found("snapshot for candidate"))?; - SourceIdentity::from_candidate(&c, &snap) - } - None => { - let rid = build - .release_id - .ok_or_else(|| Error::invalid("build has neither candidate nor release"))?; - let r = db::release_by_id(db, rid)? - .ok_or_else(|| Error::not_found("release for rebuild"))?; - SourceIdentity::from_release(&r) - } + let build = builds::get(db, build_id)?.ok_or_else(|| Error::not_found(Missing::Build(build_id.to_string())))?; + let pb = db::get_pkgbase_by_id(db, build.pkgbase_id)?.ok_or_else(|| Error::not_found("pkgbase for build"))?; + let src = if let Some(cid) = build.candidate_id { + let c = crate::review::reads::candidate(db, cid)?.ok_or_else(|| Error::not_found("candidate for build"))?; + let snap = + db::snapshot_by_id(db, c.snapshot_id)?.ok_or_else(|| Error::not_found("snapshot for candidate"))?; + SourceIdentity::from_candidate(&c, &snap) + } else { + let rid = build.release_id.ok_or_else(|| Error::invalid("build has neither candidate nor release"))?; + let r = db::release_by_id(db, rid)?.ok_or_else(|| Error::not_found("release for rebuild"))?; + SourceIdentity::from_release(&r) }; let attempt = build.attempt; let profile = build.build_profile.clone(); @@ -231,20 +222,13 @@ fn run_with_impl(ctx: &Ctx) -> Result<Outcome> { Err(e) => { let transient = e.is_transient(); builds::finish_step(&ctx.db, &ctx.build.id, step, StepState::Failed, None, Some(&e.to_string()))?; - builds::set_state( - &ctx.db, - &ctx.build.id, - BuildState::Failed, - Some(&format!("{step}: {e}")), - )?; + builds::set_state(&ctx.db, &ctx.build.id, BuildState::Failed, Some(&format!("{step}: {e}")))?; ctx.log_line(&format!("!! {step} failed: {e}")); return Ok(Outcome::Failed { step: step.to_string(), error: e.to_string(), transient }); } } } - let release_id = ctx - .release_id() - .ok_or_else(|| Error::other("publish produced no release"))?; + let release_id = ctx.release_id().ok_or_else(|| Error::other("publish produced no release"))?; builds::set_state(&ctx.db, &ctx.build.id, BuildState::Succeeded, None)?; db::audit_system( &ctx.db.writer, @@ -263,8 +247,7 @@ impl Ctx { } pub fn enqueue_for_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result<String> { - let pb = db::get_pkgbase_by_id(db, c.pkgbase_id)? - .ok_or_else(|| Error::not_found("pkgbase"))?; + let pb = db::get_pkgbase_by_id(db, c.pkgbase_id)?.ok_or_else(|| Error::not_found("pkgbase"))?; let world = publish::index_world(db)?; let world_hash = crate::hash::canonical_json(&world)?; let id = builds::build_id(&pb.name, &c.identity_hash, &world_hash, &cfg.build_profile); @@ -274,19 +257,21 @@ pub fn enqueue_for_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result< } pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result<String> { - let pb = db::get_pkgbase(db, pkgbase)? - .ok_or_else(|| Error::not_found(Missing::Pkgbase(pkgbase.to_string())))?; + let pb = db::get_pkgbase(db, pkgbase)?.ok_or_else(|| Error::not_found(Missing::Pkgbase(pkgbase.to_string())))?; let rel = db::accepted_release(db, pkgbase)? .ok_or_else(|| Error::invalid(format!("{pkgbase} has no accepted release")))?; let identity = format!( "sha256:{}", - crate::hash::hex(crate::hash::canonical_json(&serde_json::json!({ - "aur_commit": rel.aur_commit, - "recipe_hash": rel.recipe_hash, - "upstream_pins": rel.pins(), - "source_digests": rel.digests(), - "requested": "manual_rebuild", - }))?.as_bytes()) + crate::hash::hex( + crate::hash::canonical_json(&serde_json::json!({ + "aur_commit": rel.aur_commit, + "recipe_hash": rel.recipe_hash, + "upstream_pins": rel.pins(), + "source_digests": rel.digests(), + "requested": "manual_rebuild", + }))? + .as_bytes() + ) ); let world = publish::index_world(db)?; let world_hash = crate::hash::canonical_json(&world)?; diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs index d22b833..24b7cdb 100644 --- a/src/pipeline/publish.rs +++ b/src/pipeline/publish.rs @@ -166,20 +166,14 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { _ => None, }; let approval_id = approval_id.or(inherited).ok_or_else(|| { - Error::fail_closed(format!( - "refusing to publish a {} build with no approval behind it", - ctx.build.kind - )) + Error::fail_closed(format!("refusing to publish a {} build with no approval behind it", ctx.build.kind)) })?; let build_id = ctx.build.id.clone(); let packages = collect.packages.clone(); let names: Vec<String> = packages.iter().map(|p| p.name.clone()).collect(); let src = ctx.src.clone(); - let world_id = builds::get(&ctx.db, &build_id) - .ok() - .flatten() - .and_then(|b| b.world_snapshot_id); + let world_id = builds::get(&ctx.db, &build_id).ok().flatten().and_then(|b| b.world_snapshot_id); let repo_id = db::repo_id(&ctx.db)?; let expected_base: Option<i64> = match ctx.build.kind.as_str() { "manual_rebuild" => ctx.build.release_id, @@ -193,9 +187,7 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { ctx.db.writer.tx(move |tx| { let actual_base = db::accepted_pointer_in(tx, pkgbase_id)?; if actual_base != expected_base { - return Err(Error::conflict( - "accepted pointer moved while this build was running; refusing to publish", - )); + return Err(Error::conflict("accepted pointer moved while this build was running; refusing to publish")); } db::remove_index_packages_in(tx, &names)?; let release_id = db::insert_release_in( @@ -220,9 +212,7 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { db::insert_package_in(tx, repo_id, release_id, &p.name, &p.arch, &p.version, &p.digest)?; } if !db::cas_accepted_release_in(tx, pkgbase_id, release_id, expected_base)? { - return Err(Error::conflict( - "accepted pointer moved while this build was running; refusing to publish", - )); + return Err(Error::conflict("accepted pointer moved while this build was running; refusing to publish")); } builds::set_release_in(tx, &build_id, release_id)?; if let Some(cid) = candidate_id { @@ -334,18 +324,14 @@ pub(crate) fn sign_to(cfg: &Config, path: &Path, sig_out: &Path) -> Result<()> { } fn fsync_file(p: &Path) -> Result<()> { - let f = std::fs::File::open(p) - .map_err(|e| Error::other(format!("open {} for fsync: {e}", p.display())))?; - f.sync_all() - .map_err(|e| Error::other(format!("fsync {}: {e}", p.display())))?; + let f = std::fs::File::open(p).map_err(|e| Error::other(format!("open {} for fsync: {e}", p.display())))?; + f.sync_all().map_err(|e| Error::other(format!("fsync {}: {e}", p.display())))?; Ok(()) } fn fsync_dir(p: &Path) -> Result<()> { - let d = std::fs::File::open(p) - .map_err(|e| Error::other(format!("open dir {} for fsync: {e}", p.display())))?; - d.sync_all() - .map_err(|e| Error::other(format!("fsync dir {}: {e}", p.display())))?; + let d = std::fs::File::open(p).map_err(|e| Error::other(format!("open dir {} for fsync: {e}", p.display())))?; + d.sync_all().map_err(|e| Error::other(format!("fsync dir {}: {e}", p.display())))?; Ok(()) } @@ -353,11 +339,8 @@ fn dedupe_by_name(paths: Vec<PathBuf>) -> Vec<PathBuf> { let mut seen: BTreeSet<String> = BTreeSet::new(); let mut out: Vec<PathBuf> = Vec::new(); for p in paths.into_iter().rev() { - let name = package_name(&p).unwrap_or_else(|| { - p.file_name() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default() - }); + let name = + package_name(&p).unwrap_or_else(|| p.file_name().map_or_default(|s| s.to_string_lossy().into_owned())); if seen.insert(name) { out.push(p); } diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs index 775485d..9703d54 100644 --- a/src/pipeline/steps.rs +++ b/src/pipeline/steps.rs @@ -1,6 +1,9 @@ use std::path::Path; -use crate::db::{self, builds, model::*}; +use crate::db::{ + self, builds, + model::{Recipe, SourceDigest, WorldMember}, +}; use crate::error::{Error, Guard, Result, WorldGap}; use crate::git; use crate::pipeline::{Collect, CollectedPkg, Ctx, StepResult}; @@ -29,8 +32,7 @@ fn materialize(ctx: &Ctx) -> Result<StepResult> { .mirror_path .as_ref() .map(Path::new) - .map(|p| p.to_path_buf()) - .unwrap_or_else(|| ctx.cfg.mirror_path(&ctx.pb.name)); + .map_or_else(|| ctx.cfg.mirror_path(&ctx.pb.name), std::path::Path::to_path_buf); if !mirror.exists() { return Err(Error::fail_closed(format!( "mirror {} missing; refusing to fetch a recipe from the network at build time", @@ -105,10 +107,7 @@ fn provision(ctx: &Ctx) -> Result<StepResult> { if lease.is_empty() { return Ok(StepResult::Skipped("no of-our-packages dependencies to install".into())); } - let sbx = match sandbox_or_wait(ctx)? { - Some(s) => s, - None => return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])), - }; + let Some(sbx) = sandbox_or_wait(ctx)? else { return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])) }; for e in &lease { let path = ctx.cfg.store_path(&e.digest); let (digest, _) = crate::hash::digest_file(&path)?; @@ -134,11 +133,7 @@ fn provision(ctx: &Ctx) -> Result<StepResult> { } let q = sbx.run(&Cmd::new(vec![ctx.cfg.pacman_bin.clone(), "-Q".into()]), &mut |_| {})?; if !q.success() { - return Err(Error::fail_closed(format!( - "{} -Q failed: {}", - ctx.cfg.pacman_bin, - tail(&q.stderr) - ))); + return Err(Error::fail_closed(format!("{} -Q failed: {}", ctx.cfg.pacman_bin, tail(&q.stderr)))); } let installed: std::collections::BTreeSet<(String, String)> = String::from_utf8_lossy(&q.stdout) .lines() @@ -150,9 +145,7 @@ fn provision(ctx: &Ctx) -> Result<StepResult> { .collect(); for e in &lease { if !installed.contains(&(e.name.clone(), e.version.clone())) { - return Err(Error::world_mismatch(WorldGap::MissingPin { - package: format!("{}-{}", e.name, e.version), - })); + return Err(Error::world_mismatch(WorldGap::MissingPin { package: format!("{}-{}", e.name, e.version) })); } } ctx.log_line(&format!( @@ -164,9 +157,7 @@ fn provision(ctx: &Ctx) -> Result<StepResult> { Ok(StepResult::Done(Some(crate::hash::canonical_json(&world)?))) } -fn sandbox_or_wait( - ctx: &Ctx, -) -> Result<Option<std::sync::Arc<dyn crate::sandbox::Sandbox>>> { +fn sandbox_or_wait(ctx: &Ctx) -> Result<Option<std::sync::Arc<dyn crate::sandbox::Sandbox>>> { match ctx.sandbox() { Ok(s) => Ok(Some(s)), Err(e) if e.is_pool_exhausted() => { @@ -218,14 +209,12 @@ fn sources(ctx: &Ctx) -> Result<StepResult> { } } ctx.log_line(&format!(" {}/{} source digests verified", verified, digests.len())); - Ok(StepResult::Done(Some(crate::hash::hex_str( - &ctx.src.source_digests_json, - )))) + Ok(StepResult::Done(Some(crate::hash::hex_str(&ctx.src.source_digests_json)))) } fn pkgver(ctx: &Ctx) -> Result<StepResult> { let recipe = recipe_at(&ctx.srcdir)?; - let has_vcs = recipe.source_entries.iter().any(|s| s.is_vcs()); + let has_vcs = recipe.source_entries.iter().any(super::super::db::model::SourceEntry::is_vcs); if !has_vcs { let want = (ctx.src.pkgver.clone(), ctx.src.pkgrel.clone()); let got = (recipe.pkgver.clone(), recipe.pkgrel.clone()); @@ -263,10 +252,7 @@ fn pkgver(ctx: &Ctx) -> Result<StepResult> { fn build(ctx: &Ctx) -> Result<StepResult> { let argv = vec![ctx.cfg.makepkg_bin.clone(), "-c".into(), "-f".into()]; - let sbx = match sandbox_or_wait(ctx)? { - Some(s) => s, - None => return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])), - }; + let Some(sbx) = sandbox_or_wait(ctx)? else { return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])) }; if let Some(parent) = ctx.log.parent() { let _ = std::fs::create_dir_all(parent); } @@ -280,15 +266,9 @@ fn build(ctx: &Ctx) -> Result<StepResult> { let out = sbx.run(&Cmd::new(argv).in_dir(&ctx.srcdir), &mut on_log)?; drop(on_log); if !out.success() { - return Err(Error::Subprocess { - cmd: ctx.cfg.makepkg_bin.clone(), - detail: tail(&out.stderr), - }); + return Err(Error::Subprocess { cmd: ctx.cfg.makepkg_bin.clone(), detail: tail(&out.stderr) }); } - Ok(StepResult::Done(Some(crate::hash::hex_str(&format!( - "build:{}", - ctx.build.id - ))))) + Ok(StepResult::Done(Some(crate::hash::hex_str(&format!("build:{}", ctx.build.id))))) } fn tail(b: &[u8]) -> String { @@ -300,14 +280,14 @@ fn tail(b: &[u8]) -> String { fn collect(ctx: &Ctx) -> Result<StepResult> { let mut pkgs = Vec::new(); let mut entries: Vec<PathBuf> = std::fs::read_dir(&ctx.srcdir)? - .filter_map(|e| e.ok()) + .filter_map(std::result::Result::ok) .map(|e| e.path()) .filter(|p| p.to_string_lossy().ends_with(".pkg.tar.zst")) .collect(); entries.sort(); let staging_root = ctx.staging.canonicalize()?; for path in entries { - if std::fs::symlink_metadata(&path).map(|m| m.file_type().is_symlink()).unwrap_or(true) { + if std::fs::symlink_metadata(&path).map_or(true, |m| m.file_type().is_symlink()) { return Err(Error::fail_closed(format!( "{} is a symlink; a build may not smuggle bytes in from outside its own staging dir", path.display() @@ -316,15 +296,16 @@ fn collect(ctx: &Ctx) -> Result<StepResult> { let resolved = path.canonicalize()?; if !resolved.starts_with(&staging_root) { return Err(Error::fail_closed(format!( - "{} resolves outside this build's staging dir ({staging_root:?}); refusing to ingest it", - path.display() + "{} resolves outside this build's staging dir ({}); refusing to ingest it", + path.display(), + staging_root.display() ))); } let path = resolved; let bytes = std::fs::read(&path)?; let (digest, size) = crate::hash::digest_file(&path)?; - let pkginfo = crate::pkginfo::pkginfo_text(&bytes) - .map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?; + let pkginfo = + crate::pkginfo::pkginfo_text(&bytes).map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?; let meta = crate::pkginfo::parse_pkginfo(&pkginfo); let buildinfo = crate::pkginfo::buildinfo_text(&bytes).unwrap_or_default(); let sig = path.with_extension("pkg.tar.zst.sig"); @@ -340,10 +321,7 @@ fn collect(ctx: &Ctx) -> Result<StepResult> { makedepends: meta.makedepends.clone(), provides: meta.provides.clone(), conflicts: meta.conflicts.clone(), - installed: crate::pkginfo::parse_installed(&buildinfo) - .into_iter() - .map(|i| (i.name, i.version)) - .collect(), + installed: crate::pkginfo::parse_installed(&buildinfo).into_iter().map(|i| (i.name, i.version)).collect(), }); } if pkgs.is_empty() { @@ -351,7 +329,10 @@ fn collect(ctx: &Ctx) -> Result<StepResult> { } let collect = Collect { packages: pkgs.clone() }; collect.save(&ctx.collect_path)?; - ctx.log_line(&format!(" collected {}", pkgs.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>().join(", "))); + ctx.log_line(&format!( + " collected {}", + pkgs.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>().join(", ") + )); Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string(&pkgs)?)))) } @@ -359,10 +340,8 @@ fn verify(ctx: &Ctx) -> Result<StepResult> { let collect = Collect::load(&ctx.collect_path)?; let ours = db::our_package_names(&ctx.db)?; for p in &collect.packages { - if crate::pkgver::is_downgrade( - &db::index_version(&ctx.db, &p.name)?.unwrap_or_else(|| "0".into()), - &p.version, - ) { + if crate::pkgver::is_downgrade(&db::index_version(&ctx.db, &p.name)?.unwrap_or_else(|| "0".into()), &p.version) + { ctx.log_line(&format!(" note: {} is a downgrade from what we serve", p.name)); } let mut provided: std::collections::BTreeSet<String> = ours.clone(); @@ -439,10 +418,7 @@ fn ingest(ctx: &Ctx) -> Result<StepResult> { let world_id = db::put_world_snapshot(&ctx.db.writer, &members)?; builds::set_world(&ctx.db, &ctx.build.id, world_id)?; ctx.log_line(&format!(" ingested {} artifact(s), world has {} of our packages", packages.len(), members.len())); - Ok(StepResult::Done(Some(crate::hash::hex_str(&format!( - "ingest:{}", - packages.len() - ))))) + Ok(StepResult::Done(Some(crate::hash::hex_str(&format!("ingest:{}", packages.len()))))) } fn publish(ctx: &Ctx) -> Result<StepResult> { @@ -456,7 +432,7 @@ use std::path::PathBuf; fn recipe_at(dir: &Path) -> Result<Recipe> { let mut files = std::collections::BTreeMap::new(); - for entry in walkdir::WalkDir::new(dir).max_depth(2).into_iter().filter_map(|e| e.ok()) { + for entry in walkdir::WalkDir::new(dir).max_depth(2).into_iter().filter_map(std::result::Result::ok) { let p = entry.path(); if !p.is_file() { continue; @@ -468,4 +444,3 @@ fn recipe_at(dir: &Path) -> Result<Recipe> { } crate::recipe::recipe_from_tree(&files) } - diff --git a/src/pkgver/mod.rs b/src/pkgver/mod.rs index c97b4a2..5abb5c0 100644 --- a/src/pkgver/mod.rs +++ b/src/pkgver/mod.rs @@ -64,14 +64,7 @@ impl Version { } } -pub fn compare( - epoch_a: i64, - pkgver_a: &str, - pkgrel_a: &str, - epoch_b: i64, - pkgver_b: &str, - pkgrel_b: &str, -) -> Ordering { +pub fn compare(epoch_a: i64, pkgver_a: &str, pkgrel_a: &str, epoch_b: i64, pkgver_b: &str, pkgrel_b: &str) -> Ordering { match epoch_a.cmp(&epoch_b) { Ordering::Equal => {} o => return o, @@ -133,18 +126,10 @@ fn vercmp_string(a: &str, b: &str) -> Ordering { match (i >= a.len(), j >= b.len()) { (true, true) => return Ordering::Equal, (true, false) => { - return if j < b.len() && b[j].is_ascii_alphabetic() { - Ordering::Greater - } else { - Ordering::Less - } + return if j < b.len() && b[j].is_ascii_alphabetic() { Ordering::Greater } else { Ordering::Less } } (false, true) => { - return if i < a.len() && a[i].is_ascii_alphabetic() { - Ordering::Less - } else { - Ordering::Greater - } + return if i < a.len() && a[i].is_ascii_alphabetic() { Ordering::Less } else { Ordering::Greater } } (false, false) => {} } @@ -243,23 +228,13 @@ impl Dep { Some((head, _desc)) if !head.contains(['>', '<', '=']) => head, _ => s, }; - for (tok, op) in [ - (">=", DepOp::Ge), - ("<=", DepOp::Le), - ("=", DepOp::Eq), - (">", DepOp::Gt), - ("<", DepOp::Lt), - ] { + for (tok, op) in [(">=", DepOp::Ge), ("<=", DepOp::Le), ("=", DepOp::Eq), (">", DepOp::Gt), ("<", DepOp::Lt)] { if let Some((name, ver)) = s.split_once(tok) { let name = name.trim(); if name.is_empty() { return None; } - return Some(Dep { - name: name.to_string(), - op, - version: Some(ver.trim().to_string()), - }); + return Some(Dep { name: name.to_string(), op, version: Some(ver.trim().to_string()) }); } } Some(Dep { name: s.trim().to_string(), op: DepOp::Any, version: None }) @@ -368,19 +343,53 @@ mod tests { // --------------------------------------------------------------------- const ORDERED: &[(&str, &str)] = &[ - ("v1.2.3", "v1.2.4"), ("1.0", "1.1"), ("1.1", "1.2"), ("1.2", "2.0"), - ("2.0", "2.1.0"), ("2.1.0", "2.1.1"), ("1.0rc1", "1.0"), ("1.0", "1.0.0"), - ("1.0.0", "1.0.1"), ("1.0.1", "1.1.0"), ("1.1", "1.1.0"), ("1", "1.0"), - ("1.0", "1.0.1"), ("1.0.1", "1.1"), ("1.1", "1.1.1"), ("1.1.1", "1.2"), - ("1.2", "1.2.2"), ("1.2.2", "1.3"), ("1.3", "1.3.1"), ("1.3.1", "1.4"), - ("1.4", "1.4.1"), ("1.4.1", "2.0"), ("2.0", "2.0.1"), ("2.0.1", "2.1.0"), - ("2.1.0", "2.1.1"), ("2.1.1", "3.0"), ("3.0", "3.0.1"), ("3.0.1", "4.0"), - ("1.0.a", "1.0.1"), ("1.0.b", "1.0.2"), ("1.0.2", "1.0.2.a"), - ("1.0.2.a", "1.0.2.aa"), ("1.0.2.aa", "1.0.2.b"), ("1.0.2.b", "1.0.2.bb"), - ("1.0.2.bb", "1.0.3"), ("1.0.3a", "1.0.3b"), ("1.0.3b", "1.1"), - ("1.1a", "1.2"), ("1:0.8", "2:0.1"), ("2:0.1", "3:0.1"), ("1.0-1", "1.0-2"), - ("1.0-2", "1.0-3"), ("1.0-3", "1.1-1"), ("1:1.0-1", "1:1.0-2"), - ("1:1.0-2", "2:0.1-1"), ("2.5", "2.24"), ("2.0", "2.0.01"), + ("v1.2.3", "v1.2.4"), + ("1.0", "1.1"), + ("1.1", "1.2"), + ("1.2", "2.0"), + ("2.0", "2.1.0"), + ("2.1.0", "2.1.1"), + ("1.0rc1", "1.0"), + ("1.0", "1.0.0"), + ("1.0.0", "1.0.1"), + ("1.0.1", "1.1.0"), + ("1.1", "1.1.0"), + ("1", "1.0"), + ("1.0", "1.0.1"), + ("1.0.1", "1.1"), + ("1.1", "1.1.1"), + ("1.1.1", "1.2"), + ("1.2", "1.2.2"), + ("1.2.2", "1.3"), + ("1.3", "1.3.1"), + ("1.3.1", "1.4"), + ("1.4", "1.4.1"), + ("1.4.1", "2.0"), + ("2.0", "2.0.1"), + ("2.0.1", "2.1.0"), + ("2.1.0", "2.1.1"), + ("2.1.1", "3.0"), + ("3.0", "3.0.1"), + ("3.0.1", "4.0"), + ("1.0.a", "1.0.1"), + ("1.0.b", "1.0.2"), + ("1.0.2", "1.0.2.a"), + ("1.0.2.a", "1.0.2.aa"), + ("1.0.2.aa", "1.0.2.b"), + ("1.0.2.b", "1.0.2.bb"), + ("1.0.2.bb", "1.0.3"), + ("1.0.3a", "1.0.3b"), + ("1.0.3b", "1.1"), + ("1.1a", "1.2"), + ("1:0.8", "2:0.1"), + ("2:0.1", "3:0.1"), + ("1.0-1", "1.0-2"), + ("1.0-2", "1.0-3"), + ("1.0-3", "1.1-1"), + ("1:1.0-1", "1:1.0-2"), + ("1:1.0-2", "2:0.1-1"), + ("2.5", "2.24"), + ("2.0", "2.0.01"), ]; #[test] @@ -414,11 +423,7 @@ mod tests { let mut cols = line.split('\t'); let (a, b) = (cols.next().unwrap(), cols.next().unwrap()); let theirs: i32 = cols.next().unwrap().parse().expect("verdict column"); - assert_eq!( - sign(vercmp_string(a, b)), - theirs, - "vercmp({a:?}, {b:?}) disagrees with the recorded oracle" - ); + assert_eq!(sign(vercmp_string(a, b)), theirs, "vercmp({a:?}, {b:?}) disagrees with the recorded oracle"); checked += 1; recorded.insert((a, b), theirs); } @@ -443,10 +448,9 @@ mod tests { return; } let fragments = [ - "1", "1.0", "1.0.0", "1.0.1", "1.1", "2", "2.0", "1.0a", "1.0rc1", "1.0.2a", "1.0.2.1", - "1.0.2.a", "1.0.2.aa", "1.0.2.b", "1.0.2z", "1.0z", "1.0.z", "0.9", "10", "2.24", "2.5", - "1.02", "1.0_2", "1.0.p", "1.0.3a", "1.0.3b", "1.a", "1a", "1.0+git", "1.0~beta", "2.0_1", - "1.0.x", "2024.01", + "1", "1.0", "1.0.0", "1.0.1", "1.1", "2", "2.0", "1.0a", "1.0rc1", "1.0.2a", "1.0.2.1", "1.0.2.a", + "1.0.2.aa", "1.0.2.b", "1.0.2z", "1.0z", "1.0.z", "0.9", "10", "2.24", "2.5", "1.02", "1.0_2", "1.0.p", + "1.0.3a", "1.0.3b", "1.a", "1a", "1.0+git", "1.0~beta", "2.0_1", "1.0.x", "2024.01", ]; let mut checked = 0; for a in fragments { @@ -462,13 +466,9 @@ mod tests { #[test] fn equal_versions_compare_equal_and_leading_zeros_do_not_matter() { - for (a, b) in [ - ("1.0-1", "1.0-1"), - ("1:1.0-1", "1:1.0-1"), - ("1.02-1", "1.2-1"), - ("01.0-1", "1.0-1"), - ("1.0-01", "1.0-1"), - ] { + for (a, b) in + [("1.0-1", "1.0-1"), ("1:1.0-1", "1:1.0-1"), ("1.02-1", "1.2-1"), ("01.0-1", "1.0-1"), ("1.0-01", "1.0-1")] + { assert_eq!(vercmp(a, b), Ordering::Equal, "{a} vs {b}"); } } @@ -537,7 +537,7 @@ mod tests { fn provides_and_conflicts_use_the_same_grammar() { for src in ["aur-build", "aur-build=0.1-1", "virtual-thing>=1.0"] { let d = Dep::parse(src).expect(src); - assert!(!d.name().is_empty()); + assert_ne!(d.name(), ""); assert!(!d.name().contains(['>', '<', '='])); } assert_eq!(dep_names(&["aur-build=0.1-1".into(), "other".into()]), vec!["aur-build", "other"]); diff --git a/src/recipe.rs b/src/recipe.rs index 5e8f9a3..870d2bf 100644 --- a/src/recipe.rs +++ b/src/recipe.rs @@ -122,16 +122,8 @@ pub fn parse_pkgbuild(text: &str) -> Result<Recipe> { r.backup = get("backup"); r.install = get("install").into_iter().next(); let pkgnames = get("pkgname"); - r.pkgnames = if pkgnames.is_empty() { - vec![r.pkgbase.clone()] - } else { - pkgnames.clone() - }; - r.pkg_depends = r - .pkgnames - .iter() - .map(|n| (n.clone(), r.depends.clone())) - .collect(); + r.pkgnames = if pkgnames.is_empty() { vec![r.pkgbase.clone()] } else { pkgnames.clone() }; + r.pkg_depends = r.pkgnames.iter().map(|n| (n.clone(), r.depends.clone())).collect(); r.skipgpcheck = text.contains("--skippgpcheck"); r.pkgbuild = text.to_string(); r.source_entries = parse_source_entries(&r.source)?; @@ -178,10 +170,7 @@ fn split_assign(t: &str) -> Option<(String, String)> { let (name, rest) = t.split_once('=')?; let name = name.trim(); if name.is_empty() - || !name - .chars() - .next() - .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + || !name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { return None; @@ -262,10 +251,7 @@ fn parse_source_entries(list: &[String]) -> Result<Vec<SourceEntry>> { let mut branch = None; if let Some(f) = frag { for pair in f.split('&') { - let (k, v) = match pair.split_once('=') { - Some((k, v)) => (k, v), - None => continue, - }; + let Some((k, v)) = pair.split_once('=') else { continue }; match k { "commit" => commit = Some(v.to_string()), "tag" => tag = Some(v.to_string()), @@ -275,23 +261,10 @@ fn parse_source_entries(list: &[String]) -> Result<Vec<SourceEntry>> { } } let local = vcs.is_none() && !clean.contains("://"); - let filename = filename.or_else(|| { - if local { - clean.rsplit('/').next().map(|s| s.to_string()) - } else { - None - } - }); - out.push(SourceEntry { - index, - url: clean, - filename, - commit, - tag, - branch, - vcs, - local, - }); + let filename = + filename + .or_else(|| if local { clean.rsplit('/').next().map(std::string::ToString::to_string) } else { None }); + out.push(SourceEntry { index, url: clean, filename, commit, tag, branch, vcs, local }); } Ok(out) } @@ -384,7 +357,11 @@ mod tests { #[test] fn bodies_start_at_the_first_function_and_run_to_the_end() { let text = "pkgver=1.0\nsource=(x)\nbuild() {\n make\n}\n"; - assert_eq!(pkgbuild_bodies(text), "build() {\nmake\n}\n", "each line is trimmed, the bodies are compared as text"); + assert_eq!( + pkgbuild_bodies(text), + "build() {\nmake\n}\n", + "each line is trimmed, the bodies are compared as text" + ); assert_eq!(pkgbuild_bodies("pkgver=1.0\n"), ""); } diff --git a/src/review/approve.rs b/src/review/approve.rs index c5b2f07..26963d6 100644 --- a/src/review/approve.rs +++ b/src/review/approve.rs @@ -1,4 +1,4 @@ -use crate::db::{self, approvals, candidates, CandidateState, *}; +use crate::db::{self, approvals, candidates, CandidateRow, CandidateState, Db}; use crate::error::{Error, Missing, Refused, Result}; use crate::time; @@ -43,64 +43,68 @@ pub fn approve( let actor = actor.to_string(); let ih = identity_hash.to_string(); let dd = diff_digest.to_string(); - let note = note.map(|s| s.to_string()); + let note = note.map(std::string::ToString::to_string); let at = time::now(); - db.writer.tx(move |tx| -> Result<std::result::Result<Approval, ApproveError>> { - let subject = candidates::review_subject_in(tx, candidate_id)? - .ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?; - let id = subject.id; - let base = subject.base_release_id; - let current_base = subject.current_base_release_id; + db.writer + .tx(move |tx| -> Result<std::result::Result<Approval, ApproveError>> { + let subject = candidates::review_subject_in(tx, candidate_id)? + .ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?; + let id = subject.id; + let base = subject.base_release_id; + let current_base = subject.current_base_release_id; - if !subject.state.is_open() { - return Ok(Err(ApproveError::Stale(Stale::NotPending { state: subject.state.to_string() }))); - } - if subject.identity_hash != ih { - return Ok(Err(ApproveError::Stale(Stale::Identity { expected: ih.clone(), actual: subject.identity_hash }))); - } - if subject.diff_digest != dd { - return Ok(Err(ApproveError::Stale(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest }))); - } - if base != current_base { - return Ok(Err(ApproveError::Stale(Stale::Base { expected: base, actual: current_base }))); - } + if !subject.state.is_open() { + return Ok(Err(ApproveError::Stale(Stale::NotPending { state: subject.state.to_string() }))); + } + if subject.identity_hash != ih { + return Ok(Err(ApproveError::Stale(Stale::Identity { + expected: ih.clone(), + actual: subject.identity_hash, + }))); + } + if subject.diff_digest != dd { + return Ok(Err(ApproveError::Stale(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest }))); + } + if base != current_base { + return Ok(Err(ApproveError::Stale(Stale::Base { expected: base, actual: current_base }))); + } - let approval_id = approvals::record_in( - tx, - &approvals::Decision { + let approval_id = approvals::record_in( + tx, + &approvals::Decision { + candidate_id: id, + base_release_id: base, + at: &at, + decision: "approved", + risk_level: &subject.risk_level, + diff_digest: &dd, + identity_hash: &ih, + note: note.as_deref(), + }, + )?; + candidates::resolve_in(tx, id, CandidateState::Approved, &at)?; + db::audit_in( + tx, + &db::AuditEntry::human( + &at, + &actor, + "approve", + "candidate", + &id.to_string(), + serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": subject.pkgbase_id}), + ), + )?; + Ok(Ok(Approval { + id: approval_id, candidate_id: id, base_release_id: base, - at: &at, - decision: "approved", - risk_level: &subject.risk_level, - diff_digest: &dd, - identity_hash: &ih, - note: note.as_deref(), - }, - )?; - candidates::resolve_in(tx, id, CandidateState::Approved, &at)?; - db::audit_in( - tx, - &db::AuditEntry::human( - &at, - &actor, - "approve", - "candidate", - &id.to_string(), - serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": subject.pkgbase_id}), - ), - )?; - Ok(Ok(Approval { - id: approval_id, - candidate_id: id, - base_release_id: base, - decision: "approved".into(), - diff_digest: dd, - identity_hash: ih, - })) - }) - .map_err(ApproveError::System)? + decision: "approved".into(), + diff_digest: dd, + identity_hash: ih, + })) + }) + .map_err(ApproveError::System)? } pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> { @@ -111,7 +115,12 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> let state = candidates::state_in(tx, candidate_id)? .ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?; if !state.is_open() { - return Err(Error::conflict(Refused::WrongState { entity: "candidate", id: candidate_id.to_string(), found: state.to_string(), expected: "pending" })); + return Err(Error::conflict(Refused::WrongState { + entity: "candidate", + id: candidate_id.to_string(), + found: state.to_string(), + expected: "pending", + })); } let identity = candidates::identity_in(tx, candidate_id)? .ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?; @@ -141,7 +150,7 @@ pub struct BulkItem { impl BulkItem { pub fn pkgbase(&self) -> &str { - self.candidate.as_ref().map(|c| c.pkgbase.as_str()).unwrap_or("(gone)") + self.candidate.as_ref().map_or("(gone)", |c| c.pkgbase.as_str()) } } @@ -157,7 +166,7 @@ pub enum BulkOutcome { /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod bulk_refusal { - use super::*; + use super::{Error, Stale}; #[derive(Debug, thiserror::Error)] pub enum BulkRefusal { diff --git a/src/review/candidates.rs b/src/review/candidates.rs index 236f85b..f90b1ef 100644 --- a/src/review/candidates.rs +++ b/src/review/candidates.rs @@ -2,8 +2,8 @@ use crate::db::{self, candidates as sql, Db, Pkgbase, ReleaseRow}; use crate::error::Result; pub use crate::db::candidates::{ - all as all_candidates, by_id as candidate_by_id, mark_viewed, pending as pending_candidates, - set_diff_digest, NewCandidate, + all as all_candidates, by_id as candidate_by_id, mark_viewed, pending as pending_candidates, set_diff_digest, + NewCandidate, }; #[derive(Debug, Clone, PartialEq, Eq)] @@ -15,8 +15,14 @@ pub enum Upsert { Unchanged, } -pub(crate) fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc: &NewCandidate) -> Result<Upsert> { - let kind = if accepted.is_some() { db::candidate_kind::NEW_VERSION } else { db::candidate_kind::FIRST_INTRODUCTION }; +pub(crate) fn upsert_candidate( + db: &Db, + pb: &Pkgbase, + accepted: Option<&ReleaseRow>, + nc: &NewCandidate, +) -> Result<Upsert> { + let kind = + if accepted.is_some() { db::candidate_kind::NEW_VERSION } else { db::candidate_kind::FIRST_INTRODUCTION }; let base = accepted.map(|a| a.id); let pkgbase_id = pb.id; let nc = nc.clone(); diff --git a/src/review/diff.rs b/src/review/diff.rs index 39d9066..f997b3c 100644 --- a/src/review/diff.rs +++ b/src/review/diff.rs @@ -1,7 +1,8 @@ use crate::config::Config; -use crate::db::{self, *}; +use crate::db::{self, CandidateRow, Db, Recipe, ReleaseRow, SourceDigest, UpstreamPin}; use crate::error::Result; use crate::git; +use std::fmt::Write as _; #[derive(Debug, Clone)] pub struct Panel { @@ -31,9 +32,7 @@ pub fn panels(cfg: &Config, db: &Db, c: &CandidateRow, base: Option<&ReleaseRow> } out.push(digest_delta(base, c)); out.push(pin_delta(base, c)); - let old_recipe = recipe_of(db, base.candidate_id.and_then(|cid| { - candidate_snapshot_id(db, cid) - })); + let old_recipe = recipe_of(db, base.candidate_id.and_then(|cid| candidate_snapshot_id(db, cid))); let new_recipe = recipe_of(db, Some(c.snapshot_id)); if let (Some(old), Some(new)) = (&old_recipe, &new_recipe) { out.push(source_delta(old, new)); @@ -45,9 +44,7 @@ pub fn panels(cfg: &Config, db: &Db, c: &CandidateRow, base: Option<&ReleaseRow> out.push(Panel { name: "recipe_full", title: "Full recipe", - body: snap - .map(|s| s.srcinfo_json.clone()) - .unwrap_or_else(|| "(no snapshot)".into()), + body: snap.map_or_else(|| "(no snapshot)".into(), |s| s.srcinfo_json.clone()), }); } Ok(out) @@ -67,27 +64,27 @@ fn source_delta(old: &Recipe, new: &Recipe) -> Panel { let mut body = String::new(); for s in &new.source { if !old.source.contains(s) { - body.push_str(&format!("+ {s}\n")); + let _ = writeln!(body, "+ {s}"); } } for s in &old.source { if !new.source.contains(s) { - body.push_str(&format!("- {s}\n")); + let _ = writeln!(body, "- {s}"); } } let old_hosts = crate::urlutil::hosts(&old.source); let new_hosts = crate::urlutil::hosts(&new.source); for h in new_hosts.difference(&old_hosts) { - body.push_str(&format!("! new source host: {h}\n")); + let _ = writeln!(body, "! new source host: {h}"); } for h in old_hosts.difference(&new_hosts) { - body.push_str(&format!("! source host gone: {h}\n")); + let _ = writeln!(body, "! source host gone: {h}"); } for (i, sum) in new.sha256sums.iter().enumerate() { if sum.eq_ignore_ascii_case("SKIP") { match old.sha256sums.get(i) { Some(prev) if prev != "SKIP" && !prev.is_empty() => { - body.push_str(&format!("! [{i}] checksum removed (was {prev}, now SKIP)\n")) + let _ = writeln!(body, "! [{i}] checksum removed (was {prev}, now SKIP)"); } _ => {} } @@ -115,10 +112,10 @@ fn dependency_delta(old: &Recipe, new: &Recipe) -> Panel { let oset: std::collections::BTreeSet<String> = crate::pkgver::dep_names(o).into_iter().collect(); let nset: std::collections::BTreeSet<String> = crate::pkgver::dep_names(n).into_iter().collect(); for d in nset.difference(&oset) { - body.push_str(&format!("+ {label}: {d}\n")); + let _ = writeln!(body, "+ {label}: {d}"); } for d in oset.difference(&nset) { - body.push_str(&format!("- {label}: {d}\n")); + let _ = writeln!(body, "- {label}: {d}"); } } if !old.checkdepends.is_empty() && new.checkdepends.is_empty() { @@ -131,34 +128,34 @@ fn build_env_delta(old: &Recipe, new: &Recipe) -> Panel { let mut body = String::new(); for o in &new.options { if !old.options.contains(o) { - body.push_str(&format!("+ options: {o}\n")); + let _ = writeln!(body, "+ options: {o}"); } } for o in &old.options { if !new.options.contains(o) { - body.push_str(&format!("- options: {o}\n")); + let _ = writeln!(body, "- options: {o}"); } } for a in &new.arch { if !old.arch.contains(a) { - body.push_str(&format!("+ arch: {a}\n")); + let _ = writeln!(body, "+ arch: {a}"); } } for a in &old.arch { if !new.arch.contains(a) { - body.push_str(&format!("- arch: {a}\n")); + let _ = writeln!(body, "- arch: {a}"); } } if old.pkgbase != new.pkgbase { - body.push_str(&format!("! pkgbase renamed: {} -> {}\n", old.pkgbase, new.pkgbase)); + let _ = writeln!(body, "! pkgbase renamed: {} -> {}", old.pkgbase, new.pkgbase); } let old_set: std::collections::BTreeSet<String> = old.pkgnames.iter().cloned().collect(); let new_set: std::collections::BTreeSet<String> = new.pkgnames.iter().cloned().collect(); for p in new_set.difference(&old_set) { - body.push_str(&format!("+ split package: {p}\n")); + let _ = writeln!(body, "+ split package: {p}"); } for p in old_set.difference(&new_set) { - body.push_str(&format!("- split package: {p}\n")); + let _ = writeln!(body, "- split package: {p}"); } Panel { name: "buildenv", title: "Build-env delta", body } } @@ -166,9 +163,15 @@ fn build_env_delta(old: &Recipe, new: &Recipe) -> Panel { fn install_delta(old: &Recipe, new: &Recipe) -> Panel { let mut body = String::new(); match (&old.install, &new.install) { - (None, Some(f)) => body.push_str(&format!("+ install script added: {f}\n")), - (Some(f), None) => body.push_str(&format!("- install script removed: {f}\n")), - (Some(a), Some(b)) if a != b => body.push_str(&format!("! install script changed: {a} -> {b}\n")), + (None, Some(f)) => { + let _ = writeln!(body, "+ install script added: {f}"); + } + (Some(f), None) => { + let _ = writeln!(body, "- install script removed: {f}"); + } + (Some(a), Some(b)) if a != b => { + let _ = writeln!(body, "! install script changed: {a} -> {b}"); + } _ => {} } if crate::recipe::bodies_changed(&old.pkgbuild, &new.pkgbuild) { @@ -182,18 +185,20 @@ fn version_delta(base: Option<&ReleaseRow>, c: &CandidateRow) -> Panel { match base { Some(b) => { let (bv, cv) = (b.version(), c.version()); - body.push_str(&format!("{bv} -> {cv}\n")); + let _ = writeln!(body, "{bv} -> {cv}"); if b.epoch != c.epoch { - body.push_str(&format!("epoch bump: {} -> {}\n", b.epoch, c.epoch)); + let _ = writeln!(body, "epoch bump: {} -> {}", b.epoch, c.epoch); } if b.pkgrel != c.pkgrel && b.pkgver == c.pkgver { - body.push_str(&format!("pkgrel change: {} -> {}\n", b.pkgrel, c.pkgrel)); + let _ = writeln!(body, "pkgrel change: {} -> {}", b.pkgrel, c.pkgrel); } if crate::pkgver::is_downgrade(&bv, &cv) { body.push_str("DOWNGRADE: AUR now offers a lower version than we serve\n"); } } - None => body.push_str(&format!("first introduction: {}\n", c.version())), + None => { + let _ = writeln!(body, "first introduction: {}", c.version()); + } } Panel { name: "version", title: "Version delta", body } } @@ -205,24 +210,32 @@ fn digest_delta(base: &ReleaseRow, c: &CandidateRow) -> Panel { for n in &new { match old.iter().find(|o| o.index == n.index) { Some(o) if o.digest != n.digest => { - body.push_str(&format!( - "! [{}] {} {} -> {}\n", - n.index, n.url, short(&o.digest), short(&n.digest) - )); + let _ = writeln!(body, "! [{}] {} {} -> {}", n.index, n.url, short(&o.digest), short(&n.digest)); + } + Some(_) => { + let _ = writeln!(body, " [{}] {} unchanged", n.index, n.url); + } + None => { + let _ = writeln!( + body, + "+ [{}] {} NEW ({}{})", + n.index, + n.url, + n.kind, + if n.skip_declared && !n.is_vcs() { + ", sha256sums=SKIP" + } else if n.is_vcs() { + ", pinned commit" + } else { + "" + } + ); } - Some(_) => body.push_str(&format!(" [{}] {} unchanged\n", n.index, n.url)), - None => body.push_str(&format!( - "+ [{}] {} NEW ({}{})\n", - n.index, - n.url, - n.kind, - if n.skip_declared && !n.is_vcs() { ", sha256sums=SKIP" } else if n.is_vcs() { ", pinned commit" } else { "" } - )), } } for o in &old { if !new.iter().any(|n| n.index == o.index) { - body.push_str(&format!("- [{}] {} REMOVED\n", o.index, o.url)); + let _ = writeln!(body, "- [{}] {} REMOVED", o.index, o.url); } } Panel { name: "digests", title: "Source digest delta", body } @@ -238,26 +251,39 @@ fn pin_delta(base: &ReleaseRow, c: &CandidateRow) -> Panel { for n in &new { match old.iter().find(|o| o.index == n.index) { Some(o) if o.commit != n.commit => { - body.push_str(&format!( - "! [{}] {} {} -> {} (branch {})\n", - n.index, n.url, short(&o.commit), short(&n.commit), n.branch.as_deref().unwrap_or("?") - )); + let _ = writeln!( + body, + "! [{}] {} {} -> {} (branch {})", + n.index, + n.url, + short(&o.commit), + short(&n.commit), + n.branch.as_deref().unwrap_or("?") + ); + } + Some(_) => { + let _ = writeln!(body, " [{}] {} unchanged", n.index, n.url); + } + None => { + let _ = writeln!(body, "+ [{}] {} at {}", n.index, n.url, short(&n.commit)); } - Some(_) => body.push_str(&format!(" [{}] {} unchanged\n", n.index, n.url)), - None => body.push_str(&format!("+ [{}] {} at {}\n", n.index, n.url, short(&n.commit))), } } Panel { name: "upstream", title: "Upstream delta", body } } fn short(s: &str) -> String { - if s.len() > 12 { s[..12].to_string() } else { s.to_string() } + if s.len() > 12 { + s[..12].to_string() + } else { + s.to_string() + } } pub fn render_text(ps: &[Panel]) -> String { let mut s = String::new(); for p in ps { - s.push_str(&format!("### {}\n{}\n", p.title, p.body)); + let _ = write!(s, "### {}\n{}\n", p.title, p.body); } s } diff --git a/src/review/intake.rs b/src/review/intake.rs index 7d84544..78e4eb6 100644 --- a/src/review/intake.rs +++ b/src/review/intake.rs @@ -11,7 +11,11 @@ //! and review decides what a candidate means. use crate::config::Config; -use crate::db::{self, model::*, Db, Pkgbase}; +use crate::db::{ + self, + model::{Recipe, ReleaseRow, SourceDigest}, + Db, Pkgbase, +}; use crate::error::Result; use crate::review::candidates::{self, NewCandidate, Upsert}; use crate::review::risk; @@ -47,19 +51,14 @@ pub fn record( /// published yet — the reason a build would fail on a missing dep, said before /// it runs. fn missing_deps(db: &Db, pb: &Pkgbase, recipe: &Recipe) -> Vec<String> { - let ours = match db::our_package_names(db) { - Ok(o) => o, - Err(_) => return Vec::new(), - }; + let Ok(ours) = db::our_package_names(db) else { return Vec::new() }; let mut out = Vec::new(); for dep in crate::pkgver::dep_names(&recipe.depends) { if ours.contains(&dep) || dep == pb.name || recipe.pkgnames.contains(&dep) { continue; } - let ours_to_publish = db::get_subscription(db, &dep) - .map(|s| s.is_some()) - .unwrap_or(false) - || db::get_pkgbase(db, &dep).map(|p| p.is_some()).unwrap_or(false); + let ours_to_publish = db::get_subscription(db, &dep).is_ok_and(|s| s.is_some()) + || db::get_pkgbase(db, &dep).is_ok_and(|p| p.is_some()); if ours_to_publish { out.push(dep); } diff --git a/src/review/risk.rs b/src/review/risk.rs index e48ca24..4c9575f 100644 --- a/src/review/risk.rs +++ b/src/review/risk.rs @@ -1,4 +1,8 @@ -use crate::db::{self, model::*, Db}; +use crate::db::{ + self, + model::{Recipe, ReleaseRow, SourceDigest, UpstreamPin}, + Db, +}; use crate::error::Result; use crate::pkgver; @@ -22,8 +26,17 @@ pub mod level { const FETCHING_BUILD_TOOLS: &[&str] = &["cargo", "npm", "go", "pip", "python", "ruby", "deno", "rust", "nodejs"]; const BUILD_SYSTEM_FILES: &[&str] = &[ - "Cargo.toml", "Cargo.lock", "package.json", "setup.py", "pyproject.toml", "Makefile", "CMakeLists.txt", - "meson.build", "go.mod", "Gemfile", "build.gradle", + "Cargo.toml", + "Cargo.lock", + "package.json", + "setup.py", + "pyproject.toml", + "Makefile", + "CMakeLists.txt", + "meson.build", + "go.mod", + "Gemfile", + "build.gradle", ]; #[derive(Debug, Clone, Default)] @@ -32,8 +45,7 @@ pub(crate) struct Assessment { pub signals: Vec<String>, } -impl Assessment { -} +impl Assessment {} pub(crate) fn assess( db: &Db, @@ -94,7 +106,7 @@ pub(crate) fn assess( } fn accepted_pins(accepted: Option<&ReleaseRow>) -> Vec<UpstreamPin> { - accepted.map(|a| a.pins()).unwrap_or_default() + accepted.map_or_default(super::super::db::model::ReleaseRow::pins) } fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) { @@ -120,9 +132,7 @@ fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) { for (i, sum) in new.sha256sums.iter().enumerate() { if sum.eq_ignore_ascii_case("SKIP") { match old.sha256sums.get(i) { - Some(prev) if prev != "SKIP" && !prev.is_empty() => { - s.add(&format!("sums-to-skip:{i}"), level::HIGH) - } + Some(prev) if prev != "SKIP" && !prev.is_empty() => s.add(&format!("sums-to-skip:{i}"), level::HIGH), _ => {} } } @@ -172,7 +182,7 @@ fn upstream_touches_build_system(cfg: &crate::config::Config, from: &str, to: &s return false; } let range = format!("{from}..{to}"); - for dir in std::fs::read_dir(&cache).into_iter().flatten().filter_map(|d| d.ok()) { + for dir in std::fs::read_dir(&cache).into_iter().flatten().filter_map(std::result::Result::ok) { let path = dir.path(); if let Ok(files) = crate::git::git(Some(&path), &["diff", "--name-only", &range]) { if files.lines().any(|f| BUILD_SYSTEM_FILES.iter().any(|b| f.ends_with(b))) { diff --git a/src/sandbox/agent.rs b/src/sandbox/agent.rs index 3eaa799..fa813cf 100644 --- a/src/sandbox/agent.rs +++ b/src/sandbox/agent.rs @@ -22,17 +22,10 @@ pub struct AgentOptions { pub fn serve(opts: &AgentOptions) -> Result<()> { let stream = connect_with_retry(&opts.hub, Duration::from_secs(15))?; - let agent_id = opts - .agent_id - .clone() - .unwrap_or_else(|| format!("sandbox-{}", std::process::id())); + let agent_id = opts.agent_id.clone().unwrap_or_else(|| format!("sandbox-{}", std::process::id())); wire::write_frame( &mut stream.try_clone()?, - &Frame::Hello { - token: opts.token.clone(), - agent_id: agent_id.clone(), - profiles: vec![opts.profile.clone()], - }, + &Frame::Hello { token: opts.token.clone(), agent_id: agent_id.clone(), profiles: vec![opts.profile.clone()] }, )?; let mut reader = BufReader::new(stream.try_clone()?); @@ -50,8 +43,7 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { let child = Arc::new(Mutex::new(None::<u32>)); let alive = Arc::new(AtomicBool::new(true)); { - let (last, child, alive, ttl) = - (last_inbound.clone(), child.clone(), alive.clone(), ttl); + let (last, child, alive, ttl) = (last_inbound.clone(), child.clone(), alive.clone(), ttl); std::thread::spawn(crate::time::inherit(move || loop { crate::time::sleep(Duration::from_secs(1)); let quiet = last.lock().unwrap().elapsed(); @@ -102,17 +94,12 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { outcome } -fn handle( - frame: Frame, - writer: &Arc<Mutex<TcpStream>>, - blobs: &Path, - child: &Arc<Mutex<Option<u32>>>, -) -> Result<bool> { +fn handle(frame: Frame, writer: &Arc<Mutex<TcpStream>>, blobs: &Path, child: &Arc<Mutex<Option<u32>>>) -> Result<bool> { match frame { Frame::Destroy {} => Ok(true), Frame::Ping {} => Ok(false), Frame::Put { req, digest, data } => { - let bytes = wire::unhex(&data).map_err(io_err)?; + let bytes = wire::unhex(&data).map_err(|e| Error::other(e.to_string()))?; if crate::hash::hex(&bytes) != digest { reply(writer, req, Err("put: data does not hash to the claimed digest"))?; return Ok(false); @@ -121,16 +108,18 @@ fn handle( reply(writer, req, Ok(()))?; Ok(false) } - Frame::Get { req, digest } => match std::fs::read(safe_blob_path(blobs, &digest)?) { - Ok(bytes) => { - wire::write_frame(writer.lock().unwrap().deref_mut(), &Frame::Blob { req, data: wire::hex_bytes(&bytes) })?; + Frame::Get { req, digest } => { + if let Ok(bytes) = std::fs::read(safe_blob_path(blobs, &digest)?) { + wire::write_frame( + writer.lock().unwrap().deref_mut(), + &Frame::Blob { req, data: wire::hex_bytes(&bytes) }, + )?; Ok(false) - } - Err(_) => { + } else { reply(writer, req, Err("get: no such blob"))?; Ok(false) } - }, + } Frame::Run { req, argv, cwd, env } => { run_child(req, argv, cwd, env, writer, blobs, child)?; Ok(false) @@ -149,16 +138,14 @@ fn run_child( child: &Arc<Mutex<Option<u32>>>, ) -> Result<()> { let mut argv = argv; - for a in argv.iter_mut() { + for a in &mut argv { if let Some(digest) = a.strip_prefix("blob:") { *a = safe_blob_path(blobs, digest)?.display().to_string(); } } let program = argv.first().ok_or_else(|| Error::invalid("run: empty argv"))?; let mut c = std::process::Command::new(program); - c.args(&argv[1..]) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); + c.args(&argv[1..]).stdout(Stdio::piped()).stderr(Stdio::piped()); if let Some(dir) = cwd { c.current_dir(dir); } @@ -205,10 +192,7 @@ fn run_child( } let status = proc.wait()?; *child.lock().unwrap() = None; - wire::write_frame( - writer.lock().unwrap().deref_mut(), - &Frame::Exit { req, code: status.code() }, - )?; + wire::write_frame(writer.lock().unwrap().deref_mut(), &Frame::Exit { req, code: status.code() })?; Ok(()) } @@ -246,8 +230,4 @@ fn safe_blob_path(blobs: &Path, digest: &str) -> Result<PathBuf> { Ok(blobs.join(digest)) } -fn io_err(e: std::io::Error) -> Error { - Error::other(e.to_string()) -} - use std::ops::DerefMut; diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs index cfc3bd6..ca39c6b 100644 --- a/src/sandbox/kata.rs +++ b/src/sandbox/kata.rs @@ -77,11 +77,9 @@ fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value { impl K8sSandboxProvisioner { fn for_config(cfg: &Config) -> Option<Self> { match &cfg.sandbox { - crate::config::Sandbox::AgentSandbox { api, namespace, bearer, .. } => Some(Self { - api: api.clone(), - namespace: namespace.clone(), - bearer: bearer.clone(), - }), + crate::config::Sandbox::AgentSandbox { api, namespace, bearer, .. } => { + Some(Self { api: api.clone(), namespace: namespace.clone(), bearer: bearer.clone() }) + } _ => None, } } @@ -120,7 +118,7 @@ impl Provisioner for K8sSandboxProvisioner { Ok(()) } - fn name(&self) -> &str { + fn name(&self) -> &'static str { "k8s-sandbox-crd" } } @@ -173,7 +171,7 @@ impl Provisioner for LocalAgentProvisioner { Ok(()) } - fn name(&self) -> &str { + fn name(&self) -> &'static str { "local-agent" } } @@ -182,7 +180,11 @@ impl Provisioner for LocalAgentProvisioner { /// is not a nameable path from outside; the alias below is the only way to /// reach it, and the alias is what carries the feature-conditional visibility. mod kata_backend { - use super::*; + use super::{ + bounded, route_dial_in, wire, Arc, AtomicU64, Config, Duration, Error, Frame, HashMap, K8sSandboxProvisioner, + Mutex, OnceLock, Ordering, PoolFull, ProvisionRequest, Provisioner, Receiver, RemoteSandbox, Result, Sandbox, + SandboxBackend, SandboxInfo, SandboxSpec, Sender, TcpListener, TcpStream, + }; pub struct KataBackend { cfg: Config, @@ -198,22 +200,19 @@ mod kata_backend { let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } = &cfg.sandbox else { - return Err(Error::invalid( - "KataBackend::shared_for needs an agent-sandbox configuration", - )); + return Err(Error::invalid("KataBackend::shared_for needs an agent-sandbox configuration")); }; - let key = crate::hash::hex( - format!("{listen}\n{token}\n{api}\n{namespace}\n{bearer}\n{image}").as_bytes(), - ); + let key = crate::hash::hex(format!("{listen}\n{token}\n{api}\n{namespace}\n{bearer}\n{image}").as_bytes()); static CACHE: OnceLock<Mutex<HashMap<String, Arc<KataBackend>>>> = OnceLock::new(); let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); - let mut guard = cache.lock().unwrap_or_else(|p| p.into_inner()); + let mut guard = cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if let Some(existing) = guard.get(&key) { return Ok(existing.clone()); } - let provisioner = Arc::new(K8sSandboxProvisioner::for_config(cfg).ok_or_else(|| { - Error::invalid("KataBackend::shared_for needs an agent-sandbox configuration") - })?); + let provisioner = Arc::new( + K8sSandboxProvisioner::for_config(cfg) + .ok_or_else(|| Error::invalid("KataBackend::shared_for needs an agent-sandbox configuration"))?, + ); let backend = Arc::new(Self::bind(cfg, listen, token, provisioner)?); guard.insert(key, backend.clone()); Ok(backend) @@ -230,12 +229,7 @@ mod kata_backend { } } - pub fn bind( - cfg: &Config, - listen: &str, - token: &str, - provisioner: Arc<dyn Provisioner>, - ) -> Result<Self> { + pub fn bind(cfg: &Config, listen: &str, token: &str, provisioner: Arc<dyn Provisioner>) -> Result<Self> { let listener = TcpListener::bind(listen)?; let addr = listener.local_addr()?.to_string(); let pending: Arc<Mutex<HashMap<String, Sender<TcpStream>>>> = Arc::new(Mutex::new(HashMap::new())); @@ -267,10 +261,7 @@ mod kata_backend { fn nonce(&self) -> String { let n = self.counter.fetch_add(1, Ordering::SeqCst); - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); crate::hash::hex_str(&format!("{}-{n}-{nanos}", std::process::id()))[..20].to_string() } } @@ -285,19 +276,13 @@ mod kata_backend { self.pending.lock().unwrap().remove(&id); return Err(e); } - let stream = match rx.recv_timeout(spec.ttl) { - Ok(s) => s, - Err(_) => { - self.pending.lock().unwrap().remove(&id); - let _ = self.provisioner.reclaim(&id); - return Err(Error::pool_exhausted(PoolFull::Backend { - backend: "kata", - detail: format!( - "sandbox {id} for profile {} never dialed in within its TTL", - spec.profile - ), - })); - } + let Ok(stream) = rx.recv_timeout(spec.ttl) else { + self.pending.lock().unwrap().remove(&id); + let _ = self.provisioner.reclaim(&id); + return Err(Error::pool_exhausted(PoolFull::Backend { + backend: "kata", + detail: format!("sandbox {id} for profile {} never dialed in within its TTL", spec.profile), + })); }; let ttl = spec.ttl.max(Duration::from_secs(1)); wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: ttl.as_secs() })?; @@ -322,11 +307,7 @@ pub use kata_backend::KataBackend; #[cfg(not(feature = "test-support"))] pub(crate) use kata_backend::KataBackend; -fn route_dial_in( - stream: TcpStream, - token: &str, - pending: &Arc<Mutex<HashMap<String, Sender<TcpStream>>>>, -) { +fn route_dial_in(stream: TcpStream, token: &str, pending: &Arc<Mutex<HashMap<String, Sender<TcpStream>>>>) { let _ = stream.set_read_timeout(Some(Duration::from_secs(10))); let mut reader = match stream.try_clone() { Ok(s) => BufReader::new(s), @@ -361,8 +342,10 @@ mod tests { fn the_cr_asks_kata_for_a_vm_that_dies_on_its_own_by_ttl() { let cr = sandbox_cr(&req()); assert_eq!(cr["spec"]["runtimeClass"], "kata"); - assert_eq!(cr["spec"]["activeDeadlineSeconds"], 120, - "the orchestrator must enforce the TTL even if the hub dies"); + assert_eq!( + cr["spec"]["activeDeadlineSeconds"], 120, + "the orchestrator must enforce the TTL even if the hub dies" + ); assert_eq!(cr["spec"]["shutdownPolicy"], "Delete"); let args = cr["spec"]["template"]["spec"]["containers"][0]["args"] .as_array() @@ -455,17 +438,15 @@ mod tests { fn reclaim(&self, _id: &str) -> Result<()> { Ok(()) } - fn name(&self) -> &str { + fn name(&self) -> &'static str { "null" } } let cfg = Config::default(); - let backend = - KataBackend::bind(&cfg, "127.0.0.1:0", "tok", Arc::new(NullProvisioner)).unwrap(); + let backend = KataBackend::bind(&cfg, "127.0.0.1:0", "tok", Arc::new(NullProvisioner)).unwrap(); let started = std::time::Instant::now(); - let err = match backend.acquire(&SandboxSpec::new("extra-x86_64", "ghost", Duration::from_secs(1))) { - Ok(_) => panic!("nobody provisioned anything; the lease must not succeed"), - Err(e) => e, + let Err(err) = backend.acquire(&SandboxSpec::new("extra-x86_64", "ghost", Duration::from_secs(1))) else { + panic!("nobody provisioned anything; the lease must not succeed") }; assert!(started.elapsed() >= Duration::from_millis(900), "acquire gave up before the TTL"); assert!(err.to_string().contains("never dialed in"), "{err}"); @@ -495,7 +476,8 @@ mod tests { bearer: std::env::var("AUR_KATA_TOKEN").unwrap_or_default(), namespace: std::env::var("AUR_KATA_NS").unwrap_or_else(|_| "default".into()), }); - let backend = KataBackend::bind(&cfg, "0.0.0.0:9443", &std::env::var("AUR_AGENT_TOKEN").unwrap(), prov).unwrap(); + let backend = + KataBackend::bind(&cfg, "0.0.0.0:9443", &std::env::var("AUR_AGENT_TOKEN").unwrap(), prov).unwrap(); let sbx = backend .acquire(&SandboxSpec::new("extra-x86_64", "live", Duration::from_secs(300))) .expect("live kata sandbox should lease"); diff --git a/src/sandbox/loopback.rs b/src/sandbox/loopback.rs index 64875c6..fb97660 100644 --- a/src/sandbox/loopback.rs +++ b/src/sandbox/loopback.rs @@ -12,7 +12,7 @@ use crate::sandbox::{Cmd, Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpe /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod loopback_backend { - use super::*; + use super::Config; // `pub` fields inside a private module are not nameable from // outside; they stay readable by the impls below. @@ -42,18 +42,11 @@ impl SandboxBackend for LoopbackBackend { fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> { let blobs = blob_root(&self.cfg).join(safe_name(&spec.task)); fs::create_dir_all(&blobs)?; - Ok(Arc::new(LoopbackSandbox { - id: format!("loopback:{}", spec.task), - blobs, - cfg: self.cfg.clone(), - })) + Ok(Arc::new(LoopbackSandbox { id: format!("loopback:{}", spec.task), blobs, cfg: self.cfg.clone() })) } fn status(&self) -> Result<Vec<SandboxInfo>> { - Ok(vec![SandboxInfo { - id: "loopback".into(), - profile: self.cfg.build_profile.clone(), - }]) + Ok(vec![SandboxInfo { id: "loopback".into(), profile: self.cfg.build_profile.clone() }]) } } diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index bb6ab60..1c73e40 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -35,7 +35,7 @@ impl Cmd { self } pub fn name(&self) -> &str { - self.argv.first().map(String::as_str).unwrap_or("") + self.argv.first().map_or("", String::as_str) } } @@ -134,7 +134,7 @@ fn bound_listener(addr: &str, token: &str) -> Result<Bound> { let key = (addr.to_string(), token.to_string()); // A poisoned registry means a panic in another thread's bind; the map is // still sound, so recover rather than wedge every later build. - let mut reg = registry.lock().unwrap_or_else(|p| p.into_inner()); + let mut reg = registry.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if let Some(b) = reg.get(&key) { return Ok(b.clone()); } diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs index 8366e97..f881eb0 100644 --- a/src/sandbox/remote.rs +++ b/src/sandbox/remote.rs @@ -14,7 +14,7 @@ use crate::sandbox::{Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpec}; /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod remote_backend { - use super::*; + use super::{Config, Receiver}; // `pub` fields inside a private module are not nameable from // outside; they stay readable by the impls below. @@ -61,20 +61,16 @@ impl RemoteBackend { impl SandboxBackend for RemoteBackend { fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> { - let stream = self.queue.recv_timeout(spec.ttl).map_err(|_| { - Error::other(format!( - "no sandbox connected to {} within the lease window", - self.addr - )) - })?; + let stream = self + .queue + .recv_timeout(spec.ttl) + .map_err(|_| Error::other(format!("no sandbox connected to {} within the lease window", self.addr)))?; let _ = stream.set_read_timeout(Some(spec.ttl)); let mut reader = BufReader::new(stream.try_clone()?); let agent_id = match wire::read_frame(&mut reader)? { Some(Frame::Hello { token, agent_id, profiles }) => { if token != self.token { - return Err(Error::fail_closed(format!( - "sandbox {agent_id} presented the wrong token" - ))); + return Err(Error::fail_closed(format!("sandbox {agent_id} presented the wrong token"))); } if !profiles.is_empty() && !profiles.contains(&spec.profile) { return Err(Error::fail_closed(format!( @@ -89,16 +85,11 @@ impl SandboxBackend for RemoteBackend { }; wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: spec.ttl.as_secs().max(1) })?; let _ = stream.set_read_timeout(None); - Ok(Arc::new(RemoteSandbox::after_hello( - &self.cfg, stream, agent_id, spec.ttl, - ))) + Ok(Arc::new(RemoteSandbox::after_hello(&self.cfg, stream, agent_id, spec.ttl))) } fn status(&self) -> Result<Vec<SandboxInfo>> { - Ok(vec![SandboxInfo { - id: format!("remote@{}", self.addr), - profile: self.cfg.build_profile.clone(), - }]) + Ok(vec![SandboxInfo { id: format!("remote@{}", self.addr), profile: self.cfg.build_profile.clone() }]) } } @@ -112,10 +103,13 @@ pub(crate) struct RemoteSandbox { } impl RemoteSandbox { - pub(crate) fn after_hello(cfg: &Config, stream: std::net::TcpStream, agent_id: String, ttl: std::time::Duration) -> Self { - let reader = BufReader::new( - stream.try_clone().expect("cloning a connected tcp stream cannot fail"), - ); + pub(crate) fn after_hello( + cfg: &Config, + stream: std::net::TcpStream, + agent_id: String, + ttl: std::time::Duration, + ) -> Self { + let reader = BufReader::new(stream.try_clone().expect("cloning a connected tcp stream cannot fail")); Self { cfg: cfg.clone(), id: agent_id, @@ -132,9 +126,8 @@ impl RemoteSandbox { fn pump(&self, req: u64, sink: &mut dyn FnMut(&str, &[u8])) -> Result<Frame> { loop { - let frame = match wire::read_frame(&mut *self.reader.lock().unwrap())? { - Some(f) => f, - None => return Err(Error::other(format!("sandbox {} vanished", self.id))), + let Some(frame) = wire::read_frame(&mut *self.reader.lock().unwrap())? else { + return Err(Error::other(format!("sandbox {} vanished", self.id))); }; match frame { Frame::Log { req: r, ref stream, ref data } if r == req => { diff --git a/src/sandbox/wire.rs b/src/sandbox/wire.rs index 4ae1ec0..75fc0a5 100644 --- a/src/sandbox/wire.rs +++ b/src/sandbox/wire.rs @@ -36,8 +36,7 @@ pub(crate) enum Frame { } pub(crate) fn write_frame(w: &mut impl Write, f: &Frame) -> io::Result<()> { - let body = serde_json::to_vec(f) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + let body = serde_json::to_vec(f).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; if body.len() as u64 > MAX_FRAME_BYTES as u64 { return Err(io::Error::new(io::ErrorKind::InvalidInput, "frame too large")); } @@ -59,8 +58,7 @@ pub(crate) fn read_frame(r: &mut impl BufRead) -> io::Result<Option<Frame>> { } let mut body = vec![0u8; n]; r.read_exact(&mut body)?; - let f: Frame = serde_json::from_slice(&body) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + let f: Frame = serde_json::from_slice(&body).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; Ok(Some(f)) } @@ -79,7 +77,8 @@ mod tests { #[test] fn frames_round_trip_through_a_byte_stream() { let mut buf = Vec::new(); - write_frame(&mut buf, &Frame::Hello { token: "t".into(), agent_id: "a".into(), profiles: vec!["p".into()] }).unwrap(); + write_frame(&mut buf, &Frame::Hello { token: "t".into(), agent_id: "a".into(), profiles: vec!["p".into()] }) + .unwrap(); write_frame(&mut buf, &Frame::Log { req: 7, stream: "stdout".into(), data: hex_bytes(b"hello") }).unwrap(); write_frame(&mut buf, &Frame::Exit { req: 7, code: Some(0) }).unwrap(); let mut cur = std::io::BufReader::new(std::io::Cursor::new(buf)); diff --git a/src/shims/mod.rs b/src/shims/mod.rs index a918515..b605229 100644 --- a/src/shims/mod.rs +++ b/src/shims/mod.rs @@ -1,3 +1,4 @@ +use std::fmt::Write as _; use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; @@ -114,20 +115,15 @@ fn manifest_impl() -> Manifest { /// Called by `run` to log the invocation; nothing outside `shims` records a shim call. fn record(tool: &str, args: &[String]) { - let dir = match std::env::var("AUR_SHIM_DIR") { - Ok(d) => d, - Err(_) => return, - }; + let Ok(dir) = std::env::var("AUR_SHIM_DIR") else { return }; let _ = std::fs::create_dir_all(&dir); let entry = serde_json::json!({ "tool": tool, "args": args, - "cwd": std::env::current_dir().map(|p| p.display().to_string()).unwrap_or_default(), + "cwd": std::env::current_dir().map_or_default(|p| p.display().to_string()), }); - if let Ok(mut f) = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(Path::new(&dir).join("invocations.jsonl")) + if let Ok(mut f) = + std::fs::OpenOptions::new().create(true).append(true).open(Path::new(&dir).join("invocations.jsonl")) { use std::io::Write; let _ = f.write_all(format!("{entry}\n").as_bytes()); @@ -145,7 +141,7 @@ fn kill_parent_if_asked(tool: &str) { } fn forced_fail(tool: &str) -> bool { - std::env::var("AUR_SHIM_FAIL").map(|v| v == tool).unwrap_or(false) + std::env::var("AUR_SHIM_FAIL").is_ok_and(|v| v == tool) } /// Read back the shim's invocation log. @@ -159,10 +155,7 @@ fn forced_fail(tool: &str) -> bool { pub fn invocations(dir: &Path) -> Vec<serde_json::Value> { let path = dir.join("invocations.jsonl"); match std::fs::read_to_string(path) { - Ok(s) => s - .lines() - .filter_map(|l| serde_json::from_str(l).ok()) - .collect(), + Ok(s) => s.lines().filter_map(|l| serde_json::from_str(l).ok()).collect(), Err(_) => Vec::new(), } } @@ -179,10 +172,7 @@ pub fn called_with(dir: &Path, tool: &str, needle: &str) -> usize { .iter() .filter(|e| e["tool"] == tool) .filter(|e| { - e["args"] - .as_array() - .map(|a| a.iter().any(|v| v.as_str().is_some_and(|s| s.contains(needle)))) - .unwrap_or(false) + e["args"].as_array().is_some_and(|a| a.iter().any(|v| v.as_str().is_some_and(|s| s.contains(needle)))) }) .count() } @@ -257,13 +247,12 @@ fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result<i32, Strin } let startdir = std::env::current_dir().map_err(|e| e.to_string())?; if !startdir.join("PKGBUILD").exists() { - let found = std::fs::read_dir(&startdir) - .map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().into_owned()).collect::<Vec<_>>()) - .unwrap_or_default(); - return Err(format!( - "{tool}: no PKGBUILD in {} (contains {found:?})", - startdir.display() - )); + let found = std::fs::read_dir(&startdir).map_or_default(|rd| { + rd.filter_map(std::result::Result::ok) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect::<Vec<_>>() + }); + return Err(format!("{tool}: no PKGBUILD in {} (contains {found:?})", startdir.display())); } let pkgs = packages_to_emit(m, &startdir); for p in &pkgs { @@ -290,7 +279,7 @@ fn plant_link_if_asked(startdir: &Path) { { let _ = std::fs::remove_file(&link); if let Err(e) = std::os::unix::fs::symlink(&target, &link) { - eprintln!("shim: could not plant {link:?} -> {target}: {e}"); + eprintln!("shim: could not plant {} -> {target}: {e}", link.display()); } } } @@ -327,10 +316,8 @@ fn write_package(dir: &Path, p: &FakePackage, m: &Manifest) -> Result<PathBuf, S let (pkgver, pkgrel) = p.split_version(); let filename = format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch); let path = dir.join(&filename); - let enc = zstd::Encoder::new(std::io::BufWriter::new( - std::fs::File::create(&path).map_err(|e| e.to_string())?, - ), 3) - .map_err(|e| e.to_string())?; + let enc = zstd::Encoder::new(std::io::BufWriter::new(std::fs::File::create(&path).map_err(|e| e.to_string())?), 3) + .map_err(|e| e.to_string())?; let mut ar = tar::Builder::new(enc); // NOTE: the zstd frame must be finished explicitly or the archive is a // truncated stream that nothing can read back. @@ -359,35 +346,35 @@ fn write_entry<W: std::io::Write>(ar: &mut tar::Builder<W>, path: &str, body: &[ fn pkginfo(p: &FakePackage, pkgver: &str, pkgrel: &str) -> String { let mut s = String::new(); - s.push_str(&format!("pkgname = {}\n", p.name)); - s.push_str(&format!("pkgbase = {}\n", p.name)); - s.push_str(&format!("pkgver = {pkgver}-{pkgrel}\n")); - s.push_str(&format!("pkgarch = {}\n", p.arch)); - s.push_str(&format!("pkgdesc = {}\n", p.desc)); - s.push_str(&format!("url = {}\n", p.url)); + let _ = writeln!(s, "pkgname = {}", p.name); + let _ = writeln!(s, "pkgbase = {}", p.name); + let _ = writeln!(s, "pkgver = {pkgver}-{pkgrel}"); + let _ = writeln!(s, "pkgarch = {}", p.arch); + let _ = writeln!(s, "pkgdesc = {}", p.desc); + let _ = writeln!(s, "url = {}", p.url); s.push_str("builddate = 1700000000\n"); s.push_str("packager = shim <shim@example.invalid>\n"); s.push_str("size = 42\n"); for l in &p.license { - s.push_str(&format!("license = {l}\n")); + let _ = writeln!(s, "license = {l}"); } for d in &p.depends { - s.push_str(&format!("depend = {d}\n")); + let _ = writeln!(s, "depend = {d}"); } for d in &p.makedepends { - s.push_str(&format!("makedepend = {d}\n")); + let _ = writeln!(s, "makedepend = {d}"); } for d in &p.checkdepends { - s.push_str(&format!("checkdepend = {d}\n")); + let _ = writeln!(s, "checkdepend = {d}"); } for d in &p.provides { - s.push_str(&format!("provides = {d}\n")); + let _ = writeln!(s, "provides = {d}"); } for d in &p.conflicts { - s.push_str(&format!("conflicts = {d}\n")); + let _ = writeln!(s, "conflicts = {d}"); } for b in &p.backup { - s.push_str(&format!("backup = {b}\n")); + let _ = writeln!(s, "backup = {b}"); } s } @@ -395,16 +382,16 @@ fn pkginfo(p: &FakePackage, pkgver: &str, pkgrel: &str) -> String { fn buildinfo(p: &FakePackage, pkgver: &str, pkgrel: &str, m: &Manifest) -> String { let mut s = String::new(); s.push_str("format = 2\n"); - s.push_str(&format!("pkgname = {}\n", p.name)); - s.push_str(&format!("pkgbase = {}\n", p.name)); - s.push_str(&format!("pkgver = {pkgver}-{pkgrel}\n")); - s.push_str(&format!("pkgarch = {}\n", p.arch)); + let _ = writeln!(s, "pkgname = {}", p.name); + let _ = writeln!(s, "pkgbase = {}", p.name); + let _ = writeln!(s, "pkgver = {pkgver}-{pkgrel}"); + let _ = writeln!(s, "pkgarch = {}", p.arch); s.push_str("packager = shim <shim@example.invalid>\n"); s.push_str("builddate = 1700000000\n"); s.push_str("buildenv = (!debug !strip)\n"); s.push_str("installed =\n"); for i in &m.installed { - s.push_str(&format!(" {} {} {} -\n", i.name, i.version, if i.arch.is_empty() { "any" } else { &i.arch })); + let _ = writeln!(s, " {} {} {} -", i.name, i.version, if i.arch.is_empty() { "any" } else { &i.arch }); } s } @@ -428,26 +415,26 @@ fn makepkg(args: &[String], m: &Manifest) -> Result<i32, String> { if let Some(si) = r.srcinfo { s = si; } else { - s.push_str(&format!("pkgbase = {}\n", r.pkgbase)); - s.push_str(&format!("\tpkgver = {}\n", r.pkgver)); - s.push_str(&format!("\tpkgrel = {}\n", r.pkgrel)); + let _ = writeln!(s, "pkgbase = {}", r.pkgbase); + let _ = writeln!(s, "\tpkgver = {}", r.pkgver); + let _ = writeln!(s, "\tpkgrel = {}", r.pkgrel); if r.epoch != "0" { - s.push_str(&format!("\tepoch = {}\n", r.epoch)); + let _ = writeln!(s, "\tepoch = {}", r.epoch); } for a in &r.arch { - s.push_str(&format!("\tarch = {a}\n")); + let _ = writeln!(s, "\tarch = {a}"); } for d in &r.depends { - s.push_str(&format!("\tdepends = {d}\n")); + let _ = writeln!(s, "\tdepends = {d}"); } for src in &r.source { - s.push_str(&format!("\tsource = {src}\n")); + let _ = writeln!(s, "\tsource = {src}"); } for c in &r.sha256sums { - s.push_str(&format!("\tsha256sums = {c}\n")); + let _ = writeln!(s, "\tsha256sums = {c}"); } for n in &r.pkgnames { - s.push_str(&format!("pkgname = {n}\n")); + let _ = writeln!(s, "pkgname = {n}"); } } print!("{s}"); @@ -468,15 +455,11 @@ fn pacman(args: &[String]) -> Result<i32, String> { if args.iter().any(|a| a == "-U") { for path in args.iter().filter(|a| !a.starts_with('-')) { let p = std::path::Path::new(path); - let claimed = p - .file_name() - .and_then(|s| s.to_str()) - .ok_or_else(|| format!("pacman: bad blob path {path}"))?; + let claimed = + p.file_name().and_then(|s| s.to_str()).ok_or_else(|| format!("pacman: bad blob path {path}"))?; let bytes = std::fs::read(p).map_err(|e| format!("pacman: {path}: {e}"))?; if crate::hash::hex(&bytes) != claimed { - return Err(format!( - "pacman: {claimed} does not hash to the digest its name claims" - )); + return Err(format!("pacman: {claimed} does not hash to the digest its name claims")); } let pkginfo = crate::pkginfo::pkginfo_text(&bytes)?; let info = crate::pkginfo::parse_pkginfo(&pkginfo); @@ -505,13 +488,7 @@ fn installed_db() -> Option<std::path::PathBuf> { std::env::var("AUR_SHIM_DIR").ok().map(|d| std::path::Path::new(&d).join("installed.txt")) } -const DB_SUFFIXES: [&str; 5] = [ - ".db.tar", - ".db.tar.gz", - ".db.tar.zst", - ".db.tar.bz2", - ".db.tar.xz", -]; +const DB_SUFFIXES: [&str; 5] = [".db.tar", ".db.tar.gz", ".db.tar.zst", ".db.tar.bz2", ".db.tar.xz"]; /// The shim validates its own `--db` argument; tests check the verdicts. /// @@ -528,14 +505,8 @@ fn valid_db_arg(p: &Path) -> bool { } fn valid_db_arg_impl(p: &Path) -> bool { - let name = p - .file_name() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(); - !name.is_empty() - && DB_SUFFIXES - .iter() - .any(|sfx| name.ends_with(sfx)) + let name = p.file_name().map_or_default(|s| s.to_string_lossy().into_owned()); + !name.is_empty() && DB_SUFFIXES.iter().any(|sfx| name.ends_with(sfx)) } fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { @@ -559,10 +530,7 @@ fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { None => return Err("repo-add: no database given".into()), }; if !valid_db_arg(&db_path) { - eprintln!( - "==> ERROR: '{}' does not have a valid database archive extension.", - db_path.display() - ); + eprintln!("==> ERROR: '{}' does not have a valid database archive extension.", db_path.display()); return Ok(1); } let mut ar = tar::Builder::new(Vec::new()); @@ -571,30 +539,28 @@ fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { let pkginfo = crate::pkginfo::pkginfo_text(&bytes)?; let (name, version, arch, extra) = pkginfo_fields(&bytes)?; let mut entry = String::new(); - entry.push_str(&format!("%FILENAME%\n{}\n\n", pkg.file_name().unwrap().to_string_lossy())); - entry.push_str(&format!("%NAME%\n{name}\n\n")); - entry.push_str(&format!("%BASE%\n{name}\n\n")); - entry.push_str(&format!("%VERSION%\n{version}\n\n")); - entry.push_str(&format!("%ARCH%\n{arch}\n\n")); - entry.push_str(&format!("%CSIZE%\n{}\n\n", bytes.len())); + let _ = write!(entry, "%FILENAME%\n{}\n\n", pkg.file_name().unwrap().to_string_lossy()); + let _ = write!(entry, "%NAME%\n{name}\n\n"); + let _ = write!(entry, "%BASE%\n{name}\n\n"); + let _ = write!(entry, "%VERSION%\n{version}\n\n"); + let _ = write!(entry, "%ARCH%\n{arch}\n\n"); + let _ = write!(entry, "%CSIZE%\n{}\n\n", bytes.len()); entry.push_str("%DSIZE%\n42\n\n"); - entry.push_str(&format!("%MD5SUM%\n{}\n\n", hash::hex(&bytes))); - entry.push_str(&format!("%SHA256SUM%\n{}\n\n", hash::hex(&bytes))); + let _ = write!(entry, "%MD5SUM%\n{}\n\n", hash::hex(&bytes)); + let _ = write!(entry, "%SHA256SUM%\n{}\n\n", hash::hex(&bytes)); if !extra.is_empty() { - entry.push_str(&format!("{extra}\n")); + let _ = writeln!(entry, "{extra}"); } let mut h = tar::Header::new_gnu(); h.set_size(entry.len() as u64); h.set_mode(0o644); h.set_mtime(0); - ar.append_data(&mut h, format!("{name}/DESC"), entry.as_bytes()) - .map_err(|e| e.to_string())?; + ar.append_data(&mut h, format!("{name}/DESC"), entry.as_bytes()).map_err(|e| e.to_string())?; let mut h2 = tar::Header::new_gnu(); h2.set_size(pkginfo.len() as u64); h2.set_mode(0o644); h2.set_mtime(0); - ar.append_data(&mut h2, format!("{name}/.PKGINFO"), pkginfo.as_bytes()) - .map_err(|e| e.to_string())?; + ar.append_data(&mut h2, format!("{name}/.PKGINFO"), pkginfo.as_bytes()).map_err(|e| e.to_string())?; } let tar = ar.into_inner().map_err(|e| e.to_string())?; let mut enc = flate2::write::GzEncoder::new( @@ -615,10 +581,16 @@ fn pkginfo_fields(pkg_bytes: &[u8]) -> Result<(String, String, String, String), { let mut push = |tag: &str, vals: &[String]| { if !vals.is_empty() { - extra.push_str(&format!("{tag}\n{}\n\n", vals.join("\n"))); + let _ = write!(extra, "{tag}\n{}\n\n", vals.join("\n")); + } + }; + let one = |s: &str| -> Vec<String> { + if s.is_empty() { + vec![] + } else { + vec![s.to_string()] } }; - let one = |s: &str| -> Vec<String> { if s.is_empty() { vec![] } else { vec![s.to_string()] } }; push("%DESC%", &one(&info.desc)); push("%URL%", &one(&info.url)); push("%LICENSE%", &info.license); @@ -634,16 +606,9 @@ fn pkginfo_fields(pkg_bytes: &[u8]) -> Result<(String, String, String, String), /// Reached only through `run`, which matches the tool name to it. The tool name appears in test strings, which is not a caller. fn gpg(args: &[String]) -> Result<i32, String> { - let out = args - .iter() - .position(|a| a == "--output" || a == "-o") - .and_then(|i| args.get(i + 1)) - .cloned(); + let out = args.iter().position(|a| a == "--output" || a == "-o").and_then(|i| args.get(i + 1)).cloned(); let target = args.iter().rev().find(|a| !a.starts_with('-') && Some(*a) != out.as_ref()); - let target = match target { - Some(t) => t, - None => return Err("gpg: nothing to sign".into()), - }; + let Some(target) = target else { return Err("gpg: nothing to sign".into()) }; let bytes = std::fs::read(target).map_err(|e| format!("gpg: {target}: {e}"))?; let sig = match out { Some(o) => o, diff --git a/src/time.rs b/src/time.rs index b0ab4ab..4abb3f9 100644 --- a/src/time.rs +++ b/src/time.rs @@ -59,14 +59,9 @@ pub fn unpin() { } pub fn parse(ts: &str) -> Option<DateTime<Utc>> { - DateTime::parse_from_rfc3339(ts) - .ok() - .map(|d| d.with_timezone(&Utc)) - .or_else(|| { - chrono::NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S") - .ok() - .map(|n| Utc.from_utc_datetime(&n)) - }) + DateTime::parse_from_rfc3339(ts).ok().map(|d| d.with_timezone(&Utc)).or_else(|| { + chrono::NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S").ok().map(|n| Utc.from_utc_datetime(&n)) + }) } pub fn delta_secs(a: &str, b: &str) -> Option<i64> { @@ -132,7 +127,7 @@ pub fn virtualize() -> clock::VirtualClock { #[cfg(feature = "test-support")] mod clock { - use super::*; + use super::{DateTime, Utc}; use std::cell::Cell; use std::sync::{Mutex, MutexGuard}; @@ -143,7 +138,7 @@ mod clock { static AT: Mutex<Option<DateTime<Utc>>> = Mutex::new(None); static OWNER: Mutex<()> = Mutex::new(()); -// VirtualClock stays `pub`: lives in the `test-support`-gated clock module, behind the gated `virtualize()` that returns it. + // VirtualClock stays `pub`: lives in the `test-support`-gated clock module, behind the gated `virtualize()` that returns it. pub struct VirtualClock { // Held, never read: owning the mutex *is* the virtual clock's lease, // and dropping this guard is what releases it. @@ -151,7 +146,7 @@ mod clock { } pub fn virtualize() -> VirtualClock { - let owner = OWNER.lock().unwrap_or_else(|e| e.into_inner()); + let owner = OWNER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); *lock(&AT) = Some(Utc::now()); ON.set(true); VirtualClock { _owner: owner } @@ -165,7 +160,7 @@ mod clock { } fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> { - m.lock().unwrap_or_else(|e| e.into_inner()) + m.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } pub fn now() -> Option<DateTime<Utc>> { diff --git a/src/urlutil.rs b/src/urlutil.rs index 12f74e5..26677c3 100644 --- a/src/urlutil.rs +++ b/src/urlutil.rs @@ -10,7 +10,7 @@ fn host_of(source: &str) -> Option<String> { } pub fn hosts(sources: &[String]) -> BTreeSet<String> { - sources.iter().map(|s| s.as_str()).filter_map(host_of).collect() + sources.iter().map(std::string::String::as_str).filter_map(host_of).collect() } #[cfg(test)] @@ -25,10 +25,7 @@ mod tests { #[test] fn scheme_and_filename_prefixes_are_stripped() { assert_eq!(host_of("git+https://github.com/a/b.git").as_deref(), Some("github.com")); - assert_eq!( - host_of("myname::https://cdn.example.org/x.tar").as_deref(), - Some("cdn.example.org") - ); + assert_eq!(host_of("myname::https://cdn.example.org/x.tar").as_deref(), Some("cdn.example.org")); assert_eq!( host_of("myname::git+ssh://git@gitlab.example.org/a/b.git").as_deref(), Some("gitlab.example.org"), diff --git a/src/usecase/builds.rs b/src/usecase/builds.rs index c947742..265e6cb 100644 --- a/src/usecase/builds.rs +++ b/src/usecase/builds.rs @@ -29,15 +29,7 @@ pub fn cancel(db: &Db, build_id: &str) -> Result<()> { /// 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!({}), - ) + db::audit(&db.writer, actor, actor, "build.retry", "build", build_id, serde_json::json!({})) } /// Take a package out of the repository index. diff --git a/src/usecase/mod.rs b/src/usecase/mod.rs index 4a7a0a9..288d71d 100644 --- a/src/usecase/mod.rs +++ b/src/usecase/mod.rs @@ -26,10 +26,7 @@ mod subscriptions; pub use bootstrap::{init, open, serve}; pub use builds::{cancel, enqueue_candidate, manual_rebuild, retry, withdraw_package}; +pub use detect::{check, detect, Checked}; 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 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/watch/detect.rs b/src/watch/detect.rs index 1c72131..d51ca03 100644 --- a/src/watch/detect.rs +++ b/src/watch/detect.rs @@ -1,5 +1,8 @@ use crate::config::Config; -use crate::db::{self, *}; +use crate::db::{ + self, get_pkgbase, notice_kind, Db, Identity, Pkgbase, Recipe, ReleaseRow, SourceDigest, SubscriptionState, + UpstreamPin, +}; use crate::error::{Missing, Result}; use crate::pkgver; use crate::recipe::recipe_from_tree; @@ -31,10 +34,10 @@ pub struct CheckReport { } pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> { - let pb = get_pkgbase(db, name)? - .ok_or_else(|| crate::error::Error::not_found(Missing::Pkgbase(name.to_string())))?; + let pb = + get_pkgbase(db, name)?.ok_or_else(|| crate::error::Error::not_found(Missing::Pkgbase(name.to_string())))?; let sub = db::get_subscription(db, name)?; - let paused = sub.as_ref().map(|s| s.state == SubscriptionState::Paused).unwrap_or(false); + let paused = sub.as_ref().is_some_and(|s| s.state == SubscriptionState::Paused); if paused { return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Paused }); } @@ -46,7 +49,7 @@ pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> { pb.id, notice_kind::DELETED, "high", - serde_json::json!({"aur_url": pb.aur_url, "note": "repository no longer exists"}), + &serde_json::json!({"aur_url": pb.aur_url, "note": "repository no longer exists"}), )?; db::set_subscription_state(&db.writer, name, SubscriptionState::Orphaned)?; return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Gone }); @@ -77,12 +80,9 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor pb.id, notice_kind::DELETED, "high", - serde_json::json!({"mirror_divergence": a.aur_commit}), + &serde_json::json!({"mirror_divergence": a.aur_commit}), )?; - return Ok(report(Outcome::Blocked(format!( - "accepted pin {} missing from local mirror", - a.aur_commit - )))); + return Ok(report(Outcome::Blocked(format!("accepted pin {} missing from local mirror", a.aur_commit)))); } } @@ -90,13 +90,9 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor let recipe = recipe_from_tree(&tree.files)?; let recipe_hash = tree.recipe_hash(); - let has_vcs = recipe.source_entries.iter().any(|e| e.is_vcs()); - let accepted_pins: Vec<UpstreamPin> = accepted.as_ref().map(|a| a.pins()).unwrap_or_default(); - let stage_a = if has_vcs { - Some(crate::watch::upstream::probe(&recipe, &accepted_pins)?) - } else { - None - }; + let has_vcs = recipe.source_entries.iter().any(super::super::db::model::SourceEntry::is_vcs); + let accepted_pins: Vec<UpstreamPin> = accepted.as_ref().map_or_default(super::super::db::model::ReleaseRow::pins); + let stage_a = if has_vcs { Some(crate::watch::upstream::probe(&recipe, &accepted_pins)?) } else { None }; let resolved = if !has_vcs { None } else if stage_a.as_ref().unwrap().needs_stage_b() { @@ -124,14 +120,8 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor source_digests: digests.clone(), }; let identity_hash = identity.hash()?; - let snap_id = db::put_snapshot( - &db.writer, - pb.id, - head, - &recipe_hash, - &serde_json::to_string(&recipe)?, - &tree.json_list(), - )?; + let snap_id = + db::put_snapshot(&db.writer, pb.id, head, &recipe_hash, &serde_json::to_string(&recipe)?, &tree.json_list())?; let nc = NewCandidate { snapshot_id: snap_id, @@ -171,7 +161,7 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor pb.id, notice_kind::DOWNGRADE, "warning", - serde_json::json!({"served": base.version(), "aur": new_version}), + &serde_json::json!({"served": base.version(), "aur": new_version}), )?; } @@ -189,21 +179,11 @@ fn outcome_of(up: Upsert) -> Outcome { } } -fn non_publishable( - db: &Db, - pb: &Pkgbase, - base: &ReleaseRow, - nc: &NewCandidate, - recipe: &Recipe, -) -> Result<Outcome> { +fn non_publishable(db: &Db, pb: &Pkgbase, base: &ReleaseRow, nc: &NewCandidate, recipe: &Recipe) -> Result<Outcome> { let old_digests: Vec<SourceDigest> = base.digests(); let new_digests: Vec<SourceDigest> = serde_json::from_str(&nc.source_digests_json).unwrap_or_default(); - let vcs_indices: std::collections::BTreeSet<usize> = recipe - .source_entries - .iter() - .filter(|e| e.is_vcs()) - .map(|e| e.index) - .collect(); + let vcs_indices: std::collections::BTreeSet<usize> = + recipe.source_entries.iter().filter(|e| e.is_vcs()).map(|e| e.index).collect(); let changed_remote: Vec<&SourceDigest> = new_digests .iter() .filter(|n| n.kind != "local" && !vcs_indices.contains(&n.index)) @@ -223,7 +203,7 @@ fn non_publishable( .map(|n| { serde_json::json!({"index": n.index, "url": n.url, "old": old_digests.iter().find(|o| o.index == n.index) - .map(|o| o.digest.clone()).unwrap_or_default(), + .map_or_default(|o| o.digest.clone()), "new": n.digest}) }) .collect(); @@ -232,13 +212,16 @@ fn non_publishable( pb.id, notice_kind::INTEGRITY_ALERT, "high", - serde_json::json!({ + &serde_json::json!({ "version": nc.version(), "changed": changed, "message": "the artifact in your index was built from bytes upstream no longer serves; the version string is unchanged", }), )?; - return Ok(Outcome::Notice { kind: notice_kind::INTEGRITY_ALERT.into(), detail: serde_json::json!({"changed": changed}) }); + return Ok(Outcome::Notice { + kind: notice_kind::INTEGRITY_ALERT.into(), + detail: serde_json::json!({"changed": changed}), + }); } if pins_changed { db::put_notice_once( @@ -246,7 +229,7 @@ fn non_publishable( pb.id, notice_kind::PIN_DRIFT, "info", - serde_json::json!({ + &serde_json::json!({ "version": nc.version(), "message": "upstream moved; pkgver unchanged, nothing publishable", }), @@ -258,7 +241,7 @@ fn non_publishable( pb.id, notice_kind::RECIPE_DRIFT, "warning", - serde_json::json!({ + &serde_json::json!({ "version": nc.version(), "accepted_aur_commit": base.aur_commit, "aur_commit": "moved", diff --git a/src/watch/digests.rs b/src/watch/digests.rs index 027062b..ae53191 100644 --- a/src/watch/digests.rs +++ b/src/watch/digests.rs @@ -1,5 +1,5 @@ use crate::config::Config; -use crate::db::{self, *}; +use crate::db::{self, Db, Recipe, SourceDigest, UpstreamPin}; use crate::error::Result; use crate::recipe::{declared_sums, is_hex_digest, SKIP}; use crate::watch::mirror::Tree; @@ -23,10 +23,7 @@ pub(crate) fn resolve_sources( if entry.is_vcs() { let pin = pins.iter().find(|p| p.index == entry.index); - let digest = pin - .map(|p| p.commit.clone()) - .or_else(|| entry.commit.clone()) - .unwrap_or_default(); + let digest = pin.map(|p| p.commit.clone()).or_else(|| entry.commit.clone()).unwrap_or_default(); out.push(SourceDigest { index: entry.index, url: entry.url.clone(), @@ -43,11 +40,8 @@ pub(crate) fn resolve_sources( if entry.local { let name = entry.filename.clone().unwrap_or_default(); - let path = tree - .blobs - .iter() - .find(|(p, _)| p == &name || p.ends_with(&format!("/{name}"))) - .map(|(p, _)| p.clone()); + let path = + tree.blobs.iter().find(|(p, _)| p == &name || p.ends_with(&format!("/{name}"))).map(|(p, _)| p.clone()); let (digest, size) = match path { Some(p) => { let bytes = crate::watch::mirror::read_file(mirror, commit, &p)?; @@ -96,13 +90,13 @@ pub(crate) fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(St let tmp = cfg.source_cache_dir().join(format!("tmp-{}", crate::hash::short(url.as_bytes(), 16))); let (digest, size) = crate::fetch::fetch_to(url, &tmp)?; let dest = cfg.source_cache_path(&digest); - if !dest.exists() { + if dest.exists() { + let _ = std::fs::remove_file(&tmp); + } else { if let Some(parent) = dest.parent() { std::fs::create_dir_all(parent)?; } std::fs::rename(&tmp, &dest)?; - } else { - let _ = std::fs::remove_file(&tmp); } let dest_s = dest.display().to_string(); db::put_source_cache(&db.writer, url, &digest, size, &dest_s)?; @@ -110,9 +104,5 @@ pub(crate) fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(St } pub(crate) fn cached_path(db: &Db, url: &str, digest: &str) -> Option<std::path::PathBuf> { - db::source_cache_path(db, url, digest) - .ok() - .flatten() - .map(std::path::PathBuf::from) - .filter(|p| p.exists()) + db::source_cache_path(db, url, digest).ok().flatten().map(std::path::PathBuf::from).filter(|p| p.exists()) } diff --git a/src/watch/mirror.rs b/src/watch/mirror.rs index 5b7e2b1..0eb9a77 100644 --- a/src/watch/mirror.rs +++ b/src/watch/mirror.rs @@ -39,10 +39,7 @@ fn sync_mirror_impl(cfg: &Config, db: &Db, name: &str, url: &str) -> Result<Sync return Ok(Sync::Cloned { head }); } - let remote = match git::ls_remote_head(url)? { - Some(h) => h, - None => return Ok(Sync::Gone), - }; + let Some(remote) = git::ls_remote_head(url)? else { return Ok(Sync::Gone) }; let local = git::head(&mirror).ok(); if let Some(l) = &local { if *l == remote { @@ -95,9 +92,7 @@ pub(crate) fn read_tree(mirror: &Path, commit: &str) -> Result<Tree> { let contents = git::cat_file_batch(mirror, &oids)?; let mut files = BTreeMap::new(); for (path, sha) in &blobs { - let bytes = contents - .get(sha) - .ok_or_else(|| Error::not_found(Missing::MirrorPath(path.to_string())))?; + let bytes = contents.get(sha).ok_or_else(|| Error::not_found(Missing::MirrorPath(path.to_string())))?; if bytes.len() > 4 * 1024 * 1024 || !looks_textual(bytes) { continue; } @@ -114,7 +109,6 @@ pub(crate) fn read_file(mirror: &Path, commit: &str, path: &str) -> Result<Vec<u git::read_blob(mirror, commit, path) } - #[cfg(test)] mod tests { use super::*; @@ -125,10 +119,7 @@ mod tests { /// answer for, so the test does not stand up a mirror, a database or a /// config to ask it a question about one tree. fn repo(files: &[(&str, &[u8])]) -> (std::path::PathBuf, String) { - let nonce = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos(); + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); let dir = std::env::temp_dir().join(format!("aur-read-tree-{}-{}", std::process::id(), nonce)); std::fs::create_dir_all(&dir).unwrap(); let git = |args: &[&str]| { @@ -157,10 +148,13 @@ mod tests { #[test] fn read_tree_returns_every_blob_from_one_batch_read() { let (dir, head) = repo(&[ - ("PKGBUILD", b"pkgbase=foo + ( + "PKGBUILD", + b"pkgbase=foo pkgver=1.0 pkgrel=1 -"), +", + ), ("empty.txt", b""), ("blob.bin", b"\x00not text"), ]); @@ -179,8 +173,11 @@ pkgrel=1 #[test] fn read_tree_fails_closed_when_the_commit_is_gone_from_the_mirror() { - let (dir, _head) = repo(&[("PKGBUILD", b"pkgbase=foo -")]); + let (dir, _head) = repo(&[( + "PKGBUILD", + b"pkgbase=foo +", + )]); for gone in ["0123456789012345678901234567890123456789", "deadbeef"] { let err = read_tree(&dir, gone).unwrap_err().to_string(); assert!(err.contains("missing from the local mirror"), "{gone}: {err}"); diff --git a/src/watch/scheduler.rs b/src/watch/scheduler.rs index 4508a03..5aae7ea 100644 --- a/src/watch/scheduler.rs +++ b/src/watch/scheduler.rs @@ -27,17 +27,12 @@ pub fn spawn_scheduler(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>) -> JoinH pub fn sweep(cfg: &Config, db: &Db) -> usize { let now = crate::time::now(); - let due = match db::due_subscriptions(db, &now) { - Ok(d) => d, - Err(_) => return 0, - }; + let Ok(due) = db::due_subscriptions(db, &now) else { return 0 }; let mut n = 0; for sub in due { // Mark it checked first so a slow or hanging source cannot make the // scheduler re-enter it on the next tick. - let interval = sub - .poll_interval_secs - .unwrap_or(crate::db::setting_i64(db, "poll_interval", 86400)); + let interval = sub.poll_interval_secs.unwrap_or(crate::db::setting_i64(db, "poll_interval", 86400)); let _ = db::note_check(&db.writer, &sub.pkgbase, &crate::time::secs_ahead(interval), None); match check_pkgbase(cfg, db, &sub.pkgbase) { Ok(report) => { @@ -51,12 +46,7 @@ pub fn sweep(cfg: &Config, db: &Db) -> usize { } } Err(e) => { - let _ = db::note_check( - &db.writer, - &sub.pkgbase, - &crate::time::secs_ahead(600), - Some(&e.to_string()), - ); + let _ = db::note_check(&db.writer, &sub.pkgbase, &crate::time::secs_ahead(600), Some(&e.to_string())); } } n += 1; diff --git a/src/watch/staleness.rs b/src/watch/staleness.rs index 94813eb..6b83032 100644 --- a/src/watch/staleness.rs +++ b/src/watch/staleness.rs @@ -12,7 +12,7 @@ pub enum Kind { /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod stale { - use super::*; + use super::Kind; #[derive(Debug, Clone)] pub struct Stale { @@ -97,9 +97,7 @@ pub fn dependents_of(db: &Db, name: &str) -> Result<Vec<String>> { continue; } let depends = match serde_json::from_str::<crate::db::model::Recipe>(&json) { - Ok(r) => crate::pkgver::dep_names(&r.depends) - .into_iter() - .any(|d| d == name), + Ok(r) => crate::pkgver::dep_names(&r.depends).into_iter().any(|d| d == name), Err(_) => true, }; if depends { diff --git a/src/watch/upstream.rs b/src/watch/upstream.rs index 7987178..523574a 100644 --- a/src/watch/upstream.rs +++ b/src/watch/upstream.rs @@ -5,7 +5,11 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Condvar, Mutex}; use crate::config::Config; -use crate::db::{self, model::*, Db, Pkgbase}; +use crate::db::{ + self, + model::{Recipe, StageBCacheRow, UpstreamPin}, + Db, Pkgbase, +}; use crate::error::{Error, Result, TransientCause}; use crate::git; @@ -116,12 +120,7 @@ pub(crate) struct StageB { impl StageB { fn from_cache(row: StageBCacheRow) -> Self { - StageB { - epoch: row.epoch, - pkgver: row.pkgver, - pkgrel: row.pkgrel, - pins: row.pins, - } + StageB { epoch: row.epoch, pkgver: row.pkgver, pkgrel: row.pkgrel, pins: row.pins } } fn as_row(&self) -> StageBCacheRow { @@ -143,14 +142,14 @@ static SLOT_LOCK: Mutex<()> = Mutex::new(()); /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod stage_b_slot { - use super::*; + use super::{Ordering, RUNNING, SLOT_FREE, SLOT_LOCK}; pub struct StageBSlot(()); impl StageBSlot { pub fn acquire(cap: usize) -> Self { let cap = cap.max(1); - let guard = SLOT_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let guard = SLOT_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut guard = guard; loop { let n = RUNNING.load(Ordering::SeqCst); @@ -159,7 +158,7 @@ mod stage_b_slot { drop(guard); return StageBSlot(()); } - guard = SLOT_FREE.wait(guard).unwrap_or_else(|e| e.into_inner()); + guard = SLOT_FREE.wait(guard).unwrap_or_else(std::sync::PoisonError::into_inner); } } } @@ -191,7 +190,7 @@ pub(crate) fn resolve( recipe_hash: &str, stage_a: &StageA, ) -> Result<Option<StageB>> { - if !recipe.source_entries.iter().any(|e| e.is_vcs()) { + if !recipe.source_entries.iter().any(super::super::db::model::SourceEntry::is_vcs) { return Ok(None); } let tip_hash = tip_hash(&stage_a.pins); @@ -225,11 +224,11 @@ fn run( continue; } let cache = cfg.vcs_cache_path(&pin.url); - if !cache.exists() { + if cache.exists() { + let _ = git::fetch_and_head(&cache); + } else { git::clone_bare(&pin.url, &cache) .map_err(|e| Error::transient(TransientCause::Upstream(format!("vcs_cache clone {}: {e}", pin.url))))?; - } else { - let _ = git::fetch_and_head(&cache); } if let Ok(local) = git::head(&cache) { if !local.is_empty() && git::has_commit(&cache, &pin.commit) { @@ -251,10 +250,7 @@ fn run( let out = cmd.output()?; let _ = std::fs::remove_dir_all(&scratch); if !out.status.success() { - return Err(Error::transient(format!( - "makepkg --vercheck: {}", - String::from_utf8_lossy(&out.stderr).trim() - ))); + return Err(Error::transient(format!("makepkg --vercheck: {}", String::from_utf8_lossy(&out.stderr).trim()))); } let text = String::from_utf8_lossy(&out.stdout).trim().to_string(); let (pkgver, pkgrel) = match text.rsplit_once('-') { @@ -264,12 +260,7 @@ fn run( if pkgver.is_empty() { return Err(Error::other(format!("makepkg --vercheck produced {text:?}"))); } - Ok(StageB { - epoch: recipe.epoch.clone(), - pkgver, - pkgrel, - pins, - }) + Ok(StageB { epoch: recipe.epoch.clone(), pkgver, pkgrel, pins }) } fn default_branch(cache: &std::path::Path) -> Option<String> { @@ -280,16 +271,15 @@ fn default_branch(cache: &std::path::Path) -> Option<String> { } pub fn tip_hash(pins: &[UpstreamPin]) -> String { - let mut v: Vec<String> = pins - .iter() - .map(|p| format!("{}:{}:{}", p.index, p.url, p.commit)) - .collect(); + let mut v: Vec<String> = pins.iter().map(|p| format!("{}:{}:{}", p.index, p.url, p.commit)).collect(); v.sort(); crate::hash::hex_str(&v.join("\n")) } fn scratch_dir(cfg: &Config, pkgbase: &str, recipe_hash: &str, tip_hash: &str) -> PathBuf { - cfg.staging_dir() - .join("vercheck") - .join(format!("{pkgbase}-{}-{}", &recipe_hash[..8.min(recipe_hash.len())], &tip_hash[..8.min(tip_hash.len())])) + cfg.staging_dir().join("vercheck").join(format!( + "{pkgbase}-{}-{}", + &recipe_hash[..8.min(recipe_hash.len())], + &tip_hash[..8.min(tip_hash.len())] + )) } |
