Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions app/src/console/mod.rs
Original file line number Diff line number Diff line change
@@ -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(|_| ())
}
478 changes: 478 additions & 0 deletions app/src/domain/baselines.rs

Large diffs are not rendered by default.

346 changes: 346 additions & 0 deletions app/src/domain/compare.rs
Original file line number Diff line number Diff line change
@@ -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<Vec<RenderPage>> {
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<i64>,
) -> 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<i64>) -> 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<RenderPage>| {
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::<Vec<_>>();
let text = |pages: &[RenderPage]| pages.iter().map(|p| p.text.clone()).collect::<Vec<_>>();
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<String> = 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<i64>, Option<String>)> {
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<i32> = 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<String> = 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<i64>,
base: &serde_json::Value,
head: &serde_json::Value,
) -> laravel::Result<Snapshot> {
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)
}
Loading
Loading