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
3 changes: 3 additions & 0 deletions app/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,14 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
rusty-s3 = "0.12"
globset = "0.4"
tracing = "0.1"
# VisualCI's own crates, shared with the CLI.
visualci-core = { path = "../crates/visualci-core" }
snapshot-diff = { path = "../crates/snapshot-diff" }

[dev-dependencies]
regex = "1"

[profile.dev]
debug = "line-tables-only"
Expand Down
100 changes: 100 additions & 0 deletions app/src/domain/blobs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
//! Blob records: what's stored under each SHA-256, whether its bytes have arrived, and an image's size and pixel
//! fingerprint (cached on first use).

use laravel::db;
use laravel::model::update;

use crate::models::Blob;
use crate::storage::BlobStore;

/// Record a blob a client or renderer is about to upload (or already has). Returns it.
///
/// # Errors
/// On a database error.
pub async fn register(sha256: &str, size: i64, content_type: &str) -> laravel::Result<Blob> {
db::query!(
"INSERT INTO blobs (sha256, size, content_type) VALUES ({sha256}, {size}, {content_type}) \
ON CONFLICT (sha256) DO NOTHING"
)
.insert()
.await?;
Blob::find_or_fail(sha256.to_string()).await
}

#[must_use]
pub fn is_uploaded(blob: &Blob) -> bool {
blob.uploaded_at.is_some()
}

/// Which of these blobs exist (retention deletes old ones).
///
/// # Errors
/// On a database error.
pub async fn existing(shas: &[String]) -> laravel::Result<std::collections::HashSet<String>> {
let mut out = std::collections::HashSet::new();
for chunk in shas.chunks(10_000) {
out.extend(Blob::query().filter(Blob::sha256.is_in(chunk.to_vec())).get().await?.into_iter().map(|b| b.sha256));
}
Ok(out)
}

/// Check the store for blobs not yet confirmed, and mark the ones that arrived with bytes matching their hash (one
/// that doesn't match is deleted, to be uploaded again). Returns the hashes still missing.
///
/// # Errors
/// On a database or storage error.
pub async fn confirm_uploads(store: &BlobStore, hashes: &[String]) -> laravel::Result<Vec<String>> {
let mut missing = Vec::new();
for sha256 in hashes {
let Some(mut blob) = Blob::find(sha256.clone()).await? else {
missing.push(sha256.clone());
continue;
};
if is_uploaded(&blob) {
continue;
}
if let Some(size) = store.verify(sha256).await? {
let uploaded_at = Some(laravel::now().timestamp());
let size = i64::try_from(size).unwrap_or(i64::MAX);
update!(blob { uploaded_at, size }).await?;
} else {
missing.push(sha256.clone());
}
}
Ok(missing)
}

/// Store bytes the server produced itself (diff overlays) and record them.
///
/// # Errors
/// On a database or storage error.
pub async fn put(store: &BlobStore, bytes: Vec<u8>, content_type: &str) -> laravel::Result<Blob> {
let size = i64::try_from(bytes.len()).unwrap_or(i64::MAX);
let sha256 = store.put(bytes, content_type).await?;
let mut blob = register(&sha256, size, content_type).await?;
if !is_uploaded(&blob) {
let uploaded_at = Some(laravel::now().timestamp());
update!(blob { uploaded_at }).await?;
}
Ok(blob)
}

/// The image's pixel fingerprint and size, computed (and cached on the row) on first use.
///
/// # Errors
/// When the blob is missing or isn't an image.
pub async fn image_info(mut blob: Blob, store: &BlobStore) -> laravel::Result<(String, u32, u32)> {
if let (Some(fp), Some(w), Some(h)) = (&blob.pixel_fingerprint, blob.width, blob.height) {
return Ok((fp.clone(), u32::try_from(w).unwrap_or(0), u32::try_from(h).unwrap_or(0)));
}
let bytes = store.get(&blob.sha256).await?;
let image = visualci_core::image_hash::decode(&bytes)
.map_err(|e| laravel::Error::msg(format!("{}: {e}", blob.sha256)))?
.to_rgba8();
let fp = visualci_core::image_hash::fingerprint_rgba(&image);
let (w, h) = image.dimensions();
let pixel_fingerprint = Some(fp.clone());
let (width, height) = (Some(i32::try_from(w).unwrap_or(i32::MAX)), Some(i32::try_from(h).unwrap_or(i32::MAX)));
update!(blob { pixel_fingerprint, width, height }).await?;
Ok((fp, w, h))
}
248 changes: 248 additions & 0 deletions app/src/domain/build_settings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
//! The settings one build runs with: its `visualci.yml` where the file sets a field, the project's settings
//! otherwise, and a snapshot's own overrides (from the test or the upload) on top.
//!
//! The file may change settings, but not quietly loosen review: its `ci_mode` can only tighten the project's, and a
//! file that hides more than its base build's did (new or wider ignore rules, a higher threshold) makes the build
//! show a "visualci.yml" change that has to be approved (see `hides_more_than`).

