diff --git a/Cargo.lock b/Cargo.lock index ddd79d659..5a0089495 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5470,7 +5470,7 @@ dependencies = [ [[package]] name = "visualci-cli" -version = "0.2.29" +version = "0.2.30" dependencies = [ "anyhow", "base64 0.22.1", @@ -5487,7 +5487,7 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.29" +version = "0.2.30" dependencies = [ "globset", "hex", @@ -5507,7 +5507,7 @@ dependencies = [ [[package]] name = "visualci-renderer" -version = "0.2.29" +version = "0.2.30" dependencies = [ "anyhow", "image", @@ -5522,7 +5522,7 @@ dependencies = [ [[package]] name = "visualci-wasm" -version = "0.2.29" +version = "0.2.30" dependencies = [ "image", "serde", diff --git a/Cargo.toml b/Cargo.toml index 4a85f16be..f3c38e155 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/app/database/migrations/2026_12_14_000000_gallery_versions.rs b/app/database/migrations/2026_12_14_000000_gallery_versions.rs new file mode 100644 index 000000000..33d903d28 --- /dev/null +++ b/app/database/migrations/2026_12_14_000000_gallery_versions.rs @@ -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//@.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); +"; diff --git a/app/src/domain/baselines.rs b/app/src/domain/baselines.rs index dcc634bf1..d27071d85 100644 --- a/app/src/domain/baselines.rs +++ b/app/src/domain/baselines.rs @@ -273,7 +273,28 @@ pub async fn resolve( build: &Build, project: &Project, ) -> laravel::Result<(HashMap<(String, String), Resolved>, Option)> { - 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)> { + resolve_inner(build, project, true).await +} + +async fn resolve_inner( + build: &Build, + project: &Project, + at_commit: bool, +) -> laravel::Result<(HashMap<(String, String), Resolved>, Option)> { + 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(), @@ -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 = 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() @@ -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); diff --git a/app/src/domain/builds.rs b/app/src/domain/builds.rs index 042a8beb7..27c4aaa5d 100644 --- a/app/src/domain/builds.rs +++ b/app/src/domain/builds.rs @@ -127,6 +127,12 @@ fn server(e: laravel::Error) -> Outcome { /// 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) -> Outcome { @@ -136,7 +142,6 @@ pub async fn create(project: &Project, params: &CreateParams, creator: Option &'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() @@ -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> { +/// 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> { let (project_id, branch) = (project.id, project.default_branch.clone()); let all: Vec = db::query!( "SELECT * FROM builds WHERE project_id = {project_id} AND branch = {branch} AND mode = 'ci' \ @@ -81,7 +82,17 @@ async fn newest_builds(project: &Project) -> laravel::Result> { .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 @@ -137,7 +148,7 @@ pub async fn published(project: &Project) -> laravel::Result { 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); @@ -147,28 +158,46 @@ pub async fn published(project: &Project) -> laravel::Result { Ok(computed) } -async fn compute(project: &Project) -> laravel::Result { +/// 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 { + compute(project, Some(history)).await +} + +async fn compute(project: &Project, at: Option<&[String]>) -> laravel::Result { 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; @@ -401,10 +430,21 @@ pub async fn public_list(app_url: &str, org: &str, project: &Project) -> laravel }) }) .collect(); + let versions: Vec = 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, })) } diff --git a/app/src/domain/gallery_thumbs.rs b/app/src/domain/gallery_thumbs.rs index 91efac2be..4e66e428f 100644 --- a/app/src/domain/gallery_thumbs.rs +++ b/app/src/domain/gallery_thumbs.rs @@ -101,11 +101,18 @@ pub async fn sync(project: &Project, budget: std::time::Duration) -> laravel::Re let have = gallery::thumbs(project.id).await?; let wanted: HashMap<&str, &gallery::Item> = published.items.iter().filter(|i| i.wants_thumb()).map(|i| (i.sha256.as_str(), i)).collect(); + // Screenshots a version recorded before their thumbnail was made (`gallery_versions`), whether the gallery still + // publishes them or not. + let for_versions: HashSet = super::gallery_versions::thumbs_wanted(project.id).await?.into_iter().collect(); let mut changed: Vec = Vec::new(); let mut out = Synced::default(); let project_id = project.id; - let gone: Vec = have.keys().filter(|sha| !wanted.contains_key(sha.as_str())).cloned().collect(); + let gone: Vec = have + .keys() + .filter(|sha| !wanted.contains_key(sha.as_str()) && !for_versions.contains(sha.as_str())) + .cloned() + .collect(); if !gone.is_empty() { let rows = db::query!( "DELETE FROM gallery_thumbnails WHERE project_id = {project_id} AND source_sha256 IN ({...gone}) \ @@ -122,39 +129,53 @@ pub async fn sync(project: &Project, budget: std::time::Duration) -> laravel::Re let mut missing: Vec<&gallery::Item> = wanted.values().filter(|i| !have.contains_key(&i.sha256)).copied().collect(); // In the gallery's order, so the cards a visitor sees first get theirs first. missing.sort_by(|a, b| a.path.cmp(&b.path)); + let mut versions_missing: Vec<&String> = + for_versions.iter().filter(|sha| !have.contains_key(*sha) && !wanted.contains_key(sha.as_str())).collect(); + versions_missing.sort(); let mut failed: Option = None; - if !missing.is_empty() { + if !missing.is_empty() || !versions_missing.is_empty() { let store = BlobStore::current().await?; let store = &store; - let total = missing.len(); - let mut queue = missing.into_iter().cloned(); + let total = missing.len() + versions_missing.len(); + // The published screenshots first, then the ones only a version keeps. + let mut queue = missing + .into_iter() + .map(|i| (i.sha256.clone(), Some(i.clone()))) + .chain(versions_missing.into_iter().map(|sha| (sha.clone(), None))); let mut running = futures_util::stream::FuturesUnordered::new(); let (mut started, mut recorded) = (0, 0); loop { while running.len() < CONCURRENCY && (started == 0 || std::time::Instant::now() < deadline) { - let Some(item) = queue.next() else { break }; + let Some((sha, item)) = queue.next() else { break }; started += 1; running.push(async move { - let result = make_one(store, project_id, &item).await; - (item, result) + let result = make_one(store, project_id, &sha).await; + (sha, item, result) }); } - let Some((item, result)) = running.next().await else { break }; + let Some((sha, item, result)) = running.next().await else { break }; match result { Ok(true) => { recorded += 1; out.made += 1; - changed.push(item.thumb_path()); + // A published screenshot's thumbnail URL changed; a version's manifest is cached briefly until its + // thumbnails are all in. + if let Some(item) = item { + changed.push(item.thumb_path()); + } } Ok(false) => recorded += 1, Err(e) => { - tracing::warn!(project_id, sha256 = item.sha256, error = %e, "gallery thumbnail failed; tried again later"); + tracing::warn!(project_id, sha256 = sha.as_str(), error = %e, "gallery thumbnail failed; tried again later"); failed.get_or_insert(e); } } } out.more = started < total && recorded > 0; } + if !for_versions.is_empty() { + super::gallery_versions::fill_thumbs(project_id).await?; + } if out.made + out.deleted > 0 { let org = crate::models::Organization::find_or_fail(project.organization_id).await?; @@ -171,9 +192,9 @@ pub async fn sync(project: &Project, budget: std::time::Duration) -> laravel::Re /// Make one screenshot's thumbnail and record it: `true` when one was made, `false` when none can be (recorded, so /// it isn't tried again). -async fn make_one(store: &BlobStore, project_id: i64, item: &gallery::Item) -> laravel::Result { - let bytes = store.get(&item.sha256).await?; - let sha = item.sha256.clone(); +async fn make_one(store: &BlobStore, project_id: i64, sha: &str) -> laravel::Result { + let bytes = store.get(sha).await?; + let sha = sha.to_string(); let permit = DECODES.acquire().await.map_err(|e| laravel::Error::msg(format!("waiting to make a thumbnail: {e}")))?; let made = tokio::task::spawn_blocking(move || { @@ -219,6 +240,7 @@ async fn delete_blobs(shas: Vec) -> laravel::Result<()> { let marked: Vec = db::query!( "UPDATE blobs SET deleting = true, updated_at = now() WHERE sha256 IN ({...shas}) AND NOT deleting \ AND NOT EXISTS (SELECT 1 FROM gallery_thumbnails t WHERE t.thumb_sha256 = blobs.sha256) \ + AND NOT EXISTS (SELECT 1 FROM gallery_version_items v WHERE v.thumb_sha256 = blobs.sha256) \ RETURNING sha256" ) .select() diff --git a/app/src/domain/gallery_versions.rs b/app/src/domain/gallery_versions.rs new file mode 100644 index 000000000..a0e203fed --- /dev/null +++ b/app/src/domain/gallery_versions.rs @@ -0,0 +1,428 @@ +//! Gallery versions (sc-9563): what a project's gallery published at a release, kept for good. A project reports a +//! version only when its setup says so (`visualci release v2.0.0`, or the CI provider's tag); nothing changes for one +//! that doesn't. Each version is served at its own URLs, `/g//@.json` and +//! `/g//@/`, and the main manifest lists the versions, newest first. +//! +//! A version's screenshots, groups and names never change once it's recorded: its rows hold them, and its blobs are +//! kept by retention and project deletion for as long as the rows are. The one thing filled in later is a thumbnail +//! made after it ([`fill_thumbs`]); until then its manifest is cached for a minute, then like the main manifest (it +//! lists every version, so recording one purges it). Its images never change, and are cached for a year. + +use std::collections::HashMap; + +use laravel::db; + +use super::gallery::{self, Item, Published, Thumb}; +use crate::models::Project; + +/// The longest version label. +pub const MAX_LABEL: usize = 64; + +/// A recorded version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Version { + pub id: i64, + pub key: String, + pub label: String, + pub commit_sha: String, + pub released_at: String, +} + +/// A version's key, from its label: lowercase, each run of anything but letters and digits one hyphen, no hyphen at +/// either end (`v1.0.0+build.5` → `v1-0-0-build-5`), so it's a URL segment and the gallery libraries' value key +/// (`^[a-z0-9]+(-[a-z0-9]+)*$`). `None` when that leaves nothing, or `latest`, the libraries' name for the main +/// manifest. +#[must_use] +pub fn key_of(label: &str) -> Option { + let mut key = String::with_capacity(label.len()); + for c in label.chars() { + if c.is_ascii_alphanumeric() { + key.push(c.to_ascii_lowercase()); + } else if !key.is_empty() && !key.ends_with('-') { + key.push('-'); + } + } + while key.ends_with('-') { + key.pop(); + } + (!key.is_empty() && key != "latest").then_some(key) +} + +/// Whether a version label is acceptable: 1 to [`MAX_LABEL`] letters, digits, dots, dashes, pluses and underscores. +#[must_use] +pub fn valid_label(label: &str) -> bool { + !label.is_empty() + && label.len() <= MAX_LABEL + && label.bytes().all(|b| b.is_ascii_alphanumeric() || b".-+_".contains(&b)) +} + +/// Why a version wasn't recorded. +#[derive(Debug, PartialEq, Eq)] +pub enum Refused { + /// The label or its key isn't acceptable. + Invalid(String), + /// The version is already recorded at another commit. + Taken(String), + /// The gallery published nothing at that commit. + Nothing(String), + /// The project has [`MAX_VERSIONS`] already. + Full(String), +} + +/// The most versions a project keeps: a guard against a setup that tags every commit, not a price (support can raise +/// it for a project that needs more). +pub const MAX_VERSIONS: i64 = 500; + +/// A version just recorded (`true`) or recorded before at the same commit (`false`). +pub type Recorded = (Version, bool); + +/// Record a version at a commit (`history`: the commit, then its ancestors, newest first): what the gallery +/// published there, frozen. The same version at the same commit again answers the one recorded; at another commit it's +/// refused, since a version's screenshots never change. +/// +/// # Errors +/// On a database error. +pub async fn record(project: &Project, label: &str, history: &[String]) -> laravel::Result> { + let label = label.trim(); + if !valid_label(label) { + return Ok(Err(Refused::Invalid(format!( + "version must be 1 to {MAX_LABEL} letters, digits, dots, dashes, pluses and underscores (v2.0.0)" + )))); + } + let Some(key) = key_of(label) else { + return Ok(Err(Refused::Invalid(format!( + "{label:?} can't be a version: it needs a letter or digit, and isn't latest" + )))); + }; + let Some(commit) = history.first().cloned() else { + return Ok(Err(Refused::Invalid("commit is required".into()))); + }; + let project_id = project.id; + if let Some(existing) = find(project_id, &key).await? { + return Ok(if existing.commit_sha == commit { Ok((existing, false)) } else { Err(taken(&existing)) }); + } + let count: i64 = db::query!("SELECT count(*) FROM gallery_versions WHERE project_id = {project_id}") + .scalar::() + .await? + .unwrap_or(0); + if count >= MAX_VERSIONS { + return Ok(Err(Refused::Full(format!( + "this project has {count} versions, the most a project keeps ({MAX_VERSIONS}); contact support \ + (support@visualci.com) if you need more" + )))); + } + let published = gallery::published_at(project, history).await?; + if published.items.is_empty() { + return Ok(Err(Refused::Nothing(format!( + "the gallery published nothing at {commit}: it needs an approved default-branch CI build at or before \ + that commit whose visualci.yml has a gallery section" + )))); + } + let groups = serde_json::json!( + published + .groups + .iter() + .map(|(name, title)| serde_json::json!({ "name": name, "title": title })) + .collect::>() + ); + let created = db::transaction(async |_| { + let id: Option = db::query!( + "INSERT INTO gallery_versions (project_id, key, label, commit_sha, released_at, groups) \ + VALUES ({project_id}, {key}, {label}, {commit}, now(), {groups}) \ + ON CONFLICT (project_id, key) DO NOTHING RETURNING id" + ) + .scalar() + .await?; + let Some(id) = id else { return Ok(None) }; + // The thumbnails it copies, held until it commits: a thumbnail sync deleting one meanwhile waits, and then + // finds this version naming its blob, which it leaves alone. + let thumbs = locked_thumbs(project_id).await?; + for (position, item) in published.items.iter().enumerate() { + insert_item(id, i32::try_from(position).unwrap_or(i32::MAX), item, &thumbs).await?; + } + let waiting = published.items.iter().any(|i| i.wants_thumb() && !thumbs.contains_key(&i.sha256)); + Ok::<_, laravel::Error>(Some(waiting)) + }) + .await?; + let Some(version) = find(project_id, &key).await? else { + return Err(laravel::Error::msg("the version just recorded is gone")); + }; + let Some(waiting) = created else { + // Recorded meanwhile by another request. + return Ok(if version.commit_sha == commit { Ok((version, false)) } else { Err(taken(&version)) }); + }; + // Its missing thumbnails, made now (not through `request`'s debounce, which a manifest request may have just used). + if waiting && let Err(e) = (crate::jobs::gallery_thumbs::SyncGalleryThumbs { project_id }).dispatch().await { + tracing::error!(project_id, error = %e, "couldn't queue the version's thumbnails"); + } + // Every manifest lists the versions: the main one and each version's, cached at Cloudflare, are purged. + if crate::jobs::purge_gallery::configured().is_some() { + let org = crate::models::Organization::find_or_fail(project.organization_id).await?; + let app_url = crate::http::api::builds::app_url(); + let mut urls = vec![gallery::manifest_url(&app_url, &org.slug, &project.slug)]; + for v in list(project_id).await? { + urls.push(gallery::manifest_url(&app_url, &org.slug, &format!("{}@{}", project.slug, v.key))); + } + let purge = crate::jobs::purge_gallery::PurgeGallery { build_id: None, project_id: Some(project_id), urls }; + if let Err(e) = purge.dispatch().await { + tracing::error!(project_id, error = %e, "couldn't queue the purge of the gallery's manifests"); + } + } + Ok(Ok((version, true))) +} + +fn taken(existing: &Version) -> Refused { + Refused::Taken(format!( + "{} is already recorded at commit {}; a version's screenshots never change", + existing.label, existing.commit_sha + )) +} + +/// The project's thumbnails, as [`gallery::thumbs`], each row share-locked until the transaction ends. +async fn locked_thumbs(project_id: i64) -> laravel::Result>> { + let rows = db::query!( + "SELECT source_sha256, thumb_sha256, width, height, bytes FROM gallery_thumbnails \ + WHERE project_id = {project_id} FOR SHARE" + ) + .select() + .await?; + let mut out = HashMap::with_capacity(rows.len()); + for r in rows { + let thumb = match r.try_get::>("thumb_sha256")? { + Some(sha256) => Some(Thumb { + sha256, + width: r.try_get::>("width")?.unwrap_or_default(), + height: r.try_get::>("height")?.unwrap_or_default(), + bytes: r.try_get::>("bytes")?.unwrap_or_default(), + }), + None => None, + }; + out.insert(r.try_get::("source_sha256")?, thumb); + } + Ok(out) +} + +async fn insert_item( + version_id: i64, + position: i32, + item: &Item, + thumbs: &HashMap>, +) -> laravel::Result<()> { + let wanted = item.wants_thumb(); + let made = if wanted { thumbs.get(&item.sha256) } else { None }; + // Still to make: filled in by `fill_thumbs` once it is. Known to be impossible: never. + let thumb_wanted = wanted && made.is_none(); + let thumb = made.and_then(Option::as_ref); + let (thumb_sha, thumb_width, thumb_height, thumb_bytes) = + (thumb.map(|t| t.sha256.clone()), thumb.map(|t| t.width), thumb.map(|t| t.height), thumb.map(|t| t.bytes)); + let (group, name, platform, path, sha, content_type) = ( + item.group.clone(), + item.name.clone(), + item.platform.clone(), + item.path.clone(), + item.sha256.clone(), + item.content_type.clone(), + ); + let (width, height, bytes, since) = (item.width, item.height, item.bytes, item.since.clone()); + db::query!( + "INSERT INTO gallery_version_items (version_id, position, group_name, name, platform, path, sha256, \ + content_type, width, height, bytes, since, thumb_wanted, thumb_sha256, thumb_width, thumb_height, thumb_bytes) \ + VALUES ({version_id}, {position}, {group}, {name}, {platform}, {path}, {sha}, {content_type}, {width}, \ + {height}, {bytes}, {since}, {thumb_wanted}, {thumb_sha}, {thumb_width}, {thumb_height}, {thumb_bytes})" + ) + .insert() + .await?; + Ok(()) +} + +fn version_of(r: &laravel::db::AnyRow) -> laravel::Result { + Ok(Version { + id: r.try_get("id")?, + key: r.try_get("key")?, + label: r.try_get("label")?, + commit_sha: r.try_get("commit_sha")?, + released_at: gallery::rfc3339(r.try_get::("released_at")?), + }) +} + +/// One of a project's versions, by key. +/// +/// # Errors +/// On a database error. +pub async fn find(project_id: i64, key: &str) -> laravel::Result> { + let rows = db::query!( + "SELECT id, key, label, commit_sha, released_at FROM gallery_versions \ + WHERE project_id = {project_id} AND key = {key}" + ) + .select() + .await?; + rows.first().map(version_of).transpose() +} + +/// A project's versions, newest first (by release time, then the one recorded last). +/// +/// # Errors +/// On a database error. +pub async fn list(project_id: i64) -> laravel::Result> { + db::query!( + "SELECT id, key, label, commit_sha, released_at FROM gallery_versions WHERE project_id = {project_id} \ + ORDER BY released_at DESC, id DESC" + ) + .select() + .await? + .iter() + .map(version_of) + .collect() +} + +/// The versions list a manifest carries: each version's key, label, release time and manifest URL. +#[must_use] +pub fn listed(app_url: &str, org: &str, project: &str, versions: &[Version]) -> serde_json::Value { + serde_json::json!( + versions + .iter() + .map(|v| serde_json::json!({ + "key": v.key, "label": v.label, "released_at": v.released_at, + "manifest": gallery::manifest_url(app_url, org, &format!("{project}@{}", v.key)), + })) + .collect::>() + ) +} + +/// A version's frozen gallery: its groups and items as recorded, and the thumbnails it has. `complete` when no +/// thumbnail is still to come, so its manifest can be cached for good. +pub struct Frozen { + pub published: Published, + pub thumbs: HashMap>, + pub complete: bool, +} + +/// A version's frozen gallery. +/// +/// # Errors +/// On a database error. +pub async fn frozen(version: &Version) -> laravel::Result { + let id = version.id; + let groups_json: serde_json::Value = + db::query!("SELECT groups FROM gallery_versions WHERE id = {id}").scalar().await?.unwrap_or_default(); + let groups = groups_json + .as_array() + .map(|a| { + a.iter() + .map(|g| (g["name"].as_str().unwrap_or_default().to_string(), g["title"].as_str().map(str::to_string))) + .collect() + }) + .unwrap_or_default(); + let rows = + db::query!("SELECT * FROM gallery_version_items WHERE version_id = {id} ORDER BY position").select().await?; + let mut items = Vec::with_capacity(rows.len()); + let mut thumbs = HashMap::new(); + let mut complete = true; + for r in rows { + let sha256: String = r.try_get("sha256")?; + let thumb_sha: Option = r.try_get("thumb_sha256")?; + complete &= !r.try_get::("thumb_wanted")?; + if let Some(thumb_sha) = &thumb_sha { + thumbs.insert( + sha256.clone(), + Some(Thumb { + sha256: thumb_sha.clone(), + width: r.try_get::>("thumb_width")?.unwrap_or_default(), + height: r.try_get::>("thumb_height")?.unwrap_or_default(), + bytes: r.try_get::>("thumb_bytes")?.unwrap_or_default(), + }), + ); + } + items.push(Item { + group: r.try_get("group_name")?, + name: r.try_get("name")?, + platform: r.try_get("platform")?, + path: r.try_get("path")?, + sha256, + content_type: r.try_get("content_type")?, + width: r.try_get("width")?, + height: r.try_get("height")?, + bytes: r.try_get("bytes")?, + since: r.try_get("since")?, + // Its thumbnail was its own when recorded, if it has one. + thumb_path_free: thumb_sha.is_some(), + }); + } + Ok(Frozen { published: Published { groups, items }, thumbs, complete }) +} + +/// A version's manifest: the gallery's manifest as it was, with its own image URLs (`@/…`), the version, +/// and every version. +#[must_use] +pub fn manifest( + app_url: &str, + org: &str, + project: &str, + version: &Version, + frozen: &Frozen, + versions: &[Version], +) -> serde_json::Value { + let mut body = frozen.published.manifest(app_url, org, &format!("{project}@{}", version.key), &frozen.thumbs); + body["project"] = serde_json::json!(format!("{org}/{project}")); + body["version"] = + serde_json::json!({ "key": version.key, "label": version.label, "released_at": version.released_at }); + body["versions"] = listed(app_url, org, project, versions); + body +} + +/// The screenshots versions still want thumbnails of, by SHA-256: made by the thumbnail sync like the gallery's own. +/// +/// # Errors +/// On a database error. +pub async fn thumbs_wanted(project_id: i64) -> laravel::Result> { + Ok(db::query!( + "SELECT DISTINCT i.sha256 FROM gallery_version_items i JOIN gallery_versions v ON v.id = i.version_id \ + WHERE v.project_id = {project_id} AND i.thumb_wanted" + ) + .select() + .await? + .iter() + .filter_map(|r| r.try_get::("sha256").ok()) + .collect()) +} + +/// Fill in the thumbnails made since a version was recorded (or record that none can be), from the project's +/// thumbnails: the only change a version's rows ever get. Returns how many versions changed. +/// +/// # Errors +/// On a database error. +pub async fn fill_thumbs(project_id: i64) -> laravel::Result { + db::query!( + "UPDATE gallery_version_items i SET thumb_wanted = false, thumb_sha256 = t.thumb_sha256, \ + thumb_width = t.width, thumb_height = t.height, thumb_bytes = t.bytes \ + FROM gallery_versions v, gallery_thumbnails t \ + WHERE i.version_id = v.id AND v.project_id = {project_id} AND i.thumb_wanted \ + AND t.project_id = v.project_id AND t.source_sha256 = i.sha256" + ) + .update() + .await +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keys_are_lowercase_with_single_hyphens() { + assert_eq!(key_of("v2.0.0").as_deref(), Some("v2-0-0")); + assert_eq!(key_of("v1.0.0+build.5").as_deref(), Some("v1-0-0-build-5")); + assert_eq!(key_of("--Release_2--").as_deref(), Some("release-2")); + assert_eq!(key_of("..."), None); + assert_eq!(key_of("Latest"), None, "the libraries' own value"); + } + + #[test] + fn labels_are_short_and_plain() { + assert!(valid_label("v2.0.0")); + assert!(valid_label("2026.12.05+rc_1")); + assert!(!valid_label("")); + assert!(!valid_label("v2 beta")); + assert!(!valid_label("v2/0")); + assert!(!valid_label(&"1".repeat(65))); + } +} diff --git a/app/src/domain/mod.rs b/app/src/domain/mod.rs index bc6a8ac6c..305fd2949 100644 --- a/app/src/domain/mod.rs +++ b/app/src/domain/mod.rs @@ -20,6 +20,7 @@ pub mod environments; pub mod feedback; pub mod gallery; pub mod gallery_thumbs; +pub mod gallery_versions; pub mod groups; pub mod inherited; pub mod lenient; diff --git a/app/src/domain/project_deletion.rs b/app/src/domain/project_deletion.rs index 55e6f38b1..809b7987b 100644 --- a/app/src/domain/project_deletion.rs +++ b/app/src/domain/project_deletion.rs @@ -258,6 +258,10 @@ pub async fn purge(project_id: i64, store: Option<&BlobStore>) -> laravel::Resul WHERE r.project_id = {project_id} \ UNION SELECT image FROM variants WHERE project_id = {project_id} \ UNION SELECT thumb_sha256 FROM gallery_thumbnails WHERE project_id = {project_id} \ + UNION SELECT i.sha256 FROM gallery_version_items i JOIN gallery_versions v ON v.id = i.version_id \ + WHERE v.project_id = {project_id} \ + UNION SELECT i.thumb_sha256 FROM gallery_version_items i JOIN gallery_versions v ON v.id = i.version_id \ + WHERE v.project_id = {project_id} \ ) named WHERE sha IS NOT NULL" ) .select() @@ -381,6 +385,7 @@ pub async fn purge(project_id: i64, store: Option<&BlobStore>) -> laravel::Resul AND NOT EXISTS (SELECT 1 FROM renders r WHERE r.source_blob = b.sha256) \ AND NOT EXISTS (SELECT 1 FROM variants v WHERE v.image = b.sha256) \ AND NOT EXISTS (SELECT 1 FROM gallery_thumbnails t WHERE t.thumb_sha256 = b.sha256) \ + AND NOT EXISTS (SELECT 1 FROM gallery_version_items v WHERE v.sha256 = b.sha256 OR v.thumb_sha256 = b.sha256) \ AND NOT EXISTS (SELECT 1 FROM renders r, jsonb_array_elements(r.pages) pg \ WHERE pg->>'image' = b.sha256) \ FOR UPDATE SKIP LOCKED) \ diff --git a/app/src/domain/retention.rs b/app/src/domain/retention.rs index 981ad8502..eb046a293 100644 --- a/app/src/domain/retention.rs +++ b/app/src/domain/retention.rs @@ -147,6 +147,8 @@ async fn keep_sets(days: i32) -> laravel::Result<()> { SELECT sha256 FROM blobs WHERE created_at > now() - make_interval(days => {days}) \ UNION SELECT image FROM variants \ UNION SELECT thumb_sha256 FROM gallery_thumbnails WHERE thumb_sha256 IS NOT NULL \ + UNION SELECT sha256 FROM gallery_version_items \ + UNION SELECT thumb_sha256 FROM gallery_version_items WHERE thumb_sha256 IS NOT NULL \ UNION SELECT s.source_blob FROM snapshots s JOIN keep_snapshots k ON k.id = s.id \ WHERE s.source_blob IS NOT NULL \ UNION SELECT p.head_image FROM snapshot_pages p JOIN keep_snapshots k ON k.id = p.snapshot_id \ @@ -325,6 +327,7 @@ pub async fn prune(store: Option<&BlobStore>, days: i32, dry_run: bool) -> larav AND NOT EXISTS (SELECT 1 FROM diffs d WHERE d.overlay_blob = b.sha256) \ AND NOT EXISTS (SELECT 1 FROM renders r WHERE r.source_blob = b.sha256) \ AND NOT EXISTS (SELECT 1 FROM gallery_thumbnails t WHERE t.thumb_sha256 = b.sha256) \ + AND NOT EXISTS (SELECT 1 FROM gallery_version_items v WHERE v.sha256 = b.sha256 OR v.thumb_sha256 = b.sha256) \ AND NOT EXISTS (SELECT 1 FROM renders r, jsonb_array_elements(r.pages) pg \ WHERE r.used_at >= now() - make_interval(hours => {grace}) AND pg->>'image' = b.sha256) \ FOR UPDATE SKIP LOCKED) \ @@ -387,6 +390,7 @@ pub(crate) async fn delete_marked(store: Option<&BlobStore>, sha256: &str) -> la OR EXISTS (SELECT 1 FROM diffs WHERE overlay_blob = {sha256}) \ OR EXISTS (SELECT 1 FROM variants WHERE image = {sha256}) \ OR EXISTS (SELECT 1 FROM gallery_thumbnails WHERE thumb_sha256 = {sha256}) \ + OR EXISTS (SELECT 1 FROM gallery_version_items WHERE sha256 = {sha256} OR thumb_sha256 = {sha256}) \ OR EXISTS (SELECT 1 FROM renders r, jsonb_array_elements(r.pages) pg \ WHERE r.used_at >= now() - interval '24 hours' AND pg->>'image' = {sha256})" ) diff --git a/app/src/http/api/mod.rs b/app/src/http/api/mod.rs index 3d9cf4ff5..382984c48 100644 --- a/app/src/http/api/mod.rs +++ b/app/src/http/api/mod.rs @@ -5,6 +5,7 @@ pub mod builds; pub mod downloads; pub mod support; +pub mod versions; use axum::extract::FromRequestParts; use axum::http::StatusCode; @@ -23,6 +24,7 @@ pub fn routes(route: &mut Router) { builds::routes(route); route.post("/v1/support/feedback", support::feedback); downloads::routes(route); + versions::routes(route); crate::auth::device::api_routes(route); super::live::api_routes(route); route.fallback(async || laravel::abort(404)); @@ -62,6 +64,14 @@ impl ApiError { } } + #[must_use] + pub fn unprocessable(message: impl Into) -> Self { + Self { + status: StatusCode::UNPROCESSABLE_ENTITY, + body: json!({ "error": "unprocessable", "description": message.into() }), + } + } + #[must_use] pub fn not_found() -> Self { Self { diff --git a/app/src/http/api/versions.rs b/app/src/http/api/versions.rs new file mode 100644 index 000000000..28b460278 --- /dev/null +++ b/app/src/http/api/versions.rs @@ -0,0 +1,76 @@ +//! Gallery versions (sc-9563): `POST /api/v1/versions` records what the project's gallery published at a commit as a +//! release (`visualci release`), and `GET /api/v1/versions` lists them. See `domain::gallery_versions`. + +use laravel::prelude::*; +use serde::Deserialize; +use serde_json::json; + +use super::{ApiError, ApiProject, Body}; +use crate::domain::gallery_versions::{self as versions, Refused}; + +pub fn routes(route: &mut Router) { + route.post("/v1/versions", record); + route.get("/v1/versions", list); +} + +#[derive(Debug, Deserialize)] +pub struct RecordParams { + /// The version, as the project names it: `v2.0.0`. + pub version: String, + /// The commit it was released at. + pub commit: String, + /// Its ancestor commits, nearest first, for finding what the gallery published there. + #[serde(default)] + pub parent_commits: Vec, +} + +fn body(v: &versions::Version, org: &str, project: &str) -> serde_json::Value { + let app_url = super::builds::app_url(); + json!({ + "key": v.key, "label": v.label, "commit": v.commit_sha, "released_at": v.released_at, + "manifest": crate::domain::gallery::manifest_url(&app_url, org, &format!("{project}@{}", v.key)), + }) +} + +/// `POST /api/v1/versions`: 201 when recorded, 200 when the same version was already recorded at that commit, 409 +/// when it was recorded at another, 422 when the gallery published nothing at that commit. +pub async fn record(auth: Result, Body(params): Body) -> axum::response::Response { + let result = async { + let ApiProject { project, organization, .. } = auth?; + let commits = std::iter::once(¶ms.commit).chain(params.parent_commits.iter()); + if params.parent_commits.len() > 1000 || commits.clone().any(|c| !crate::domain::builds::id_like(c)) { + return Err(ApiError::bad_request("commit and parent_commits must be commit SHAs, at most 1,000 parents")); + } + let history: Vec = commits.cloned().collect(); + match versions::record(&project, ¶ms.version, &history).await? { + Ok((v, created)) => Ok((created, body(&v, &organization.slug, &project.slug))), + Err(Refused::Invalid(m)) => Err(ApiError::bad_request(m)), + Err(Refused::Taken(m)) => Err(ApiError::conflict(m)), + Err(Refused::Nothing(m) | Refused::Full(m)) => Err(ApiError::unprocessable(m)), + } + } + .await; + match result { + Ok((created, body)) => { + let status = if created { axum::http::StatusCode::CREATED } else { axum::http::StatusCode::OK }; + axum::response::IntoResponse::into_response((status, axum::Json(body))) + } + Err(e) => axum::response::IntoResponse::into_response(e), + } +} + +/// `GET /api/v1/versions`: the project's versions, newest first. +pub async fn list(auth: Result) -> axum::response::Response { + let result = async { + let ApiProject { project, organization, .. } = auth?; + let all = versions::list(project.id).await?; + Ok::<_, ApiError>(json!({ + "versions": all.iter().map(|v| body(v, &organization.slug, &project.slug)).collect::>(), + })) + } + .await; + match result { + Ok(b) => axum::response::IntoResponse::into_response(axum::Json(b)), + Err(e) => axum::response::IntoResponse::into_response(e), + } +} diff --git a/app/src/http/gallery.rs b/app/src/http/gallery.rs index 810af873f..7f92e1c26 100644 --- a/app/src/http/gallery.rs +++ b/app/src/http/gallery.rs @@ -22,6 +22,10 @@ use crate::storage::BlobStore; /// Cloudflare keeps a copy for a day; browsers check again after five minutes, since a purge doesn't reach them. const CACHE: &str = "public, max-age=300, s-maxage=86400"; +/// A version's images never change: cached for a year. +const FOREVER: &str = "public, max-age=31536000, immutable"; +/// A version's manifest while a thumbnail is still being made: a minute. +const BRIEFLY: &str = "public, max-age=60, s-maxage=60"; /// Requests per address per minute, per web process. const PER_MINUTE: u32 = 120; @@ -104,6 +108,12 @@ pub async fn manifest(Params((org, file)): Params<(String, String)>, request: Re return r; } let Some(slug) = file.strip_suffix(".json") else { return status(StatusCode::NOT_FOUND, "not found") }; + if let Some((slug, key)) = slug.split_once('@') { + return match version_manifest(&org, slug, key).await { + Ok(r) => r, + Err(e) => server(&e), + }; + } let published = async { let Some((_, project)) = gallery::project_by_slugs(&org, slug).await? else { return Ok(None) }; let published = gallery::published(&project).await?; @@ -112,12 +122,18 @@ pub async fn manifest(Params((org, file)): Params<(String, String)>, request: Re if published.items.iter().any(|i| i.wants_thumb() && !thumbs.contains_key(&i.sha256)) { crate::domain::gallery_thumbs::request(project.id).await; } - Ok::<_, laravel::Error>(Some((published, thumbs))) + let versions = crate::domain::gallery_versions::list(project.id).await?; + Ok::<_, laravel::Error>(Some((published, thumbs, versions))) } .await; match published { - Ok(Some((p, thumbs))) if !p.items.is_empty() => { - let body = p.manifest(&crate::http::api::builds::app_url(), &org, slug, &thumbs); + Ok(Some((p, thumbs, versions))) if !p.items.is_empty() => { + let app_url = crate::http::api::builds::app_url(); + let mut body = p.manifest(&app_url, &org, slug, &thumbs); + // Only once the project has reported one (sc-9563). + if !versions.is_empty() { + body["versions"] = crate::domain::gallery_versions::listed(&app_url, &org, slug, &versions); + } let mut r = axum::Json(body).into_response(); r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE)); public(r) @@ -131,6 +147,30 @@ pub async fn manifest(Params((org, file)): Params<(String, String)>, request: Re } } +/// `/g//@.json`: a version's manifest, as it was recorded. +async fn version_manifest(org: &str, slug: &str, key: &str) -> laravel::Result { + use crate::domain::gallery_versions as versions; + let Some((_, project)) = gallery::project_by_slugs(org, slug).await? else { + return Ok(status(StatusCode::NOT_FOUND, "not found")); + }; + let Some(version) = versions::find(project.id, key).await? else { + return Ok(status(StatusCode::NOT_FOUND, "no such version")); + }; + let frozen = versions::frozen(&version).await?; + // A thumbnail still to make: the background sync is asked again (it may have been missed). + if !frozen.complete { + crate::domain::gallery_thumbs::request(project.id).await; + } + let all = versions::list(project.id).await?; + let body = versions::manifest(&crate::http::api::builds::app_url(), org, slug, &version, &frozen, &all); + let mut r = axum::Json(body).into_response(); + // The versions list it carries changes when a newer version is recorded; the screenshots never do. A day at + // Cloudflare, and the browser keeps it for five minutes, like the main manifest, once its thumbnails are in. + let cache = if frozen.complete { CACHE } else { BRIEFLY }; + r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); + Ok(public(r)) +} + /// `/g///`: one published screenshot. pub async fn image(Params((org, slug, path)): Params<(String, String, String)>, request: Request) -> Response { if let Some(r) = guard(&request) { @@ -143,12 +183,33 @@ pub async fn image(Params((org, slug, path)): Params<(String, String, String)>, } async fn serve(org: &str, slug: &str, path: &str, if_none_match: Option<&str>) -> laravel::Result { + let (slug, key) = match slug.split_once('@') { + Some((slug, key)) => (slug, Some(key)), + None => (slug, None), + }; let Some((_, project)) = gallery::project_by_slugs(org, slug).await? else { if let Some(r) = moved(org, slug, |app, org| gallery::item_url(app, org, slug, path)).await? { return Ok(r); } return Ok(status(StatusCode::NOT_FOUND, "not found")); }; + // A version's image: its own, frozen, so cached for good. + if let Some(key) = key { + let Some(version) = crate::domain::gallery_versions::find(project.id, key).await? else { + return Ok(status(StatusCode::NOT_FOUND, "not found")); + }; + let frozen = crate::domain::gallery_versions::frozen(&version).await?; + let sha256 = if let Some(item) = frozen.published.find(path) { + item.sha256.clone() + } else if let Some(Some(thumb)) = + frozen.published.find_thumb(path).and_then(|item| frozen.thumbs.get(&item.sha256).cloned()) + { + thumb.sha256 + } else { + return Ok(status(StatusCode::NOT_FOUND, "not found")); + }; + return send(&project, &sha256, if_none_match, FOREVER).await; + } let published = gallery::published(&project).await?; let sha256 = if let Some(item) = published.find(path) { item.sha256.clone() @@ -166,13 +227,23 @@ async fn serve(org: &str, slug: &str, path: &str, if_none_match: Option<&str>) - } else { return Ok(status(StatusCode::NOT_FOUND, "not found")); }; + send(&project, &sha256, if_none_match, CACHE).await +} + +/// Serve one blob of a project's gallery: its bytes as the image they are, an ETag, and a credit. +async fn send( + project: &crate::models::Project, + sha256: &str, + if_none_match: Option<&str>, + cache: &'static str, +) -> laravel::Result { let etag = format!("\"{sha256}\""); if if_none_match == Some(etag.as_str()) { let mut r = StatusCode::NOT_MODIFIED.into_response(); - r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE)); + r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); return Ok(public(r)); } - let bytes = BlobStore::current().await?.get(&sha256).await?; + let bytes = BlobStore::current().await?.get(sha256).await?; // The type the bytes are, never the one a client declared: this is the app's own origin, where HTML would run. let content_type = match image::guess_format(&bytes) { Ok(image::ImageFormat::Png) => "image/png", @@ -183,13 +254,13 @@ async fn serve(org: &str, slug: &str, path: &str, if_none_match: Option<&str>) - // Served from VisualCI's own servers: a credit, kept even when the organization is out of them, up to the day's // cap per project (past it, images are served free). let cap = laravel::config().section::().daily_credits; - crate::domain::credits::spend_gallery(&project, 1, cap).await?; + crate::domain::credits::spend_gallery(project, 1, cap).await?; let mut r = bytes.into_response(); let h = r.headers_mut(); h.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type)); h.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); h.insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static("default-src 'none'; sandbox")); - h.insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE)); + h.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); if let Ok(v) = HeaderValue::from_str(&etag) { h.insert(header::ETAG, v); } diff --git a/app/tests/gallery.rs b/app/tests/gallery.rs index 7ad1c2a63..0d2f2d628 100644 --- a/app/tests/gallery.rs +++ b/app/tests/gallery.rs @@ -590,3 +590,121 @@ async fn renamed_gallery(app: Application) -> laravel::Result<()> { app.get(format!("/g/{old}/nothing/web/home.png")).await.assert_status(404); Ok(()) } + +#[laravel::test] +async fn a_reported_version_keeps_what_the_gallery_published_at_its_commit(app: Application) -> laravel::Result<()> { + Box::pin(versions(app)).await +} + +/// sc-9563: `POST /api/v1/versions` freezes what the gallery published at a commit; the version is served at its own +/// URLs as it was, whatever the gallery publishes later, and every manifest lists the versions. +async fn versions(app: Application) -> laravel::Result<()> { + let w = world().await?; + let auth = format!("Bearer {}", w.token); + let base = format!("/g/{}/web", w.org.slug); + let wide = |rgb| png_sized(1000, 500, rgb); + w.build_files(&app, "A", "main", &[], &[("web/home", wide(RED)), ("web/about", png(GREEN))]).await; + let release = |version: &str, commit: &str, parents: &[&str]| { + let body = json!({ "version": version, "commit": commit, "parent_commits": parents }); + let auth = auth.clone(); + let app = &app; + async move { app.post("/api/v1/versions").header("authorization", &auth).json(body).await } + }; + + // No version yet: the manifest has no versions list. + assert!(app.get(format!("{base}.json")).await.json().get("versions").is_none()); + + // v1.0.0 at A. + let v1 = release("v1.0.0", "A", &[]).await; + v1.assert_status(201); + assert_eq!(v1.json()["key"], "v1-0-0"); + let at = format!("{}/g/{}/web", app::http::api::builds::app_url(), w.org.slug); + assert_eq!(v1.json()["manifest"], format!("{at}@v1-0-0.json")); + release("v1.0.0", "A", &[]).await.assert_status(200); + let taken = release("v1.0.0", "B", &["A"]).await; + taken.assert_status(409); + assert!(taken.text().contains("already recorded at commit A"), "{}", taken.text()); + release("latest", "A", &[]).await.assert_status(400); + release("v 2", "A", &[]).await.assert_status(400); + release("v0.1", "Z", &[]).await.assert_status(422); + + // The gallery moves on: B changes home, approved. + let b = w.build_files(&app, "B", "main", &["A"], &[("web/home", wide(BLUE)), ("web/about", png(GREEN))]).await; + w.review(b, "approve").await; + assert_eq!(header(&app.get(format!("{base}/web/home.png")).await, "etag"), etag_of(&wide(BLUE))); + + // v1.0.0 still serves what it froze, cached for good, and its thumbnail once made. + let m = app.get(format!("{base}@v1-0-0.json")).await; + m.assert_ok(); + let manifest: Value = m.json().clone(); + assert_eq!(manifest["project"], format!("{}/web", w.org.slug)); + assert_eq!(manifest["version"]["label"], "v1.0.0"); + let home = manifest["groups"][0]["items"].as_array().unwrap().iter().find(|i| i["name"] == "web/home").unwrap(); + assert_eq!(home["url"], format!("{at}@v1-0-0/web/home.png")); + let old = app.get(format!("{base}@v1-0-0/web/home.png")).await; + old.assert_ok(); + assert_eq!(header(&old, "etag"), etag_of(&wide(RED))); + assert_eq!(header(&old, "cache-control"), "public, max-age=31536000, immutable"); + app.get(format!("{base}@v9/web/home.png")).await.assert_status(404); + app.get(format!("{base}@v1-0-0/web/nope.png")).await.assert_status(404); + // Thumbnails are made in the background (the sync queue runs at once in tests): the version's is filled in. + app::domain::gallery_thumbs::sync(&w.project, app::domain::gallery_thumbs::BUDGET).await?; + let manifest: Value = app.get(format!("{base}@v1-0-0.json")).await.json().clone(); + let home = manifest["groups"][0]["items"].as_array().unwrap().iter().find(|i| i["name"] == "web/home").unwrap(); + assert_eq!(home["thumb"]["width"], 640, "{manifest}"); + let thumb = app.get(format!("{base}@v1-0-0/web/home.thumb.webp")).await; + thumb.assert_ok(); + assert_eq!(header(&thumb, "content-type"), "image/webp"); + + // v2.0.0 at B: newest first in every manifest. + release("v2.0.0", "B", &["A"]).await.assert_status(201); + for path in [format!("{base}.json"), format!("{base}@v1-0-0.json")] { + let m: Value = app.get(&path).await.json().clone(); + let keys: Vec<&str> = m["versions"].as_array().unwrap().iter().map(|v| v["key"].as_str().unwrap()).collect(); + assert_eq!(keys, ["v2-0-0", "v1-0-0"], "{path}: {m}"); + } + let listed: Value = app.get("/api/v1/versions").header("authorization", &auth).await.json().clone(); + assert_eq!(listed["versions"][0]["label"], "v2.0.0"); + + // A version recorded after main moved on keeps what was approved at its commit. C changes home and waits for + // review; D, after it, is approved (approving home's change). v3.0.0, recorded at C afterwards, still has B's home. + w.build_files(&app, "C", "main", &["B"], &[("web/home", wide(PURPLE)), ("web/about", png(GREEN))]).await; + let d = w.build_files(&app, "D", "main", &["C"], &[("web/home", wide(PURPLE)), ("web/about", png(GREEN))]).await; + w.review(d, "approve").await; + assert_eq!(header(&app.get(format!("{base}/web/home.png")).await, "etag"), etag_of(&wide(PURPLE))); + release("v3.0.0", "C", &["B", "A"]).await.assert_status(201); + let at_c = app.get(format!("{base}@v3-0-0/web/home.png")).await; + at_c.assert_ok(); + assert_eq!(header(&at_c, "etag"), etag_of(&wide(BLUE))); + + // At most 500 versions a project: the next is refused, naming the limit; one already recorded still answers. + let project_id = w.project.id; + db::query!( + "INSERT INTO gallery_versions (project_id, key, label, commit_sha, released_at, groups) \ + SELECT {project_id}, 'filler-' || n, 'filler-' || n, 'A', now() - interval '1 year', '[]' \ + FROM generate_series(1, 497) AS n" + ) + .update() + .await?; + let full = release("v4.0.0", "D", &["C", "B", "A"]).await; + full.assert_status(422); + assert!( + full.text().contains("the most a project keeps (500)") && full.text().contains("support"), + "{}", + full.text() + ); + release("v1.0.0", "A", &[]).await.assert_status(200); + + // Retention keeps a version's screenshots, however old: v1's red home is in no kept build's baselines now. + let red = visualci_core::sha256_hex(&wide(RED)); + db::query!("UPDATE blobs SET created_at = now() - interval '400 days', updated_at = now() - interval '400 days' WHERE sha256 = {red}") + .update() + .await?; + app::domain::retention::prune(None, 30, false).await?; + app.get(format!("{base}@v1-0-0/web/home.png")).await.assert_ok(); + Ok(()) +} + +fn etag_of(bytes: &[u8]) -> String { + format!("\"{}\"", visualci_core::sha256_hex(bytes)) +} diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_project.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_project.json index b2692ac6a..bc669818c 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_project.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_project.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"gallery\":{\"enabled\":false,\"items\":[],\"manifest_url\":null},\"project\":\"-b/docs\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":false,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.generated_at\"],\"snapshots\":\"api/**\",\"text_patterns\":[\"\\\\d{4}-\\\\d{2}-\\\\d{2}\"]}],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":3,\"last_used_at\":null,\"name\":\"CircleCI\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test/-b/docs\"}", + "text": "{\"gallery\":{\"enabled\":false,\"items\":[],\"manifest_url\":null,\"versions\":[]},\"project\":\"-b/docs\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":false,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.generated_at\"],\"snapshots\":\"api/**\",\"text_patterns\":[\"\\\\d{4}-\\\\d{2}-\\\\d{2}\"]}],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":3,\"last_used_at\":null,\"name\":\"CircleCI\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test/-b/docs\"}", "type": "text" } ], @@ -14,7 +14,8 @@ "gallery": { "enabled": false, "items": [], - "manifest_url": null + "manifest_url": null, + "versions": [] }, "project": "-b/docs", "repository_seen_in_ci": null, diff --git a/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/get_project.json b/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/get_project.json index fcfc5ff5a..44b36081c 100644 --- a/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/get_project.json +++ b/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/get_project.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"/pdfs\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":1,\"last_used_at\":null,\"name\":\"ci\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test//pdfs\"}", + "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null,\"versions\":[]},\"project\":\"/pdfs\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":1,\"last_used_at\":null,\"name\":\"ci\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test//pdfs\"}", "type": "text" } ], @@ -14,7 +14,8 @@ "gallery": { "enabled": true, "items": [], - "manifest_url": null + "manifest_url": null, + "versions": [] }, "project": "/pdfs", "repository_seen_in_ci": null, diff --git a/app/tests/golden/mcp/projects_can_be_renamed/get_project-2.json b/app/tests/golden/mcp/projects_can_be_renamed/get_project-2.json index 3e7bbea9b..39238226f 100644 --- a/app/tests/golden/mcp/projects_can_be_renamed/get_project-2.json +++ b/app/tests/golden/mcp/projects_can_be_renamed/get_project-2.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"/monorepo\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"monorepo\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":1,\"last_used_at\":null,\"name\":\"ci\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test//monorepo\"}", + "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null,\"versions\":[]},\"project\":\"/monorepo\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"monorepo\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":1,\"last_used_at\":null,\"name\":\"ci\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test//monorepo\"}", "type": "text" } ], @@ -14,7 +14,8 @@ "gallery": { "enabled": true, "items": [], - "manifest_url": null + "manifest_url": null, + "versions": [] }, "project": "/monorepo", "repository_seen_in_ci": null, diff --git a/app/tests/golden/mcp_admin/staff_read_and_write_with_a_reason_and_every_call_is_audited/get_project.json b/app/tests/golden/mcp_admin/staff_read_and_write_with_a_reason_and_every_call_is_audited/get_project.json index 5e257f3ec..511e2275e 100644 --- a/app/tests/golden/mcp_admin/staff_read_and_write_with_a_reason_and_every_call_is_audited/get_project.json +++ b/app/tests/golden/mcp_admin/staff_read_and_write_with_a_reason_and_every_call_is_audited/get_project.json @@ -9,7 +9,7 @@ "type": "text" }, { - "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"acme/invoices\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"Invoices\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"invoices\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[],\"url\":\"https://app.visualci.test/acme/invoices\"}", + "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null,\"versions\":[]},\"project\":\"acme/invoices\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"Invoices\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"invoices\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[],\"url\":\"https://app.visualci.test/acme/invoices\"}", "type": "text" } ], @@ -18,7 +18,8 @@ "gallery": { "enabled": true, "items": [], - "manifest_url": null + "manifest_url": null, + "versions": [] }, "project": "acme/invoices", "repository_seen_in_ci": null, diff --git a/clients/circleci-orb/orb.yml b/clients/circleci-orb/orb.yml index 9e84fc092..bb3876e55 100644 --- a/clients/circleci-orb/orb.yml +++ b/clients/circleci-orb/orb.yml @@ -15,8 +15,8 @@ commands: parameters: version: type: string - default: "0.2.29" - description: The CLI release to install, such as 0.2.29. Pin it, so a new release never changes a build. + default: "0.2.30" + description: The CLI release to install, such as 0.2.30. Pin it, so a new release never changes a build. install-dir: type: string default: $HOME/.local/bin @@ -70,7 +70,7 @@ commands: description: Fail the step when VisualCI can't be reached. By default it only reports. version: type: string - default: "0.2.29" + default: "0.2.30" steps: - install: version: << parameters.version >> @@ -117,7 +117,7 @@ commands: default: false version: type: string - default: "0.2.29" + default: "0.2.30" steps: - install: version: << parameters.version >> @@ -160,7 +160,7 @@ jobs: default: false version: type: string - default: "0.2.29" + default: "0.2.30" steps: - install: version: << parameters.version >> diff --git a/clients/github-action/action.yml b/clients/github-action/action.yml index 9b49afc8f..f09e160ac 100644 --- a/clients/github-action/action.yml +++ b/clients/github-action/action.yml @@ -45,7 +45,7 @@ inputs: The visualci CLI release to install. Default: the release this tag of the action came with, so @v0 installs the newest. Pin it to keep a release from changing a build. required: false - default: "0.2.29" + default: "0.2.30" cli: description: A visualci binary to use instead of installing a release (VisualCI's own CI tests its latest CLI). required: false diff --git a/crates/visualci-cli/examples/release/circleci.yml b/crates/visualci-cli/examples/release/circleci.yml new file mode 100644 index 000000000..53c2f4516 --- /dev/null +++ b/crates/visualci-cli/examples/release/circleci.yml @@ -0,0 +1,22 @@ +# .circleci/config.yml: a job, and a workflow that runs it for tags only +jobs: + gallery-version: + docker: + - image: cimg/base:current + steps: + - checkout + - run: | + curl -fsSLo visualci.tar.gz https://github.com/DocSpring/visualci/releases/download/v{{cli_version}}/visualci-x86_64-unknown-linux-musl.tar.gz + echo "{{cli_sha256}} visualci.tar.gz" | sha256sum -c + sudo tar xzf visualci.tar.gz --strip-components=1 -C /usr/local/bin visualci-x86_64-unknown-linux-musl/visualci + - run: visualci release +workflows: + release: + jobs: + - gallery-version: + context: visualci # holds VISUALCI_TOKEN + filters: + tags: + only: /^v.*/ + branches: + ignore: /.*/ diff --git a/crates/visualci-cli/examples/release/github-actions.yml b/crates/visualci-cli/examples/release/github-actions.yml new file mode 100644 index 000000000..a9ecb8a74 --- /dev/null +++ b/crates/visualci-cli/examples/release/github-actions.yml @@ -0,0 +1,21 @@ +# .github/workflows/release.yml +name: Release +on: + push: + tags: ["v*"] +jobs: + gallery-version: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # VisualCI finds what the gallery published through the commit's ancestors + - name: Install VisualCI + run: | + curl -fsSLo visualci.tar.gz https://github.com/DocSpring/visualci/releases/download/v{{cli_version}}/visualci-x86_64-unknown-linux-musl.tar.gz + echo "{{cli_sha256}} visualci.tar.gz" | sha256sum -c + mkdir -p "$RUNNER_TEMP" && tar xzf visualci.tar.gz --strip-components=1 -C "$RUNNER_TEMP" visualci-x86_64-unknown-linux-musl/visualci + echo "$RUNNER_TEMP" >> "$GITHUB_PATH" + - run: visualci release + env: + VISUALCI_TOKEN: ${{ secrets.VISUALCI_TOKEN }} diff --git a/crates/visualci-cli/examples/release/gitlab-ci.yml b/crates/visualci-cli/examples/release/gitlab-ci.yml new file mode 100644 index 000000000..22be53644 --- /dev/null +++ b/crates/visualci-cli/examples/release/gitlab-ci.yml @@ -0,0 +1,12 @@ +# .gitlab-ci.yml +gallery-version: + image: node:lts + rules: + - if: $CI_COMMIT_TAG + variables: + GIT_DEPTH: 0 # VisualCI finds what the gallery published through the commit's ancestors + script: + - curl -fsSLo visualci.tar.gz https://github.com/DocSpring/visualci/releases/download/v{{cli_version}}/visualci-x86_64-unknown-linux-musl.tar.gz + - echo "{{cli_sha256}} visualci.tar.gz" | sha256sum -c + - mkdir -p /usr/local/bin && tar xzf visualci.tar.gz --strip-components=1 -C /usr/local/bin visualci-x86_64-unknown-linux-musl/visualci + - visualci release diff --git a/crates/visualci-cli/src/ci.rs b/crates/visualci-cli/src/ci.rs index 2947c6939..06a096eb2 100644 --- a/crates/visualci-cli/src/ci.rs +++ b/crates/visualci-cli/src/ci.rs @@ -169,6 +169,26 @@ pub fn environment(env: &dyn Fn(&str) -> Option, provider: Option<&str>, } } +/// The tag this run builds, when the CI provider says it builds one (`v2.0.0` for a release workflow), for `visualci +/// release` without a version. +pub fn tag(env: &dyn Fn(&str) -> Option) -> Option { + let get = |k: &str| env(k).filter(|v| !v.is_empty()); + if get("GITHUB_REF_TYPE").as_deref() == Some("tag") { + return get("GITHUB_REF_NAME"); + } + [ + "CIRCLE_TAG", + "CI_COMMIT_TAG", + "BUILDKITE_TAG", + "BITBUCKET_TAG", + "SEMAPHORE_GIT_TAG_NAME", + "TRAVIS_TAG", + "TAG_NAME", + ] + .iter() + .find_map(|k| get(k)) +} + /// Whether this runs in CI: a detected provider, or `CI` set to anything but `false` or `0`. pub fn in_ci(env: &dyn Fn(&str) -> Option, provider: Option<&str>) -> bool { // Variables CI systems set, beyond the providers `detect` reads. @@ -285,6 +305,18 @@ mod tests { CiContext { base_branch: Some(base.into()), ..c } } + #[test] + fn tags_come_from_the_ci_provider() { + let env = |vars: &'static [(&'static str, &'static str)]| { + move |k: &str| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string()) + }; + assert_eq!(tag(&env(&[("GITHUB_REF_TYPE", "tag"), ("GITHUB_REF_NAME", "v2.0.0")])).as_deref(), Some("v2.0.0")); + assert_eq!(tag(&env(&[("GITHUB_REF_TYPE", "branch"), ("GITHUB_REF_NAME", "main")])), None); + assert_eq!(tag(&env(&[("CIRCLE_TAG", "v1.2.3")])).as_deref(), Some("v1.2.3")); + assert_eq!(tag(&env(&[("CI_COMMIT_TAG", "")])), None); + assert_eq!(tag(&env(&[])), None); + } + #[test] fn environments() { let env = |vars: &'static [(&'static str, &'static str)]| { diff --git a/crates/visualci-cli/src/client.rs b/crates/visualci-cli/src/client.rs index f3bdec102..4d9b3d239 100644 --- a/crates/visualci-cli/src/client.rs +++ b/crates/visualci-cli/src/client.rs @@ -279,6 +279,11 @@ impl Client { Ok(serde_json::from_value(self.post("/api/v1/builds", params)?)?) } + /// Record a gallery version at a commit (`POST /api/v1/versions`): its key, label, commit and manifest URL. + pub fn record_version(&self, params: &serde_json::Value) -> Result { + self.post("/api/v1/versions", params) + } + pub fn build(&self, id: &str) -> Result { Ok(serde_json::from_value(self.get(&format!("/api/v1/builds/{id}"))?)?) } diff --git a/crates/visualci-cli/src/config_file.rs b/crates/visualci-cli/src/config_file.rs index 0215e17d9..f5942dc14 100644 --- a/crates/visualci-cli/src/config_file.rs +++ b/crates/visualci-cli/src/config_file.rs @@ -83,6 +83,19 @@ pub fn discover() -> Result> { #[cfg(test)] mod tests { + #[test] + fn the_release_examples_in_the_docs_are_yaml_that_run_visualci_release() { + // Shown in frontend/content/docs/gallery/versions.md. + for text in [ + include_str!("../examples/release/github-actions.yml"), + include_str!("../examples/release/circleci.yml"), + include_str!("../examples/release/gitlab-ci.yml"), + ] { + let _: serde_json::Value = serde_norway::from_str(text).unwrap(); + assert!(text.contains("visualci release")); + } + } + #[test] fn the_laptop_gallery_example_in_the_docs_is_valid() { // Shown in frontend/content/docs/gallery/without-ci.md. diff --git a/crates/visualci-cli/src/main.rs b/crates/visualci-cli/src/main.rs index e67e24d80..d80048ecf 100644 --- a/crates/visualci-cli/src/main.rs +++ b/crates/visualci-cli/src/main.rs @@ -244,6 +244,20 @@ enum Command { #[command(flatten)] connection: Connection, }, + /// Record a gallery version: keep what the project's gallery published at this commit, for good, at its own URLs + /// (`/g//@.json`), listed in every manifest. Run it where a release is made, after the commit's + /// default-branch build is approved: in a release or tag workflow, or by hand. Without a version, it uses the tag + /// the CI provider builds, else the commit's own tag. Exits 0 when recorded (or recorded before at this commit), + /// 1 when refused (the version is taken by another commit, or the gallery published nothing here). + /// + /// visualci release v2.0.0 + /// visualci release # in a tag workflow + Release { + /// The version, as you name it: `v2.0.0`. Default: the CI provider's tag, else `git describe --exact-match --tags`. + version: Option, + #[command(flatten)] + connection: Connection, + }, /// Publish a full set of screenshots from any machine, for a project's gallery: a CI-mode build of everything in the /// paths (what it doesn't send is removed), on the current branch and commit, in the gallery's environment /// (visualci.yml's `gallery.environment`, else `ci`). It lands in the builds list like any build: once it's approved @@ -804,6 +818,26 @@ fn run() -> Result<()> { print_build(&client, &build)?; std::process::exit(test_exit_code(status, &build, no_wait)); } + Command::Release { version, connection } => { + let client = Client::from_env(connection.api_url, connection.token, connection.project)?; + let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); + let version = version.or_else(|| ci::tag(&env)).or_else(git_tag).ok_or_else(|| { + anyhow::anyhow!( + "name the version (visualci release v2.0.0): no CI tag, and the commit has no tag of its own" + ) + })?; + let context = client::git_context(None); + let params = json!({ + "version": version, "commit": context["commit"], "parent_commits": context["parent_commits"], + }); + let recorded = client.record_version(¶ms)?; + eprintln!( + "Version {} at {}: {}", + recorded["label"].as_str().unwrap_or(&version), + recorded["commit"].as_str().unwrap_or_default(), + recorded["manifest"].as_str().unwrap_or_default() + ); + } Command::Publish { paths, environment, snapshot, name, timeout, connection } => { let client = Client::from_env(connection.api_url, connection.token, connection.project)?; // The gallery's groups come from visualci.yml, sent with the build: without them nothing is published. @@ -1328,6 +1362,12 @@ fn read_manifest(path: &Path) -> Result> { .collect() } +/// The commit's own tag, when it has exactly one name: `git describe --exact-match --tags`. +fn git_tag() -> Option { + let out = std::process::Command::new("git").args(["describe", "--exact-match", "--tags", "HEAD"]).output().ok()?; + out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|t| !t.is_empty()) +} + /// The environment `publish` sends to when none is given: the gallery's in visualci.yml, else `ci`. fn publish_environment(config: Option<&visualci_core::config::Config>) -> String { config diff --git a/frontend/content/changelog/2026-12-06-0054-gallery-versions.md b/frontend/content/changelog/2026-12-06-0054-gallery-versions.md new file mode 100644 index 000000000..43fa45520 --- /dev/null +++ b/frontend/content/changelog/2026-12-06-0054-gallery-versions.md @@ -0,0 +1 @@ +**CLI 0.2.30: gallery versions.** `visualci release v2.0.0` (or bare `visualci release` in a tag workflow) keeps what your gallery showed at that release, for good, at its own URLs (`/g//@v2-0-0.json`), and every manifest lists the versions, newest first, so a page can show v1.0.0 beside v2.0.0. Opt-in: nothing changes until you report one. [Gallery versions](/docs/gallery/versions/) diff --git a/frontend/content/docs/gallery.md b/frontend/content/docs/gallery.md index 6467cdeb4..55e8e13af 100644 --- a/frontend/content/docs/gallery.md +++ b/frontend/content/docs/gallery.md @@ -95,6 +95,8 @@ Always the approved version on the default branch: what the next build there wou } ``` +Once the project [reports versions](/docs/gallery/versions/), the manifest also lists them, each with a manifest of its own that keeps the gallery as it was at that release. + The manifest changes only when an image does, so a site can build its own gallery from it. Light and dark, or phone and desktop, are separate screenshots with their own URLs; pairing them is up to your page. Every gallery URL works from any site (`Access-Control-Allow-Origin: *`), including one that turns on cross-origin isolation (`Cross-Origin-Resource-Policy: cross-origin`). They take no query parameters: anything else is a 404. diff --git a/frontend/content/docs/gallery/versions.md b/frontend/content/docs/gallery/versions.md new file mode 100644 index 000000000..67fa518c4 --- /dev/null +++ b/frontend/content/docs/gallery/versions.md @@ -0,0 +1,116 @@ +--- +title: Gallery versions +description: Keep what your gallery showed at each release, v1.0.0 and v2.0.0 side by side, at stable URLs, by reporting versions from your release workflow. +--- + +A gallery always shows the default branch as it is now. To keep what it showed at a release, so people can see what your app looked like at v1.0.0 and at v2.0.0, report the version when you release. Each reported version keeps the gallery's screenshots, groups and names as they were at that commit, for good, at URLs of its own. Nothing changes for a project that doesn't report versions. + +## Report a version + +Run `visualci release` where you release, once the release commit's default-branch build is approved: + +```sh +visualci release v2.0.0 +``` + +Without a version, it takes the tag the CI run builds (`GITHUB_REF_NAME` on a tag push, `CIRCLE_TAG`, `CI_COMMIT_TAG`, `BUILDKITE_TAG`, `BITBUCKET_TAG`, `SEMAPHORE_GIT_TAG_NAME`, `TRAVIS_TAG`, `TAG_NAME`), else the commit's own tag. It records what the gallery published at that commit: the approved screenshots of the newest default-branch builds at or before it. A later commit's approval doesn't count, even when it's made before you record the version. It takes the commit and its ancestors from git, so the checkout needs its history. + +A version is recorded once. Running the same command again answers the version already recorded. The same version at another commit is refused, since a version's screenshots never change. A version is up to 64 letters, digits, dots, dashes, underscores and plus signs, with at least one letter or digit, and can't be called `latest`. + +### GitHub Actions + + +```yaml +# .github/workflows/release.yml +name: Release +on: + push: + tags: ["v*"] +jobs: + gallery-version: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # VisualCI finds what the gallery published through the commit's ancestors + - name: Install VisualCI + run: | + curl -fsSLo visualci.tar.gz https://github.com/DocSpring/visualci/releases/download/v{{cli_version}}/visualci-x86_64-unknown-linux-musl.tar.gz + echo "{{cli_sha256}} visualci.tar.gz" | sha256sum -c + mkdir -p "$RUNNER_TEMP" && tar xzf visualci.tar.gz --strip-components=1 -C "$RUNNER_TEMP" visualci-x86_64-unknown-linux-musl/visualci + echo "$RUNNER_TEMP" >> "$GITHUB_PATH" + - run: visualci release + env: + VISUALCI_TOKEN: ${{ secrets.VISUALCI_TOKEN }} +``` + +### CircleCI + + +```yaml +# .circleci/config.yml: a job, and a workflow that runs it for tags only +jobs: + gallery-version: + docker: + - image: cimg/base:current + steps: + - checkout + - run: | + curl -fsSLo visualci.tar.gz https://github.com/DocSpring/visualci/releases/download/v{{cli_version}}/visualci-x86_64-unknown-linux-musl.tar.gz + echo "{{cli_sha256}} visualci.tar.gz" | sha256sum -c + sudo tar xzf visualci.tar.gz --strip-components=1 -C /usr/local/bin visualci-x86_64-unknown-linux-musl/visualci + - run: visualci release +workflows: + release: + jobs: + - gallery-version: + context: visualci # holds VISUALCI_TOKEN + filters: + tags: + only: /^v.*/ + branches: + ignore: /.*/ +``` + +### GitLab CI + + +```yaml +# .gitlab-ci.yml +gallery-version: + image: node:lts + rules: + - if: $CI_COMMIT_TAG + variables: + GIT_DEPTH: 0 # VisualCI finds what the gallery published through the commit's ancestors + script: + - curl -fsSLo visualci.tar.gz https://github.com/DocSpring/visualci/releases/download/v{{cli_version}}/visualci-x86_64-unknown-linux-musl.tar.gz + - echo "{{cli_sha256}} visualci.tar.gz" | sha256sum -c + - mkdir -p /usr/local/bin && tar xzf visualci.tar.gz --strip-components=1 -C /usr/local/bin visualci-x86_64-unknown-linux-musl/visualci + - visualci release +``` + +Other CI providers: run `visualci release` in the job your tags start, after installing the CLI as in [your provider's guide](/docs/ci/other/), with `VISUALCI_TOKEN` set. + +## What's served + +Each version has a key: its label lowercased, with each run of other characters one hyphen (`v1.0.0+build.5` is `v1-0-0-build-5`). + +- **Its manifest:** `https://app.visualci.com/g//@.json`, the same shape as the [gallery's manifest](/docs/gallery/#whats-served) with the groups and screenshots as they were, plus `version` (`key`, `label`, `released_at`) and the `versions` list. +- **Its images:** `https://app.visualci.com/g//@/.png`, and `.thumb.webp` thumbnails. They never change, so they're cached for a year. +- **The `versions` list** in the main manifest and in every version's: each version's `key`, `label`, `released_at` and `manifest` URL, newest first. Versions released at the same moment come in the order they were recorded, the last recorded first. The gallery libraries show the list in this order. + +```text +"versions": [ + { "key": "v2-0-0", "label": "v2.0.0", "released_at": "2026-12-05T04:00:00+00:00", "manifest": "https://app.visualci.com/g/acme/web@v2-0-0.json" }, + { "key": "v1-0-0", "label": "v1.0.0", "released_at": "2026-11-02T10:31:07+00:00", "manifest": "https://app.visualci.com/g/acme/web@v1-0-0.json" } +] +``` + +The main manifest stays the default branch's gallery as it is now (call it Latest), which may be ahead of the newest version. A version's thumbnails appear a few seconds after it's recorded, like the gallery's. A version recorded while the gallery is off is kept, and served once the gallery is on. + +The project's page lists its versions under its public screenshots. `GET /api/v1/versions` lists them with a project token. + +## Storage and cost + +A version's images are kept for as long as the project, however old, while other images go after 30 days unless a baseline needs them. A project keeps up to 500 versions; past that, `visualci release` is refused, so tag releases rather than every commit, and [contact support](mailto:support@visualci.com) if you need more. Images served from a version's URLs cost credits like the gallery's own (see [Caching and cost](/docs/gallery/#caching-and-cost)); there's no charge for keeping them. diff --git a/frontend/content/docs/reference/api.md b/frontend/content/docs/reference/api.md index 62c9fbaba..b75d72767 100644 --- a/frontend/content/docs/reference/api.md +++ b/frontend/content/docs/reference/api.md @@ -128,6 +128,10 @@ return the same download. An archive over 2 GB stops with an error that suggests The archive holds `[@platform][/page-N]/{base,head,diff,regions}.png` and `manifest.json`, which lists each snapshot's name, platform, state, path and pages (changed fraction, regions and files). +## Gallery versions + +`POST /api/v1/versions` with `{"version": "v2.0.0", "commit": "", "parent_commits": ["", …]}` records what the project's [gallery](/docs/gallery/versions/) published at that commit as a version: the answer is `{"key", "label", "commit", "released_at", "manifest"}`, 201 when it's recorded, 200 when the same version was recorded at that commit before. A version that isn't up to 64 letters, digits and `._+-` (or is `latest`) is a 400, the same version recorded at another commit a 409, and a commit the gallery published nothing at a 422, as is a new version once the project has 500. `GET /api/v1/versions` lists the project's versions, newest first, as `{"versions": [...]}`. + ## Feedback `POST /api/v1/support/feedback`: see [Support](/docs/support/). diff --git a/frontend/content/docs/reference/cli.md b/frontend/content/docs/reference/cli.md index 7858f53f2..1970f93e4 100644 --- a/frontend/content/docs/reference/cli.md +++ b/frontend/content/docs/reference/cli.md @@ -102,6 +102,10 @@ Prints a build's status as JSON. `--build `, default `$VISUALCI_BUILD_ID`. `visualci check ` is a one-shot local check: it creates a local build, uploads, waits and prints what changed, with a link. The server renders the PDFs, so a laptop gets the same pixels as CI. It takes `upload`'s options, plus `--name` and `--timeout` (default 600). It exits 0 when nothing changed and 1 when something did, or when the paths hold nothing to check. +## visualci release + +`visualci release [version]` records a [gallery version](/docs/gallery/versions/): what the project's gallery published at the current commit, kept for good at its own URLs. Without a version, it takes the tag the CI run builds, else the commit's own tag (`git describe --exact-match --tags`). It exits 0 when the version is recorded (or was, at this commit), and 1 when it's refused: taken by another commit, or nothing published at this one. + ## visualci publish `visualci publish ` sends a full set of screenshots from any machine for a project's [gallery](/docs/gallery/without-ci/): one CI-mode build of everything in the paths (a screenshot it doesn't send shows as removed), on the current branch and commit, in the gallery's environment (`gallery.environment` in visualci.yml, else `ci`). It takes `upload`'s options, plus: diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index f4a5cc0f0..a5ffaf7ee 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -594,6 +594,8 @@ export type PublicGallery = { enabled: boolean manifest_url: string | null items: { group: string; name: string; platform: string; url: string }[] + /** Versions reported with `visualci release`, newest first: each kept as it was, with its own manifest. */ + versions: { key: string; label: string; commit: string; released_at: string; manifest: string }[] } /** One snapshot a pull request adds, changes or removes against its fork point. */ diff --git a/frontend/src/docs/nav.ts b/frontend/src/docs/nav.ts index 52644d6b1..0a8fc8ceb 100644 --- a/frontend/src/docs/nav.ts +++ b/frontend/src/docs/nav.ts @@ -29,7 +29,7 @@ export const docsSections: DocsSection[] = [ }, { title: 'Public gallery', - slugs: ['gallery', 'gallery/js', 'gallery/astro', 'gallery/react', 'gallery/docusaurus', 'gallery/vitepress', 'gallery/mkdocs', 'gallery/hugo', 'gallery/ruby', 'gallery/python', 'gallery/rust', 'gallery/options', 'gallery/without-ci'], + slugs: ['gallery', 'gallery/js', 'gallery/astro', 'gallery/react', 'gallery/docusaurus', 'gallery/vitepress', 'gallery/mkdocs', 'gallery/hugo', 'gallery/ruby', 'gallery/python', 'gallery/rust', 'gallery/options', 'gallery/without-ci', 'gallery/versions'], }, { title: 'Reference', slugs: ['reference/cli', 'reference/config', 'reference/api', 'reference/access', 'reference/credits', 'self-hosting', 'self-hosting/environment-variables', 'support'] }, ] diff --git a/frontend/src/pages/ProjectPage.tsx b/frontend/src/pages/ProjectPage.tsx index 7197ce888..2140d9930 100644 --- a/frontend/src/pages/ProjectPage.tsx +++ b/frontend/src/pages/ProjectPage.tsx @@ -105,6 +105,19 @@ function PublicList({ gallery }: { gallery: PublicGallery }) { {gallery.manifest_url.replace(/^https?:\/\//, '')}

+ {gallery.versions.length > 0 && ( +

+ Versions:{' '} + {gallery.versions.map((v, i) => ( + + {i > 0 && ', '} + + {v.label} + + + ))} +

+ )}
diff --git a/plugin/skills/visualci-gallery/SKILL.md b/plugin/skills/visualci-gallery/SKILL.md index edcf81cf5..654ca0769 100644 --- a/plugin/skills/visualci-gallery/SKILL.md +++ b/plugin/skills/visualci-gallery/SKILL.md @@ -100,6 +100,8 @@ Always the approved version on the default branch: what the next build there wou } ``` +Once the project [reports versions](https://visualci.com/docs/gallery/versions.md), the manifest also lists them, each with a manifest of its own that keeps the gallery as it was at that release. + The manifest changes only when an image does, so a site can build its own gallery from it. Light and dark, or phone and desktop, are separate screenshots with their own URLs; pairing them is up to your page. Every gallery URL works from any site (`Access-Control-Allow-Origin: *`), including one that turns on cross-origin isolation (`Cross-Origin-Resource-Policy: cross-origin`). They take no query parameters: anything else is a 404.