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
8 changes: 4 additions & 4 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ resolver = "3"
members = ["crates/*", "app"]

[workspace.package]
version = "0.2.29"
version = "0.2.30"
edition = "2024"
license = "Apache-2.0"
repository = "https://github.com/DocSpring/visualci"
Expand Down
48 changes: 48 additions & 0 deletions app/database/migrations/2026_12_14_000000_gallery_versions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//! Gallery versions (sc-9563): a project that reports a release (`visualci release v2.0.0`) keeps what its gallery
//! published at that commit, for good, at its own URLs (`/g/<org>/<project>@<key>.json`). A version's rows never
//! change once recorded, except that a thumbnail made after it is filled in. Its screenshots and thumbnails are blobs
//! these rows keep: retention and project deletion leave a blob a row names alone.

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.query(SCHEMA).unprepared().await?;
Ok(())
}

const SCHEMA: &str = r"
SET LOCAL lock_timeout = '5s';
CREATE TABLE gallery_versions (
id bigserial PRIMARY KEY,
project_id bigint NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
key text NOT NULL,
label text NOT NULL,
commit_sha text NOT NULL,
released_at timestamp with time zone NOT NULL,
groups jsonb NOT NULL,
created_at timestamp with time zone NOT NULL DEFAULT now(),
UNIQUE (project_id, key)
);
CREATE TABLE gallery_version_items (
version_id bigint NOT NULL REFERENCES gallery_versions(id) ON DELETE CASCADE,
position integer NOT NULL,
group_name text NOT NULL,
name text NOT NULL,
platform text NOT NULL,
path text NOT NULL,
sha256 text NOT NULL,
content_type text NOT NULL,
width integer,
height integer,
bytes bigint NOT NULL,
since text NOT NULL,
thumb_wanted boolean NOT NULL,
thumb_sha256 text,
thumb_width integer,
thumb_height integer,
thumb_bytes bigint,
PRIMARY KEY (version_id, path)
);
CREATE INDEX gallery_version_items_sha256 ON gallery_version_items (sha256);
CREATE INDEX gallery_version_items_thumb_sha256 ON gallery_version_items (thumb_sha256);
";
34 changes: 29 additions & 5 deletions app/src/domain/baselines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,28 @@ pub async fn resolve(
build: &Build,
project: &Project,
) -> laravel::Result<(HashMap<(String, String), Resolved>, Option<Build>)> {
let anchor = anchor(build, project).await?;
resolve_inner(build, project, false).await
}

/// [`resolve`] as at the build's commit, for a gallery version (`domain::gallery_versions`): only what was approved at
/// that commit or its ancestors counts. No anchor beyond its history, and no approval just for being on the same
/// branch (a later commit's).
///
/// # Errors
/// On a database error.
pub async fn resolve_at_commit(
build: &Build,
project: &Project,
) -> laravel::Result<(HashMap<(String, String), Resolved>, Option<Build>)> {
resolve_inner(build, project, true).await
}

