diff --git a/app/src/console/mod.rs b/app/src/console/mod.rs new file mode 100644 index 00000000..4da66664 --- /dev/null +++ b/app/src/console/mod.rs @@ -0,0 +1,24 @@ +//! The schedule (`laravel schedule:run` every minute, in production a CronJob): the builds sweep every five minutes, +//! each run pushing its result to a heartbeat so a sweep that failed or stopped running alerts. + +use laravel::schedule::{self, Schedule}; + +// The heartbeat every scheduled task pushes to (`crate::heartbeat`). +pub use crate::heartbeat; + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.call(sweep_builds).name("builds-sweep").every_five_minutes().without_overlapping().on_one_runner(); +} + +/// [`crate::domain::processing::sweep`], with its heartbeat (`VISUALCI_BUILDS_SWEEP_HEARTBEAT_URL` and `_TOKEN`). +/// `/status` reports `oldest_processing_seconds` and `oldest_receiving_seconds`, which stay low while it runs. +async fn sweep_builds() -> laravel::Result<()> { + let outcome = crate::domain::processing::sweep().await; + match &outcome { + Ok(swept) => tracing::info!(?swept, "builds swept"), + Err(e) => tracing::error!(error = %e, "sweeping builds failed"), + } + heartbeat::push("VISUALCI_BUILDS_SWEEP_HEARTBEAT", outcome.as_ref().map(|_| ()).map_err(ToString::to_string)).await; + outcome.map(|_| ()) +} diff --git a/app/src/domain/baselines.rs b/app/src/domain/baselines.rs new file mode 100644 index 00000000..f74fcf0f --- /dev/null +++ b/app/src/domain/baselines.rs @@ -0,0 +1,478 @@ +//! Per-snapshot baselines. +//! +//! A build compares each snapshot with its own baseline, worked out in two layers: +//! +//! 1. **The anchor**: the nearest ancestor commit's completed CI build of the same suite (else the default branch's +//! latest approved one). Every build holds every snapshot (its own rows and the groups it reads from earlier builds, +//! `effective_snapshots`), so the anchor knows each one's approved state at that commit: an approved change is its +//! new version, an unapproved change is the version it was compared with, an unchanged snapshot is itself. +//! 2. **Approvals since**: every approved change is a row in `baselines` (the snapshot, or its removal) with the +//! build, commit, branch, environment and mode it came from. Rows newer than the anchor are laid on top: CI +//! approvals on the build's ancestry, and any approval on the build's own branch. A local approval counts on its +//! own branch only, never through ancestry. +//! +//! Documents and text are the same everywhere and keep one shared set (environment `""`). Screenshots keep a set per +//! environment: CI's comes from the anchor and CI approvals; a laptop's from its own approvals on the branch (or CI +//! approvals on the default branch), falling back to the closest environment's. + +use std::collections::{HashMap, HashSet}; + +use laravel::db; + +use super::environments::{SHARED, search_order}; +use super::snapshots::is_config_item; +use crate::models::{Baseline, Build, Project, Snapshot}; + +/// A snapshot's baseline: the snapshot to compare with, and the approval row it came from (`None` when it came from the +/// anchor build). +#[derive(Clone, Debug)] +pub struct Resolved { + pub row: Option, + pub snapshot: Snapshot, +} + +/// The commit and its ancestors, nearest first. +#[must_use] +pub fn ancestry(build: &Build) -> Vec { + let mut commits = vec![build.commit_sha.clone()]; + commits.extend(build.parent_commits.iter().cloned()); + commits +} + +/// The anchor build: the nearest ancestor commit's completed CI build of this suite, else the default branch's latest +/// approved CI build. +/// +/// # Errors +/// On a database error. +pub async fn anchor(build: &Build, project: &Project) -> laravel::Result> { + let commits = ancestry(build); + let (project_id, name, id) = (build.project_id, build.name.as_str(), build.id); + let candidates: Vec = db::query!( + "SELECT * FROM builds WHERE project_id = {project_id} AND name = {name} AND mode = 'ci' \ + AND state = 'completed' AND id <> {id} AND commit_sha IN ({...commits}) ORDER BY id DESC" + ) + .select_as() + .await?; + if let Some(best) = commits.iter().find_map(|c| candidates.iter().find(|b| &b.commit_sha == c)) { + return Ok(Some(best.clone())); + } + let default_branch = project.default_branch.as_str(); + let fallback: Option = db::query!( + "SELECT * FROM builds WHERE project_id = {project_id} AND name = {name} AND mode = 'ci' \ + AND state = 'completed' AND id <> {id} AND branch = {default_branch} \ + AND review_state IN ('approved', 'auto_approved') AND id < {id} ORDER BY id DESC LIMIT 1" + ) + .select_one_as() + .await?; + Ok(fallback) +} + +/// What a build says about one snapshot's approved state. +enum Said { + /// This version is the approved one. + Is(Box), + /// Its removal was approved: it isn't expected any more. + Removed, + /// Nothing approved here: look in the build's own base. + LookFurther, +} + +/// What one build says about each of its snapshots, its own and those it reads from earlier builds. +async fn effective_one(build: &Build) -> laravel::Result> { + let list: Vec = + super::snapshots::of_build(build.id).await?.into_iter().filter(|s| !is_config_item(s)).collect(); + let all_approved = matches!(build.review_state.as_str(), "approved" | "auto_approved"); + let approved = |s: &Snapshot| all_approved || s.review.as_deref() == Some("approved"); + // Unapproved changes (and failures) stand for the version they were compared with. + let stands_for_base = + |s: &Snapshot| (matches!(s.state.as_str(), "changed" | "removed") && !approved(s)) || s.state == "failed"; + let base_ids: Vec = list.iter().filter(|s| stands_for_base(s)).filter_map(|s| s.base_snapshot_id).collect(); + let bases = load(&base_ids).await?; + Ok(list + .into_iter() + .map(|s| { + let key = (s.name.clone(), s.platform.clone()); + let said = if stands_for_base(&s) { + s.base_snapshot_id + .and_then(|id| bases.get(&id).cloned()) + .map_or(Said::LookFurther, |b| Said::Is(Box::new(b))) + } else if s.state == "removed" && approved(&s) { + Said::Removed + } else if s.state == "added" && !approved(&s) { + Said::LookFurther + } else { + Said::Is(Box::new(s)) + }; + (key, said) + }) + .collect()) +} + +/// Snapshots by id (real rows: a base or baseline id is always one). +async fn load(ids: &[i64]) -> laravel::Result> { + let mut out = HashMap::new(); + for chunk in ids.chunks(10_000) { + for s in Snapshot::query().filter(Snapshot::id.is_in(chunk.to_vec())).get().await? { + out.insert(s.id, s); + } + } + Ok(out) +} + +/// Each snapshot's approved state in the anchor build, keyed by (name, platform). An unapproved addition in a pending +/// build says nothing, so those snapshots are looked up in the anchor's own base build, and so on back: a chain of +/// unreviewed builds never hides an older approval. +async fn effective( + anchor: &Build, + for_build: &Build, + project: &Project, +) -> laravel::Result> { + // Only builds on the resolving build's history count: its ancestors, its branch, the default branch. + let ancestors: HashSet = ancestry(for_build).into_iter().collect(); + let counts = |b: &Build| { + ancestors.contains(&b.commit_sha) || b.branch == for_build.branch || b.branch == project.default_branch + }; + let mut out = HashMap::new(); + let mut pending: Option> = None; + let mut seen = HashSet::new(); + let mut build = anchor.clone(); + for _ in 0..50 { + if !seen.insert(build.id) { + break; + } + let mut still = HashSet::new(); + for (key, said) in effective_one(&build).await? { + if pending.as_ref().is_some_and(|p| !p.contains(&key)) { + continue; + } + match said { + Said::Is(s) => { + out.insert(key, *s); + } + Said::Removed => {} + Said::LookFurther => { + still.insert(key); + } + } + } + // Snapshots this build didn't have at all stay unresolved too. + if let Some(p) = &pending { + for key in p { + if !out.contains_key(key) && !still.contains(key) { + still.insert(key.clone()); + } + } + } + if still.is_empty() { + break; + } + let Some(base_id) = build.base_build_id else { break }; + let Some(base) = Build::find(base_id).await? else { break }; + if !counts(&base) { + break; + } + build = base; + pending = Some(still); + } + Ok(out) +} + +/// The baseline of every snapshot the build could compare against, keyed by (name, platform), and the anchor build. +/// Snapshots whose removal was approved are left out. +/// +/// # Errors +/// On a database error. +pub async fn resolve( + build: &Build, + project: &Project, +) -> laravel::Result<(HashMap<(String, String), Resolved>, Option)> { + let anchor = anchor(build, project).await?; + let from_anchor = match &anchor { + Some(a) => effective(a, build, project).await?, + None => HashMap::new(), + }; + let after = anchor.as_ref().map_or(0, |a| a.id); + + // Approvals newer than the anchor: CI ones on the ancestry, and any on this branch. A merged pull request's + // approvals count only through their merge commit's place in this build's history. For local environments also + // older ones, since the anchor (a CI build) doesn't carry their screenshots. Local approvals apply only to their + // own branch; on the default branch only CI approvals count for other branches. + let history = ancestry(build); + let (project_id, build_name, id, branch, default_branch) = + (build.project_id, build.name.as_str(), build.id, build.branch.as_str(), project.default_branch.as_str()); + let rows: Vec = db::query!( + "SELECT * FROM baselines WHERE project_id = {project_id} AND build_name = {build_name} AND build_id <> {id} \ + AND ( \ + (build_id > {after} AND approval <> 'merged' \ + AND ((mode = 'ci' AND commit_sha IN ({...history})) OR branch = {branch})) \ + OR (approval = 'merged' AND commit_sha IN ({...history})) \ + OR (environment NOT IN ('', 'ci') AND (branch = {branch} OR (branch = {default_branch} AND mode = 'ci'))) \ + ) ORDER BY id" + ) + .select_as() + .await?; + + // A merged pull request's approvals count until the anchor is at or past the merge: then the anchor carries them, + // and a later approval must win. + let anchor_history: HashSet = anchor.as_ref().map(ancestry).unwrap_or_default().into_iter().collect(); + let merged_and_new = |r: &Baseline| r.approval == "merged" && !anchor_history.contains(&r.commit_sha); + let rows: Vec = rows.into_iter().filter(|r| r.approval != "merged" || merged_and_new(r)).collect(); + + // The latest row per (name, platform, environment); rows newer than the anchor or on this branch win over older + // default-branch ones. + let mut latest: HashMap<(String, String, String), Baseline> = HashMap::new(); + let rank = |r: &Baseline| (r.build_id > after || r.branch == build.branch || merged_and_new(r), r.id); + // Between two merged pull requests' approvals, the nearer merge in this build's history wins (it was merged later + // on this line), whatever order the webhooks arrived in. + let nearness = |r: &Baseline| history.iter().position(|c| c == &r.commit_sha).unwrap_or(usize::MAX); + let better = |new: &Baseline, old: &Baseline| { + if new.approval == "merged" && old.approval == "merged" && nearness(new) != nearness(old) { + nearness(new) < nearness(old) + } else { + rank(old) < rank(new) + } + }; + for row in rows { + let key = (row.name.clone(), row.platform.clone(), row.environment.clone()); + if latest.get(&key).is_none_or(|existing| better(&row, existing)) { + latest.insert(key, row); + } + } + + let mut names: Vec<(String, String)> = from_anchor.keys().cloned().collect(); + names.extend(latest.keys().map(|(n, p, _)| (n.clone(), p.clone()))); + names.sort(); + names.dedup(); + + let mut chosen: HashMap<(String, String), (Option, Option)> = HashMap::new(); + for key in names { + let anchor_snapshot = from_anchor.get(&key); + let shared = anchor_snapshot.map_or_else( + || latest.keys().any(|(n, p, e)| (n, p) == (&key.0, &key.1) && e == SHARED), + |s| s.environment == SHARED, + ); + let order = if shared { search_order(SHARED) } else { search_order(&build.environment) }; + let pick = order.iter().find_map(|env| { + let row = latest.get(&(key.0.clone(), key.1.clone(), env.clone())); + if env == SHARED || env == "ci" { + // CI's set and the shared set: a newer approval, else the anchor's snapshot. + match row { + Some(r) => Some((Some(r.clone()), r.snapshot_id)), + None => anchor_snapshot.filter(|s| &s.environment == env).map(|s| (None, Some(s.id))), + } + } else { + row.map(|r| (Some(r.clone()), r.snapshot_id)) + } + }); + if let Some(p) = pick { + chosen.insert(key, p); + } + } + + // Last: a snapshot this build sent that has no baseline on its history takes the suite's latest current CI + // approval of it from any branch. That's a squash-merged pull request's approval: its commits aren't ancestors of + // the default branch's, but what it approved is what the default branch now has. + let sent: Vec<(String, String, String)> = Snapshot::query() + .filter(Snapshot::build_id.eq(build.id) & Snapshot::carried_forward.eq(false)) + .get() + .await? + .into_iter() + .filter(|s| !is_config_item(s)) + .map(|s| (s.name, s.platform, s.environment)) + .collect(); + let missing: Vec<&(String, String, String)> = + sent.iter().filter(|(n, p, _)| !chosen.contains_key(&(n.clone(), p.clone()))).collect(); + if !missing.is_empty() { + let mut names: Vec = missing.iter().map(|(n, _, _)| n.clone()).collect(); + names.sort(); + names.dedup(); + let mut rows: Vec = Vec::new(); + for chunk in names.chunks(10_000) { + let chunk = chunk.to_vec(); + let found: Vec = db::query!( + "SELECT DISTINCT ON (name, platform, environment) * FROM baselines bl \ + WHERE project_id = {project_id} AND build_name = {build_name} AND build_id <> {id} AND mode = 'ci' \ + AND name IN ({...chunk}) \ + AND NOT EXISTS (SELECT 1 FROM baselines b2 WHERE b2.project_id = bl.project_id \ + AND b2.build_name = bl.build_name AND b2.name = bl.name AND b2.platform = bl.platform \ + AND b2.environment = bl.environment AND b2.branch = bl.branch AND b2.id > bl.id) \ + ORDER BY name, platform, environment, id DESC" + ) + .select_as() + .await?; + rows.extend(found); + } + for (name, platform, environment) in missing { + let order = search_order(environment); + let row = order.iter().find_map(|env| { + rows.iter().find(|r| &r.name == name && &r.platform == platform && &r.environment == env) + }); + if let Some(r) = row.filter(|r| r.snapshot_id.is_some()) { + chosen.insert((name.clone(), platform.clone()), (Some(r.clone()), r.snapshot_id)); + } + } + } + + let ids: Vec = chosen.values().filter_map(|(_, id)| *id).collect(); + let mut snapshots = load(&ids).await?; + let resolved = chosen + .into_iter() + .filter_map(|(key, (row, id))| { + // A removal ends the lookup: the snapshot isn't expected any more. + let snapshot = id.and_then(|id| snapshots.remove(&id))?; + Some((key, Resolved { row, snapshot })) + }) + .collect(); + Ok((resolved, anchor)) +} + +/// Whether a build's working tree had uncommitted changes (local builds only). +fn dirty(build: &Build) -> bool { + build.mode == "local" && build.environment_info.get("dirty").and_then(serde_json::Value::as_bool) == Some(true) +} + +struct NewRow { + project_id: i64, + build_name: String, + name: String, + platform: String, + environment: String, + branch: String, + commit_sha: String, + build_id: i64, + snapshot_id: Option, + approved_by: Option, + review_id: Option, + approval: String, + mode: String, +} + +/// Record approved snapshots as baselines: changed and added ones as themselves, removed ones as their removal. +/// Unchanged snapshots already match a baseline and aren't recorded again. Returns how many were left out: a local +/// build with uncommitted changes can only approve its own environment's screenshots, never the shared set or CI's. +/// +/// # Errors +/// On a database error. +pub async fn record( + build: &Build, + approved: &[&Snapshot], + approved_by: Option, + review_id: Option, + approval: &str, +) -> laravel::Result { + let changes: Vec<&Snapshot> = approved + .iter() + .copied() + .filter(|s| matches!(s.state.as_str(), "changed" | "added" | "removed") && !is_config_item(s)) + .collect(); + let allowed = |s: &Snapshot| !dirty(build) || (s.environment != SHARED && s.environment != "ci"); + let rows: Vec = changes + .iter() + .filter(|s| allowed(s)) + .map(|s| NewRow { + project_id: build.project_id, + build_name: build.name.clone(), + name: s.name.clone(), + platform: s.platform.clone(), + environment: s.environment.clone(), + branch: build.branch.clone(), + commit_sha: build.commit_sha.clone(), + build_id: build.id, + snapshot_id: (s.state != "removed").then_some(s.id), + approved_by, + review_id, + approval: approval.to_string(), + mode: build.mode.clone(), + }) + .collect(); + let skipped = changes.len() - rows.len(); + // 13 parameters a row, well under PostgreSQL's 65,535. + for chunk in rows.chunks(4000) { + db::query!( + "INSERT INTO baselines (project_id, build_name, name, platform, environment, branch, commit_sha, build_id, \ + snapshot_id, approved_by, review_id, approval, mode) \ + VALUES {...chunk(project_id, build_name, name, platform, environment, branch, commit_sha, build_id, \ + snapshot_id, approved_by, review_id, approval, mode)}" + ) + .insert() + .await?; + } + Ok(skipped) +} + +/// A pull request was merged: its branch's current CI approvals become the base branch's at the merge commit, so the +/// base branch's next build compares with what the pull request approved, even after a squash merge. Safe to call twice +/// for the same merge. Returns how many it recorded. +/// +/// # Errors +/// On a database error. +pub async fn record_merge( + project_id: i64, + head_branch: &str, + base_branch: &str, + merge_commit: &str, +) -> laravel::Result { + let done = db::query!( + "INSERT INTO baselines (project_id, build_name, name, platform, environment, branch, commit_sha, build_id, \ + snapshot_id, approved_by, review_id, approval, mode, created_at) \ + SELECT project_id, build_name, name, platform, environment, {base_branch}, {merge_commit}, build_id, snapshot_id, \ + approved_by, review_id, 'merged', 'ci', now() \ + FROM (SELECT DISTINCT ON (build_name, name, platform, environment) * FROM baselines \ + WHERE project_id = {project_id} AND branch = {head_branch} AND mode = 'ci' \ + ORDER BY build_name, name, platform, environment, id DESC) latest \ + WHERE NOT EXISTS (SELECT 1 FROM baselines m WHERE m.project_id = {project_id} AND m.approval = 'merged' \ + AND m.commit_sha = {merge_commit})" + ) + .insert() + .await?; + Ok(done.rows_affected()) +} + +/// Withdraw the baselines a build's approval of these snapshots made: they were rejected after all. +/// +/// # Errors +/// On a database error. +pub async fn withdraw(build: &Build, rejected: &[&Snapshot]) -> laravel::Result<()> { + let id = build.id; + for s in rejected { + let (name, platform) = (s.name.as_str(), s.platform.as_str()); + db::query!("DELETE FROM baselines WHERE build_id = {id} AND name = {name} AND platform = {platform}") + .delete() + .await?; + } + Ok(()) +} + +/// For baseline rows that came from local approvals: "approved locally by nathan on macbook (local-mac)", by row id. +/// +/// # Errors +/// On a database error. +pub async fn local_notes(ids: &[i64]) -> laravel::Result> { + if ids.is_empty() { + return Ok(HashMap::new()); + } + let ids = ids.to_vec(); + let rows = db::query!( + "SELECT bl.id, b.environment, b.environment_info->>'user' AS who, b.environment_info->>'machine' AS machine \ + FROM baselines bl JOIN builds b ON b.id = bl.build_id WHERE bl.id IN ({...ids}) AND bl.mode = 'local'" + ) + .select() + .await?; + let mut out = HashMap::new(); + for r in rows { + let id: i64 = r.try_get("id")?; + let env: String = r.try_get("environment")?; + let who: Option = r.try_get("who")?; + let machine: Option = r.try_get("machine")?; + let mut note = "approved locally".to_string(); + if let Some(w) = who { + note.push_str(&format!(" by {w}")); + } + if let Some(m) = machine { + note.push_str(&format!(" on {m}")); + } + note.push_str(&format!(" ({env})")); + out.insert(id, note); + } + Ok(out) +} diff --git a/app/src/domain/compare.rs b/app/src/domain/compare.rs new file mode 100644 index 00000000..fd2d7309 --- /dev/null +++ b/app/src/domain/compare.rs @@ -0,0 +1,346 @@ +//! Comparing a snapshot with its baseline, page by page, and the "visualci.yml" item. + +use laravel::db; +use laravel::model::update; +use visualci_core::align::{PageOp, align_pages}; +use visualci_core::snapshot_text::{self, Format}; + +use super::build_settings::BuildSettings; +use super::pages::{self, Page}; +use super::renders::RenderPage; +use super::snapshots::{CONFIG_NAME, CONFIG_PLATFORM, text_format}; +use crate::models::{Blob, IgnoredChange, Project, Snapshot, Variant}; +use crate::storage::BlobStore; + +/// The exact-match passes below take a baseline row `bl` only when it's current for the snapshot's build: the same +/// suite, a CI approval or one from the build's own branch (local approvals count on their own branch only), and not +/// superseded by a later approval of the same snapshot on the same branch and environment. (Rejected approvals are +/// deleted.) +/// The snapshot's pages: a document's rendered pages, or an image or a text as a single page. +/// +/// # Errors +/// When a render or blob is missing. +pub async fn snapshot_pages(snapshot: &Snapshot, store: &BlobStore) -> laravel::Result> { + match snapshot.kind.as_str() { + "document" => { + let render_id = snapshot.render_id.ok_or_else(|| laravel::Error::msg("a document without a render"))?; + let render = crate::models::Render::find_or_fail(render_id).await?; + super::renders::with_text(super::renders::pages(&render)).await + } + "image" => { + let sha = snapshot.source_blob.clone().ok_or_else(|| laravel::Error::msg("an image without a file"))?; + let blob = + Blob::find(sha.clone()).await?.ok_or_else(|| laravel::Error::msg("the image's file is missing"))?; + let (fingerprint, width, height) = super::blobs::image_info(blob, store).await?; + Ok(vec![RenderPage { + image: sha, + image_fingerprint: fingerprint.clone(), + fingerprint, + width, + height, + text_sha: String::new(), + text: String::new(), + }]) + } + _ => { + let sha = snapshot.source_blob.clone().ok_or_else(|| laravel::Error::msg("a text without a file"))?; + let text = String::from_utf8_lossy(&store.get(&sha).await?).into_owned(); + Ok(vec![RenderPage { + image: String::new(), + image_fingerprint: String::new(), + fingerprint: snapshot.source_fingerprint.clone(), + width: 0, + height: 0, + text_sha: String::new(), + text, + }]) + } + } +} + +fn page_row( + position: usize, + op: &str, + state: &str, + head: Option<(usize, &RenderPage)>, + base: Option<(usize, &RenderPage)>, + diff_id: Option, +) -> Page { + let image = |p: &RenderPage| (!p.image.is_empty()).then(|| p.image.clone()); + let index = |i: usize| i32::try_from(i).unwrap_or(i32::MAX); + Page { + position: index(position), + op: op.to_string(), + state: state.to_string(), + head_index: head.map(|(i, _)| index(i)), + base_index: base.map(|(i, _)| index(i)), + head_image: head.and_then(|(_, p)| image(p)), + base_image: base.and_then(|(_, p)| image(p)), + head_text: head.map(|(_, p)| p.text.clone()), + base_text: base.map(|(_, p)| p.text.clone()), + diff_id, + } +} + +async fn set_state(snapshot: &mut Snapshot, state: &str, base_id: Option) -> laravel::Result<()> { + let state = state.to_string(); + update!(snapshot { state, base_snapshot_id: base_id, error: None }).await +} + +/// Mark a snapshot failed with the reason. +/// +/// # Errors +/// On a database error. +pub async fn mark_failed(snapshot: &mut Snapshot, error: &str) -> laravel::Result<()> { + let error = Some(error.to_string()); + update!(snapshot { state: "failed", error }).await +} + +/// Compare with the baseline snapshot (or record it as added), storing its pages unless every one is the same as the +/// base's ([`pages::plain_unchanged`]). Sets the snapshot's state. +/// +/// # Errors +/// When a page can't be loaded or diffed. +pub async fn compare( + snapshot: &mut Snapshot, + store: &BlobStore, + settings: &BuildSettings<'_>, + base: Option<&Snapshot>, +) -> laravel::Result<()> { + let project = settings.project; + // Text is compared in the head's format, base and head alike, after the head's ignore rules (its build's file or + // the project's, and the test's own). + let rules = settings.compiled_rules(snapshot); + let format = text_format(snapshot); + let normalize = |mut pages: Vec| { + if let Some(format) = format { + for p in &mut pages { + p.text = snapshot_text::normalize(format, &p.text, &rules).text; + } + } + pages + }; + let head_pages = normalize(snapshot_pages(snapshot, store).await?); + let mut rows = Vec::new(); + + let Some(base) = base else { + for (i, page) in head_pages.iter().enumerate() { + rows.push(page_row(i, "inserted", "changed", Some((i, page)), None, None)); + } + pages::store(snapshot.id, rows).await?; + return set_state(snapshot, "added", None).await; + }; + + let base_pages = if base.kind == snapshot.kind { + normalize(snapshot_pages(base, store).await?) + } else { + snapshot_pages(base, store).await? + }; + let fp = |pages: &[RenderPage]| pages.iter().map(|p| p.fingerprint.clone()).collect::>(); + let text = |pages: &[RenderPage]| pages.iter().map(|p| p.text.clone()).collect::>(); + let (base_text, head_text) = (text(&base_pages), text(&head_pages)); + let has_text = base_text.iter().chain(&head_text).any(|t| !t.is_empty()); + let ops = align_pages( + &fp(&base_pages), + &fp(&head_pages), + has_text.then_some(base_text.as_slice()), + has_text.then_some(head_text.as_slice()), + ); + + let options = settings.diff_options(snapshot); + let (mut changed, mut ignored) = (false, false); + let mut matched_environment: Option = None; + for (position, op) in ops.iter().enumerate() { + let row = match *op { + PageOp::Unchanged { base: b, head: h } => { + page_row(position, "unchanged", "unchanged", Some((h, &head_pages[h])), Some((b, &base_pages[b])), None) + } + PageOp::Inserted { head: h } => { + changed = true; + page_row(position, "inserted", "changed", Some((h, &head_pages[h])), None, None) + } + PageOp::Removed { base: b } => { + changed = true; + page_row(position, "removed", "changed", None, Some((b, &base_pages[b])), None) + } + PageOp::Changed { base: b, head: h } => { + let (bp, hp) = (&base_pages[b], &head_pages[h]); + let (state, diff_id, matched) = page_state(snapshot, store, project, h, bp, hp, options).await?; + if matched.is_some() { + matched_environment = matched; + } + match state { + "changed" => changed = true, + "ignored" => ignored = true, + _ => {} + } + page_row(position, "changed", state, Some((h, hp)), Some((b, bp)), diff_id) + } + }; + rows.push(row); + } + if pages::plain_unchanged(&rows) { + pages::store(snapshot.id, Vec::new()).await?; + } else { + pages::store(snapshot.id, rows).await?; + } + let state = if changed { + "changed" + } else if ignored { + "ignored" + } else { + "unchanged" + }; + // "matched local-mac": it passed on another environment's approved image, not its own baseline. + let matched_environment = if changed { None } else { matched_environment }; + if snapshot.matched_environment != matched_environment { + update!(snapshot { matched_environment }).await?; + } + set_state(snapshot, state, Some(base.id)).await +} + +/// The state of a page whose fingerprint changed: identical pixels, an accepted variant, an image approved before, +/// within the threshold, an ignored change, or a change. With the diff, and the other environment it matched. +async fn page_state( + snapshot: &Snapshot, + store: &BlobStore, + project: &Project, + head_index: usize, + base: &RenderPage, + head: &RenderPage, + options: visualci_core::diff::DiffOptions, +) -> laravel::Result<(&'static str, Option, Option)> { + let (project_id, build_id) = (project.id, snapshot.build_id); + let (name, platform) = (snapshot.name.as_str(), snapshot.platform.as_str()); + if snapshot.kind == "text" { + if base.text == head.text { + return Ok(("unchanged", None, None)); + } + // Exactly this text was approved for this snapshot elsewhere in the project (a squash-merged pull request's + // branch): it passes, as an image would. + let fingerprint = snapshot.source_fingerprint.as_str(); + let approved: Option = db::query!( + "SELECT 1 FROM baselines bl JOIN snapshots s ON s.id = bl.snapshot_id \ + WHERE bl.project_id = {project_id} AND bl.name = {name} AND bl.platform = {platform} \ + AND s.source_fingerprint = {fingerprint} AND bl.build_name = (SELECT name FROM builds WHERE id = {build_id}) \ + AND (bl.mode = 'ci' OR bl.branch = (SELECT branch FROM builds WHERE id = {build_id})) \ + AND NOT EXISTS (SELECT 1 FROM baselines b2 WHERE b2.project_id = bl.project_id \ + AND b2.build_name = bl.build_name AND b2.name = bl.name AND b2.platform = bl.platform \ + AND b2.environment = bl.environment AND b2.branch = bl.branch AND b2.id > bl.id) LIMIT 1" + ) + .scalar() + .await?; + return Ok((if approved.is_some() { "variant" } else { "changed" }, None, None)); + } + if base.image == head.image + || (!head.image_fingerprint.is_empty() && base.image_fingerprint == head.image_fingerprint) + { + return Ok(("unchanged", None, None)); + } + let page_index = i32::try_from(head_index).unwrap_or(i32::MAX); + let is_variant = Variant::query() + .filter( + Variant::project_id.eq(project_id) + & Variant::name.eq(name) + & Variant::platform.eq(platform) + & Variant::page_index.eq(page_index) + & Variant::image.eq(head.image.as_str()), + ) + .exists() + .await?; + if is_variant { + return Ok(("variant", None, None)); + } + // Approved before: a current baseline, in any environment, branch or commit of the suite, with exactly this image + // for this snapshot: its own environment's first, then CI's. Covers squash merges and other environments (a Linux + // agent's screenshot that matches the approved Mac one passes). + let image = head.image.as_str(); + let environment = snapshot.environment.as_str(); + let approved: Option = db::query!( + "SELECT s.environment FROM baselines bl \ + JOIN snapshots s ON s.id = bl.snapshot_id JOIN snapshot_pages p ON p.snapshot_id = s.id \ + WHERE bl.project_id = {project_id} AND bl.name = {name} AND bl.platform = {platform} AND p.head_image = {image} \ + AND bl.build_name = (SELECT name FROM builds WHERE id = {build_id}) \ + AND (bl.mode = 'ci' OR bl.branch = (SELECT branch FROM builds WHERE id = {build_id})) \ + AND NOT EXISTS (SELECT 1 FROM baselines b2 WHERE b2.project_id = bl.project_id \ + AND b2.build_name = bl.build_name AND b2.name = bl.name AND b2.platform = bl.platform \ + AND b2.environment = bl.environment AND b2.branch = bl.branch AND b2.id > bl.id) \ + ORDER BY (s.environment = {environment}) DESC, (s.environment = 'ci') DESC, bl.id DESC LIMIT 1" + ) + .scalar() + .await?; + if let Some(env) = approved { + let other = (env != snapshot.environment).then_some(env); + return Ok(("variant", None, other)); + } + let diff = super::diffs::find_or_compute(store, &base.image, &head.image, options).await?; + if !super::diffs::is_change(&diff) { + return Ok(("within_threshold", Some(diff.id), None)); + } + if let Some(fingerprint) = &diff.fingerprint { + let is_ignored = IgnoredChange::query() + .filter( + IgnoredChange::project_id.eq(project_id) + & IgnoredChange::name.eq(name) + & IgnoredChange::platform.eq(platform) + & IgnoredChange::fingerprint.eq(fingerprint.as_str()), + ) + .exists() + .await?; + if is_ignored { + return Ok(("ignored", Some(diff.id), None)); + } + } + Ok(("changed", Some(diff.id), None)) +} + +/// Add the "visualci.yml" item to a build: a changed text snapshot whose diff is the settings that decide what counts +/// as a change, base against head. It's reviewed like any change, so loosened rules can't pass unseen. +/// +/// # Errors +/// On a database error. +pub async fn record_config_change( + build_id: i64, + base_build_id: i64, + base_id: Option, + base: &serde_json::Value, + head: &serde_json::Value, +) -> laravel::Result { + let text = |v: &serde_json::Value| snapshot_text::normalize(Format::Json, &v.to_string(), &Default::default()).text; + let (base_text, head_text) = (text(base), text(head)); + let page = |t: &str| RenderPage { + image: String::new(), + image_fingerprint: String::new(), + fingerprint: visualci_core::sha256_hex(t.as_bytes()), + width: 0, + height: 0, + text_sha: String::new(), + text: t.to_string(), + }; + let snapshot = laravel::model::create!(Snapshot { + pid: laravel::str::uuid7(), + build_id: build_id, + name: CONFIG_NAME, + platform: CONFIG_PLATFORM, + kind: "text", + format: Some("json".to_string()), + source_fingerprint: visualci_core::sha256_hex(head_text.as_bytes()), + source_blob: None, + render_id: None, + engine: None, + threshold: None, + ignore_anti_aliasing: None, + meta: serde_json::json!({ "config": true, "base_build_id": base_build_id }), + state: "changed", + base_snapshot_id: base_id, + review: None, + error: None, + matched_environment: None, + baseline_id: None, + matches_build_id: None, + }) + .await?; + let (b, h) = (page(&base_text), page(&head_text)); + pages::store(snapshot.id, vec![page_row(0, "changed", "changed", Some((0, &h)), Some((0, &b)), None)]).await?; + Ok(snapshot) +} diff --git a/app/src/domain/diffs.rs b/app/src/domain/diffs.rs new file mode 100644 index 00000000..5760ac22 --- /dev/null +++ b/app/src/domain/diffs.rs @@ -0,0 +1,90 @@ +//! Image diffs, cached by (base image, head image, options): the same pair is never diffed twice. + +use std::io::Cursor; + +use laravel::db; +use laravel::model::update; +use visualci_core::diff::{DiffOptions, DiffResult}; + +use crate::models::Diff; +use crate::storage::BlobStore; + +#[must_use] +pub fn options_key(options: &DiffOptions) -> String { + format!("{}/t{}/aa{}", visualci_core::diff::ALGORITHM, options.threshold, u8::from(options.ignore_anti_aliasing)) +} + +#[must_use] +pub fn result(diff: &Diff) -> Option { + serde_json::from_value(diff.result.clone()).ok() +} + +#[must_use] +pub fn is_change(diff: &Diff) -> bool { + diff.size_changed || diff.changed_pixels > 0 +} + +async fn find(base_image: &str, head_image: &str, key: &str) -> laravel::Result> { + Diff::query() + .filter(Diff::base_image.eq(base_image) & Diff::head_image.eq(head_image) & Diff::options_key.eq(key)) + .first() + .await +} + +/// The diff of two images, computed (with its overlay stored as a blob) on first use. A diff whose overlay retention +/// deleted is computed again, and keeps its row. +/// +/// # Errors +/// When an image is missing or can't be decoded. +pub async fn find_or_compute( + store: &BlobStore, + base_image: &str, + head_image: &str, + options: DiffOptions, +) -> laravel::Result { + let key = options_key(&options); + let stale = match find(base_image, head_image, &key).await? { + Some(diff) if diff.overlay_blob.is_some() || result(&diff).is_none_or(|r| r.is_identical()) => return Ok(diff), + other => other, + }; + let (base_bytes, head_bytes) = (store.get(base_image).await?, store.get(head_image).await?); + let (outcome, overlay_png) = laravel::task::spawn_blocking(move || -> Result<_, String> { + let base = visualci_core::image_hash::decode(&base_bytes).map_err(|e| e.to_string())?.to_rgba8(); + let head = visualci_core::image_hash::decode(&head_bytes).map_err(|e| e.to_string())?.to_rgba8(); + let (outcome, overlay) = visualci_core::diff::diff(&base, &head, options); + let overlay_png = if outcome.is_identical() { + None + } else { + let mut png = Vec::new(); + overlay.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| e.to_string())?; + Some(png) + }; + Ok((outcome, overlay_png)) + }) + .await + .map_err(|e| laravel::Error::msg(e.to_string()))? + .map_err(|e| laravel::Error::msg(format!("diffing {base_image} and {head_image}: {e}")))?; + + let overlay_blob = match overlay_png { + Some(png) => Some(super::blobs::put(store, png, "image/png").await?.sha256), + None => None, + }; + if let Some(mut diff) = stale { + update!(diff { overlay_blob }).await?; + return Ok(diff); + } + let changed_pixels = i64::try_from(outcome.changed_pixels).unwrap_or(i64::MAX); + let (fraction, size_changed, fingerprint) = + (outcome.changed_fraction, outcome.size_changed, outcome.fingerprint.clone()); + let json = serde_json::to_value(&outcome).unwrap_or_default(); + db::query!( + "INSERT INTO diffs (base_image, head_image, options_key, changed_pixels, changed_fraction, size_changed, \ + fingerprint, result, overlay_blob) \ + VALUES ({base_image}, {head_image}, {key}, {changed_pixels}, {fraction}, {size_changed}, {fingerprint}, \ + {json}, {overlay_blob}) \ + ON CONFLICT (base_image, head_image, options_key) DO NOTHING" + ) + .insert() + .await?; + find(base_image, head_image, &key).await?.ok_or_else(|| laravel::Error::msg("the diff vanished after its insert")) +} diff --git a/app/src/domain/groups.rs b/app/src/domain/groups.rs index 9e0c075b..cb982922 100644 --- a/app/src/domain/groups.rs +++ b/app/src/domain/groups.rs @@ -11,3 +11,410 @@ pub fn grouping(depth: Option) -> Grouping { _ => Grouping::AllButLastTwo, } } + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use laravel::db; +use visualci_core::manifest::{self, Entry}; + +use super::snapshots::{CONFIG_PLATFORM, is_config_item}; +use crate::models::{Build, Project, Snapshot}; + +/// A group as a client sends it. +#[derive(Clone, Debug, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GroupParam { + pub key: String, + pub hash: String, + pub count: i32, +} + +/// What a build said about its groups. +#[derive(Clone, Debug, Default, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CheckParams { + /// The hash of every snapshot the run has (`manifest::manifest_hash`). + #[serde(default)] + pub manifest_hash: Option, + /// Absent for the default grouping (all but the last two segments), else the leading segments kept. + #[serde(default)] + pub group_depth: Option, + #[serde(default)] + pub groups: Vec, + /// The shard sending these groups, for a sharded build: groups must not span shards. + #[serde(default)] + pub shard: Option, +} + +/// The server's answer. +#[derive(Clone, Debug, Default, serde::Serialize)] +pub struct Checked { + /// The whole manifest matched this build's: nothing needs sending. + pub same_as_build: Option, + /// Groups whose files the client must send. + pub changed: Vec, + /// Groups carried forward from their baselines. + pub unchanged: Vec, +} + +/// A stored snapshot as a manifest entry: the same fields, normalized the same way, as the CLI hashes. +#[must_use] +pub fn entry_of(s: &Snapshot) -> Entry { + Entry { + name: s.name.clone(), + platform: s.platform.clone(), + kind: s.kind.clone(), + fingerprint: s.source_fingerprint.clone(), + format: s.format.clone(), + engine: s.engine.clone(), + threshold: s.threshold, + ignore_anti_aliasing: s.ignore_anti_aliasing, + ignore: s.ignore_rules.clone(), + } +} + +/// Compare a build's manifest and groups with its baseline's, record them, and say which groups the client must send. +/// A group is recorded once per build: a second shard naming a group another already sent is refused. +/// +/// # Errors +/// `Ok(Err(message))` for a build that isn't receiving any more, a bad group, or a group another shard sent; `Err` on +/// a database error. +pub async fn check(build: &Build, project: &Project, params: &CheckParams) -> laravel::Result> { + if build.state != "receiving" { + return Ok(Err("the build isn't receiving snapshots any more".into())); + } + if params.groups.len() > 100_000 { + return Ok(Err("at most 100000 groups".into())); + } + if build.group_depth.is_some() && build.group_depth != params.group_depth { + return Ok(Err("every shard must group names the same way (group_depth)".into())); + } + let grouping = grouping(params.group_depth); + // The baseline's side, from the server's own rows: each snapshot's approved version. + let (resolved, anchor) = super::baselines::resolve(build, project).await?; + let entries: Vec = + resolved.values().map(|r| &r.snapshot).filter(|s| s.platform != CONFIG_PLATFORM).map(entry_of).collect(); + let baseline_groups: HashMap = + manifest::groups(&entries, grouping).into_iter().map(|g| (g.key, g.hash)).collect(); + let manifest_matched = !entries.is_empty() + && params.manifest_hash.as_deref() == Some(manifest::manifest_hash(&entries).as_str()) + && anchor.is_some(); + + let mut out = Checked::default(); + let mut rows: BTreeMap = BTreeMap::new(); + if manifest_matched { + out.same_as_build = anchor.as_ref().map(|a| a.number); + // Every baseline group is unchanged: recorded from the server's own side. + for g in manifest::groups(&entries, grouping) { + out.unchanged.push(g.key.clone()); + rows.insert(g.key, (g.hash, i32::try_from(g.count).unwrap_or(i32::MAX), true)); + } + } else { + let mut seen = HashSet::new(); + for g in ¶ms.groups { + if !seen.insert(g.key.clone()) { + return Ok(Err(format!("group {:?} is listed twice", g.key))); + } + if g.key.len() > 1000 || g.hash.len() > 200 || g.count < 0 { + return Ok(Err(format!("group {:?} isn't valid", g.key))); + } + // A group matches only when the server's own baseline rows give the same hash; a claimed hash with no + // baseline behind it is a changed group. + let unchanged = baseline_groups.get(&g.key).is_some_and(|h| *h == g.hash); + if unchanged { + out.unchanged.push(g.key.clone()); + } else { + out.changed.push(g.key.clone()); + } + rows.insert(g.key.clone(), (g.hash.clone(), g.count, unchanged)); + } + } + + let (id, shard, depth) = (build.id, params.shard, params.group_depth); + let same_as = anchor.as_ref().filter(|_| manifest_matched).map(|a| a.id); + let recorded: Result<(), String> = db::transaction(async |_| { + for (key, (hash, count, matched)) in &rows { + let inserted = db::query!( + "INSERT INTO build_groups (build_id, key, hash, snapshot_count, matched, shard) \ + VALUES ({id}, {key}, {hash}, {count}, {matched}, {shard}) ON CONFLICT (build_id, key) DO NOTHING" + ) + .insert() + .await? + .rows_affected(); + if inserted == 0 { + return Err(laravel::Error::msg(format!( + "group {key:?} was already sent for this build (by another shard?): groups can't span shards; group \ + by a deeper prefix (group_depth) or keep each group's snapshots in one shard" + ))); + } + } + // A build that listed its groups has said what it holds: one whose groups all matched sends no files, and + // isn't an empty build. + db::query!( + "UPDATE builds SET group_depth = {depth}, allow_empty = true, \ + manifest_same_as_build_id = COALESCE({same_as}, manifest_same_as_build_id), updated_at = now() \ + WHERE id = {id}" + ) + .update() + .await?; + Ok(()) + }) + .await + .map_err(|e| e.to_string()); + Ok(recorded.map(|()| out)) +} + +/// Which baseline snapshots processing carries forward into a build besides a subset build's: all of them after a +/// whole-manifest match, else those in the groups that matched. +pub enum Carry { + Nothing, + All, + Groups(Grouping, HashSet), +} + +impl Carry { + #[must_use] + pub fn covers(&self, name: &str) -> bool { + match self { + Self::Nothing => false, + Self::All => true, + Self::Groups(grouping, keys) => keys.contains(&grouping.key(name)), + } + } +} + +/// A build's carry rule. +/// +/// # Errors +/// On a database error. +pub async fn carry(build: &Build) -> laravel::Result { + if build.manifest_same_as_build_id.is_some() { + return Ok(Carry::All); + } + let id = build.id; + let keys: Vec = db::query!("SELECT key FROM build_groups WHERE build_id = {id} AND matched") + .select() + .await? + .iter() + .filter_map(|r| r.try_get("key").ok()) + .collect(); + if keys.is_empty() { + return Ok(Carry::Nothing); + } + Ok(Carry::Groups(grouping(build.group_depth), keys.into_iter().collect())) +} + +/// Group checks to charge: one for a whole-manifest match, else one per matched group. +/// +/// # Errors +/// On a database error. +pub async fn checks(build: &Build) -> laravel::Result { + if build.manifest_same_as_build_id.is_some() { + return Ok(1); + } + let id = build.id; + Ok(db::query!("SELECT COUNT(*) FROM build_groups WHERE build_id = {id} AND matched").scalar().await?.unwrap_or(0)) +} + +/// A build's groups for the UI and `get_build`: how many matched (with their snapshot count) and the build they're +/// the same as, and the changed ones. `None` for a build that sent no groups. +/// +/// # Errors +/// On a database error. +pub async fn summary(build: &Build) -> laravel::Result> { + let id = build.id; + let rows = db::query!( + "SELECT key, snapshot_count, matched FROM build_groups WHERE build_id = {id} AND matched IS NOT NULL ORDER BY key" + ) + .select() + .await?; + if rows.is_empty() { + return Ok(None); + } + let (mut unchanged, mut snapshots_unchanged, mut changed) = (Vec::new(), 0i64, Vec::new()); + for r in &rows { + let key: String = r.try_get("key")?; + let count: i32 = r.try_get("snapshot_count")?; + if r.try_get::("matched")? { + snapshots_unchanged += i64::from(count); + unchanged.push(key); + } else { + changed.push(key); + } + } + let same_as = match build.manifest_same_as_build_id.or(build.base_build_id) { + Some(id) => Build::find(id).await?.map(|b| b.number), + None => None, + }; + Ok(Some(serde_json::json!({ + "manifest_matched": build.manifest_same_as_build_id.is_some(), + "unchanged_groups": unchanged.len(), + "unchanged_snapshots": snapshots_unchanged, + "same_as_build": same_as, + "changed_groups": changed, + "unchanged_group_keys": unchanged, + }))) +} + +/// Whether a snapshot holds the same content, with the same settings, as another: the one can stand for the other. +#[must_use] +pub fn same_content(a: &Snapshot, b: &Snapshot) -> bool { + a.name == b.name + && a.platform == b.platform + && a.kind == b.kind + && a.format == b.format + && a.source_fingerprint == b.source_fingerprint + && a.render_id == b.render_id + && a.engine == b.engine + && a.threshold == b.threshold + && a.ignore_anti_aliasing == b.ignore_anti_aliasing + && a.ignore_rules == b.ignore_rules + && a.environment == b.environment + && a.meta == b.meta +} + +/// A group a build could read from an earlier build instead of storing it. +pub struct Candidate { + /// Its snapshots' baselines: the rows that would stand for them. + pub base_ids: Vec, + /// Its manifest hash (`manifest::groups`), for the record. + pub hash: String, +} + +struct Wanted { + key: String, + base_id: i64, +} + +/// Of these groups, the ones one earlier build of the same project holds exactly (the same group key, every baseline +/// its own row, and no other row of the group there), with that build. Never another project's build: retention and the +/// demo reset rely on a group reading only from its own project. +/// +/// # Errors +/// On a database error. +pub async fn holders( + project_id: i64, + candidates: &BTreeMap, +) -> laravel::Result> { + let wanted: Vec = candidates + .iter() + .flat_map(|(key, c)| c.base_ids.iter().map(|id| Wanted { key: key.clone(), base_id: *id })) + .collect(); + let mut out = BTreeMap::new(); + if wanted.is_empty() { + return Ok(out); + } + // A group's rows all go in one query, so its whole membership is checked together. + let mut chunk: Vec = Vec::new(); + let mut groups = wanted.into_iter().peekable(); + while let Some(w) = groups.next() { + let last_of_group = groups.peek().is_none_or(|n| n.key != w.key); + chunk.push(w); + if last_of_group && (chunk.len() >= 20_000 || groups.peek().is_none()) { + let rows = db::query!( + "WITH wanted (key, base_id) AS (VALUES {...chunk(key, base_id)}), \ + found AS ( \ + SELECT w.key, MIN(b.build_id) AS holder, COUNT(*) AS n FROM wanted w \ + LEFT JOIN snapshots b ON b.id = w.base_id \ + GROUP BY w.key \ + HAVING bool_and(b.id IS NOT NULL AND b.group_key = w.key AND b.platform <> 'visualci') \ + AND COUNT(DISTINCT b.build_id) = 1) \ + SELECT f.key, f.holder FROM found f JOIN builds hb ON hb.id = f.holder AND hb.project_id = {project_id} \ + WHERE (SELECT COUNT(*) FROM snapshots h WHERE h.build_id = f.holder AND h.group_key = f.key \ + AND h.platform <> 'visualci') = f.n \ + AND NOT EXISTS (SELECT 1 FROM snapshots h WHERE h.build_id = f.holder AND h.group_key = f.key \ + AND h.state IN ('pending', 'failed', 'removed'))" + ) + .select() + .await?; + for r in rows { + out.insert(r.try_get::("key")?, r.try_get::("holder")?); + } + chunk.clear(); + } + } + Ok(out) +} + +/// Record groups as read from their holders. A group the client checked keeps its check. +/// +/// # Errors +/// On a database error. +pub async fn record_sources( + build_id: i64, + candidates: &BTreeMap, + sources: &BTreeMap, +) -> laravel::Result<()> { + for (key, holder) in sources { + let Some(c) = candidates.get(key) else { continue }; + let (hash, count) = (c.hash.as_str(), i32::try_from(c.base_ids.len()).unwrap_or(i32::MAX)); + db::query!( + "INSERT INTO build_groups (build_id, key, hash, snapshot_count, source_build_id) \ + VALUES ({build_id}, {key}, {hash}, {count}, {holder}) \ + ON CONFLICT (build_id, key) DO UPDATE SET source_build_id = EXCLUDED.source_build_id" + ) + .insert() + .await?; + } + Ok(()) +} + +/// After comparison: read every group of a CI build whose snapshots are all unchanged, and the same as their +/// baselines, from the build that holds those baselines, and delete the build's own rows of it. Runs while the build is +/// still processing, so no other build has anchored on it yet. Returns how many rows that saved. +/// +/// # Errors +/// On a database error. +pub async fn source_unchanged(build: &Build) -> laravel::Result { + if build.mode != "ci" { + return Ok(0); + } + let own = Snapshot::query().filter(Snapshot::build_id.eq(build.id)).get().await?; + let base_ids: Vec = own.iter().filter_map(|s| s.base_snapshot_id).collect(); + let mut bases: HashMap = HashMap::new(); + for chunk in base_ids.chunks(10_000) { + for b in Snapshot::query().filter(Snapshot::id.is_in(chunk.to_vec())).get().await? { + bases.insert(b.id, b); + } + } + let mut by_key: BTreeMap> = BTreeMap::new(); + for s in &own { + by_key.entry(s.group_key.clone()).or_default().push(s); + } + let grouping = grouping(build.group_depth); + let mut candidates = BTreeMap::new(); + for (key, list) in by_key { + let fits = |s: &&Snapshot| { + !is_config_item(s) + && s.state == "unchanged" + && s.matched_environment.is_none() + && s.base_snapshot_id.and_then(|id| bases.get(&id)).is_some_and(|b| same_content(s, b)) + }; + if !list.iter().all(fits) { + continue; + } + let entries: Vec = list.iter().map(|s| entry_of(s)).collect(); + let Some(g) = manifest::groups(&entries, grouping).into_iter().next() else { continue }; + let base_ids = list.iter().filter_map(|s| s.base_snapshot_id).collect(); + candidates.insert(key, Candidate { base_ids, hash: g.hash }); + } + let sources = holders(build.project_id, &candidates).await?; + if sources.is_empty() { + return Ok(0); + } + let (id, keys): (i64, Vec) = (build.id, sources.keys().cloned().collect()); + db::transaction(async |_| { + record_sources(id, &candidates, &sources).await?; + let mut deleted = 0; + for chunk in keys.chunks(10_000) { + let chunk = chunk.to_vec(); + deleted += db::query!( + "DELETE FROM snapshots WHERE build_id = {id} AND group_key IN ({...chunk}) AND platform <> 'visualci'" + ) + .delete() + .await?; + } + Ok(deleted) + }) + .await +} diff --git a/app/src/domain/matching.rs b/app/src/domain/matching.rs new file mode 100644 index 00000000..baa6a5d1 --- /dev/null +++ b/app/src/domain/matching.rs @@ -0,0 +1,234 @@ +//! Changes made of other pull requests' approved changes. Two pull requests that change the same screenshot and merge +//! separately leave an image neither of them showed: PR A approved its change without B's, B approved its change +//! without A's. The next build compares with one of those approvals and shows the other's change again, although it +//! was reviewed (main build #93 on 2 Dec 2026: PR #8's settings checkbox over PR #6's approved page). +//! +//! When every changed region of a snapshot's changed pages is exactly a region a merged pull request's build had +//! changed and that PR approved (the same box, the same old pixels and the same new pixels), the snapshot points at +//! that build (`snapshots.matches_build_id`): "matches PR #8's approved change". It's a hint and approves nothing; +//! `review` with `only: "matching"` approves those snapshots in one call. + +use std::collections::HashMap; + +use image::RgbaImage; +use laravel::db; +use visualci_core::diff::{DiffResult, Region}; + +use crate::models::{Build, Diff, Snapshot, SnapshotPage}; +use crate::storage::BlobStore; + +/// A page's change: the diff's canvas and regions, and its two images. +struct PageChange { + position: i32, + width: u32, + height: u32, + regions: Vec, + base_image: String, + head_image: String, +} + +/// The changed pages of a snapshot that has stored rows (a changed snapshot always does). +async fn page_changes(snapshot_id: i64) -> laravel::Result> { + let pages: Vec = SnapshotPage::query() + .filter(SnapshotPage::snapshot_id.eq(snapshot_id) & SnapshotPage::state.eq("changed")) + .order_by(SnapshotPage::position.asc()) + .get() + .await?; + let mut out = Vec::new(); + for p in pages { + let (Some(diff_id), Some(base_image), Some(head_image)) = (p.diff_id, p.base_image, p.head_image) else { + continue; + }; + let Some(diff) = Diff::find(diff_id).await? else { continue }; + let Ok(result) = serde_json::from_value::(diff.result) else { continue }; + out.push(PageChange { + position: p.position, + width: result.width, + height: result.height, + regions: result.regions, + base_image, + head_image, + }); + } + Ok(out) +} + +type Candidate = (usize, i64, i64); +/// Decoded images, by blob, so a page shared by several candidates is read once. +struct Images<'a> { + store: &'a BlobStore, + cache: HashMap>, +} + +impl Images<'_> { + async fn get(&mut self, sha: &str) -> Option<&RgbaImage> { + if !self.cache.contains_key(sha) { + let decoded = match self.store.get(sha).await { + Ok(bytes) => image::load_from_memory(&bytes).ok().map(|i| i.to_rgba8()), + Err(_) => None, + }; + self.cache.insert(sha.to_string(), decoded); + } + self.cache.get(sha).and_then(Option::as_ref) + } +} + +/// Whether two images have the same pixels inside a region (a pixel one has and the other doesn't is a difference). +#[must_use] +pub fn same_in(a: &RgbaImage, b: &RgbaImage, r: &Region) -> bool { + for y in r.y..r.y.saturating_add(r.height) { + for x in r.x..r.x.saturating_add(r.width) { + let pa = (x < a.width() && y < a.height()).then(|| a.get_pixel(x, y)); + let pb = (x < b.width() && y < b.height()).then(|| b.get_pixel(x, y)); + if pa != pb { + return false; + } + } + } + true +} + +/// Whether every region of `ours` is a region `theirs` changed, from the same old pixels to the same new ones. +async fn covered(images: &mut Images<'_>, ours: &PageChange, theirs: &PageChange) -> bool { + if (ours.width, ours.height) != (theirs.width, theirs.height) || ours.regions.is_empty() { + return false; + } + if !ours.regions.iter().all(|r| theirs.regions.contains(r)) { + return false; + } + for (a, b) in [(&ours.base_image, &theirs.base_image), (&ours.head_image, &theirs.head_image)] { + let Some(a) = images.get(a).await.cloned() else { return false }; + let Some(b) = images.get(b).await else { return false }; + if !ours.regions.iter().all(|r| same_in(&a, b, r)) { + return false; + } + } + true +} + +/// Mark the build's changed snapshots that are made only of changes merged pull requests approved. Returns how many. +/// +/// # Errors +/// On a database or blob store error. +pub async fn mark(store: &BlobStore, build: &Build) -> laravel::Result { + if build.mode != "ci" { + return Ok(0); + } + let changed: Vec = Snapshot::query() + .filter(Snapshot::build_id.eq(build.id) & Snapshot::state.eq("changed") & Snapshot::kind.ne("text")) + .get() + .await?; + if changed.is_empty() { + return Ok(0); + } + let names: Vec = changed.iter().map(|s| s.name.clone()).collect(); + let ancestry = super::baselines::ancestry(build); + let (project_id, build_name) = (build.project_id, build.name.as_str()); + // The pull requests' own snapshots behind each merged approval in this build's history, nearest merge first. + let rows = db::query!( + "SELECT bl.name, bl.platform, bl.commit_sha, bl.build_id, s.id AS snapshot_id \ + FROM baselines bl JOIN snapshots s ON s.id = bl.snapshot_id \ + WHERE bl.project_id = {project_id} AND bl.build_name = {build_name} AND bl.approval = 'merged' \ + AND bl.commit_sha IN ({...ancestry}) AND bl.name IN ({...names}) AND s.state = 'changed'" + ) + .select() + .await?; + let mut candidates: HashMap<(String, String), Vec> = HashMap::new(); + for r in rows { + let commit: String = r.try_get("commit_sha")?; + let near = ancestry.iter().position(|c| c == &commit).unwrap_or(usize::MAX); + candidates.entry((r.try_get("name")?, r.try_get("platform")?)).or_default().push(( + near, + r.try_get("build_id")?, + r.try_get("snapshot_id")?, + )); + } + let mut images = Images { store, cache: HashMap::new() }; + let mut marked = 0; + for s in changed { + let Some(mut theirs) = candidates.remove(&(s.name.clone(), s.platform.clone())) else { continue }; + theirs.sort_unstable(); + let ours = page_changes(s.id).await?; + if ours.is_empty() { + continue; + } + let mut matched = None; + for (_, their_build, their_snapshot) in theirs { + let their_pages = page_changes(their_snapshot).await?; + let mut all = true; + for page in &ours { + let Some(other) = their_pages.iter().find(|p| p.position == page.position) else { + all = false; + break; + }; + if !covered(&mut images, page, other).await { + all = false; + break; + } + } + if all { + matched = Some(their_build); + break; + } + } + if let Some(their_build) = matched { + let id = s.id; + db::query!("UPDATE snapshots SET matches_build_id = {their_build} WHERE id = {id}").update().await?; + marked += 1; + } + } + Ok(marked) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compares_pixels_inside_a_region_only() { + let mut a = RgbaImage::from_pixel(8, 8, image::Rgba([255, 255, 255, 255])); + let b = a.clone(); + a.put_pixel(6, 6, image::Rgba([0, 0, 0, 255])); + let inside = Region { x: 0, y: 0, width: 4, height: 4 }; + let around = Region { x: 4, y: 4, width: 4, height: 4 }; + assert!(same_in(&a, &b, &inside)); + assert!(!same_in(&a, &b, &around)); + // A pixel only one image has (a taller page) is a difference. + let tall = RgbaImage::from_pixel(8, 12, image::Rgba([255, 255, 255, 255])); + assert!(!same_in(&b, &tall, &Region { x: 0, y: 6, width: 8, height: 6 })); + } +} + +/// Where a matching change was approved: the pull request's build, for "matches PR #8's approved change". +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +pub struct Matches { + pub build: i32, + pub branch: String, + pub pr_number: Option, + /// "matches PR #8's approved change" (or "the change approved on sc-8740" with no pull request). + pub label: String, +} + +/// The build's matching changes, by snapshot id. +/// +/// # Errors +/// On a database error. +pub async fn of_build(build_id: i64) -> laravel::Result> { + let rows = db::query!( + "SELECT s.id, b.number, b.branch, b.pr_number FROM snapshots s JOIN builds b ON b.id = s.matches_build_id \ + WHERE s.build_id = {build_id} AND s.state = 'changed'" + ) + .select() + .await?; + let mut out = HashMap::new(); + for r in rows { + let pr_number: Option = r.try_get("pr_number")?; + let branch: String = r.try_get("branch")?; + let label = match pr_number { + Some(n) => format!("matches PR #{n}'s approved change"), + None => format!("matches the change approved on {branch}"), + }; + out.insert(r.try_get("id")?, Matches { build: r.try_get("number")?, branch, pr_number, label }); + } + Ok(out) +} diff --git a/app/src/domain/mod.rs b/app/src/domain/mod.rs index 9a84771a..bd6d2660 100644 --- a/app/src/domain/mod.rs +++ b/app/src/domain/mod.rs @@ -1,12 +1,19 @@ //! VisualCI's domain: builds, snapshots, baselines and the rules between them (sc-8900, the data side), on the //! models in `crate::models`. +pub mod baselines; pub mod blobs; pub mod build_settings; pub mod builds; +pub mod compare; pub mod credits; +pub mod diffs; pub mod environments; pub mod groups; pub mod lenient; +pub mod matching; +pub mod pages; +pub mod processing; pub mod projects; +pub mod renders; pub mod snapshots; diff --git a/app/src/domain/pages.rs b/app/src/domain/pages.rs new file mode 100644 index 00000000..3ed3b2ba --- /dev/null +++ b/app/src/domain/pages.rs @@ -0,0 +1,236 @@ +//! A snapshot's pages as compared with its baseline (docs/design-storage.md). +//! +//! Rows are stored only for a comparison that found something: an added snapshot, a change, a page within the +//! threshold or accepted as a variant, pages that moved. An unchanged snapshot (every page the same as its base, in +//! order) stores none, and neither do the snapshots a build reads from another build: their pages are read from the +//! snapshot itself ([`of_many`]). Page text is stored once in `texts`, by hash. + +use std::collections::HashMap; + +use laravel::db; + +use super::build_settings::BuildSettings; +use super::renders::RenderPage; +use crate::models::{Build, Project, Render, Snapshot, SnapshotPage}; +use crate::storage::{BlobStore, texts}; + +/// One page of a snapshot's comparison, with its text. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Page { + pub position: i32, + pub op: String, + pub state: String, + pub head_index: Option, + pub base_index: Option, + pub head_image: Option, + pub base_image: Option, + pub head_text: Option, + pub base_text: Option, + pub diff_id: Option, +} + +struct Row { + snapshot_id: i64, + position: i32, + op: String, + state: String, + head_index: Option, + base_index: Option, + head_image: Option, + base_image: Option, + head_text_sha: Option, + base_text_sha: Option, + diff_id: Option, +} + +/// Store a snapshot's page rows (replacing any it had), their texts first. +/// +/// # Errors +/// On a database error. +pub async fn store(snapshot_id: i64, pages: Vec) -> laravel::Result<()> { + db::query!("DELETE FROM snapshot_pages WHERE snapshot_id = {snapshot_id}").delete().await?; + if pages.is_empty() { + return Ok(()); + } + let bodies: Vec<&str> = + pages.iter().flat_map(|p| [p.head_text.as_deref(), p.base_text.as_deref()]).flatten().collect(); + texts::store(&bodies).await?; + let rows: Vec = pages + .into_iter() + .map(|p| Row { + snapshot_id, + position: p.position, + op: p.op, + state: p.state, + head_index: p.head_index, + base_index: p.base_index, + head_image: p.head_image, + base_image: p.base_image, + head_text_sha: p.head_text.as_deref().map(texts::sha), + base_text_sha: p.base_text.as_deref().map(texts::sha), + diff_id: p.diff_id, + }) + .collect(); + for chunk in rows.chunks(5000) { + db::query!( + "INSERT INTO snapshot_pages (snapshot_id, position, op, state, head_index, base_index, head_image, \ + base_image, head_text_sha, base_text_sha, diff_id) \ + VALUES {...chunk(snapshot_id, position, op, state, head_index, base_index, head_image, base_image, \ + head_text_sha, base_text_sha, diff_id)}" + ) + .insert() + .await?; + } + Ok(()) +} + +/// Whether a comparison's pages say nothing beyond "the same as the base": every page unchanged, in order, with the +/// same image and text. Those aren't stored. +#[must_use] +pub fn plain_unchanged(pages: &[Page]) -> bool { + pages.iter().enumerate().all(|(i, p)| { + let i = i32::try_from(i).ok(); + p.op == "unchanged" + && p.state == "unchanged" + && p.head_index == i + && p.base_index == i + && p.head_image == p.base_image + && p.head_text == p.base_text + && p.diff_id.is_none() + }) +} + +fn from_row(m: SnapshotPage, texts: &HashMap) -> Page { + let text = |sha: Option| sha.map(|s| texts.get(&s).cloned().unwrap_or_default()); + Page { + position: m.position, + op: m.op, + state: m.state, + head_index: m.head_index, + base_index: m.base_index, + head_image: m.head_image, + base_image: m.base_image, + head_text: text(m.head_text_sha), + base_text: text(m.base_text_sha), + diff_id: m.diff_id, + } +} + +/// Each snapshot's pages, by snapshot id, in order: its stored rows, or for an unchanged snapshot (one of its own +/// build's, or one read from another build) its pages as themselves. With `store`, every page's text too (text +/// snapshots' normalized as they were compared); without it, only stored rows' text. +/// +/// # Errors +/// On a database error, or when a text snapshot's file is missing. +pub async fn of_many(store: Option<&BlobStore>, list: &[&Snapshot]) -> laravel::Result>> { + let own: Vec = list.iter().filter(|s| !s.sourced).map(|s| s.id).collect(); + let mut rows: Vec = Vec::new(); + for chunk in own.chunks(10_000) { + let chunk = chunk.to_vec(); + let found: Vec = + db::query!("SELECT * FROM snapshot_pages WHERE snapshot_id IN ({...chunk}) ORDER BY snapshot_id, position") + .select_as() + .await?; + rows.extend(found); + } + let shas: Vec = + rows.iter().flat_map(|r| [r.head_text_sha.clone(), r.base_text_sha.clone()]).flatten().collect(); + let stored_texts = texts::load(&shas).await?; + let mut out: HashMap> = HashMap::new(); + for r in rows { + out.entry(r.snapshot_id).or_default().push(from_row(r, &stored_texts)); + } + + // The rest are unchanged (or have no pages: pending, failed, removed). + let plain: Vec<&Snapshot> = + list.iter().copied().filter(|s| s.state == "unchanged" && !out.contains_key(&s.id)).collect(); + let render_ids: Vec = plain.iter().filter_map(|s| s.render_id).collect(); + let mut renders_by_id: HashMap> = HashMap::new(); + for chunk in render_ids.chunks(10_000) { + for r in Render::query().filter(Render::id.is_in(chunk.to_vec())).get().await? { + renders_by_id.insert(r.id, super::renders::pages(&r)); + } + } + let with_text = store.is_some(); + let render_texts = if with_text { + let shas: Vec = renders_by_id.values().flatten().map(|p| p.text_sha.clone()).collect(); + texts::load(&shas).await? + } else { + HashMap::new() + }; + let mut settings_of: HashMap = HashMap::new(); + for s in plain { + let pages: Vec<(Option, Option)> = match s.kind.as_str() { + "document" => s + .render_id + .and_then(|id| renders_by_id.get(&id)) + .map(|pages| { + pages + .iter() + .map(|p| { + let image = (!p.image.is_empty()).then(|| p.image.clone()); + let text = with_text.then(|| render_texts.get(&p.text_sha).cloned().unwrap_or_default()); + (image, text) + }) + .collect() + }) + .unwrap_or_default(), + "image" => vec![(s.source_blob.clone(), with_text.then(String::new))], + _ => { + let text = match store { + Some(store) => Some(normalized_text(store, s, &mut settings_of).await?), + None => None, + }; + vec![(None, text)] + } + }; + let synthesized = pages + .into_iter() + .enumerate() + .map(|(i, (image, text))| { + let i = i32::try_from(i).unwrap_or(i32::MAX); + Page { + position: i, + op: "unchanged".into(), + state: "unchanged".into(), + head_index: Some(i), + base_index: Some(i), + head_image: image.clone(), + base_image: image, + head_text: text.clone(), + base_text: text, + diff_id: None, + } + }) + .collect(); + out.insert(s.id, synthesized); + } + Ok(out) +} + +/// One snapshot's pages, with their text ([`of_many`]). +/// +/// # Errors +/// On a database error, or when a text snapshot's file is missing. +pub async fn of(store: &BlobStore, snapshot: &Snapshot) -> laravel::Result> { + Ok(of_many(Some(store), &[snapshot]).await?.remove(&snapshot.id).unwrap_or_default()) +} + +/// A text snapshot's text as it was compared: normalized in its format with its build's ignore rules. +async fn normalized_text( + store: &BlobStore, + snapshot: &Snapshot, + settings_of: &mut HashMap, +) -> laravel::Result { + let sha = snapshot.source_blob.clone().ok_or_else(|| laravel::Error::msg("a text snapshot without a file"))?; + let raw = String::from_utf8_lossy(&store.get(&sha).await?).into_owned(); + let Some(format) = super::snapshots::text_format(snapshot) else { return Ok(raw) }; + if let std::collections::hash_map::Entry::Vacant(slot) = settings_of.entry(snapshot.build_id) { + let build = Build::find_or_fail(snapshot.build_id).await?; + let project = Project::find_or_fail(build.project_id).await?; + slot.insert((build, project)); + } + let (build, project) = &settings_of[&snapshot.build_id]; + let rules = BuildSettings::new(project, build).compiled_rules(snapshot); + Ok(visualci_core::snapshot_text::normalize(format, &raw, &rules).text) +} diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs new file mode 100644 index 00000000..fe96067c --- /dev/null +++ b/app/src/domain/processing.rs @@ -0,0 +1,837 @@ +//! Processing a finalized build: confirm its uploads, wait for its renders, compare each snapshot with its baseline, +//! carry forward or source what it didn't send, conclude, and charge. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use laravel::db; +use laravel::model::update; +use visualci_core::manifest::{self, Entry}; + +use super::baselines::{self, Resolved}; +use super::build_settings::{BuildSettings, Source}; +use super::builds::{ + CREDITS_PER_GROUP_CHECK, CREDITS_PER_IMAGE_DIFF, CREDITS_PER_RENDERED_PAGE, CREDITS_PER_SNAPSHOT_CHECK, + CREDITS_PER_TEXT_DIFF, EMPTY_BUILD, Stats, +}; +use super::compare::{compare, mark_failed, record_config_change}; +use super::credits::{self, Spender}; +use super::groups::{self, Candidate}; +use super::snapshots::{CONFIG_PLATFORM, is_change, is_config_item}; +use crate::events::{BuildStoppedForCredits, CreditsRanOut}; +use crate::models::{Build, Organization, Project, Render, Snapshot}; +use crate::storage::BlobStore; + +/// A local run the expiry finished keeps saying so. +pub const LOCAL_FINISHED: &str = "Local run, finished without `visualci build finalize`: nothing new arrived for an \ +hour, so VisualCI compared what it had, as a subset (nothing counts as removed). `visualci test -- ` \ +finalizes a run when it ends."; + +/// `error_code` of a build that wasn't compared because its organization had no credits left. +pub const OUT_OF_CREDITS: &str = "out_of_credits"; + +/// What a build used, by kind of work. +#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] +pub struct Usage { + pub snapshot_checks: i64, + pub text_diffs: i64, + pub image_diffs: i64, + pub rendered_pages: i64, + /// Groups that matched their baselines, or 1 for a whole-manifest match. + #[serde(default)] + pub groups_checked: i64, +} + +impl Usage { + #[must_use] + pub fn credits(&self) -> i64 { + self.snapshot_checks * CREDITS_PER_SNAPSHOT_CHECK + + self.groups_checked * CREDITS_PER_GROUP_CHECK + + self.text_diffs * CREDITS_PER_TEXT_DIFF + + self.image_diffs * CREDITS_PER_IMAGE_DIFF + + self.rendered_pages * CREDITS_PER_RENDERED_PAGE + } + + /// "120 snapshots checked, 2 image diffs, 3 pages drawn", leaving out what's zero. + #[must_use] + pub fn describe(&self) -> String { + let plural = |n: i64, one: &str, many: &str| if n == 1 { format!("1 {one}") } else { format!("{n} {many}") }; + [ + (self.snapshot_checks, "snapshot checked", "snapshots checked"), + (self.groups_checked, "group checked", "groups checked"), + (self.text_diffs, "text diff", "text diffs"), + (self.image_diffs, "image diff", "image diffs"), + (self.rendered_pages, "page drawn", "pages drawn"), + ] + .into_iter() + .filter(|(n, _, _)| *n > 0) + .map(|(n, one, many)| plural(n, one, many)) + .collect::>() + .join(", ") + } +} + +/// Hold the build's lock until the transaction ends: one worker (or one early comparison) works on a build at a time. +/// +/// # Errors +/// On a database error. +pub async fn lock(build_id: i64) -> laravel::Result<()> { + // 1447249201 is "VCI1": a namespace for VisualCI's build locks. + db::query!("SELECT pg_advisory_xact_lock(1447249201, ({build_id} % 2147483647)::int)").select().await?; + Ok(()) +} + +/// A document's base, drawn the way the head is drawn. +enum Redraw { + Ready(Box), + Waiting, +} + +/// Documents compare with their base drawn the same way. When the head renders differently (its visualci.yml sets +/// another engine or DPI, or the renderer was upgraded), the base's PDF is drawn again with the head's settings. A base +/// that can't be drawn again (its file may be gone) compares with the render it has. +async fn redraw_base( + settings: &BuildSettings<'_>, + renderer_version: &str, + head: &Snapshot, + base: &Snapshot, +) -> laravel::Result { + if head.kind != "document" || base.kind != "document" { + return Ok(Redraw::Ready(Box::new(base.clone()))); + } + let head_key = settings.renderer_key(head.engine.as_deref(), renderer_version); + let base_key = match base.render_id { + Some(id) => Render::find(id).await?.map(|r| r.renderer), + None => None, + }; + let Some(blob) = base.source_blob.clone() else { return Ok(Redraw::Ready(Box::new(base.clone()))) }; + if base_key.as_deref() == Some(head_key.as_str()) { + return Ok(Redraw::Ready(Box::new(base.clone()))); + } + let render = super::renders::find_or_queue(settings.project.id, &base.source_fingerprint, &head_key, &blob).await?; + Ok(match render.state.as_str() { + "done" => { + let mut redrawn = base.clone(); + redrawn.render_id = Some(render.id); + Redraw::Ready(Box::new(redrawn)) + } + "failed" => Redraw::Ready(Box::new(base.clone())), + _ => Redraw::Waiting, + }) +} + +/// Record which approval row a snapshot was compared with (for "approved locally by …"). +async fn set_baseline_id(snapshot: &mut Snapshot, row: Option) -> laravel::Result<()> { + if snapshot.baseline_id != row { + update!(snapshot { baseline_id: row }).await?; + } + Ok(()) +} + +/// The build whose settings count as approved for builds anchored on `build`: the build itself, unless its +/// "visualci.yml" item wasn't approved, in which case the build that item was compared with (and so on). +async fn approved_settings_build(mut build: Build) -> laravel::Result { + for _ in 0..20 { + let item = Snapshot::query() + .filter(Snapshot::build_id.eq(build.id) & Snapshot::platform.eq(CONFIG_PLATFORM)) + .first() + .await?; + let approved = matches!(build.review_state.as_str(), "approved" | "auto_approved"); + let Some(item) = item.filter(|i| !approved && i.review.as_deref() != Some("approved")) else { + return Ok(build); + }; + let Some(base_id) = item.meta.get("base_build_id").and_then(serde_json::Value::as_i64) else { + return Ok(build); + }; + build = Build::find_or_fail(base_id).await?; + } + Ok(build) +} + +/// Process a finalized build as far as it can go: confirm uploads, queue renders, and once every render is done, +/// compare and conclude. Returns whether the build concluded (false while renders are outstanding). +/// +/// # Errors +/// On a database or storage error. +#[allow(clippy::too_many_lines)] +pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> laravel::Result { + if build.state != "processing" { + return Ok(build.state == "completed"); + } + let project = Project::find_or_fail(build.project_id).await?; + let settings = BuildSettings::new(&project, &build); + let id = build.id; + // The "visualci.yml" item is worked out again below. + db::query!("DELETE FROM snapshots WHERE build_id = {id} AND platform = 'visualci'").delete().await?; + let mut snapshots: Vec = Snapshot::query() + .filter(Snapshot::build_id.eq(id)) + .order_by(Snapshot::name.asc()) + .order_by(Snapshot::platform.asc()) + .get() + .await?; + + // Confirm the uploads the build needs: sources of snapshots that have no render. + let needed: Vec = snapshots + .iter() + .filter(|s| s.render_id.is_none() && s.state != "removed") + .filter_map(|s| s.source_blob.clone()) + .collect(); + let missing = super::blobs::confirm_uploads(store, &needed).await?; + + let mut waiting = false; + for snapshot in &mut snapshots { + if snapshot.state == "failed" || snapshot.state == "removed" { + continue; + } + let blob_missing = snapshot.source_blob.as_ref().is_some_and(|b| missing.contains(b)); + if snapshot.kind == "document" { + if snapshot.render_id.is_none() { + if blob_missing { + mark_failed(snapshot, "the file was never uploaded").await?; + continue; + } + let blob = snapshot.source_blob.clone().unwrap_or_default(); + let key = settings.renderer_key(snapshot.engine.as_deref(), renderer_version); + let render = + super::renders::find_or_queue(project.id, &snapshot.source_fingerprint, &key, &blob).await?; + let render_id = Some(render.id); + update!(snapshot { render_id }).await?; + } + let render = Render::find_or_fail(snapshot.render_id.unwrap_or_default()).await?; + match render.state.as_str() { + "done" => {} + "failed" => { + let error = format!("rendering failed: {}", render.error.unwrap_or_default()); + mark_failed(snapshot, &error).await?; + } + _ => waiting = true, + } + } else if blob_missing { + mark_failed(snapshot, "the file was never uploaded").await?; + } + } + if waiting { + return Ok(false); + } + + // Each snapshot's own baseline, and the anchor build ("compared with #N"). + let (resolved, anchor) = baselines::resolve(&build, &project).await?; + let base_build_id = anchor.as_ref().map(|a| a.id); + let baseline_rows: HashMap<(String, String), i64> = + resolved.iter().filter_map(|(k, r)| r.row.as_ref().map(|row| (k.clone(), row.id))).collect(); + let originals: HashMap<(String, String), Snapshot> = + resolved.iter().map(|(k, Resolved { snapshot, .. })| (k.clone(), snapshot.clone())).collect(); + let mut base_snapshots: HashMap<(String, String), Snapshot> = + resolved.into_iter().map(|(key, r)| (key, r.snapshot)).collect(); + + for snapshot in snapshots.iter().filter(|s| s.state != "failed") { + let key = (snapshot.name.clone(), snapshot.platform.clone()); + if let Some(base) = base_snapshots.get(&key) { + match redraw_base(&settings, renderer_version, snapshot, base).await? { + Redraw::Ready(b) => { + base_snapshots.insert(key, *b); + } + Redraw::Waiting => waiting = true, + } + } + } + if waiting { + return Ok(false); + } + + let mut seen = HashSet::new(); + for mut snapshot in snapshots { + seen.insert((snapshot.name.clone(), snapshot.platform.clone())); + if snapshot.state == "failed" { + continue; + } + let key = (snapshot.name.clone(), snapshot.platform.clone()); + match compare(&mut snapshot, store, &settings, base_snapshots.get(&key)).await { + Ok(()) => set_baseline_id(&mut snapshot, baseline_rows.get(&key).copied()).await?, + Err(e) => { + tracing::warn!(build = id, snapshot = snapshot.id, error = %e, "comparing a snapshot failed"); + mark_failed(&mut snapshot, &format!("comparison failed: {e}")).await?; + } + } + } + + // What the build didn't send: a subset build (CI skipped the jobs whose inputs didn't change) and the groups that + // matched their baselines carry it forward unchanged; anything else was removed. + let carry = groups::carry(&build).await?; + let grouping = groups::grouping(build.group_depth); + let sent_keys: HashSet = seen.iter().map(|(name, _)| grouping.key(name)).collect(); + let mut carried: BTreeMap> = BTreeMap::new(); + let mut removed: Vec<(String, String)> = Vec::new(); + for key in base_snapshots.keys() { + if seen.contains(key) { + continue; + } + if build.subset || carry.covers(&key.0) { + carried.entry(grouping.key(&key.0)).or_default().push(key.clone()); + } else { + removed.push(key.clone()); + } + } + // A carried group the build sent nothing of, whose baselines one earlier build holds exactly, is read from that + // build: no rows are written for it (docs/design-storage.md). + let mut candidates = BTreeMap::new(); + for (group, keys) in &carried { + if sent_keys.contains(group) || build.mode != "ci" { + continue; + } + let bases: Vec<&Snapshot> = keys.iter().filter_map(|k| base_snapshots.get(k)).collect(); + let unchanged_render = + keys.iter().all(|k| base_snapshots.get(k).map(|b| b.render_id) == originals.get(k).map(|o| o.render_id)); + if bases.len() != keys.len() || !unchanged_render { + continue; + } + let entries: Vec = bases.iter().map(|s| groups::entry_of(s)).collect(); + let Some(g) = manifest::groups(&entries, grouping).into_iter().next() else { continue }; + candidates.insert(group.clone(), Candidate { base_ids: bases.iter().map(|b| b.id).collect(), hash: g.hash }); + } + let sourced = groups::holders(build.project_id, &candidates).await?; + groups::record_sources(id, &candidates, &sourced).await?; + for (group, keys) in &carried { + if sourced.contains_key(group) { + continue; + } + for key in keys { + let Some(base) = base_snapshots.get(key) else { continue }; + carry_forward(&build, &settings, store, base).await?; + } + } + for (name, platform) in &removed { + let Some(base) = base_snapshots.get(&(name.clone(), platform.clone())) else { continue }; + let pid = laravel::str::uuid7(); + let (kind, fingerprint, blob, render_id, environment) = + (&base.kind, &base.source_fingerprint, &base.source_blob, base.render_id, &base.environment); + let group_key = grouping.key(name); + let (base_id, baseline_id) = (base.id, baseline_rows.get(&(name.clone(), platform.clone())).copied()); + db::query!( + "INSERT INTO snapshots (pid, build_id, group_key, name, platform, kind, source_fingerprint, source_blob, \ + render_id, environment, state, base_snapshot_id, baseline_id) \ + VALUES ({pid}, {id}, {group_key}, {name}, {platform}, {kind}, {fingerprint}, {blob}, {render_id}, \ + {environment}, 'removed', {base_id}, {baseline_id}) \ + ON CONFLICT (build_id, name, platform) DO NOTHING" + ) + .insert() + .await?; + } + + // The file's settings: a loosening ci_mode it can't use, ignore rules that matched nothing, and whether they hide + // more than the base build's (then the build gets a "visualci.yml" item to review). + let mut warnings = settings.config_warnings(); + let names: Vec = super::snapshots::of_build(id).await?.into_iter().map(|s| s.name).collect(); + if settings.scoped_rules().0 == Source::File { + for rule in settings.unmatched_rules(names.iter().map(String::as_str)) { + warnings.push(format!( + "The ignore rule for {:?} in visualci.yml matched no snapshot in this build. Globs match snapshot \ + names as VisualCI shows them, without the root of the uploaded path.", + rule.snapshots + )); + } + } + // Compare the settings with the anchor's approved ones: when the anchor's own visualci.yml item wasn't approved, + // with the settings that item was compared with. + if let Some(a) = &anchor { + let base = approved_settings_build(a.clone()).await?; + let base_settings = BuildSettings::new(&project, &base); + if settings.hides_more_than(&base_settings) { + let base_item = Snapshot::query() + .filter(Snapshot::build_id.eq(base.id) & Snapshot::platform.eq(CONFIG_PLATFORM)) + .first() + .await?; + record_config_change( + id, + base.id, + base_item.map(|s| s.id), + &base_settings.review_settings(), + &settings.review_settings(), + ) + .await?; + } + } + + // Changes made only of changes merged pull requests approved say so (a hint). A failure here costs the hint, never + // the build. + if let Err(e) = super::matching::mark(store, &build).await { + tracing::warn!(build = id, error = %e, "matching approved changes"); + } + + // A local run the expiry finished keeps saying so. + let earlier: Vec = serde_json::from_value(build.warnings.clone()).unwrap_or_default(); + if earlier.iter().any(|w| w == LOCAL_FINISHED) { + warnings.push(LOCAL_FINISHED.to_string()); + } + let has_base = !base_snapshots.is_empty(); + + // What depends on the build's own rows comes before sourcing deletes the unchanged ones: the charge, and whether + // it sent anything (an empty build fails). + charge(&build).await?; + let sent: i64 = db::query!( + "SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND state <> 'removed' \ + AND platform <> 'visualci'" + ) + .scalar() + .await? + .unwrap_or(0); + groups::source_unchanged(&build).await?; + + let mut build = build; + let warnings = serde_json::json!(warnings); + update!(build { warnings }).await?; + let build = conclude(build, base_build_id, has_base, sent).await?; + if build.review_state == "auto_approved" { + // Nothing to review (or the project's first build): its changes are the baselines now. + let all = super::snapshots::of_build(build.id).await?; + let changes: Vec<&Snapshot> = all.iter().filter(|s| !is_config_item(s)).collect(); + baselines::record(&build, &changes, None, None, "auto").await?; + } + Ok(true) +} + +/// Carry a base snapshot forward into a build as its own row, compared with the base (unchanged). +async fn carry_forward( + build: &Build, + settings: &BuildSettings<'_>, + store: &BlobStore, + base: &Snapshot, +) -> laravel::Result<()> { + let (id, pid) = (build.id, laravel::str::uuid7()); + let group_key = groups::grouping(build.group_depth).key(&base.name); + let (name, platform, kind, format, fingerprint, blob, render_id, engine, rules, environment, threshold, aa, meta) = ( + &base.name, + &base.platform, + &base.kind, + &base.format, + &base.source_fingerprint, + &base.source_blob, + base.render_id, + &base.engine, + &base.ignore_rules, + &base.environment, + base.threshold, + base.ignore_anti_aliasing, + &base.meta, + ); + // A second run of this processing (the job retried, or run twice at once) finds the row there already. + let inserted = db::query!( + "INSERT INTO snapshots (pid, build_id, group_key, name, platform, kind, format, source_fingerprint, source_blob, \ + render_id, engine, ignore_rules, environment, threshold, ignore_anti_aliasing, meta, state, carried_forward) \ + VALUES ({pid}, {id}, {group_key}, {name}, {platform}, {kind}, {format}, {fingerprint}, {blob}, {render_id}, \ + {engine}, {rules}, {environment}, {threshold}, {aa}, {meta}, 'pending', true) \ + ON CONFLICT (build_id, name, platform) DO NOTHING" + ) + .insert() + .await? + .rows_affected(); + if inserted == 0 { + return Ok(()); + } + let mut carried = Snapshot::query() + .filter(Snapshot::build_id.eq(id) & Snapshot::name.eq(name.as_str()) & Snapshot::platform.eq(platform.as_str())) + .first() + .await? + .ok_or_else(|| laravel::Error::msg("the carried snapshot wasn't saved"))?; + if let Err(e) = compare(&mut carried, store, settings, Some(base)).await { + tracing::warn!(build = id, snapshot = carried.id, error = %e, "carrying a snapshot forward failed"); + mark_failed(&mut carried, &format!("comparison failed: {e}")).await?; + } + Ok(()) +} + +/// Count snapshot states (a config item counts apart). +#[must_use] +pub fn stats_of(snapshots: &[Snapshot]) -> Stats { + let mut stats = Stats::default(); + for s in snapshots { + if is_config_item(s) { + stats.config += usize::from(is_change(s)); + continue; + } + stats.total += 1; + match s.state.as_str() { + "unchanged" => stats.unchanged += 1, + "changed" => stats.changed += 1, + "added" => stats.added += 1, + "removed" => stats.removed += 1, + "ignored" => stats.ignored += 1, + "failed" => stats.failed += 1, + _ => stats.pending += 1, + } + } + stats +} + +/// Count snapshot states, set the conclusion and review state, and mark the build completed. `sent` is how many +/// snapshots the build was sent itself: none means the upload found nothing, which mustn't pass as "unchanged". +async fn conclude(mut build: Build, base_build_id: Option, has_base: bool, sent: i64) -> laravel::Result { + let all = super::snapshots::of_build(build.id).await?; + let stats = stats_of(&all); + let empty = sent == 0 && !build.allow_empty; + let conclusion = if stats.failed > 0 || empty { + "failed" + } else if stats.changes() > 0 { + "changes" + } else { + "unchanged" + }; + // A local run's changes always wait for review, even in a project's first build: approving one sets the baseline + // for its branch and environment. + let review_state = match (build.mode.as_str(), conclusion, has_base) { + (_, "failed", _) => "none", + (_, "unchanged", _) | ("ci", _, false) => "auto_approved", + _ => "pending", + }; + let stats = serde_json::to_value(&stats).unwrap_or_default(); + let error = empty.then(|| EMPTY_BUILD.to_string()); + let (conclusion, review_state) = (Some(conclusion.to_string()), review_state.to_string()); + let completed_at = Some(laravel::now().timestamp()); + update!(build { state: "completed", conclusion, review_state, base_build_id, stats, completed_at, error }).await?; + Ok(build) +} + +/// Recount after a review action changed snapshot states (an ignored change, an accepted variant). +/// +/// # Errors +/// On a database error. +pub async fn recount(mut build: Build) -> laravel::Result { + let all = super::snapshots::of_build(build.id).await?; + let stats = stats_of(&all); + let changes = stats.changes(); + let stats = serde_json::to_value(&stats).unwrap_or_default(); + if build.conclusion.as_deref() == Some("changes") && changes == 0 { + let review_state = + if build.review_state == "pending" { "auto_approved".to_string() } else { build.review_state.clone() }; + update!(build { stats, conclusion: Some("unchanged".to_string()), review_state }).await?; + } else { + update!(build { stats }).await?; + } + Ok(build) +} + +/// Charge the organization for this build: every snapshot it sent (carried-forward snapshots weren't sent), the text +/// and image diffs it computed, the PDF pages it drew and the groups it checked. Charges only what wasn't charged +/// before (an early comparison charges as it goes), and records the total in `builds.charged`. +/// +/// # Errors +/// On a database error. +pub async fn charge(build: &Build) -> laravel::Result<()> { + let project = Project::find_or_fail(build.project_id).await?; + let mut fresh = Build::find_or_fail(build.id).await?; + let charged: Usage = serde_json::from_value(fresh.charged.clone()).unwrap_or_default(); + let (id, since) = (build.id, build.created_at); + let row = db::query!( + "SELECT \ + (SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND state <> 'removed')::BIGINT AS checks, \ + (SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND kind = 'text' AND state = 'changed')::BIGINT AS text_diffs, \ + (SELECT COALESCE(SUM(jsonb_array_length(r.pages)), 0) FROM renders r \ + WHERE r.id IN (SELECT render_id FROM snapshots WHERE build_id = {id}) AND r.created_at >= {since})::BIGINT AS pages, \ + (SELECT COUNT(DISTINCT d.id) FROM diffs d JOIN snapshot_pages p ON p.diff_id = d.id \ + JOIN snapshots s ON s.id = p.snapshot_id WHERE s.build_id = {id} AND d.created_at >= {since})::BIGINT AS image_diffs" + ) + .select_one() + .await?; + let get = |name: &str| -> i64 { row.as_ref().and_then(|r| r.try_get(name).ok()).unwrap_or(0) }; + let usage = Usage { + snapshot_checks: get("checks"), + text_diffs: get("text_diffs"), + image_diffs: get("image_diffs"), + rendered_pages: get("pages"), + groups_checked: groups::checks(&fresh).await?, + }; + let delta = Usage { + snapshot_checks: (usage.snapshot_checks - charged.snapshot_checks).max(0), + text_diffs: (usage.text_diffs - charged.text_diffs).max(0), + image_diffs: (usage.image_diffs - charged.image_diffs).max(0), + rendered_pages: (usage.rendered_pages - charged.rendered_pages).max(0), + groups_checked: (usage.groups_checked - charged.groups_checked).max(0), + }; + let amount = delta.credits(); + if amount > 0 { + let reference = format!("build {}/{}: {}", project.slug, build.number, delta.describe()); + credits::spend( + project.organization_id, + amount, + "build", + Some(&reference), + Some(Spender::of(&project)), + Some(build.id), + ) + .await?; + } + let total = Usage { + snapshot_checks: usage.snapshot_checks.max(charged.snapshot_checks), + text_diffs: usage.text_diffs.max(charged.text_diffs), + image_diffs: usage.image_diffs.max(charged.image_diffs), + rendered_pages: usage.rendered_pages.max(charged.rendered_pages), + groups_checked: usage.groups_checked.max(charged.groups_checked), + }; + let charged = serde_json::to_value(total).unwrap_or_default(); + update!(fresh { charged }).await?; + Ok(()) +} + +/// Fail a build that's processing when its organization is out of credits, after billing's chance to reload (the +/// `CreditsRanOut` event's listeners run first). Billing's listeners hear `BuildStoppedForCredits` (the monthly email). +/// +/// # Errors +/// On a database error. +pub async fn stop_if_out_of_credits(mut build: Build) -> laravel::Result { + if build.state != "processing" { + return Ok(build); + } + let project = Project::find_or_fail(build.project_id).await?; + let spender = Spender::of(&project); + let org = Organization::find_or_fail(project.organization_id).await?; + if !credits::out_of_credits_for(&org, spender).await? { + return Ok(build); + } + CreditsRanOut { organization_id: org.id }.dispatch().await?; + let org = Organization::find_or_fail(org.id).await?; + if !credits::out_of_credits_for(&org, spender).await? { + return Ok(build); + } + let plan = credits::plan_by_id(&org.plan); + let what_now = if plan.credit_packs { + "Buy a credit pack on the billing page, or raise the limit on automatic reloads." + } else { + "Upgrade to Team on the billing page, or wait for the allowance to renew on the 1st." + }; + let error = Some(format!( + "{} has used this month's {} credits on the {} plan and has no pack credits left, so this build wasn't \ + compared. {what_now}", + org.name, + credits::thousands(plan.included_credits), + plan.name + )); + update!(build { state: "failed", error_code: Some(OUT_OF_CREDITS.to_string()), error }).await?; + BuildStoppedForCredits { build_id: build.id, organization_id: org.id }.dispatch().await?; + Ok(build) +} + +/// A build stopped: its queued renders that no other receiving or processing build waits on aren't drawn. +/// +/// # Errors +/// On a database error. +pub async fn drop_unneeded_renders(build_id: i64) -> laravel::Result<()> { + let id = build_id; + db::query!( + "UPDATE renders SET state = 'failed', error = 'its build ran out of credits', updated_at = now() \ + WHERE state = 'queued' AND id IN (SELECT render_id FROM snapshots WHERE build_id = {id}) \ + AND NOT EXISTS (SELECT 1 FROM snapshots s JOIN builds b ON b.id = s.build_id \ + WHERE s.render_id = renders.id AND s.build_id <> {id} AND b.state IN ('receiving', 'processing'))" + ) + .update() + .await?; + Ok(()) +} + +/// How long a build may wait for its next upload or shard before it's given up on. +pub const ABANDON_AFTER_MINUTES: i32 = 60; + +/// The error an abandoned build carries. +pub const ABANDONED: &str = "Nothing arrived for this build for an hour, so VisualCI gave up on it: the CI job most \ +likely stopped (or failed) before `visualci build finalize`. Re-run the job to send a new build."; + +/// Builds nothing arrived for in [`ABANDON_AFTER_MINUTES`] (in one project, or everywhere): CI builds fail with +/// [`ABANDONED`]; local runs (which often end without finalizing) are finished as subsets and processed. Their checks +/// and pages follow (`BuildChanged`). Returns how many it expired. +/// +/// # Errors +/// On a database or queue error. +pub async fn expire_abandoned(project_id: Option) -> laravel::Result { + let minutes = ABANDON_AFTER_MINUTES; + let ids = + |rows: Vec| -> Vec { rows.iter().filter_map(|r| r.try_get("id").ok()).collect() }; + let failed = ids(db::query!( + "UPDATE builds b SET state = 'failed', conclusion = 'failed', review_state = 'none', error = {ABANDONED}, \ + completed_at = now(), updated_at = now() \ + WHERE b.mode <> 'local' AND b.state = 'receiving' AND ({project_id}::BIGINT IS NULL OR b.project_id = {project_id}) \ + AND GREATEST(b.updated_at, \ + COALESCE((SELECT MAX(s.updated_at) FROM snapshots s WHERE s.build_id = b.id), b.created_at)) \ + < now() - make_interval(mins => {minutes}) \ + RETURNING b.id" + ) + .select() + .await?); + let finished = ids(db::query!( + "UPDATE builds b SET state = 'processing', subset = true, allow_empty = true, \ + warnings = b.warnings || jsonb_build_array({LOCAL_FINISHED}::TEXT), finalized_at = now(), updated_at = now() \ + WHERE b.mode = 'local' AND b.state = 'receiving' AND ({project_id}::BIGINT IS NULL OR b.project_id = {project_id}) \ + AND GREATEST(b.updated_at, \ + COALESCE((SELECT MAX(s.updated_at) FROM snapshots s WHERE s.build_id = b.id), b.created_at)) \ + < now() - make_interval(mins => {minutes}) \ + RETURNING b.id" + ) + .select() + .await?); + for id in &failed { + crate::events::BuildChanged { build_id: *id }.dispatch().await?; + } + for id in &finished { + let build = stop_if_out_of_credits(Build::find_or_fail(*id).await?).await?; + if build.state == "processing" { + crate::jobs::process_build::ProcessBuild { build_id: *id }.dispatch().await?; + } else { + crate::events::BuildChanged { build_id: *id }.dispatch().await?; + } + } + Ok(failed.len() + finished.len()) +} + +/// Compare some of a build's snapshots now, before it's finalized: a local run checks each test's snapshots as the test +/// makes them. Snapshots whose files haven't arrived or whose PDFs are still rendering come back `pending`; ask again. +/// Finalizing compares everything again, so these results are never the final word. +/// +/// # Errors +/// `Ok(Err(message))` when the organization is out of credits; `Err` on a database or storage error. +pub async fn compare_now( + build: &Build, + store: &BlobStore, + renderer_version: &str, + wanted: &[(String, String)], +) -> laravel::Result, String>> { + let project = Project::find_or_fail(build.project_id).await?; + if build.state == "receiving" { + let org = Organization::find_or_fail(project.organization_id).await?; + if credits::out_of_credits_for(&org, Spender::of(&project)).await? { + return Ok(Err(format!( + "{} is out of VisualCI credits, so snapshots can't be compared: its billing page has the fix (the \ + build's `blocked` says more)", + org.name + ))); + } + } + let settings = BuildSettings::new(&project, build); + let snapshots: Vec = super::snapshots::of_build(build.id) + .await? + .into_iter() + .filter(|s| wanted.iter().any(|(n, p)| *n == s.name && *p == s.platform)) + .collect(); + if build.state != "receiving" { + return Ok(Ok(snapshots)); + } + let needed: Vec = + snapshots.iter().filter(|s| s.render_id.is_none()).filter_map(|s| s.source_blob.clone()).collect(); + let missing = super::blobs::confirm_uploads(store, &needed).await?; + let (resolved, _) = baselines::resolve(build, &project).await?; + let mut out = Vec::with_capacity(snapshots.len()); + for mut snapshot in snapshots { + if snapshot.source_blob.as_ref().is_some_and(|b| missing.contains(b)) { + out.push(snapshot); + continue; + } + if snapshot.kind == "document" { + if snapshot.render_id.is_none() { + let blob = snapshot.source_blob.clone().unwrap_or_default(); + let key = settings.renderer_key(snapshot.engine.as_deref(), renderer_version); + let render = + super::renders::find_or_queue(project.id, &snapshot.source_fingerprint, &key, &blob).await?; + let render_id = Some(render.id); + update!(snapshot { render_id }).await?; + } + let render = Render::find_or_fail(snapshot.render_id.unwrap_or_default()).await?; + match render.state.as_str() { + "done" => {} + "failed" => { + let error = format!("rendering failed: {}", render.error.unwrap_or_default()); + mark_failed(&mut snapshot, &error).await?; + out.push(snapshot); + continue; + } + _ => { + out.push(snapshot); + continue; + } + } + } + let key = (snapshot.name.clone(), snapshot.platform.clone()); + let row = resolved.get(&key).and_then(|r| r.row.as_ref().map(|row| row.id)); + let base = match resolved.get(&key) { + Some(r) => match redraw_base(&settings, renderer_version, &snapshot, &r.snapshot).await? { + Redraw::Ready(b) => Some(*b), + Redraw::Waiting => { + out.push(snapshot); + continue; + } + }, + None => None, + }; + match compare(&mut snapshot, store, &settings, base.as_ref()).await { + Ok(()) => set_baseline_id(&mut snapshot, row).await?, + Err(e) => { + tracing::warn!(build = build.id, snapshot = snapshot.id, error = %e, "comparing a snapshot early failed") + } + } + out.push(snapshot); + } + // Charge for what this did (snapshot checks, diffs, pages drawn); finalizing charges only the rest. + charge(build).await?; + Ok(Ok(out)) +} + +/// The warning on a local build nobody reviewed for [`LOCAL_IDLE_DAYS`]. +pub const LOCAL_IDLE: &str = "Closed without review: a local build, idle for 7 days."; +/// How long a local build waits for its own person's review before it leaves the waiting lists. +pub const LOCAL_IDLE_DAYS: i32 = 7; +/// A build still processing this long after its last change is run again: its job's dispatch may have been lost. +pub const RESTART_AFTER_MINUTES: i32 = 10; +/// A build still processing this long after it was finalized fails: something keeps it from finishing. +pub const GIVE_UP_AFTER_HOURS: i32 = 6; +/// The error on a build that never finished processing. +pub const STUCK: &str = "This build didn't finish comparing within 6 hours, so VisualCI stopped it. Re-run the CI job \ +to send it again; if it happens again, tell us with `support_send`."; + +/// What a sweep did. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Swept { + pub expired: usize, + pub idle_local_closed: usize, + pub restarted: usize, + pub stuck_failed: usize, +} + +/// The sweep the scheduler runs every few minutes: expire abandoned builds ([`expire_abandoned`]), close local builds +/// idle for a week, run again builds processing with no change for [`RESTART_AFTER_MINUTES`] (a lost dispatch, a +/// crashed worker), and fail builds still processing [`GIVE_UP_AFTER_HOURS`] after they were finalized. +/// +/// # Errors +/// On a database or queue error. +pub async fn sweep() -> laravel::Result { + let expired = expire_abandoned(None).await?; + let days = LOCAL_IDLE_DAYS; + let idle: Vec = db::query!( + "UPDATE builds b SET review_state = 'closed', warnings = b.warnings || jsonb_build_array({LOCAL_IDLE}::TEXT), \ + updated_at = now() \ + WHERE b.mode = 'local' AND b.review_state = 'pending' \ + AND GREATEST(b.updated_at, \ + COALESCE((SELECT MAX(s.updated_at) FROM snapshots s WHERE s.build_id = b.id), b.created_at)) \ + < now() - make_interval(days => {days}) \ + RETURNING b.id" + ) + .select_as() + .await?; + let hours = GIVE_UP_AFTER_HOURS; + let stuck: Vec = db::query!( + "UPDATE builds SET state = 'failed', conclusion = 'failed', review_state = 'none', error = {STUCK}, \ + completed_at = now(), updated_at = now() \ + WHERE state = 'processing' AND COALESCE(finalized_at, created_at) < now() - make_interval(hours => {hours}) \ + RETURNING id" + ) + .select_as() + .await?; + let minutes = RESTART_AFTER_MINUTES; + let restart: Vec = db::query!( + "SELECT id FROM builds WHERE state = 'processing' AND updated_at < now() - make_interval(mins => {minutes}) \ + ORDER BY id" + ) + .select_as() + .await?; + for id in idle.iter().chain(&stuck) { + crate::events::BuildChanged { build_id: *id }.dispatch().await?; + } + for id in &restart { + crate::jobs::process_build::ProcessBuild { build_id: *id }.dispatch().await?; + } + Ok(Swept { expired, idle_local_closed: idle.len(), restarted: restart.len(), stuck_failed: stuck.len() }) +} diff --git a/app/src/domain/renders.rs b/app/src/domain/renders.rs new file mode 100644 index 00000000..721f7db8 --- /dev/null +++ b/app/src/domain/renders.rs @@ -0,0 +1,115 @@ +//! Renders: a source (a PDF) turned into page images by one renderer. Cached per project by (source fingerprint, +//! renderer), so a document that hasn't changed is never drawn twice, whichever build, branch or laptop sends it. +//! Never across projects: the fingerprint is the client's word, and another account's render under it would be +//! compared in place of the project's own PDF. + +use laravel::db; +use laravel::model::update; +use serde::{Deserialize, Serialize}; + +use crate::models::Render; + +/// A claim older than this is treated as abandoned (the renderer died) and the render is handed out again. +pub const CLAIM_TIMEOUT_SECONDS: i64 = 600; +pub const MAX_ATTEMPTS: i32 = 3; + +/// One rendered page, as stored in `renders.pages`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RenderPage { + /// SHA-256 of the page's PNG (a blob). + pub image: String, + /// Pixel fingerprint of the PNG. + pub image_fingerprint: String, + /// The page's PDF fingerprint (what it draws): the alignment key. + pub fingerprint: String, + pub width: u32, + pub height: u32, + /// SHA-256 of the page's extracted text (`texts`): what `renders.pages` stores. + #[serde(default)] + pub text_sha: String, + /// The page's extracted text: sent by the renderer, and filled from `texts` by [`with_text`]. Never stored here. + #[serde(default, skip_serializing)] + pub text: String, +} + +/// A render's pages, without their text. +#[must_use] +pub fn pages(render: &Render) -> Vec { + serde_json::from_value(render.pages.clone()).unwrap_or_default() +} + +/// Fill in pages' text from `texts`. +/// +/// # Errors +/// On a database error. +pub async fn with_text(mut pages: Vec) -> laravel::Result> { + let shas: Vec = pages.iter().map(|p| p.text_sha.clone()).collect(); + let texts = crate::storage::texts::load(&shas).await?; + for p in &mut pages { + if let Some(t) = texts.get(&p.text_sha) { + p.text.clone_from(t); + } + } + Ok(pages) +} + +/// The render for this source, queued when it doesn't exist yet (or failed before, under [`MAX_ATTEMPTS`]). +/// +/// # Errors +/// On a database error. +pub async fn find_or_queue( + project_id: i64, + fingerprint: &str, + renderer: &str, + source_blob: &str, +) -> laravel::Result { + db::query!( + "INSERT INTO renders (project_id, source_fingerprint, renderer, source_blob) \ + VALUES ({project_id}, {fingerprint}, {renderer}, {source_blob}) \ + ON CONFLICT (project_id, source_fingerprint, renderer) DO NOTHING" + ) + .insert() + .await?; + let mut render = Render::query() + .filter( + Render::project_id.eq(project_id) + & Render::source_fingerprint.eq(fingerprint) + & Render::renderer.eq(renderer), + ) + .first() + .await? + .ok_or_else(|| laravel::Error::msg("the queued render wasn't saved"))?; + if render.state == "failed" && render.attempts < MAX_ATTEMPTS { + let source_blob = source_blob.to_string(); + update!(render { state: "queued", source_blob }).await?; + } + Ok(render) +} + +/// Record a render's pages: their texts go to `texts`, and the pages keep the hashes. +/// +/// # Errors +/// On a database error. +pub async fn complete(mut render: Render, pages: &[RenderPage]) -> laravel::Result { + let bodies: Vec<&str> = pages.iter().map(|p| p.text.as_str()).collect(); + let shas = crate::storage::texts::store(&bodies).await?; + let stored: Vec = + pages.iter().zip(shas).map(|(p, text_sha)| RenderPage { text_sha, text: String::new(), ..p.clone() }).collect(); + let pages = serde_json::to_value(stored).unwrap_or_default(); + let now = laravel::now().timestamp(); + let render_ms = render.claimed_at.map(|claimed| now.as_millisecond() - claimed.as_millisecond()); + update!(render { state: "done", pages, error: None, completed_at: Some(now), render_ms }).await?; + Ok(render) +} + +/// Record a failure. The render is drawn again by the next build that needs it, up to [`MAX_ATTEMPTS`]. +/// +/// # Errors +/// On a database error. +pub async fn fail(mut render: Render, error: &str) -> laravel::Result { + let now = laravel::now().timestamp(); + let render_ms = render.claimed_at.map(|claimed| now.as_millisecond() - claimed.as_millisecond()); + let error = Some(error.chars().take(4000).collect::()); + update!(render { state: "failed", error, completed_at: Some(now), render_ms }).await?; + Ok(render) +} diff --git a/app/src/domain/snapshots.rs b/app/src/domain/snapshots.rs index bb08c4ea..bbcedef4 100644 --- a/app/src/domain/snapshots.rs +++ b/app/src/domain/snapshots.rs @@ -209,6 +209,26 @@ pub async fn register( Ok(Ok(Registration { snapshot, needs_upload })) } +/// Every snapshot of a build, its own and those it reads from earlier builds (`effective_snapshots`), by name and +/// platform. A row read from another build is `sourced`: unchanged, compared with itself, never reviewed, and its +/// id and pid are the holder's. +/// +/// # Errors +/// On a database error. +pub async fn of_build(build_id: i64) -> laravel::Result> { + db::query!("SELECT * FROM effective_snapshots WHERE build_id = {build_id} ORDER BY name, platform") + .select_as() + .await +} + +/// A build's snapshot by pid: one of its own, or one it reads from another build. +/// +/// # Errors +/// On a database error. +pub async fn in_build(build_id: i64, pid: laravel::str::Uuid) -> laravel::Result> { + db::query!("SELECT * FROM effective_snapshots WHERE build_id = {build_id} AND pid = {pid}").select_one_as().await +} + /// A text snapshot's format (`None` for documents and images). Plain text when none was stored. #[must_use] pub fn text_format(snapshot: &Snapshot) -> Option { diff --git a/app/src/events.rs b/app/src/events.rs new file mode 100644 index 00000000..240df212 --- /dev/null +++ b/app/src/events.rs @@ -0,0 +1,28 @@ +//! Events the domain fires for the other side's listeners (sc-8900): forge checks and PR comments, live updates, +//! billing and emails listen to them. Each listener decides whether to queue its work. + +/// A build's state, review or snapshots changed: its forge check, PR comment, live updates and gallery follow. +#[derive(laravel::event::Event, Clone, Debug)] +pub struct BuildChanged { + pub build_id: i64, +} + +/// A build spent credits: billing may reload a pack (Team, automatic packs) and notices may go out. +#[derive(laravel::event::Event, Clone, Debug)] +pub struct CreditsSpent { + pub organization_id: i64, +} + +/// An organization has no credits left for a build about to be compared. Its listeners run before the build is +/// stopped: billing tries an automatic reload, and the domain checks the credits again afterwards. +#[derive(laravel::event::Event, Clone, Debug)] +pub struct CreditsRanOut { + pub organization_id: i64, +} + +/// A build was stopped because its organization is out of credits: its admins hear about it (once a month). +#[derive(laravel::event::Event, Clone, Debug)] +pub struct BuildStoppedForCredits { + pub build_id: i64, + pub organization_id: i64, +} diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index 90778dc8..e1d2b80a 100644 --- a/app/src/http/api/builds.rs +++ b/app/src/http/api/builds.rs @@ -18,6 +18,9 @@ pub fn routes(route: &mut Router) { route.get("/v1/builds/{pid}", show); route.post("/v1/builds/{pid}/snapshots", add_snapshots); route.post("/v1/builds/{pid}/finalize", finalize); + route.post("/v1/builds/{pid}/groups", check_groups); + route.post("/v1/builds/{pid}/compare", compare); + route.get("/v1/builds/{pid}/snapshots", list_snapshots); } /// The renderer version documents are drawn with: part of the render cache key. @@ -106,6 +109,9 @@ pub async fn create(auth: Result, Body(params): Body Some(user.id), _ => None, }; + // The project's earlier builds that stopped arriving are given up on now (also every few minutes by the expiry + // task), so they don't sit "receiving" beside this one. + crate::domain::processing::expire_abandoned(Some(project.id)).await?; let build = domain::create(&project, ¶ms, creator).await.map_err(ApiError::from)?; Ok(BuildResponse::new(&build, &project, &organization)) } @@ -221,10 +227,156 @@ pub async fn finalize( Some(reason) => domain::allow_empty_because(build, reason).await.map_err(ApiError::from)?, None => build, }; + let was_receiving = build.state == "receiving"; let allow_empty = params.allow_empty || params.empty_reason.is_some(); let build = domain::finalize_shard(build, params.shard, allow_empty).await.map_err(ApiError::from)?; + let build = + if was_receiving { crate::domain::processing::stop_if_out_of_credits(build).await? } else { build }; + if was_receiving && build.state == "processing" { + crate::jobs::process_build::ProcessBuild { build_id: build.id }.dispatch().await?; + } else if was_receiving && build.state == "failed" { + crate::events::BuildChanged { build_id: build.id }.dispatch().await?; + } + // The job may have run already (a synchronous queue): answer with the build as it is now. + let build = Build::find(build.id).await?.unwrap_or(build); Ok(BuildResponse::new(&build, &project, &organization)) } .await, ) } + +/// `POST /api/v1/builds/{pid}/groups`: large suites (sc-8868) send the run's manifest hash and one hash per group of +/// names before any files. The answer says which groups the client must send; the rest are carried forward from their +/// baselines (or read from the build that holds them) when the build processes. +pub async fn check_groups( + auth: Result, + Params(pid): Params, + Body(params): Body, +) -> Response { + respond( + async { + let ApiProject { project, .. } = auth?; + let build = own_build(&project, pid).await?; + crate::domain::groups::check(&build, &project, ¶ms).await?.map_err(ApiError::bad_request) + } + .await, + ) +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CompareParams { + /// The snapshots to compare now, by name (and platform). + snapshots: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct CompareTarget { + name: String, + #[serde(default)] + platform: String, +} + +/// `POST /api/v1/builds/{pid}/compare`: compare some snapshots of a build that's still receiving, for a local run that +/// checks each test as it goes. Each comes back with its state: `pending` while its file is missing or its PDF is +/// rendering (ask again), `unchanged`, `changed`, `added`, `ignored` or `failed`. +pub async fn compare( + auth: Result, + Params(pid): Params, + Body(params): Body, +) -> Response { + respond( + async { + let ApiProject { project, organization, .. } = auth?; + let store = BlobStore::current().await?; + let build = own_build(&project, pid).await?; + if params.snapshots.len() > 200 { + return Err(ApiError::bad_request("at most 200 snapshots per request")); + } + let wanted: Vec<(String, String)> = params.snapshots.into_iter().map(|t| (t.name, t.platform)).collect(); + let version = renderer_version(); + let compared = laravel::db::transaction(async |_| { + crate::domain::processing::lock(build.id).await?; + let build = Build::find_or_fail(build.id).await?; + crate::domain::processing::compare_now(&build, &store, &version, &wanted).await + }) + .await? + .map_err(ApiError::bad_request)?; + let missing: Vec<&str> = wanted + .iter() + .filter(|(n, p)| !compared.iter().any(|s| &s.name == n && &s.platform == p)) + .map(|(n, _)| n.as_str()) + .collect(); + if !missing.is_empty() { + return Err(ApiError::bad_request(format!("not in build {}: {}", build.number, missing.join(", ")))); + } + let build_url = format!("{}/{}/{}/builds/{}", app_url(), organization.slug, project.slug, build.number); + let list: Vec = compared + .iter() + .map(|s| { + serde_json::json!({ + "name": s.name, "platform": s.platform, "state": s.state, "environment": s.environment, + "matched_environment": s.matched_environment, "error": s.error, + "url": format!("{build_url}/snapshots/{}", s.pid), + }) + }) + .collect(); + Ok(serde_json::json!({ "snapshots": list })) + } + .await, + ) +} + +#[derive(Debug, Default, Deserialize)] +pub struct SnapshotFilter { + /// A state, or `changes` for changed, added and removed. + state: Option, +} + +#[derive(Debug, Serialize)] +struct SnapshotSummary { + id: Uuid, + name: String, + platform: String, + kind: String, + state: String, + review: Option, + error: Option, +} + +/// `GET /api/v1/builds/{pid}/snapshots?state=`: every snapshot of the build, its own and those it reads from earlier +/// builds. +pub async fn list_snapshots( + auth: Result, + Params(pid): Params, + filter: axum::extract::Query, +) -> Response { + respond( + async { + let ApiProject { project, .. } = auth?; + let build = own_build(&project, pid).await?; + let state = filter.0.state; + let list: Vec = crate::domain::snapshots::of_build(build.id) + .await? + .into_iter() + .filter(|s| { + state + .as_deref() + .is_none_or(|st| st == s.state || (st == "changes" && crate::domain::snapshots::is_change(s))) + }) + .map(|s| SnapshotSummary { + id: s.pid, + name: s.name, + platform: s.platform, + kind: s.kind, + state: s.state, + review: s.review, + error: s.error, + }) + .collect(); + Ok(serde_json::json!({ "snapshots": list })) + } + .await, + ) +} diff --git a/app/src/http/mod.rs b/app/src/http/mod.rs index 44cc1f01..e405da68 100644 --- a/app/src/http/mod.rs +++ b/app/src/http/mod.rs @@ -2,3 +2,4 @@ pub mod api; pub mod hosts; +pub mod status; diff --git a/app/src/http/status.rs b/app/src/http/status.rs new file mode 100644 index 00000000..750b397d --- /dev/null +++ b/app/src/http/status.rs @@ -0,0 +1,47 @@ +//! `GET /status`: the deployed commit and how the background work is keeping up, for uptime checks and alerts (each +//! number has a threshold in Gatus). The data side's numbers; subdomains' (emails, sign-up notices, forge syncs) join +//! them in the same answer. + +use axum::Json; +use laravel::db; +use serde_json::{Value, json}; + +/// The commit this build of the app came from (`BUILD_SHA` at compile time). +pub const COMMIT: &str = match option_env!("BUILD_SHA") { + Some(sha) => sha, + None => "dev", +}; + +pub async fn status() -> laravel::Result> { + let row = db::query!( + "SELECT \ + (SELECT COUNT(*) FROM renders WHERE state = 'queued')::BIGINT AS renders_queued, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(created_at)) FROM renders \ + WHERE state IN ('queued', 'rendering')), 0)::BIGINT AS oldest_render_seconds, \ + (SELECT COUNT(*) FROM builds WHERE state = 'processing')::BIGINT AS builds_processing, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(finalized_at)) FROM builds WHERE state = 'processing'), 0)::BIGINT \ + AS oldest_processing_seconds, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MAX(updated_at)) FROM renders WHERE state = 'done'), -1)::BIGINT \ + AS last_render_seconds_ago, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(GREATEST(b.updated_at, COALESCE((SELECT MAX(s.updated_at) \ + FROM snapshots s WHERE s.build_id = b.id), b.created_at)))) FROM builds b WHERE b.state = 'receiving'), 0)::BIGINT \ + AS oldest_receiving_seconds" + ) + .select_one() + .await? + .ok_or_else(|| laravel::Error::msg("no status row"))?; + let get = |k: &str| -> laravel::Result { row.try_get::(k) }; + Ok(Json(json!({ + "ok": true, + "commit": COMMIT, + "renders_queued": get("renders_queued")?, + "oldest_render_seconds": get("oldest_render_seconds")?, + "builds_processing": get("builds_processing")?, + // The builds sweep (every five minutes) runs a build again after 10 minutes without progress and fails it + // after 6 hours: past that, the sweep has stopped. + "oldest_processing_seconds": get("oldest_processing_seconds")?, + "last_render_seconds_ago": get("last_render_seconds_ago")?, + // A build left receiving: the sweep fails it after an hour without uploads, so past two hours it has stopped. + "oldest_receiving_seconds": get("oldest_receiving_seconds")?, + }))) +} diff --git a/app/src/jobs/mod.rs b/app/src/jobs/mod.rs new file mode 100644 index 00000000..68e2b123 --- /dev/null +++ b/app/src/jobs/mod.rs @@ -0,0 +1,3 @@ +//! Queued jobs. + +pub mod process_build; diff --git a/app/src/jobs/process_build.rs b/app/src/jobs/process_build.rs new file mode 100644 index 00000000..2204c575 --- /dev/null +++ b/app/src/jobs/process_build.rs @@ -0,0 +1,83 @@ +//! Processes a finalized build: confirms uploads, queues renders, and once they're done compares and concludes. Queued +//! when a build's last shard finalizes, and again whenever a render it waits on finishes: dispatches for one build +//! within a few seconds run once (a build of 1,000 PDFs finishing its renders together is one run, not 1,000). + +use laravel::db; +use laravel::queue::{Queueable, job}; + +use crate::domain::processing; +use crate::events::{BuildChanged, CreditsSpent}; +use crate::models::Build; +use crate::storage::BlobStore; + +#[derive(Queueable)] +pub struct ProcessBuild { + pub build_id: i64, +} + +#[job(name = "builds.process", debounce_for = 3.seconds(), max_wait = 30.seconds())] +impl ProcessBuild { + fn debounce_id(&self) -> i64 { + self.build_id + } + + async fn handle(self) -> laravel::Result<()> { + let id = self.build_id; + let store = BlobStore::current().await?; + let version = crate::http::api::builds::renderer_version(); + // Charge what the build has used so far in a short transaction of its own: the organization's row is locked + // only while it's charged, never for a whole run, and what's charged stays charged if the run fails. + let charged = db::transaction(async |_| { + processing::lock(id).await?; + let build = Build::find_or_fail(id).await?; + if build.state == "processing" { + processing::charge(&build).await?; + } + Ok(build) + }) + .await?; + if charged.state != "processing" { + return Ok(()); + } + // Out of credits part-way (a large build's pages): stop here rather than draw the rest. Outside any + // transaction, so billing's listeners (an automatic reload charges the card) run on committed data. + let build = processing::stop_if_out_of_credits(charged).await?; + if build.state == "failed" { + processing::drop_unneeded_renders(id).await?; + finished(id, build.project_id).await?; + return Ok(()); + } + // One run at a time per build (the advisory lock), all its comparison writes together. + let result = db::transaction(async |_| { + processing::lock(id).await?; + let build = Build::find_or_fail(id).await?; + if build.state != "processing" { + return Ok(false); + } + processing::process(build, &store, &version).await + }) + .await; + match result { + Ok(true) => finished(id, build.project_id).await?, + Ok(false) => tracing::debug!(build_id = id, "build waiting for renders"), + Err(e) => { + tracing::error!(build_id = id, error = %e, "processing a build failed"); + let error = Some(e.to_string()); + if let Some(mut build) = Build::find(id).await? { + laravel::model::update!(build { state: "failed", error }).await?; + } + BuildChanged { build_id: id }.dispatch().await?; + } + } + Ok(()) + } +} + +/// The build concluded (or stopped): billing hears what was spent, and its checks, comment and pages follow. +async fn finished(build_id: i64, project_id: i64) -> laravel::Result<()> { + if let Some(project) = crate::models::Project::find(project_id).await? { + CreditsSpent { organization_id: project.organization_id }.dispatch().await?; + } + BuildChanged { build_id }.dispatch().await?; + Ok(()) +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 6cbdcc4c..9cc13675 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -3,10 +3,13 @@ pub mod auth; pub mod billing; pub mod config; +pub mod console; pub mod domain; +pub mod events; pub mod forge; pub mod heartbeat; pub mod http; +pub mod jobs; pub mod listeners; pub mod models; pub mod notify; @@ -58,6 +61,7 @@ pub fn configure() -> ApplicationBuilder { .api(http::api::routes) .routes(|route| { route.post("/webhooks/stripe", billing::webhook::handle); + route.get("/status", http::status::status); }) .health("/up"); }) diff --git a/app/tests/groups.rs b/app/tests/groups.rs new file mode 100644 index 00000000..14897237 --- /dev/null +++ b/app/tests/groups.rs @@ -0,0 +1,38 @@ +//! A build reads a group only from an earlier build of its own project (`groups::holders`). Retention and the demo +//! reset delete one project's builds and group rows together, which is safe only because no other project reads them. + +use std::collections::BTreeMap; + +use app::domain::build_settings::BuildSettings; +use app::domain::builds::{self, CreateParams}; +use app::domain::groups::{self, Candidate}; +use app::domain::snapshots::{self, SnapshotParams}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn a_group_is_read_only_from_a_build_of_its_own_project(_app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let mine = fixtures::project(&org, "docs").await?; + let theirs = fixtures::project(&org, "other").await?; + let params: CreateParams = + serde_json::from_value(serde_json::json!({ "commit": "a".repeat(40), "branch": "main" }))?; + let holder = builds::create(&mine, ¶ms, None).await.map_err(|e| laravel::Error::msg(format!("{e:?}")))?; + let snapshot: SnapshotParams = serde_json::from_value(serde_json::json!({ + "name": "suite/home", "kind": "text", "fingerprint": "c".repeat(64), "sha256": "d".repeat(64), "size": 2, + "content_type": "text/plain", + }))?; + let settings = BuildSettings::new(&mine, &holder); + let row = snapshots::register(&holder, &settings, "1", &snapshot).await?.expect("registered").snapshot; + let id = row.id; + db::query!("UPDATE snapshots SET state = 'unchanged' WHERE id = {id}").update().await?; + + let candidates: BTreeMap = + [(row.group_key.clone(), Candidate { base_ids: vec![row.id], hash: "h".into() })].into_iter().collect(); + let found = groups::holders(mine.id, &candidates).await?; + assert_eq!(found.get(&row.group_key), Some(&holder.id), "its own project's build holds it"); + let found = groups::holders(theirs.id, &candidates).await?; + assert!(found.is_empty(), "another project's build never holds a group: {found:?}"); + Ok(()) +} diff --git a/app/tests/processing.rs b/app/tests/processing.rs new file mode 100644 index 00000000..37857da5 --- /dev/null +++ b/app/tests/processing.rs @@ -0,0 +1,246 @@ +//! Processing builds end to end through the CI API, against the blob store (RustFS in CI): baselines, comparisons, +//! page rows only for changes, and unchanged groups read from the build that holds them (docs/design-storage.md). + +use app::models::{Build, Snapshot, SnapshotPage}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +async fn project_token() -> laravel::Result { + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(token) +} + +fn png(rgb: [u8; 3]) -> Vec { + let image = image::RgbaImage::from_pixel(16, 16, image::Rgba([rgb[0], rgb[1], rgb[2], 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).expect("a PNG encodes"); + bytes +} + +/// Send one build of these screenshots on commit `commit` (its parent `parent`), uploading new files, and finalize it. +async fn run(app: &Application, token: &str, commit: &str, parent: &str, shots: &[(&str, [u8; 3])]) -> Value { + let id = send(app, token, commit, parent, shots).await; + finalize(app, token, &id).await +} + +async fn finalize(app: &Application, token: &str, id: &str) -> Value { + let done = + app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", format!("Bearer {token}")).await; + done.assert_ok(); + done.json().clone() +} + +/// Create a build and send these screenshots (uploading new files), without finalizing it. Returns its id. +async fn send(app: &Application, token: &str, commit: &str, parent: &str, shots: &[(&str, [u8; 3])]) -> String { + let auth = format!("Bearer {token}"); + let build = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": commit, "branch": "main", "parent_commits": [parent] })) + .await; + build.assert_ok(); + let id = build.json()["id"].as_str().unwrap().to_string(); + let mut files = Vec::new(); + let mut snapshots = Vec::new(); + for (name, rgb) in shots { + let bytes = png(*rgb); + let sha = visualci_core::sha256_hex(&bytes); + let image = image::load_from_memory(&bytes).unwrap().to_rgba8(); + snapshots.push(json!({ + "name": name, "kind": "image", "fingerprint": visualci_core::image_hash::fingerprint_rgba(&image), + "sha256": sha, "size": bytes.len(), "content_type": "image/png" + })); + files.push(bytes); + } + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": snapshots })) + .await; + registered.assert_ok(); + let client = reqwest::Client::new(); + for (answer, bytes) in registered.json()["snapshots"].as_array().unwrap().iter().zip(files) { + if let Some(url) = answer["upload_url"].as_str() { + let put = client.put(url).header("content-type", "image/png").body(bytes).send().await.expect("an upload"); + assert!(put.status().is_success(), "uploading: {}", put.status()); + } + } + id +} + +async fn states(number: i32) -> laravel::Result> { + let build = Build::query().filter(Build::number.eq(number)).first().await?.expect("the build"); + let all = app::domain::snapshots::of_build(build.id).await?; + for s in &all { + if let Some(e) = &s.error { + eprintln!("{}: {e}", s.name); + } + } + Ok(all.into_iter().map(|s| (s.name, s.state, s.sourced)).collect()) +} + +#[laravel::test] +async fn builds_compare_with_their_baselines_and_read_unchanged_groups_from_the_build_that_holds_them( + app: Application, +) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let (red, green) = ([255, 0, 0], [0, 200, 0]); + + // #1: the first build adds both screenshots and is approved on its own. + let first = run(&app, &token, "c1", "c0", &[("home/hero/desktop.png", red), ("about/team/desktop.png", red)]).await; + let errors: Vec<(String, Option)> = + Snapshot::query().get().await?.into_iter().map(|s| (s.name, s.error)).collect(); + assert_eq!( + (first["state"].as_str(), first["review_state"].as_str()), + (Some("completed"), Some("auto_approved")), + "{first} {errors:?}" + ); + assert_eq!( + states(1).await?, + vec![ + ("about/team/desktop.png".into(), "added".into(), false), + ("home/hero/desktop.png".into(), "added".into(), false) + ] + ); + + // #2: nothing changed. Its groups are read from #1: it holds no snapshot rows of its own, and no page rows. + let second = + run(&app, &token, "c2", "c1", &[("home/hero/desktop.png", red), ("about/team/desktop.png", red)]).await; + assert_eq!(second["conclusion"], "unchanged"); + assert_eq!(second["stats"]["unchanged"], 2); + assert_eq!( + states(2).await?, + vec![ + ("about/team/desktop.png".into(), "unchanged".into(), true), + ("home/hero/desktop.png".into(), "unchanged".into(), true) + ] + ); + let two = Build::query().filter(Build::number.eq(2)).first().await?.unwrap(); + assert_eq!(Snapshot::query().filter(Snapshot::build_id.eq(two.id)).count().await?, 0, "no rows of its own"); + + // #3: the hero changed. Its group holds its own row (changed, with page rows and a diff); the other group is read + // from #1, which still holds it. + let third = + run(&app, &token, "c3", "c2", &[("home/hero/desktop.png", green), ("about/team/desktop.png", red)]).await; + assert_eq!(third["conclusion"], "changes"); + assert_eq!(third["review_state"], "pending"); + assert_eq!( + states(3).await?, + vec![ + ("about/team/desktop.png".into(), "unchanged".into(), true), + ("home/hero/desktop.png".into(), "changed".into(), false) + ] + ); + let hero = Snapshot::query() + .filter(Snapshot::name.eq("home/hero/desktop.png") & Snapshot::state.eq("changed")) + .first() + .await? + .unwrap(); + let pages = SnapshotPage::query().filter(SnapshotPage::snapshot_id.eq(hero.id)).get().await?; + assert_eq!(pages.len(), 1); + assert_eq!((pages[0].state.as_str(), pages[0].diff_id.is_some()), ("changed", true)); + Ok(()) +} + +async fn charges(number: i32) -> laravel::Result> { + let build = Build::query().filter(Build::number.eq(number)).first().await?.expect("the build"); + let id = build.id; + let rows = db::query!("SELECT amount FROM credit_transactions WHERE build_id = {id} ORDER BY id").select().await?; + Ok(rows.iter().map(|r| r.try_get::("amount").unwrap()).collect()) +} + +#[laravel::test] +async fn finalizing_twice_processes_and_charges_once(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let id = send(&app, &token, "c1", "c0", &[("home/hero/desktop.png", [255, 0, 0])]).await; + let first = finalize(&app, &token, &id).await; + let again = finalize(&app, &token, &id).await; + assert_eq!((first["state"].as_str(), again["state"].as_str()), (Some("completed"), Some("completed"))); + assert_eq!(charges(1).await?, vec![-1], "one snapshot check, charged once"); + Ok(()) +} + +#[laravel::test] +async fn shards_finalizing_at_once_process_the_build_once(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let id = send(&app, &token, "c1", "c0", &[("home/hero/desktop.png", [255, 0, 0])]).await; + let (a, b) = tokio::join!(finalize(&app, &token, &id), finalize(&app, &token, &id)); + assert_eq!((a["state"].as_str(), b["state"].as_str()), (Some("completed"), Some("completed"))); + assert_eq!(charges(1).await?, vec![-1]); + assert_eq!(states(1).await?, vec![("home/hero/desktop.png".into(), "added".into(), false)]); + Ok(()) +} + +#[laravel::test] +async fn an_organization_out_of_credits_gets_a_failed_build_that_says_why(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let org: i64 = db::query!("SELECT organization_id FROM projects LIMIT 1").scalar().await?.unwrap(); + db::query!( + "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind) VALUES ({org}, -25000, 0, 'build')" + ) + .insert() + .await?; + let id = send(&app, &token, "c1", "c0", &[("home/hero/desktop.png", [255, 0, 0])]).await; + let done = finalize(&app, &token, &id).await; + assert_eq!(done["state"], "failed"); + let error = done["error"].as_str().unwrap(); + assert!(error.contains("has used this month's 25,000 credits on the Free plan"), "{error}"); + Ok(()) +} + +#[laravel::test] +async fn a_build_whose_manifest_matches_writes_no_snapshots_and_is_charged_one_group_check( + app: Application, +) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + run(&app, &token, "c1", "c0", &[("home/hero/desktop.png", [255, 0, 0]), ("about/team/desktop.png", [0, 0, 255])]) + .await; + // The client hashes the same entries the server does. + let one = Build::query().filter(Build::number.eq(1)).first().await?.unwrap(); + let entries: Vec = + app::domain::snapshots::of_build(one.id).await?.iter().map(app::domain::groups::entry_of).collect(); + let grouping = app::domain::groups::grouping(None); + let groups: Vec = visualci_core::manifest::groups(&entries, grouping) + .into_iter() + .map(|g| json!({ "key": g.key, "hash": g.hash, "count": g.count })) + .collect(); + let auth = format!("Bearer {token}"); + let build = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": "c2", "branch": "main", "parent_commits": ["c1"] })) + .await + .json() + .clone(); + let id = build["id"].as_str().unwrap().to_string(); + let checked = app + .post(format!("/api/v1/builds/{id}/groups")) + .header("authorization", &auth) + .json(json!({ "manifest_hash": visualci_core::manifest::manifest_hash(&entries), "groups": groups })) + .await; + checked.assert_ok(); + assert_eq!(checked.json()["same_as_build"], 1); + let done = finalize(&app, &token, &id).await; + assert_eq!((done["state"].as_str(), done["conclusion"].as_str()), (Some("completed"), Some("unchanged"))); + let two = Build::query().filter(Build::number.eq(2)).first().await?.unwrap(); + assert_eq!(Snapshot::query().filter(Snapshot::build_id.eq(two.id)).count().await?, 0, "no rows written"); + assert_eq!(states(2).await?.len(), 2); + assert_eq!(charges(2).await?, vec![-1], "one credit: the manifest's group check"); + Ok(()) +} diff --git a/app/tests/sweep.rs b/app/tests/sweep.rs new file mode 100644 index 00000000..5d568341 --- /dev/null +++ b/app/tests/sweep.rs @@ -0,0 +1,79 @@ +//! The builds sweep (every five minutes): abandoned builds expire, idle local builds close, builds that stopped +//! progressing run again, and builds stuck for hours fail. `/status` reports how far behind the background work is. + +use app::domain::builds::{self, CreateParams}; +use app::domain::processing::{self, ABANDONED, LOCAL_IDLE, STUCK}; +use app::models::Build; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; + +async fn build(project: &app::models::Project, commit: &str, mode: &str) -> laravel::Result { + let params: CreateParams = + serde_json::from_value(serde_json::json!({ "commit": commit, "branch": "main", "mode": mode }))?; + let build = builds::create(project, ¶ms, None).await.map_err(|e| laravel::Error::msg(format!("{e:?}")))?; + Ok(build.id) +} + +#[laravel::test] +async fn the_sweep_expires_closes_restarts_and_gives_up(app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let project = fixtures::project(&org, "docs").await?; + let abandoned = build(&project, "a1", "ci").await?; + let idle_local = build(&project, "a2", "local").await?; + let stuck = build(&project, "a3", "ci").await?; + let slow = build(&project, "a4", "ci").await?; + let fresh = build(&project, "a5", "ci").await?; + db::query!( + "UPDATE builds SET updated_at = now() - interval '2 hours', created_at = now() - interval '2 hours' \ + WHERE id = {abandoned}" + ) + .update() + .await?; + db::query!( + "UPDATE builds SET state = 'completed', review_state = 'pending', updated_at = now() - interval '8 days', \ + created_at = now() - interval '8 days' WHERE id = {idle_local}" + ) + .update() + .await?; + db::query!( + "UPDATE builds SET state = 'processing', finalized_at = now() - interval '7 hours', \ + updated_at = now() - interval '7 hours' WHERE id = {stuck}" + ) + .update() + .await?; + db::query!( + "UPDATE builds SET state = 'processing', finalized_at = now() - interval '20 minutes', \ + updated_at = now() - interval '20 minutes' WHERE id = {slow}" + ) + .update() + .await?; + + let status = app.get("/status").await; + status.assert_ok(); + let status = status.json().clone(); + assert!(status["oldest_processing_seconds"].as_i64().unwrap() >= 7 * 3600, "{status}"); + assert!(status["oldest_receiving_seconds"].as_i64().unwrap() >= 2 * 3600, "{status}"); + assert_eq!(status["builds_processing"], 2); + + let swept = processing::sweep().await?; + assert_eq!(swept.expired, 1); + assert_eq!(swept.idle_local_closed, 1); + assert_eq!(swept.stuck_failed, 1); + assert_eq!(swept.restarted, 1, "{swept:?}"); + + let b = Build::find_or_fail(abandoned).await?; + assert_eq!((b.state.as_str(), b.error.as_deref()), ("failed", Some(ABANDONED))); + let b = Build::find_or_fail(idle_local).await?; + assert_eq!(b.review_state, "closed"); + assert_eq!(b.warnings, serde_json::json!([LOCAL_IDLE])); + let b = Build::find_or_fail(stuck).await?; + assert_eq!((b.state.as_str(), b.error.as_deref()), ("failed", Some(STUCK))); + // Run again (the test queue runs it at once): an empty build concludes. + assert_ne!(Build::find_or_fail(slow).await?.state, "processing"); + assert_eq!(Build::find_or_fail(fresh).await?.state, "receiving", "a build still arriving is left alone"); + + let again = processing::sweep().await?; + assert_eq!(again, processing::Swept::default(), "a second sweep finds nothing"); + Ok(()) +}