use globset::GlobMatcher;
use serde::Serialize;
use visualci_core::config::{self, Config, ScopedIgnoreRule, Threshold};
use visualci_core::snapshot_text::{CompiledRules, IgnoreRules};

use crate::models::{Build, Project, Snapshot};

pub struct BuildSettings<'a> {
pub project: &'a Project,
/// The build's `visualci.yml`, when it was sent one.
pub config: Option<Config>,
/// Where the ignore rules come from, and each with its glob compiled once.
source: Source,
rules: Vec<(Option<GlobMatcher>, ScopedIgnoreRule)>,
/// The file's thresholds by glob (one number is the glob `**`).
thresholds: Vec<(GlobMatcher, String, f64)>,
}

/// Where a setting or rule came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Source {
/// The build's `visualci.yml`.
File,
/// Set next to the assertion, in the test (the upload's `ignore`).
Test,
/// The project's settings.
Project,
}

/// An ignore rule that applies to a snapshot, and where it came from.
#[derive(Clone, Debug, Serialize)]
pub struct AppliedRule {
pub source: Source,
/// The rule's glob; `None` for rules set in the test, which apply to that snapshot only.
pub snapshots: Option<String>,
pub json_paths: Vec<String>,
pub text_patterns: Vec<String>,
}

const MODES: &[&str] = &["review", "wait", "strict"];

fn strictness(mode: &str) -> usize {
MODES.iter().position(|m| *m == mode).unwrap_or(0)
}

impl<'a> BuildSettings<'a> {
pub fn new(project: &'a Project, build: &Build) -> Self {
// The config was validated when the build was created; one that no longer parses (a later, stricter version)
// is treated as absent rather than failing the build.
let config = build.config.as_ref().and_then(|v| {
Config::from_json(v)
.inspect_err(|e| tracing::warn!(build = build.id, error = %e, "stored config no longer validates"))
.ok()
});
let (source, scoped) = match config.as_ref().and_then(|c| c.ignore.clone()) {
Some(rules) => (Source::File, rules),
None => (Source::Project, super::projects::ignore_rules(project)),
};
let rules = scoped.into_iter().map(|r| (config::glob(&r.snapshots).ok(), r)).collect();
let thresholds = match config.as_ref().and_then(|c| c.threshold.clone()) {
Some(Threshold::All(t)) => vec![("**".to_string(), t)],
Some(Threshold::ByGlob(map)) => map.into_iter().collect(),
None => vec![],
}
.into_iter()
.filter_map(|(g, t)| config::glob(&g).ok().map(|m| (m, g, t)))
.collect();
Self { project, config, source, rules, thresholds }
}

/// The scoped ignore rules in force: the file's when it has `ignore`, else the project's.
pub fn scoped_rules(&self) -> (Source, Vec<ScopedIgnoreRule>) {
(self.source, self.rules.iter().map(|(_, r)| r.clone()).collect())
}

/// Every ignore rule that applies to a snapshot, with its source.
pub fn applied_rules(&self, snapshot: &Snapshot) -> Vec<AppliedRule> {
let mut out: Vec<AppliedRule> = self
.rules
.iter()
.filter(|(m, _)| m.as_ref().is_some_and(|m| m.is_match(&snapshot.name)))
.map(|(_, r)| AppliedRule {
source: self.source,
snapshots: Some(r.snapshots.clone()),
json_paths: r.json_paths.clone(),
text_patterns: r.text_patterns.clone(),
})
.collect();
let own: IgnoreRules = serde_json::from_value(snapshot.ignore_rules.clone()).unwrap_or_default();
if !own.is_empty() {
out.push(AppliedRule {
source: Source::Test,
snapshots: None,
json_paths: own.json_paths,
text_patterns: own.text_patterns,
});
}
out
}

/// The ignore rules for a snapshot, parsed. They're applied to both sides of the comparison, so a newly ignored
/// value stops showing as a change without approving the baseline again. Each rule is parsed on its own, so a
/// rule that no longer parses is skipped (and logged) without dropping the others.
pub fn compiled_rules(&self, snapshot: &Snapshot) -> CompiledRules {
let mut out = CompiledRules::default();
for r in self.applied_rules(snapshot) {
let rules = IgnoreRules { json_paths: r.json_paths, text_patterns: r.text_patterns };
match rules.compile() {
Ok(c) => out.extend(c),
Err(e) => {
tracing::warn!(snapshot = snapshot.id, rule = ?r.snapshots, error = %e, "skipping an invalid ignore rule")
}
}
}
out
}

/// The file's threshold for a snapshot name: the longest matching glob's.
fn file_threshold(&self, name: &str) -> Option<f64> {
self.thresholds.iter().filter(|(m, _, _)| m.is_match(name)).max_by_key(|(_, g, _)| g.len()).map(|(_, _, t)| *t)
}

/// Diff options for a snapshot: its own threshold, else the file's for its name, else the project's.
pub fn diff_options(&self, snapshot: &Snapshot) -> visualci_core::diff::DiffOptions {
let threshold = snapshot.threshold.or_else(|| self.file_threshold(&snapshot.name));
super::projects::diff_options(self.project, threshold, snapshot.ignore_anti_aliasing)
}

/// The render cache key for a document: the snapshot's engine, else the file's, else the project's, at the file's
/// DPI or the project's.
pub fn renderer_key(&self, engine: Option<&str>, renderer_version: &str) -> String {
let pdf = self.config.as_ref().and_then(|c| c.pdf.as_ref());
let engine = engine
.map(str::to_string)
.or_else(|| pdf.and_then(|p| p.engine).map(|e| e.as_str().to_string()))
.unwrap_or_else(|| self.project.renderer.clone());
let dpi = pdf.and_then(|p| p.dpi).unwrap_or(self.project.dpi);
super::projects::renderer_key(&engine, dpi, renderer_version)
}

/// The CI mode: the file's when it's stricter than the project's (review, then wait, then strict), else the
/// project's. The file can't loosen it.
pub fn ci_mode(&self) -> &str {
match self.config.as_ref().and_then(|c| c.ci_mode) {
Some(m) if strictness(m.as_str()) >= strictness(&self.project.ci_mode) => m.as_str(),
_ => self.project.ci_mode.as_str(),
}
}

/// Warnings about the file that don't stop the build.
pub fn config_warnings(&self) -> Vec<String> {
let mut out = Vec::new();
if let Some(m) = self.config.as_ref().and_then(|c| c.ci_mode)
&& strictness(m.as_str()) < strictness(&self.project.ci_mode)
{
out.push(format!(
"visualci.yml sets ci_mode: {}, but the project's mode is {}. The file can only make the mode \
stricter, so {} applies.",
m.as_str(),
self.project.ci_mode,
self.project.ci_mode
));
}
out
}

/// The scoped ignore rules whose globs matched none of these snapshot names.
pub fn unmatched_rules<'n>(&self, names: impl IntoIterator<Item = &'n str> + Clone) -> Vec<&ScopedIgnoreRule> {
self.rules
.iter()
.filter(|(m, _)| !names.clone().into_iter().any(|n| m.as_ref().is_some_and(|m| m.is_match(n))))
.map(|(_, r)| r)
.collect()
}

