Skip to content
Open
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
1 change: 1 addition & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ hmac = "0.12"
jsonwebtoken = "9"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# Names the field at fault when a visualci.yml doesn't parse (build_settings::parse_config)
serde_path_to_error = "0.1"
sha2 = "0.10"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
Expand Down
103 changes: 94 additions & 9 deletions app/src/domain/build_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,100 @@ fn strictness(mode: &str) -> usize {
MODES.iter().position(|m| *m == mode).unwrap_or(0)
}

/// `error_code` of a build that failed because its stored `visualci.yml` no longer validates.
pub const CONFIG_INVALID: &str = "config_invalid";

/// A build's stored `visualci.yml` that no longer validates: one an earlier version accepted that a later, stricter
/// one refuses, or one a parsing bug refuses. The build's settings can't be known, so nothing falls back to the
/// project's quietly: processing fails the build with this message, early comparisons and uploads refuse with it, and
/// pages that show an already-compared build add it to the build's warnings ([`warnings_of`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConfigInvalid {
/// The parser's message, naming the field: `threshold: a threshold is a number, not "x"`.
pub reason: String,
}

impl std::fmt::Display for ConfigInvalid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "visualci.yml no longer validates: {}; send the build again", self.reason)
}
}

impl std::error::Error for ConfigInvalid {}

/// Parse a `visualci.yml` sent as JSON, with a message that names the field at fault (`threshold: …`,
/// `pdf.dpi: …`). Creation and every later read of a stored config use this, so they agree.
///
/// # Errors
/// The first problem, prefixed with the path to the field when it's not the top level.
pub fn parse_config(value: &serde_json::Value) -> Result<Config, String> {
let config: Config = serde_path_to_error::deserialize(value.clone()).map_err(|e| {
let path = e.path().to_string();
let inner = e.into_inner();
if path == "." { inner.to_string() } else { format!("{path}: {inner}") }
})?;
config.validate()?;
Ok(config)
}

/// A build's stored `visualci.yml`, parsed: `Ok(None)` when it was sent none.
///
/// # Errors
/// When the stored file no longer validates.
pub fn stored_config(build: &Build) -> Result<Option<Config>, ConfigInvalid> {
match &build.config {
Some(v) if !v.is_null() => parse_config(v).map(Some).map_err(|reason| ConfigInvalid { reason }),
_ => Ok(None),
}
}

/// The warnings to show with a build: the ones stored when it was created and processed, and, when its stored
/// `visualci.yml` no longer validates and the build didn't already fail for it, that problem first. Used by every view
/// of a build (the API and MCP answers, the build's page, its check), so a build compared before its file stopped
/// validating says so wherever it's read.
#[must_use]
pub fn warnings_of(build: &Build) -> Vec<String> {
let mut out: Vec<String> = serde_json::from_value(build.warnings.clone()).unwrap_or_default();
if build.error_code.as_deref() != Some(CONFIG_INVALID)
&& let Err(e) = stored_config(build)
{
out.insert(
0,
format!(
"visualci.yml no longer validates: {}. This build was compared before the file stopped validating, \
and is now shown with the project's settings; send the build again to compare it with a valid file.",
e.reason
),
);
}
out
}

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()
});
/// The settings a build runs with. Every path that compares, registers or uploads uses this and refuses (or fails
/// the build) on the error.
///
/// # Errors
/// When the build's stored `visualci.yml` no longer validates.
pub fn new(project: &'a Project, build: &Build) -> Result<Self, ConfigInvalid> {
Ok(Self::with_config(project, stored_config(build)?))
}

/// The settings for showing a build that has already been compared or has failed: its own, or when its stored
/// `visualci.yml` no longer validates, the project's. That case is never silent: [`warnings_of`] adds the problem to
/// the build's warnings in every view, and a build processed since fails with it. Never use this to compare.
#[must_use]
pub fn shown(project: &'a Project, build: &Build) -> Self {
Self::with_config(project, stored_config(build).unwrap_or(None))
}

/// The project's settings alone, as for a build sent without a `visualci.yml`.
#[must_use]
pub fn of_project(project: &'a Project) -> Self {
Self::with_config(project, None)
}