async fn resolve_inner(
build: &Build,
project: &Project,
at_commit: bool,
) -> laravel::Result<(HashMap<(String, String), Resolved>, Option<Build>)> {
let anchor = if at_commit { nearest_approved(build).await? } else { anchor(build, project).await? };
let from_anchor = match &anchor {
Some(a) => effective(a, build, project).await?,
None => HashMap::new(),
Expand All @@ -295,14 +316,17 @@ pub async fn resolve(
// own branch; on the base branch (and the default branch when the anchor came from it) only CI approvals count for
// other branches.
let trusted = trusted_branches(build, project, anchor.as_ref());
let (project_id, build_name, id, branch) = (build.project_id, build.name.as_str(), build.id, build.branch.as_str());
let (project_id, build_name, id) = (build.project_id, build.name.as_str(), build.id);
// As at a commit, no row counts for its branch alone.
let branch = build.branch.as_str();
let rows: Vec<Baseline> = db::query!(
"SELECT * FROM baselines WHERE project_id = {project_id} AND build_name = {build_name} AND build_id <> {id} \
AND ( \
(approval <> 'merged' AND (build_id > {after} OR commit_sha IN ({...nearer_or_none})) \
AND ((mode = 'ci' AND commit_sha IN ({...history})) OR branch = {branch})) \
AND ((mode = 'ci' AND commit_sha IN ({...history})) OR (branch = {branch} AND NOT {at_commit}))) \
OR (approval = 'merged' AND commit_sha IN ({...history})) \
OR (environment NOT IN ('', 'ci') AND (branch = {branch} OR (branch IN ({...trusted}) AND mode = 'ci'))) \
OR (environment NOT IN ('', 'ci') AND ((branch = {branch} AND NOT {at_commit}) OR (branch IN ({...trusted}) AND mode = 'ci')) \
AND (NOT {at_commit} OR commit_sha IN ({...history}))) \
) ORDER BY id"
)
.select_as()
Expand All @@ -318,7 +342,7 @@ pub async fn resolve(
// default-branch ones.
let mut latest: HashMap<(String, String, String), Baseline> = HashMap::new();
let newer = |r: &Baseline| r.build_id > after || nearer_set.contains(&r.commit_sha);
let rank = |r: &Baseline| (newer(r) || r.branch == build.branch || merged_and_new(r), r.id);
let rank = |r: &Baseline| (newer(r) || (!at_commit && 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);
Expand Down
7 changes: 6 additions & 1 deletion app/src/domain/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,12 @@ fn server<T>(e: laravel::Error) -> Outcome<T> {

/// Make a build (or, for a nonce that already made one, return that build).
///
/// Whether a string can be a commit: 1 to 64 letters and digits (a commit SHA).
#[must_use]
pub fn id_like(s: &str) -> bool {
(1..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric())
}

/// # Errors
/// `Invalid` for bad parameters; else on a database error.
pub async fn create(project: &Project, params: &CreateParams, creator: Option<i64>) -> Outcome<Build> {
Expand All @@ -136,7 +142,6 @@ pub async fn create(project: &Project, params: &CreateParams, creator: Option<i6
if params.commit.is_empty() || params.branch.is_empty() {
return invalid("commit and branch are required");
}
let id_like = |s: &str| (1..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric());
if !id_like(&params.commit) {
return invalid("commit must be 1 to 64 letters and digits (a commit SHA)");
}
Expand Down
58 changes: 49 additions & 9 deletions app/src/domain/gallery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ fn extension(content_type: &str) -> &'static str {
}

/// A time as today's server wrote it (RFC 3339 in UTC, `+00:00`, with milli- or microseconds when there are any).
fn rfc3339(t: laravel::time::Timestamp) -> String {
pub(crate) fn rfc3339(t: laravel::time::Timestamp) -> String {
let micros = t.subsec_microsecond();
let fraction = if micros == 0 {
String::new()
Expand All @@ -71,8 +71,9 @@ fn rfc3339(t: laravel::time::Timestamp) -> String {
format!("{utc}{fraction}+00:00")
}

/// The newest completed CI build of each suite on the default branch.
async fn newest_builds(project: &Project) -> laravel::Result<Vec<Build>> {
/// The newest completed CI build of each suite on the default branch: of those at one of the `at` commits, when given
/// (a version's commit and its ancestors, newest first).
async fn newest_builds(project: &Project, at: Option<&[String]>) -> laravel::Result<Vec<Build>> {
let (project_id, branch) = (project.id, project.default_branch.clone());
let all: Vec<Build> = db::query!(
"SELECT * FROM builds WHERE project_id = {project_id} AND branch = {branch} AND mode = 'ci' \
Expand All @@ -81,7 +82,17 @@ async fn newest_builds(project: &Project) -> laravel::Result<Vec<Build>> {
.select_as()
.await?;
let mut seen = HashSet::new();
Ok(all.into_iter().filter(|b| seen.insert(b.name.clone())).collect())
let Some(at) = at else { return Ok(all.into_iter().filter(|b| seen.insert(b.name.clone())).collect()) };
// The nearest commit's build of each suite, its newest build there.
let mut out = Vec::new();
for commit in at {
for b in all.iter().filter(|b| &b.commit_sha == commit) {
if seen.insert(b.name.clone()) {
out.push(b.clone());
}
}
}
Ok(out)
}

/// The gallery a build's visualci.yml asks for, if any. A file that no longer validates has none: the public page can't
Expand Down Expand Up @@ -137,7 +148,7 @@ pub async fn published(project: &Project) -> laravel::Result<Published> {
if let Some(p) = hit {
return Ok(p);
}
let computed = compute(project).await?;
let computed = compute(project, None).await?;
if let Ok(mut c) = cache.lock() {
if c.len() > 10_000 {
c.retain(|_, (_, _, at, _)| at.elapsed() < CACHE_FOR);
Expand All @@ -147,28 +158,46 @@ pub async fn published(project: &Project) -> laravel::Result<Published> {
Ok(computed)
}

async fn compute(project: &Project) -> laravel::Result<Published> {
/// What a project's gallery published at a commit (its ancestry, newest first: the commit, then its parents), for a
/// version (`super::gallery_versions`): the same as [`published`], from the default-branch builds at or before it.
///
/// # Errors
/// On a database error.
pub async fn published_at(project: &Project, history: &[String]) -> laravel::Result<Published> {
compute(project, Some(history)).await
}

async fn compute(project: &Project, at: Option<&[String]>) -> laravel::Result<Published> {
let mut out = Published::default();
let mut found = Vec::new();
// A screenshot two suites both publish (CI's and `visualci publish`'s) comes from the newest build's suite.
let mut taken: HashSet<(String, String)> = HashSet::new();
for newest in newest_builds(project).await? {
for newest in newest_builds(project, at).await? {
let Some(gallery) = gallery_of(&newest) else { continue };
for g in &gallery.groups {
if !out.groups.iter().any(|(n, _)| n == &g.name) {
out.groups.push((g.name.clone(), g.title.clone()));
}
}
// What the next build on the default branch would compare with: resolve as a build just after the newest.
// What the next build on the default branch would compare with: resolve as a build just after the newest
// (for a version, one on its commit).
let mut next = newest.clone();
next.id = i64::MAX;
next.parent_commits =
Json(std::iter::once(newest.commit_sha.clone()).chain(newest.parent_commits.iter().cloned()).collect());
if let Some((commit, parents)) = at.and_then(<[String]>::split_first) {
next.commit_sha.clone_from(commit);
next.parent_commits = Json(parents.to_vec());
}
// The gallery's environment (`ci` unless visualci.yml names another, such as a laptop's): only its own
// screenshots, never another environment's a lookup falls back to.
let environment = gallery.environment().to_string();
next.environment.clone_from(&environment);
let (resolved, _) = super::baselines::resolve(&next, project).await?;
let (resolved, _) = if at.is_some() {
super::baselines::resolve_at_commit(&next, project).await?
} else {
super::baselines::resolve(&next, project).await?
};
for ((name, _), r) in resolved {
if r.snapshot.kind != "image" || r.snapshot.environment != environment {
continue;
Expand Down Expand Up @@ -401,10 +430,21 @@ pub async fn public_list(app_url: &str, org: &str, project: &Project) -> laravel
})
})
.collect();
let versions: Vec<serde_json::Value> = super::gallery_versions::list(project.id)
.await?
.iter()
.map(|v| {
serde_json::json!({
"key": v.key, "label": v.label, "commit": v.commit_sha, "released_at": v.released_at,
"manifest": manifest_url(app_url, org, &format!("{}@{}", project.slug, v.key)),
})
})
.collect();
Ok(serde_json::json!({
"enabled": project.gallery_enabled,
"manifest_url": (!items.is_empty()).then(|| manifest_url(app_url, org, &project.slug)),
"items": items,
"versions": versions,
}))
}

Expand Down
Loading
Loading