/// The settings that decide what counts as a change, as JSON: the ignore rules and thresholds in force. Shown as
/// the "visualci.yml" item when they hide more than the base build's.
pub fn review_settings(&self) -> serde_json::Value {
let threshold: serde_json::Value = if self.thresholds.is_empty() {
serde_json::json!(self.project.threshold)
} else {
self.thresholds
.iter()
.map(|(_, g, t)| (g.clone(), serde_json::json!(t)))
.collect::<serde_json::Map<_, _>>()
.into()
};
serde_json::json!({
"ignore": self.rules.iter().map(|(_, r)| r).collect::<Vec<_>>(),
"ignore_from": self.source,
"threshold": threshold,
})
}

/// Whether these settings could hide a change the base build's settings would show: an ignore rule (glob and path
/// or pattern) the base didn't have, or a higher threshold for some glob.
pub fn hides_more_than(&self, base: &BuildSettings<'_>) -> bool {
let pairs = |s: &BuildSettings<'_>| -> std::collections::HashSet<(String, String)> {
s.rules
.iter()
.flat_map(|(_, r)| {
r.json_paths
.iter()
.map(|p| (r.snapshots.clone(), format!("json:{p}")))
.chain(r.text_patterns.iter().map(|p| (r.snapshots.clone(), format!("text:{p}"))))
.collect::<Vec<_>>()
})
.collect()
};
let base_pairs = pairs(base);
if pairs(self).iter().any(|p| !base_pairs.contains(p)) {
return true;
}
let base_threshold = |glob: &str| {
base.thresholds
.iter()
.find(|(_, g, _)| g == glob)
.or_else(|| base.thresholds.iter().find(|(_, g, _)| g == "**"))
.map_or(base.project.threshold, |(_, _, t)| *t)
};
self.thresholds.iter().any(|(_, g, t)| *t > base_threshold(g) + f64::EPSILON)
}
}

/// Validate a config a client sent with a new build.
///
/// # Errors
/// A message that starts with `visualci.yml:`.
pub fn validate_config(value: &serde_json::Value) -> Result<serde_json::Value, String> {
let config = Config::from_json(value).map_err(|e| format!("visualci.yml: {e}"))?;
serde_json::to_value(config).map_err(|e| format!("visualci.yml: {e}"))
}

/// Validate a test's own ignore rules (unscoped: they apply to the one snapshot).
///
/// # Errors
/// A message naming the invalid path or pattern.
pub fn validate_own_rules(rules: &IgnoreRules) -> Result<(), String> {
rules.compile().map(|_| ())
}
Loading
Loading