fn with_config(project: &'a Project, config: Option<Config>) -> Self {
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)),
Expand Down Expand Up @@ -251,7 +336,7 @@ impl<'a> BuildSettings<'a> {
/// # 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}"))?;
let config = parse_config(value).map_err(|e| format!("visualci.yml: {e}"))?;
serde_json::to_value(config).map_err(|e| format!("visualci.yml: {e}"))
}

Expand Down
6 changes: 5 additions & 1 deletion app/src/domain/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,11 @@ pub async fn create(project: &Project, params: &CreateParams, creator: Option<i6
}
// Warnings the CLI prints when the build is created: a ci_mode the file can't loosen, a build from another
// repository than the project's.
let mut warnings = BuildSettings::new(project, &build).config_warnings();
// The file was validated above, so it parses; were it not to, the build says so rather than drop it.
let mut warnings = match BuildSettings::new(project, &build) {
Ok(settings) => settings.config_warnings(),
Err(invalid) => vec![invalid.to_string()],
};
if let Some(w) = repository_warning(project, &build) {
warnings.push(w);
}
Expand Down
2 changes: 1 addition & 1 deletion app/src/domain/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ impl Seeder<'_> {
Err(Err(e)) => Err(e),
};
let build = outcome(super::builds::create(project, &params, None).await)?;
let settings = BuildSettings::new(project, &build);
let settings = BuildSettings::new(project, &build).map_err(error)?;
for item in items {
let snapshot = self.snapshot(project, item).await?;
snapshot.validate().map_err(error)?;
Expand Down
12 changes: 9 additions & 3 deletions app/src/domain/gallery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
use std::collections::{BTreeMap, HashMap, HashSet};

use laravel::db::{self, Json};
use visualci_core::config::{Config, Gallery};
use visualci_core::config::Gallery;

use crate::models::{Blob, Build, Organization, Project};

Expand Down Expand Up @@ -79,9 +79,15 @@ async fn newest_builds(project: &Project) -> laravel::Result<Vec<Build>> {
Ok(all.into_iter().filter(|b| seen.insert(b.name.clone())).collect())
}

/// The gallery a build's visualci.yml asks for, if any.
/// The gallery a build's visualci.yml asks for, if any. A file that no longer validates has none: the public page can't
/// show why, so it's logged as an error, and the build's warnings say so to its members
/// ([`super::build_settings::warnings_of`]).
fn gallery_of(build: &Build) -> Option<Gallery> {
build.config.as_ref().and_then(|c| Config::from_json(c).ok()).and_then(|c| c.gallery)
super::build_settings::stored_config(build)
.inspect_err(|e| tracing::error!(build = build.id, error = %e, "no gallery: the stored visualci.yml no longer validates"))
.ok()
.flatten()
.and_then(|c| c.gallery)
}

/// How long a computed gallery is reused when nothing it depends on changed.
Expand Down
3 changes: 2 additions & 1 deletion app/src/domain/pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ async fn normalized_text(
slot.insert((build, project));
}
let (build, project) = &settings_of[&snapshot.build_id];
let rules = BuildSettings::new(project, build).compiled_rules(snapshot);
// Shown, not compared again: a file that no longer validates is in the build's warnings.
let rules = BuildSettings::shown(project, build).compiled_rules(snapshot);
Ok(visualci_core::snapshot_text::normalize(format, &raw, &rules).text)
}
48 changes: 44 additions & 4 deletions app/src/domain/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use laravel::model::update;
use visualci_core::manifest::{self, Entry};

use super::baselines::{self, Resolved};
use super::build_settings::{BuildSettings, Source};
use super::build_settings::{BuildSettings, CONFIG_INVALID, ConfigInvalid, 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,
Expand Down Expand Up @@ -232,6 +232,28 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la
Ok(())
}

/// Fail a processing build whose stored `visualci.yml` no longer validates, rather than compare it with settings it
/// wasn't sent: its `error` names the field and the problem (shown by get_build, its page and its check's title), and
/// its queued renders that nothing else waits on are dropped.
///
/// # Errors
/// On a database error.
async fn fail_for_config(mut build: Build, invalid: &ConfigInvalid) -> laravel::Result<()> {
tracing::warn!(build = build.id, reason = %invalid.reason, "stored visualci.yml no longer validates; failing the build");
let error = Some(invalid.to_string());
let completed_at = Some(laravel::now().timestamp());
update!(build {
state: "failed",
conclusion: Some("failed".to_string()),
review_state: "none",
error_code: Some(CONFIG_INVALID.to_string()),
error,
completed_at,
})
.await?;
drop_unneeded_renders(build.id).await
}

/// 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) = Project::find(project_id).await? {
Expand Down Expand Up @@ -413,7 +435,13 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
return Ok(build.state == "completed");
}
let project = Project::find_or_fail(build.project_id).await?;
let settings = BuildSettings::new(&project, &build);
let settings = match BuildSettings::new(&project, &build) {
Ok(s) => s,
Err(invalid) => {
fail_for_config(build, &invalid).await?;
return Ok(true);
}
};
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?;
Expand Down Expand Up @@ -588,7 +616,16 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
// 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);
// A base whose own file no longer validates can't say what it hid: compare with the project's settings, and
// say so in the build's warnings.
let base_settings = BuildSettings::new(&project, &base).unwrap_or_else(|invalid| {
warnings.push(format!(
"Build #{}'s visualci.yml, which this build's settings are compared with, no longer validates ({}), \
so they were compared with the project's settings instead.",
base.number, invalid.reason
));
BuildSettings::of_project(&project)
});
if settings.hides_more_than(&base_settings) {
let base_item = Snapshot::query()
.filter(Snapshot::build_id.eq(base.id) & Snapshot::platform.eq(CONFIG_PLATFORM))
Expand Down Expand Up @@ -1038,7 +1075,10 @@ pub async fn compare_now(
)));
}
}
let settings = BuildSettings::new(&project, build);
let settings = match BuildSettings::new(&project, build) {
Ok(s) => s,
Err(invalid) => return Ok(Err(invalid.to_string())),
};
let mut snapshots: Vec<Snapshot> = super::snapshots::of_build(build.id)
.await?
.into_iter()
Expand Down
13 changes: 11 additions & 2 deletions app/src/forge/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use laravel::queue::{Attempt, Queueable, job};

use super::report::{self, Check, RateLimited};
use crate::domain::build_settings::BuildSettings;
use crate::domain::build_settings::{self, BuildSettings};
use crate::domain::builds::stats;
use crate::models::{Build, Organization, Project};

Expand Down Expand Up @@ -57,7 +57,7 @@ pub fn check_state(build: &Build, project: &Project, superseded_by: Option<i32>)
// Its pull request was closed without merging, or its branch deleted
("completed", _, "closed") => done("neutral", "Closed without review".to_string()),
("completed", _, _) if build.mode == "local" => done("neutral", format!("{changes} changes (local run)")),
("completed", _, _) if BuildSettings::new(project, build).ci_mode() == "strict" => {
("completed", _, _) if BuildSettings::shown(project, build).ci_mode() == "strict" => {
done("failure", format!("{changes} changes to review"))
}
("completed", _, _) => ("in_progress".to_string(), None, format!("{changes} changes waiting for review")),
Expand Down Expand Up @@ -96,6 +96,15 @@ pub async fn check_for(build: &Build, project: &Project, org: &Organization) ->
if let Some(line) = crate::domain::summary::summary_line(build).await? {
summary = format!("{line}\n\n{summary}");
}
// Why it failed as a whole, in full (the title has its first clause), and what to point out about its settings
if build.state == "failed"
&& let Some(error) = &build.error
{
summary.push_str(&format!("\n\n**Error:** {error}"));
}
for warning in build_settings::warnings_of(build) {
summary.push_str(&format!("\n\n**Warning:** {warning}"));
}
if status == "in_progress" && build.state == "completed" {
summary = format!("{summary}\n\n{}", review_hint(&org.slug, &project.slug, build.number));
}
Expand Down
6 changes: 3 additions & 3 deletions app/src/http/api/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub struct BuildResponse {
impl BuildResponse {
#[must_use]
pub fn new(build: &Build, project: &Project, organization: &Organization) -> Self {
let settings = BuildSettings::new(project, build);
let settings = BuildSettings::shown(project, build);
Self {
id: build.pid,
number: build.number,
Expand All @@ -76,7 +76,7 @@ impl BuildResponse {
stats: domain::stats(build),
error: build.error.clone(),
url: format!("{}/{}/{}/builds/{}", app_url(), organization.slug, project.slug, build.number),
warnings: serde_json::from_value(build.warnings.clone()).unwrap_or_default(),
warnings: crate::domain::build_settings::warnings_of(build),
reviewable: domain::reviewable(build),
blocked: None,
}
Expand Down Expand Up @@ -208,7 +208,7 @@ pub async fn add_snapshots(
build.number, build.state
)));
}
let settings = BuildSettings::new(&project, &build);
let settings = BuildSettings::new(&project, &build).map_err(|e| ApiError::bad_request(e.to_string()))?;
let version = renderer_version();
// Every snapshot is checked before any is written.
for p in &params.snapshots {
Expand Down
7 changes: 4 additions & 3 deletions app/src/http/ui/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,9 @@ pub async fn show_build(auth: Auth<User>, Params((org, project, number)): Params
}
let mut summary = build_summary(&build, member);
summary["base_build_number"] = json!(base_number);
summary["ci_mode"] = json!(BuildSettings::new(project, &build).ci_mode());
summary["ci_mode"] = json!(BuildSettings::shown(project, &build).ci_mode());
summary["config"] = json!(build.config);
summary["warnings"] = build.warnings.clone();
summary["warnings"] = json!(domain::build_settings::warnings_of(&build));
summary["error"] = json!(build.error);
// What changed, computed from the comparison.
summary["summary"] = json!(domain::summary::summary_line(&build).await?);
Expand Down Expand Up @@ -238,7 +238,8 @@ pub async fn show_snapshot(
(Some("previous"), Some((b, s))) => Some((b, s)),
_ => None,
};
let settings = BuildSettings::new(project, &build);
// A view of a compared build: a file that no longer validates is in the build's warnings.
let settings = BuildSettings::shown(project, &build);
let shown = match against {
Some((_, earlier)) => {
let options = settings.diff_options(&snapshot);
Expand Down
12 changes: 8 additions & 4 deletions app/src/mcp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1213,8 +1213,8 @@ impl VisualCi {
out["config"] = json!(build.config);
// What changed, computed from the comparison ("invoice: page 1 changed (2 regions); 3 added").
out["summary"] = json!(domain::summary::summary_line(&build).await.map_err(internal)?);
out["warnings"] = build.warnings.clone();
out["ci_mode"] = json!(BuildSettings::new(&project, &build).ci_mode());
out["warnings"] = json!(domain::build_settings::warnings_of(&build));
out["ci_mode"] = json!(BuildSettings::shown(&project, &build).ci_mode());
if paged {
out["groups"] = json!(
groups
Expand Down Expand Up @@ -1326,7 +1326,8 @@ impl VisualCi {
}
let snapshot = need!(Self::find_snapshot(&build, key, &args.platform));
let store = BlobStore::current().await.map_err(internal)?;
let settings = BuildSettings::new(&project, &build);
// A view of a compared build: a file that no longer validates is in the build's warnings.
let settings = BuildSettings::shown(&project, &build);
let earlier = match args.against.as_deref().map(str::trim) {
None | Some("" | "baseline") => None,
Some(other) => {
Expand Down Expand Up @@ -1936,7 +1937,10 @@ impl VisualCi {
return Ok(tool_error(e));
}
}
let settings = BuildSettings::new(&project, &build);
let settings = match BuildSettings::new(&project, &build) {
Ok(s) => s,
Err(e) => return Ok(tool_error(e.to_string())),
};
let version = renderer_version();
let store = BlobStore::current().await.map_err(internal)?;
let mut out = Vec::new();
Expand Down
Loading
Loading