diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index ea36c27d..2e237864 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,7 +5,7 @@ "plugins": [ { "name": "visualci", - "version": "0.1.44", + "version": "0.1.45", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "author": { "name": "DocSpring", "url": "https://visualci.com" }, "homepage": "https://visualci.com/docs/skills/", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 8688f7b3..8a80ecf3 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.44", + "version": "0.1.45", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "author": { "name": "DocSpring", "url": "https://visualci.com" }, "homepage": "https://visualci.com/docs/skills/", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 1420245c..488d8bd6 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "visualci", "displayName": "VisualCI", - "version": "0.1.44", + "version": "0.1.45", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "author": { "name": "DocSpring" diff --git a/Cargo.lock b/Cargo.lock index 7656b01a..803d552f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -773,6 +773,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -1471,6 +1473,16 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.16" @@ -2263,6 +2275,16 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.107" @@ -4588,6 +4610,16 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -5206,7 +5238,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "visualci-cli" -version = "0.2.16" +version = "0.2.17" dependencies = [ "anyhow", "base64 0.22.1", @@ -5223,7 +5255,7 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.16" +version = "0.2.17" dependencies = [ "globset", "hex", @@ -5235,12 +5267,15 @@ dependencies = [ "sha2 0.10.9", "similar", "snapshot-diff", + "tar", + "tempfile", "thiserror 2.0.21", + "zstd", ] [[package]] name = "visualci-renderer" -version = "0.2.16" +version = "0.2.17" dependencies = [ "anyhow", "image", @@ -5255,7 +5290,7 @@ dependencies = [ [[package]] name = "visualci-wasm" -version = "0.2.16" +version = "0.2.17" dependencies = [ "image", "serde", @@ -5265,7 +5300,7 @@ dependencies = [ [[package]] name = "visualci_server" -version = "0.2.16" +version = "0.2.17" dependencies = [ "aes-gcm", "async-trait", @@ -5298,6 +5333,7 @@ dependencies = [ "serde_json", "serial_test", "sha2 0.10.9", + "tempfile", "time", "tokio", "tracing", @@ -5762,6 +5798,34 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zstd" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b04655dc7bf4abd8ebe23dac6bef20fceea52a29ad19e37a4101b3951d7e8b45" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df2575690b2a3eccad509fe7898cdde32a5afca06a06449ff4dcfb318c7b7281" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.2.0+zstd.1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" +dependencies = [ + "cc", + "pkg-config", +] + [[package]] name = "zune-core" version = "0.5.4" diff --git a/Cargo.toml b/Cargo.toml index 87637380..68f2f156 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*", "server", "server/migration"] [workspace.package] -version = "0.2.16" +version = "0.2.17" edition = "2024" license = "Apache-2.0" repository = "https://github.com/DocSpring/visualci" @@ -30,6 +30,9 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" similar = "2" +# Bundles of snapshot files (visualci-core::bundle): tar archives compressed with zstd +tar = { version = "0.4", default-features = false } +zstd = "0.13" thiserror = "2" visualci-core = { path = "crates/visualci-core" } snapshot-diff = { path = "crates/snapshot-diff", version = "0.1.0" } diff --git a/crates/visualci-cli/Cargo.toml b/crates/visualci-cli/Cargo.toml index 3098d53e..d665f01b 100644 --- a/crates/visualci-cli/Cargo.toml +++ b/crates/visualci-cli/Cargo.toml @@ -18,7 +18,7 @@ image.workspace = true serde.workspace = true serde_json.workspace = true serde_norway = "0.9" -visualci-core.workspace = true +visualci-core = { workspace = true, features = ["bundle"] } reqwest = { workspace = true, features = ["blocking"] } # macOS keeps `visualci login`'s token in the Keychain; elsewhere a 0600 file (the static Linux builds can't link D-Bus diff --git a/crates/visualci-core/Cargo.toml b/crates/visualci-core/Cargo.toml index d1e73e78..647e9fd8 100644 --- a/crates/visualci-core/Cargo.toml +++ b/crates/visualci-core/Cargo.toml @@ -18,3 +18,12 @@ sha2.workspace = true similar.workspace = true snapshot-diff = { workspace = true, features = ["schemars"] } thiserror.workspace = true +tar = { workspace = true, optional = true } +zstd = { workspace = true, optional = true } + +[features] +# Writing and unpacking tar.zst bundles (the CLI and the server; not the wasm build, which can't build zstd's C) +bundle = ["dep:tar", "dep:zstd"] + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/visualci-core/src/bundle.rs b/crates/visualci-core/src/bundle.rs new file mode 100644 index 00000000..7982ca0b --- /dev/null +++ b/crates/visualci-core/src/bundle.rs @@ -0,0 +1,203 @@ +//! Bundles: many snapshot files in one tar archive compressed with zstd (`.tar.zst`). A build's images download as one +//! (`visualci build download`), and a client can upload many files as one (sc-8868). Both sides stream: entries are +//! written one at a time, and unpacking reads one at a time, so a bundle of thousands of images is never held whole. + +use std::io::{self, Read, Write}; +use std::path::{Component, Path, PathBuf}; + +/// The zstd level: fast, and PNGs are already compressed, so a higher level saves little. +pub const LEVEL: i32 = 3; + +/// The file at a bundle's top that describes its other files. +pub const MANIFEST: &str = "manifest.json"; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("{0}")] + Io(#[from] io::Error), + #[error("a bundle path must be relative, without `..` or empty parts: {0:?}")] + UnsafePath(String), + #[error("{path} is {size} bytes, more than the {max} a bundle entry may be")] + EntryTooLarge { path: String, size: u64, max: u64 }, +} + +/// Writes a bundle to `W`, one entry at a time. +pub struct Writer { + tar: tar::Builder>, +} + +impl Writer { + /// # Errors + /// When the encoder can't start. + pub fn new(out: W) -> Result { + let encoder = zstd::Encoder::new(out, LEVEL)?; + let mut tar = tar::Builder::new(encoder); + tar.mode(tar::HeaderMode::Deterministic); + Ok(Self { tar }) + } + + /// Add a file at `path` (relative, `/`-separated) with these bytes. + /// + /// # Errors + /// For an unsafe path, or when writing fails. + pub fn add(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> { + safe_path(path)?; + let mut header = tar::Header::new_gnu(); + header.set_size(bytes.len() as u64); + header.set_mode(0o644); + header.set_entry_type(tar::EntryType::Regular); + self.tar.append_data(&mut header, path, bytes)?; + Ok(()) + } + + /// Finish the archive and the compressed stream, and return the output. + /// + /// # Errors + /// When writing fails. + pub fn finish(self) -> Result { + let encoder = self.tar.into_inner()?; + Ok(encoder.finish()?) + } +} + +/// Unpack a bundle into `dir`, creating it. Returns the paths written, relative to `dir`. Only regular files and +/// directories are written; a path that's absolute or climbs out with `..` stops the unpacking with an error. +/// +/// # Errors +/// For a path that isn't safe, a stream that isn't a tar.zst, or when writing fails. +pub fn unpack(input: impl Read, dir: &Path) -> Result, Error> { + std::fs::create_dir_all(dir)?; + let mut archive = tar::Archive::new(zstd::Decoder::new(input)?); + let mut written = Vec::new(); + for entry in archive.entries()? { + let mut entry = entry?; + let path = entry.path()?.into_owned(); + let shown = path.to_string_lossy().into_owned(); + let relative = safe_path(&shown)?; + match entry.header().entry_type() { + tar::EntryType::Directory => std::fs::create_dir_all(dir.join(&relative))?, + tar::EntryType::Regular => { + let target = dir.join(&relative); + if let Some(parent) = target.parent() { + std::fs::create_dir_all(parent)?; + } + let mut file = std::fs::File::create(&target)?; + io::copy(&mut entry, &mut file)?; + written.push(relative); + } + // Links and anything else: skipped, so a bundle can't point outside `dir` + _ => {} + } + } + Ok(written) +} + +/// Read a bundle's regular files one at a time, in archive order, without writing them anywhere: `f` gets each one's +/// safe relative path (`/`-separated) and bytes. Directories and links are skipped. An unsafe path, or an entry larger +/// than `max_entry_bytes` (refused before it's read), stops it with an error; so does an error from `f`, returned as +/// `Err(Ok(e))` while the bundle's own errors come as `Err(Err(_))`. +/// +/// # Errors +/// As above. +pub fn for_each_entry( + input: impl Read, + max_entry_bytes: u64, + mut f: impl FnMut(&str, Vec) -> Result<(), E>, +) -> Result<(), Result> { + let mut archive = tar::Archive::new(zstd::Decoder::new(input).map_err(|e| Err(e.into()))?); + for entry in archive.entries().map_err(|e| Err(e.into()))? { + let mut entry = entry.map_err(|e| Err(e.into()))?; + if entry.header().entry_type() != tar::EntryType::Regular { + continue; + } + let shown = entry.path().map_err(|e| Err(e.into()))?.to_string_lossy().into_owned(); + let relative = safe_path(&shown).map_err(Err)?; + let path = relative.components().map(|c| c.as_os_str().to_string_lossy()).collect::>().join("/"); + let size = entry.size(); + if size > max_entry_bytes { + return Err(Err(Error::EntryTooLarge { path, size, max: max_entry_bytes })); + } + let mut bytes = Vec::with_capacity(usize::try_from(size).unwrap_or(0)); + (&mut entry).take(max_entry_bytes + 1).read_to_end(&mut bytes).map_err(|e| Err(e.into()))?; + if bytes.len() as u64 > max_entry_bytes { + return Err(Err(Error::EntryTooLarge { path, size: bytes.len() as u64, max: max_entry_bytes })); + } + f(&path, bytes).map_err(Ok)?; + } + Ok(()) +} + +/// The path as a relative path of normal parts, or an error. +fn safe_path(path: &str) -> Result { + let p = Path::new(path); + let mut out = PathBuf::new(); + for c in p.components() { + match c { + Component::Normal(part) => out.push(part), + Component::CurDir => {} + _ => return Err(Error::UnsafePath(path.to_string())), + } + } + if out.as_os_str().is_empty() { + return Err(Error::UnsafePath(path.to_string())); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn writes_and_unpacks_a_bundle() { + let mut w = Writer::new(Vec::new()).unwrap(); + w.add("invoice/page-1/head.png", b"head").unwrap(); + w.add("invoice/page-1/base.png", b"base").unwrap(); + w.add(MANIFEST, b"{}").unwrap(); + let bytes = w.finish().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let written = unpack(bytes.as_slice(), dir.path()).unwrap(); + assert_eq!(written.len(), 3); + assert_eq!(std::fs::read(dir.path().join("invoice/page-1/head.png")).unwrap(), b"head"); + assert_eq!(std::fs::read(dir.path().join(MANIFEST)).unwrap(), b"{}"); + } + + #[test] + fn reads_entries_one_at_a_time_and_refuses_large_ones() { + let mut w = Writer::new(Vec::new()).unwrap(); + w.add("a/one.png", b"one").unwrap(); + w.add("two.png", b"twotwo").unwrap(); + let bytes = w.finish().unwrap(); + let mut seen = Vec::new(); + for_each_entry::<()>(bytes.as_slice(), 100, |path, b| { + seen.push((path.to_string(), b)); + Ok(()) + }) + .unwrap(); + assert_eq!(seen, vec![("a/one.png".to_string(), b"one".to_vec()), ("two.png".to_string(), b"twotwo".to_vec())]); + let err = for_each_entry::<()>(bytes.as_slice(), 4, |_, _| Ok(())).unwrap_err(); + assert!(matches!(err, Err(Error::EntryTooLarge { ref path, size: 6, max: 4 }) if path == "two.png"), "{err:?}"); + let stopped = for_each_entry(bytes.as_slice(), 100, |_, _| Err("stop")).unwrap_err(); + assert!(matches!(stopped, Ok("stop"))); + } + + #[test] + fn refuses_paths_that_leave_the_directory() { + let mut w = Writer::new(Vec::new()).unwrap(); + for bad in ["../x", "/etc/passwd", "a/../../x", ""] { + assert!(matches!(w.add(bad, b"x"), Err(Error::UnsafePath(_))), "{bad}"); + } + // A hand-made archive with an unsafe path is refused when unpacking + let mut tar = tar::Builder::new(zstd::Encoder::new(Vec::new(), LEVEL).unwrap()); + let mut header = tar::Header::new_gnu(); + header.set_size(1); + header.set_entry_type(tar::EntryType::Regular); + header.as_gnu_mut().unwrap().name[..5].copy_from_slice(b"../x\0"); + header.set_cksum(); + tar.append(&header, &b"x"[..]).unwrap(); + let bytes = tar.into_inner().unwrap().finish().unwrap(); + let dir = tempfile::tempdir().unwrap(); + assert!(matches!(unpack(bytes.as_slice(), dir.path()), Err(Error::UnsafePath(_)))); + assert!(!dir.path().parent().unwrap().join("x").exists()); + } +} diff --git a/crates/visualci-core/src/lib.rs b/crates/visualci-core/src/lib.rs index 0b9035f1..e64cba1a 100644 --- a/crates/visualci-core/src/lib.rs +++ b/crates/visualci-core/src/lib.rs @@ -6,6 +6,8 @@ pub mod adapters; pub mod align; +#[cfg(feature = "bundle")] +pub mod bundle; pub mod config; pub mod diff; pub mod image_hash; diff --git a/gemini-extension.json b/gemini-extension.json index d4167084..ae128fcb 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.44", + "version": "0.1.45", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "mcpServers": { "visualci": { diff --git a/server/Cargo.toml b/server/Cargo.toml index baa92bb1..0a810802 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -39,7 +39,7 @@ uuid = { version = "1.6", features = ["v4"] } ts-rs = { version = "12", features = ["chrono-impl", "serde-compat"] } include_dir = { version = "0.7" } axum-extra = { version = "0.10", features = ["form", "cookie"] } -visualci-core = { workspace = true } +visualci-core = { workspace = true, features = ["bundle"] } image = { workspace = true } sha2 = { workspace = true } hex = { workspace = true } @@ -71,6 +71,7 @@ loco-rs = { workspace = true, features = ["testing-core"] } serial_test = { version = "3.1.1" } axum-test = "17.3" insta = { version = "1.34", features = ["filters"] } +tempfile.workspace = true # Dependencies build without debug info. Your own crates keep it, so # breakpoints and backtraces in app code work as before; this roughly halves diff --git a/server/frontend/content/docs/agents.md b/server/frontend/content/docs/agents.md index 8cfbcb35..9699afea 100644 --- a/server/frontend/content/docs/agents.md +++ b/server/frontend/content/docs/agents.md @@ -210,6 +210,7 @@ failing in the repository instead of sending them. - `get_build`: a build's status and the snapshots that need attention, each with its link, 30 at a time (`offset` and `limit`); a longer list also comes grouped by state and name prefix. - `get_snapshot`: one snapshot's comparison, page by page, with images scaled to 1200 pixels wide (`max_width`), or cropped to what changed (`crop: changed`). The platform can be left out when the name is on one platform only. - `contact_sheet`: many snapshots at a glance, as one grid of thumbnails with the list of what's in it, for checking a build with many new snapshots in a few calls. +- `download_build`: a build's images as one tar.zst, for a close look at a big build or for checks of your own (pixel counts, OCR, a script over every page). Filter by `state` (`changed` by default), `sides` (`base`, `head`, `diff`, `regions`: the head cropped to the changes) and a `glob` on snapshot names. It returns a link that lasts an hour and a summary, never the images. The archive has `[@platform][/page-N]/{base,head,diff,regions}.png` and a `manifest.json` with each snapshot's state, pages, changed fraction and regions. With a big build (thousands of pages), scan it with `contact_sheet`, then download the changed images and look at them on disk. Free. - `snapshot_history`: one snapshot across recent builds. - `list_comments`, `post_comment`, `update_comment`, `resolve_comment`, `delete_comment`: comment threads pinned to snapshots. - `get_pr_changeset`: a pull request's (or branch's) changes across all its builds, against its fork point. diff --git a/server/frontend/content/docs/reference/api.md b/server/frontend/content/docs/reference/api.md index 04723e1f..9c7b5394 100644 --- a/server/frontend/content/docs/reference/api.md +++ b/server/frontend/content/docs/reference/api.md @@ -77,6 +77,25 @@ A name (with its platform) is one snapshot per build. Registering it again with `GET /api/v1/builds/{id}/snapshots` lists the build's snapshots: `id`, `name`, `platform`, `kind`, `state`, `review` and `error`. Add `?state=changes` for the changed, added and removed ones, or any single state. +## Download a build's images + +`POST /api/v1/builds/{id or number}/downloads` with a filter (all fields optional) puts the build's images in one +tar.zst: + +| Field | Meaning | +| --- | --- | +| `state` | Which snapshots: `changed` (the default), `added`, `removed`, `unchanged` or `all`. | +| `sides` | Which images of each page: `base`, `head`, `diff`, `regions` (the head cropped to the changed regions). Default: base, head and diff. | +| `glob` | Only snapshots whose name matches, like `v2/pdfjs/**`. | + +The response is the download: `id`, `state` (`pending`, `building`, `ready` or `failed`), and once it's `ready` a +`url` to the archive (it lasts an hour), `files`, `bytes` and a `summary` (how many snapshots of each state, the first +names). `GET /api/v1/downloads/{id}` reads it again until it's ready. The same build and filter within the hour +return the same download. An archive over 2 GB stops with an error that suggests a narrower glob. Downloads are free. + +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). + ## Feedback `POST /api/v1/support/feedback`: see [Support](/docs/support/). diff --git a/server/migration/src/lib.rs b/server/migration/src/lib.rs index fc91132a..36679cc8 100644 --- a/server/migration/src/lib.rs +++ b/server/migration/src/lib.rs @@ -48,6 +48,7 @@ mod m20261202_000041_build_creator; mod m20261202_000042_build_groups; mod m20261203_000046_waitlist; mod m20261203_000047_empty_reason; +mod m20261203_000048_downloads; pub struct Migrator; @@ -102,6 +103,7 @@ impl MigratorTrait for Migrator { Box::new(m20261202_000042_build_groups::Migration), Box::new(m20261203_000046_waitlist::Migration), Box::new(m20261203_000047_empty_reason::Migration), + Box::new(m20261203_000048_downloads::Migration), // inject-above (do not remove this comment) ] } diff --git a/server/migration/src/m20261203_000048_downloads.rs b/server/migration/src/m20261203_000048_downloads.rs new file mode 100644 index 00000000..41121509 --- /dev/null +++ b/server/migration/src/m20261203_000048_downloads.rs @@ -0,0 +1,45 @@ +//! Bulk downloads (sc-8869): a build's images as one tar.zst, built by a worker and kept in the bucket for a day. A +//! ready download of the same build and filter from the last hour is handed out again instead of built anew. +use sea_orm_migration::prelude::*; + +pub struct Migration; + +impl MigrationName for Migration { + fn name(&self) -> &str { + "m20261203_000048_downloads" + } +} + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection() + .execute_unprepared( + "CREATE TABLE downloads ( + id BIGSERIAL PRIMARY KEY, + pid UUID NOT NULL UNIQUE, + build_id BIGINT NOT NULL REFERENCES builds(id) ON DELETE CASCADE, + filter JSONB NOT NULL, + filter_key TEXT NOT NULL, + state TEXT NOT NULL DEFAULT 'pending', + object_key TEXT, + files INTEGER NOT NULL DEFAULT 0, + bytes BIGINT NOT NULL DEFAULT 0, + summary JSONB NOT NULL DEFAULT '{}', + error TEXT, + ready_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() + ); + CREATE INDEX downloads_build_filter ON downloads (build_id, filter_key, created_at DESC); + CREATE INDEX downloads_created_at ON downloads (created_at);", + ) + .await?; + Ok(()) + } + + async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection().execute_unprepared("DROP TABLE downloads;").await?; + Ok(()) + } +} diff --git a/server/src/app.rs b/server/src/app.rs index cba8cb6a..297a0685 100644 --- a/server/src/app.rs +++ b/server/src/app.rs @@ -107,6 +107,7 @@ impl Hooks for App { } async fn connect_workers(ctx: &AppContext, queue: &Queue) -> Result<()> { queue.register(ProcessBuildWorker::build(ctx)).await?; + queue.register(crate::workers::build_download::BuildDownloadWorker::build(ctx)).await?; queue.register(CheckWorker::build(ctx)).await?; queue.register(crate::workers::gallery_purge::GalleryPurgeWorker::build(ctx)).await?; queue.register(crate::workers::pr_comment::PrCommentWorker::build(ctx)).await?; diff --git a/server/src/blobstore.rs b/server/src/blobstore.rs index 0b5e5fc4..de2fedf0 100644 --- a/server/src/blobstore.rs +++ b/server/src/blobstore.rs @@ -174,6 +174,53 @@ impl BlobStore { } } + /// A URL a browser or client can GET a stored object other than a blob from (a bulk download), for an hour. + pub fn object_url(&self, key: &str) -> String { + self.public_bucket.get_object(Some(&self.credentials), key).sign(URL_TTL).to_string() + } + + /// Delete a stored object other than a blob. Deleting one that isn't there succeeds. + /// + /// # Errors + /// When the store can't be reached or refuses. + pub async fn delete_object(&self, key: &str) -> Result<()> { + let url = self.bucket.delete_object(Some(&self.credentials), key).sign(URL_TTL); + let response = self.http.delete(url).send().await.map_err(|e| Error::string(&e.to_string()))?; + let status = response.status(); + if status.is_success() || status.as_u16() == 404 { + Ok(()) + } else { + Err(Error::string(&format!("deleting {key}: HTTP {status}"))) + } + } + + /// Start a multipart upload to `key`, for an object written in parts as it's made (a bulk download). + /// + /// # Errors + /// When the store can't be reached or refuses. + pub async fn start_multipart(&self, key: &str, content_type: &str) -> Result { + let url = self.bucket.create_multipart_upload(Some(&self.credentials), key).sign(URL_TTL); + let response = self + .http + .post(url) + .header("content-type", content_type) + .send() + .await + .map_err(|e| Error::string(&e.to_string()))?; + if !response.status().is_success() { + return Err(Error::string(&format!("starting upload of {key}: HTTP {}", response.status()))); + } + let body = response.text().await.map_err(|e| Error::string(&e.to_string()))?; + let parsed = rusty_s3::actions::CreateMultipartUpload::parse_response(&body) + .map_err(|e| Error::string(&format!("starting upload of {key}: {e}")))?; + Ok(Multipart { + store: self.clone(), + key: key.to_string(), + upload_id: parsed.upload_id().to_string(), + etags: vec![], + }) + } + /// Create the bucket if it doesn't exist (development and tests; production buckets are made by Terraform). /// /// # Errors @@ -197,3 +244,69 @@ impl BlobStore { ctx.shared_store.get::().ok_or_else(|| Error::string("BlobStore isn't in the shared store")) } } + +/// An object being uploaded in parts. Every part but the last must be at least 5 MiB. +pub struct Multipart { + store: BlobStore, + key: String, + upload_id: String, + etags: Vec, +} + +impl Multipart { + /// Upload the next part. + /// + /// # Errors + /// When the store can't be reached or refuses. + pub async fn part(&mut self, bytes: Vec) -> Result<()> { + let number = u16::try_from(self.etags.len() + 1).map_err(|_| Error::string("too many parts"))?; + let url = self + .store + .bucket + .upload_part(Some(&self.store.credentials), &self.key, number, &self.upload_id) + .sign(URL_TTL); + let response = self.store.http.put(url).body(bytes).send().await.map_err(|e| Error::string(&e.to_string()))?; + if !response.status().is_success() { + return Err(Error::string(&format!("uploading part {number} of {}: HTTP {}", self.key, response.status()))); + } + let etag = response + .headers() + .get("etag") + .and_then(|v| v.to_str().ok()) + .ok_or_else(|| Error::string(&format!("part {number} of {}: no ETag", self.key)))?; + self.etags.push(etag.to_string()); + Ok(()) + } + + /// Finish the upload: the object appears. + /// + /// # Errors + /// When the store can't be reached or refuses. + pub async fn complete(self) -> Result<()> { + let action = self.store.bucket.complete_multipart_upload( + Some(&self.store.credentials), + &self.key, + &self.upload_id, + self.etags.iter().map(String::as_str), + ); + let url = action.sign(URL_TTL); + let body = action.body(); + let response = self.store.http.post(url).body(body).send().await.map_err(|e| Error::string(&e.to_string()))?; + if !response.status().is_success() { + return Err(Error::string(&format!("finishing upload of {}: HTTP {}", self.key, response.status()))); + } + Ok(()) + } + + /// Give the upload up, so its parts don't stay in the bucket. + pub async fn abort(self) { + let url = self + .store + .bucket + .abort_multipart_upload(Some(&self.store.credentials), &self.key, &self.upload_id) + .sign(URL_TTL); + if let Err(e) = self.store.http.delete(url).send().await { + tracing::warn!(key = %self.key, error = %e, "aborting a multipart upload failed"); + } + } +} diff --git a/server/src/controllers/api.rs b/server/src/controllers/api.rs index 8dba9b57..ad75d39c 100644 --- a/server/src/controllers/api.rs +++ b/server/src/controllers/api.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; use crate::{ blobstore::BlobStore, - models::{builds, feedback, project_tokens, projects, snapshots, user_tokens}, + models::{builds, downloads, feedback, project_tokens, projects, snapshots, user_tokens}, settings::Settings, workers::process_build::{ProcessBuildWorker, ProcessBuildWorkerArgs}, }; @@ -433,6 +433,48 @@ async fn show_build( ) } +/// A bulk download of a build's images (sc-8869): `POST /api/v1/builds/{id or number}/downloads` with a filter +/// (`state`, `sides`, `glob`) returns the download, building or ready; `GET /api/v1/downloads/{id}` polls it. A ready +/// one has a `url` (an hour) to the tar.zst. Free. +async fn request_download( + ProjectAuth(project): ProjectAuth, + State(ctx): State, + Path(build): Path, + Body(filter): Body, +) -> Result { + let build = match build.parse::() { + Ok(pid) => own_build(&ctx, &project, pid).await?, + Err(_) => { + let number = build.trim_start_matches('#').parse().map_err(|_| Error::NotFound)?; + builds::Model::find_by_number(&ctx.db, project.id, number).await.map_err(|_| Error::NotFound)? + } + }; + let (mut download, new) = downloads::Model::request(&ctx.db, &build, &filter).await.map_err(model_error)?; + if new { + crate::workers::build_download::BuildDownloadWorker::perform_later( + &ctx, + crate::workers::build_download::BuildDownloadWorkerArgs { download_id: download.id }, + ) + .await?; + // A worker that runs inline (or quickly) has already finished it + download = downloads::Model::find_by_pid(&ctx.db, download.pid).await.map_err(model_error)?; + } + format::json(download.to_json(&BlobStore::from_context(&ctx)?)) +} + +async fn show_download( + ProjectAuth(project): ProjectAuth, + State(ctx): State, + Path(pid): Path, +) -> Result { + let download = downloads::Model::find_by_pid(&ctx.db, pid).await.map_err(|_| Error::NotFound)?; + let build = builds::Model::find_by_id(&ctx.db, download.build_id).await.map_err(|_| Error::NotFound)?; + if build.project_id != project.id { + return Err(Error::NotFound); + } + format::json(download.to_json(&BlobStore::from_context(&ctx)?)) +} + #[derive(Debug, Serialize)] struct SnapshotSummary { id: Uuid, @@ -581,4 +623,6 @@ pub fn routes() -> Routes { .add("/builds/{pid}/snapshots", get(list_snapshots)) .add("/builds/{pid}/finalize", post(finalize)) .add("/builds/{pid}/compare", post(compare)) + .add("/builds/{pid}/downloads", post(request_download)) + .add("/downloads/{pid}", get(show_download)) } diff --git a/server/src/mcp.rs b/server/src/mcp.rs index 190365db..89457cce 100644 --- a/server/src/mcp.rs +++ b/server/src/mcp.rs @@ -41,7 +41,7 @@ use crate::{ controllers::api::BuildResponse, models::{ _entities::{credit_transactions, organizations as org_entity, snapshot_pages, users}, - blobs, builds, feedback, identities, invitations, + blobs, builds, downloads, feedback, identities, invitations, memberships::Role, organizations, project_tokens, projects, snapshots, user_tokens, }, @@ -462,6 +462,22 @@ pub struct UploadArgs { pub files: Vec, } +#[derive(Debug, Deserialize, JsonSchema)] +pub struct DownloadArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub build: BuildRef, + /// Which snapshots: `changed` (the default), `added`, `removed`, `unchanged`, or `all`. + pub state: Option, + /// Which images of each page: `base`, `head`, `diff`, `regions` (the head cropped to the changes). Default: base, + /// head and diff. + pub sides: Option>, + /// Only snapshots whose name matches this glob, like `v2/pdfjs/**`. + pub glob: Option, + /// Seconds to wait for the archive (default 50, at most 60). Not ready by then: call again with the same arguments. + pub wait: Option, +} + #[derive(Debug, Deserialize, JsonSchema)] pub struct FinalizeArgs { /// `org/project`. Optional with a project token. @@ -2448,6 +2464,46 @@ impl VisualCi { Ok(CallToolResult::structured(self.build_json(&project, &build, true).await?)) } + #[tool( + description = "Download a build's images as one tar.zst, for a close look at a big build or for checks of your own: a URL (it lasts an hour) and a summary, never the images themselves. Filter by `state` (changed by default, added, removed, unchanged, all), `sides` (base, head, diff, regions: the head cropped to the changes) and a `glob` on snapshot names. The archive has `[@platform][/page-N]/{base,head,diff,regions}.png` and `manifest.json` (each snapshot's state, pages, changed fraction, regions and files). It's built in the background: when `state` is `building`, call again with the same arguments. Free.", + annotations( + title = "Download a build's images", + read_only_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn download_build( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(self.project(&rc, args.project.as_deref())); + let Some(build) = self.find_build(&project, &args.build).await else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let filter = downloads::Filter { state: args.state, sides: args.sides, glob: args.glob }; + let (mut download, new) = match downloads::Model::request(&self.ctx.db, &build, &filter).await { + Ok(d) => d, + Err(e) => return Ok(tool_error(e.to_string())), + }; + if new { + crate::workers::build_download::BuildDownloadWorker::perform_later( + &self.ctx, + crate::workers::build_download::BuildDownloadWorkerArgs { download_id: download.id }, + ) + .await + .map_err(internal)?; + } + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(args.wait.unwrap_or(50).min(60)); + while matches!(download.state.as_str(), "pending" | "building") && std::time::Instant::now() < deadline { + tokio::time::sleep(std::time::Duration::from_secs(2)).await; + download = downloads::Model::find_by_pid(&self.ctx.db, download.pid).await.map_err(internal)?; + } + let store = BlobStore::from_context(&self.ctx).map_err(internal)?; + Ok(CallToolResult::structured(download.to_json(&store))) + } + #[tool( description = "Send something to the VisualCI team. Only about VisualCI itself. Never include secrets, credentials or the user's data. feedback: something got in your way and the work still got done (title, kind, description). Nobody replies. Send it without asking, once per problem, then tell the user what you sent. If a call fails, carry on and don't retry.", annotations( diff --git a/server/src/mcp_images.rs b/server/src/mcp_images.rs index 0d4e55ea..13936f56 100644 --- a/server/src/mcp_images.rs +++ b/server/src/mcp_images.rs @@ -45,6 +45,16 @@ pub fn prepare(bytes: &[u8], crop: Option<&[Region]>, max_width: u32) -> (Vec Option> { + let img = visualci_core::image_hash::decode(bytes).ok()?; + let b = crop_box(regions, img.width(), img.height())?; + let mut png = std::io::Cursor::new(Vec::new()); + img.crop_imm(b.x, b.y, b.width, b.height).write_to(&mut png, ImageFormat::Png).ok()?; + Some(png.into_inner()) +} + fn encode(img: &DynamicImage) -> (Vec, &'static str) { let mut png = std::io::Cursor::new(Vec::new()); if img.write_to(&mut png, ImageFormat::Png).is_ok() && png.get_ref().len() <= PNG_LIMIT { diff --git a/server/src/models/_entities/downloads.rs b/server/src/models/_entities/downloads.rs new file mode 100644 index 00000000..f9365a99 --- /dev/null +++ b/server/src/models/_entities/downloads.rs @@ -0,0 +1,49 @@ +//! `SeaORM` Entity for bulk downloads (sc-8869) + +use sea_orm::entity::prelude::*; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)] +#[sea_orm(table_name = "downloads")] +pub struct Model { + #[sea_orm(primary_key)] + pub id: i64, + #[sea_orm(unique)] + pub pid: Uuid, + pub build_id: i64, + #[sea_orm(column_type = "JsonBinary")] + pub filter: Json, + #[sea_orm(column_type = "Text")] + pub filter_key: String, + #[sea_orm(column_type = "Text")] + pub state: String, + #[sea_orm(column_type = "Text", nullable)] + pub object_key: Option, + pub files: i32, + pub bytes: i64, + #[sea_orm(column_type = "JsonBinary")] + pub summary: Json, + #[sea_orm(column_type = "Text", nullable)] + pub error: Option, + pub ready_at: Option, + pub created_at: DateTimeWithTimeZone, + pub updated_at: DateTimeWithTimeZone, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation { + #[sea_orm( + belongs_to = "super::builds::Entity", + from = "Column::BuildId", + to = "super::builds::Column::Id", + on_update = "NoAction", + on_delete = "Cascade" + )] + Builds, +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::Builds.def() + } +} diff --git a/server/src/models/_entities/mod.rs b/server/src/models/_entities/mod.rs index de5a464c..a20f53e0 100644 --- a/server/src/models/_entities/mod.rs +++ b/server/src/models/_entities/mod.rs @@ -9,6 +9,7 @@ pub mod comment_threads; pub mod comments; pub mod credit_transactions; pub mod diffs; +pub mod downloads; pub mod feedback; pub mod gitlab_instances; pub mod identities; diff --git a/server/src/models/downloads.rs b/server/src/models/downloads.rs new file mode 100644 index 00000000..47bfaa89 --- /dev/null +++ b/server/src/models/downloads.rs @@ -0,0 +1,423 @@ +//! Bulk downloads (sc-8869): a build's images as one tar.zst, for a close look at a big build on disk or for checks +//! of one's own. A worker builds the archive and streams it to the bucket in parts; it's handed out as a presigned URL. +//! A ready download of the same build and filter from the last hour is handed out again. Free: it's a read of what was +//! already compared. +//! +//! The archive holds `[@][/page-]/{base,head,diff,regions}.` (`regions` is the head cropped to +//! the changed regions) and `manifest.json`, which lists every snapshot with its state, pages, changed fraction, +//! regions, files and URL. + +use std::sync::{Arc, Mutex}; + +use loco_rs::prelude::*; +use schemars::JsonSchema; +use sea_orm::{DbBackend, Statement}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use visualci_core::bundle; + +pub use super::_entities::downloads::{self, ActiveModel, Entity, Model}; +use super::{builds, snapshots}; +use crate::blobstore::BlobStore; + +impl ActiveModelBehavior for ActiveModel {} + +/// The most an archive may hold, compressed. A bigger one stops with an error that suggests a narrower glob. +pub const MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024; +/// How long a ready download is handed out again. +pub const REUSE_MINUTES: i64 = 60; +/// How long the archive stays in the bucket (the URL itself lasts an hour from each request). +pub const KEEP_HOURS: i64 = 24; +/// A download still building after this long has stopped (a worker restart): the next request starts another. +pub const STALE_MINUTES: i64 = 15; +/// The bucket's parts: every part but the last must be at least 5 MiB. +const PART_BYTES: usize = 16 * 1024 * 1024; + +/// What to put in the archive. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Filter { + /// Which snapshots: `changed` (the default), `added`, `removed`, `unchanged`, or `all`. + #[serde(default)] + pub state: Option, + /// Which images of each page: `base`, `head`, `diff`, `regions` (the head cropped to the changes). Default: base, + /// head and diff. + #[serde(default)] + pub sides: Option>, + /// Only snapshots whose name matches this glob, like `v2/pdfjs/**`. + #[serde(default)] + pub glob: Option, +} + +pub const STATES: &[&str] = &["changed", "added", "removed", "unchanged", "all"]; +pub const SIDES: &[&str] = &["base", "head", "diff", "regions"]; + +impl Filter { + /// The filter with its defaults filled in and its sides in a fixed order, or an error that says what's wrong. + /// + /// # Errors + /// For an unknown state or side, or a glob that doesn't parse. + pub fn normalized(&self) -> std::result::Result { + let state = self.state.clone().unwrap_or_else(|| "changed".to_string()); + if !STATES.contains(&state.as_str()) { + return Err(format!("state must be one of {}", STATES.join(", "))); + } + let wanted = self.sides.clone().unwrap_or_else(|| vec!["base".into(), "head".into(), "diff".into()]); + if let Some(bad) = wanted.iter().find(|s| !SIDES.contains(&s.as_str())) { + return Err(format!("unknown side {bad:?}: sides are {}", SIDES.join(", "))); + } + let sides: Vec = + SIDES.iter().filter(|s| wanted.iter().any(|w| w == *s)).map(|s| (*s).to_string()).collect(); + if sides.is_empty() { + return Err(format!("sides needs at least one of {}", SIDES.join(", "))); + } + let glob = self.glob.clone().filter(|g| !g.trim().is_empty()); + if let Some(g) = &glob { + globset::Glob::new(g).map_err(|e| format!("glob {g:?}: {e}"))?; + } + Ok(Self { state: Some(state), sides: Some(sides), glob }) + } + + fn key(&self) -> String { + visualci_core::sha256_hex(serde_json::to_string(self).unwrap_or_default().as_bytes()) + } + + fn wants(&self, side: &str) -> bool { + self.sides.as_ref().is_some_and(|s| s.iter().any(|x| x == side)) + } +} + +impl Model { + /// The download for this build and filter: a ready or building one from the last hour, or a new pending one + /// (`true` when it's new and needs a worker). + /// + /// # Errors + /// `Message` for a filter that isn't valid; on a database error. + pub async fn request(db: &DatabaseConnection, build: &builds::Model, filter: &Filter) -> ModelResult<(Self, bool)> { + let filter = filter.normalized().map_err(ModelError::Message)?; + let key = filter.key(); + let recent = Entity::find() + .from_raw_sql(Statement::from_sql_and_values( + DbBackend::Postgres, + "SELECT * FROM downloads WHERE build_id = $1 AND filter_key = $2 AND ( \ + (state = 'ready' AND ready_at > now() - make_interval(mins => $3)) \ + OR (state IN ('pending', 'building') AND updated_at > now() - make_interval(mins => $4))) \ + ORDER BY created_at DESC LIMIT 1", + [build.id.into(), key.clone().into(), (REUSE_MINUTES as i32).into(), (STALE_MINUTES as i32).into()], + )) + .one(db) + .await?; + if let Some(d) = recent { + return Ok((d, false)); + } + let created = ActiveModel { + pid: Set(Uuid::new_v4()), + build_id: Set(build.id), + filter: Set(serde_json::to_value(&filter).unwrap_or_default()), + filter_key: Set(key), + state: Set("pending".to_string()), + ..Default::default() + } + .insert(db) + .await?; + Ok((created, true)) + } + + /// # Errors + /// `EntityNotFound`. + pub async fn find_by_pid(db: &DatabaseConnection, pid: Uuid) -> ModelResult { + Entity::find().filter(downloads::Column::Pid.eq(pid)).one(db).await?.ok_or(ModelError::EntityNotFound) + } + + /// What the API, MCP and the web app show: its state, and when it's ready the URL (an hour), files, size and the + /// manifest's summary. + pub fn to_json(&self, store: &BlobStore) -> serde_json::Value { + let url = (self.state == "ready").then(|| self.object_key.as_deref().map(|k| store.object_url(k))).flatten(); + json!({ + "id": self.pid, + "state": self.state, + "filter": self.filter, + "url": url, + "files": self.files, + "bytes": self.bytes, + "summary": self.summary, + "error": self.error, + }) + } + + async fn set(self, db: &DatabaseConnection, f: impl FnOnce(&mut ActiveModel)) -> ModelResult { + let mut active = self.into_active_model(); + f(&mut active); + active.updated_at = Set(chrono::Utc::now().into()); + Ok(active.update(db).await?) + } + + /// Build the archive and upload it. The download ends `ready`, or `failed` with the reason. + /// + /// # Errors + /// On a database error (a failed build of the archive is recorded on the download, not returned). + pub async fn build(self, db: &DatabaseConnection, store: &BlobStore) -> ModelResult { + if self.state != "pending" { + return Ok(self); + } + let download = self.set(db, |a| a.state = Set("building".to_string())).await?; + let key = format!("downloads/{}.tar.zst", download.pid); + match write_archive(db, store, &download, &key).await { + Ok((files, bytes, summary)) => { + download + .set(db, |a| { + a.state = Set("ready".to_string()); + a.object_key = Set(Some(key)); + a.files = Set(files); + a.bytes = Set(i64::try_from(bytes).unwrap_or(i64::MAX)); + a.summary = Set(summary); + a.ready_at = Set(Some(chrono::Utc::now().into())); + }) + .await + } + Err(e) => { + tracing::warn!(download = %download.pid, error = %e, "building a download failed"); + download + .set(db, |a| { + a.state = Set("failed".to_string()); + a.error = Set(Some(e)); + }) + .await + } + } + } + + /// Delete downloads older than [`KEEP_HOURS`] and their archives (retention:prune runs it daily). Returns how + /// many it deleted. + /// + /// # Errors + /// On a database error. An archive the store can't delete is logged and left for the next run. + pub async fn prune(db: &DatabaseConnection, store: Option<&BlobStore>) -> ModelResult { + let old = Entity::find() + .from_raw_sql(Statement::from_sql_and_values( + DbBackend::Postgres, + "SELECT * FROM downloads WHERE created_at < now() - make_interval(hours => $1)", + [(KEEP_HOURS as i32).into()], + )) + .all(db) + .await?; + let mut deleted = 0; + for d in old { + if let (Some(store), Some(key)) = (store, d.object_key.as_deref()) + && let Err(e) = store.delete_object(key).await + { + tracing::warn!(key, error = %e, "deleting an old download failed"); + continue; + } + Entity::delete_by_id(d.id).exec(db).await?; + deleted += 1; + } + Ok(deleted) + } +} + +/// A `Write` the archive goes into, from which full parts are taken and uploaded. +#[derive(Clone, Default)] +struct Parts(Arc>>); + +impl std::io::Write for Parts { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().map_err(|_| std::io::Error::other("poisoned"))?.extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl Parts { + /// The buffered bytes when there are at least `min` of them (all of them when `min` is 0). + fn take(&self, min: usize) -> Option> { + let mut buf = self.0.lock().ok()?; + (buf.len() >= min && !buf.is_empty()).then(|| std::mem::take(&mut *buf)) + } +} + +/// A path part made safe for a file name: `/` stays a directory separator, `.` and `..` parts and anything outside +/// letters, digits and a few marks become `_`. +fn path_part(name: &str) -> String { + name.split('/') + .filter(|p| !p.is_empty()) + .map(|p| { + let s: String = + p.chars().map(|c| if c.is_alphanumeric() || " ._-()+=,@".contains(c) { c } else { '_' }).collect(); + if s == "." || s == ".." { "_".to_string() } else { s } + }) + .collect::>() + .join("/") +} + +fn extension(bytes: &[u8]) -> &'static str { + match image::guess_format(bytes) { + Ok(image::ImageFormat::Jpeg) => "jpg", + Ok(image::ImageFormat::WebP) => "webp", + _ => "png", + } +} + +/// Write the archive to the bucket. Returns its files, its compressed size and the manifest's summary. +async fn write_archive( + db: &DatabaseConnection, + store: &BlobStore, + download: &Model, + key: &str, +) -> std::result::Result<(i32, u64, serde_json::Value), String> { + let filter: Filter = serde_json::from_value(download.filter.clone()).map_err(|e| e.to_string())?; + let build = builds::Model::find_by_id(db, download.build_id).await.map_err(|e| e.to_string())?; + let glob = filter + .glob + .as_deref() + .map(|g| globset::Glob::new(g).map(|g| g.compile_matcher())) + .transpose() + .map_err(|e| e.to_string())?; + let state = filter.state.clone().unwrap_or_else(|| "changed".to_string()); + let chosen: Vec = snapshots::Model::for_build(db, build.id) + .await + .map_err(|e| e.to_string())? + .into_iter() + .filter(|s| s.platform != snapshots::CONFIG_PLATFORM && s.kind != "text") + .filter(|s| state == "all" || s.state == state) + .filter(|s| glob.as_ref().is_none_or(|g| g.is_match(&s.name))) + .collect(); + + let parts = Parts::default(); + let mut writer = bundle::Writer::new(parts.clone()).map_err(|e| e.to_string())?; + let mut upload = store.start_multipart(key, "application/zstd").await.map_err(|e| e.to_string())?; + let mut sent: u64 = 0; + let mut files = 0i32; + let mut entries = Vec::new(); + let result: std::result::Result<(), String> = async { + for s in &chosen { + let detail = s.review_detail(db, store, 0).await.map_err(|e| e.to_string())?; + let mut dir = path_part(&s.name); + if !s.platform.is_empty() { + dir = format!("{dir}@{}", path_part(&s.platform)); + } + let several = detail.pages.len() > 1; + let mut pages = Vec::new(); + for p in &detail.pages { + let page_dir = if several { format!("{dir}/page-{}", p.position + 1) } else { dir.clone() }; + let mut written = Vec::new(); + for side in SIDES { + if !filter.wants(side) { + continue; + } + let sha = match *side { + "base" => p.base_image.as_deref(), + "head" | "regions" => p.head_image.as_deref(), + _ => p.overlay_image.as_deref(), + }; + let Some(sha) = sha else { continue }; + let regions = p.diff.as_ref().map(|d| d.regions.as_slice()).unwrap_or_default(); + if *side == "regions" && regions.is_empty() { + continue; + } + let mut bytes = store.get(sha).await.map_err(|e| e.to_string())?; + if *side == "regions" { + bytes = crate::mcp_images::crop_png(&bytes, regions).unwrap_or(bytes); + } + let path = format!("{page_dir}/{side}.{}", extension(&bytes)); + writer.add(&path, &bytes).map_err(|e| e.to_string())?; + files += 1; + written.push(path); + if let Some(part) = parts.take(PART_BYTES) { + sent += part.len() as u64; + if sent > MAX_BYTES { + return Err(too_big()); + } + upload.part(part).await.map_err(|e| e.to_string())?; + } + } + pages.push(json!({ + "position": p.position, + "state": p.state, + "changed_fraction": p.diff.as_ref().map(|d| d.changed_fraction), + "regions": p.diff.as_ref().map(|d| &d.regions), + "files": written, + })); + } + entries.push(json!({ + "name": s.name, + "platform": s.platform, + "state": s.state, + "path": dir, + "pages": pages, + })); + } + Ok(()) + } + .await; + if let Err(e) = result { + upload.abort().await; + return Err(e); + } + let mut counts = std::collections::BTreeMap::::new(); + for s in &chosen { + *counts.entry(s.state.clone()).or_default() += 1; + } + let summary = json!({ + "build": build.number, + "snapshots": chosen.len(), + "by_state": counts, + "names": chosen.iter().take(20).map(|s| &s.name).collect::>(), + }); + let manifest = json!({ "build": build.number, "commit": build.commit_sha, "filter": filter, "snapshots": entries }); + let finished = async { + writer + .add(bundle::MANIFEST, &serde_json::to_vec_pretty(&manifest).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; + writer.finish().map_err(|e| e.to_string())?; + if let Some(last) = parts.take(0) { + sent += last.len() as u64; + if sent > MAX_BYTES { + return Err(too_big()); + } + upload.part(last).await.map_err(|e| e.to_string())?; + } + Ok::<_, String>(()) + } + .await; + if let Err(e) = finished { + upload.abort().await; + return Err(e); + } + upload.complete().await.map_err(|e| e.to_string())?; + Ok((files + 1, sent, summary)) +} + +fn too_big() -> String { + format!( + "The archive would be larger than {} GB: download part of the build with a narrower glob (like `v2/**`) or \ + fewer sides", + MAX_BYTES / (1024 * 1024 * 1024) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn path_parts_stay_inside_the_archive() { + assert_eq!(path_part("v2/pdfjs/invoice page"), "v2/pdfjs/invoice page"); + assert_eq!(path_part("../../etc/passwd"), "_/_/etc/passwd"); + assert_eq!(path_part("/a//b:c"), "a/b_c"); + } + + #[test] + fn a_filter_fills_its_defaults_and_refuses_what_it_does_not_know() { + let f = Filter::default().normalized().unwrap(); + assert_eq!(f.state.as_deref(), Some("changed")); + assert_eq!(f.sides, Some(vec!["base".into(), "head".into(), "diff".into()])); + let same = Filter { sides: Some(vec!["diff".into(), "head".into(), "base".into()]), ..Default::default() }; + assert_eq!(same.normalized().unwrap().key(), f.key(), "the order of sides doesn't matter"); + assert!(Filter { state: Some("new".into()), ..Default::default() }.normalized().is_err()); + assert!(Filter { sides: Some(vec!["left".into()]), ..Default::default() }.normalized().is_err()); + assert!(Filter { glob: Some("a/[".into()), ..Default::default() }.normalized().is_err()); + } +} diff --git a/server/src/models/mod.rs b/server/src/models/mod.rs index 624dc7ac..bb8677a4 100644 --- a/server/src/models/mod.rs +++ b/server/src/models/mod.rs @@ -9,6 +9,7 @@ pub mod comments; pub mod credit_transactions; pub mod device_logins; pub mod diffs; +pub mod downloads; pub mod feedback; pub mod gallery; pub mod gitlab_instances; diff --git a/server/src/tasks/retention_prune.rs b/server/src/tasks/retention_prune.rs index a8f5df20..a8f24217 100644 --- a/server/src/tasks/retention_prune.rs +++ b/server/src/tasks/retention_prune.rs @@ -1,7 +1,8 @@ //! `cargo loco task retention:prune [days:90] [dry_run:true]`: delete the images, PDFs and render rows nothing needs -//! any more (see `models::retention` for what's kept). Runs daily in production and pings its heartbeat when it -//! ends (`VISUALCI_RETENTION_HEARTBEAT_URL`, a Gatus external endpoint, with `VISUALCI_RETENTION_HEARTBEAT_TOKEN`): -//! Gatus alerts on a failed run and on a day with no run. +//! any more (see `models::retention` for what's kept), and bulk downloads older than a day (`models::downloads`). +//! Runs daily in production and pings its heartbeat when it ends (`VISUALCI_RETENTION_HEARTBEAT_URL`, a Gatus +//! external endpoint, with `VISUALCI_RETENTION_HEARTBEAT_TOKEN`): Gatus alerts on a failed run and on a day with no +//! run. use loco_rs::prelude::*; @@ -38,11 +39,17 @@ impl Task for RetentionPrune { println!("retention (dry run, {days} days): would delete {}", result?); return Ok(()); } - let outcome = match &result { - Ok(report) if report.store_errors > 0 => Err(format!("{} store deletes failed", report.store_errors)), - Ok(_) => Ok(()), - Err(e) => Err(e.to_string()), + // Bulk downloads older than a day, and their archives + let downloads = crate::models::downloads::Model::prune(&ctx.db, Some(&store)).await; + let outcome = match (&result, &downloads) { + (Ok(report), _) if report.store_errors > 0 => Err(format!("{} store deletes failed", report.store_errors)), + (Err(e), _) => Err(e.to_string()), + (_, Err(e)) => Err(format!("pruning downloads: {e}")), + _ => Ok(()), }; + if let Ok(n) = &downloads { + println!("downloads: deleted {n}"); + } crate::heartbeat::push("VISUALCI_RETENTION_HEARTBEAT", outcome.clone()).await; println!("retention ({days} days): deleted {}", result?); outcome.map_err(|e| Error::string(&e)) diff --git a/server/src/workers/build_download.rs b/server/src/workers/build_download.rs new file mode 100644 index 00000000..ac344580 --- /dev/null +++ b/server/src/workers/build_download.rs @@ -0,0 +1,33 @@ +//! Builds a bulk download's archive (sc-8869, `models::downloads`). Enqueued when a download is requested and no +//! ready or building one of the same build and filter is recent. A download left building by a worker that stopped +//! is replaced on the next request after `downloads::STALE_MINUTES`. + +use loco_rs::prelude::*; +use serde::{Deserialize, Serialize}; + +use crate::{blobstore::BlobStore, models::downloads}; + +pub struct BuildDownloadWorker { + pub ctx: AppContext, +} + +#[derive(Deserialize, Debug, Serialize)] +pub struct BuildDownloadWorkerArgs { + pub download_id: i64, +} + +#[async_trait] +impl BackgroundWorker for BuildDownloadWorker { + fn build(ctx: &AppContext) -> Self { + Self { ctx: ctx.clone() } + } + + async fn perform(&self, args: BuildDownloadWorkerArgs) -> Result<()> { + let store = BlobStore::from_context(&self.ctx)?; + let Some(download) = downloads::Entity::find_by_id(args.download_id).one(&self.ctx.db).await? else { + return Ok(()); + }; + download.build(&self.ctx.db, &store).await?; + Ok(()) + } +} diff --git a/server/src/workers/mod.rs b/server/src/workers/mod.rs index eadf272c..d7dee6d4 100644 --- a/server/src/workers/mod.rs +++ b/server/src/workers/mod.rs @@ -1,3 +1,4 @@ +pub mod build_download; pub mod forge_check; pub mod gallery_purge; pub mod notify_feedback; diff --git a/server/tests/requests/downloads.rs b/server/tests/requests/downloads.rs new file mode 100644 index 00000000..0496173f --- /dev/null +++ b/server/tests/requests/downloads.rs @@ -0,0 +1,183 @@ +//! Bulk downloads (sc-8869): a build's images as one tar.zst, filtered by state, sides and glob, reused within the +//! hour, and deleted by retention after a day. +//! +//! These need the S3-compatible blob store (MinIO on the dev box). Where it can't be reached (CI has none), they print +//! why and pass without running. + +use loco_rs::testing::prelude::*; +use sea_orm::{ActiveModelTrait, IntoActiveModel, Set}; +use serial_test::serial; +use visualci_server::{ + app::App, + blobstore::BlobStore, + models::{_entities::users, builds, downloads, organizations, project_tokens, projects, snapshots}, +}; + +fn png(rgb: [u8; 3]) -> Vec { + // Big enough that the changed square, with the crop's margin, is smaller than the image + let mut img = image::RgbImage::from_pixel(200, 150, image::Rgb([255, 255, 255])); + for x in 90..110 { + for y in 60..80 { + img.put_pixel(x, y, image::Rgb(rgb)); + } + } + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() +} + +const RED: [u8; 3] = [255, 0, 0]; +const GREEN: [u8; 3] = [0, 255, 0]; +const BLUE: [u8; 3] = [0, 0, 255]; + +struct World<'a> { + db: &'a sea_orm::DatabaseConnection, + store: BlobStore, + project: projects::Model, + token: String, +} + +impl World<'_> { + async fn build(&self, commit: &str, parents: &[&str], files: &[(&str, [u8; 3])]) -> builds::Model { + let params: builds::CreateParams = serde_json::from_value(serde_json::json!({ + "commit": commit, "branch": "main", "parent_commits": parents, "environment": "ci", "mode": "ci", + })) + .unwrap(); + let build = builds::Model::create(self.db, &self.project, ¶ms).await.unwrap(); + let mut list = Vec::new(); + for (name, rgb) in files { + let bytes = png(*rgb); + let sha = self.store.put(bytes.clone(), "image/png").await.unwrap(); + let blob = visualci_server::models::blobs::Model::register(self.db, &sha, bytes.len() as i64, "image/png") + .await + .unwrap(); + let mut active = blob.into_active_model(); + active.uploaded_at = Set(Some(chrono::Utc::now().into())); + active.update(self.db).await.unwrap(); + list.push( + serde_json::from_value::(serde_json::json!({ + "name": name, "kind": "image", "sha256": sha, "size": bytes.len(), "content_type": "image/png", + "fingerprint": visualci_core::image_hash::fingerprint_bytes(&bytes).unwrap(), + })) + .unwrap(), + ); + } + build.register_snapshots(self.db, &self.project, "test", &list).await.unwrap(); + let build = build.finalize_shard(self.db, None, false).await.unwrap(); + let id = build.id; + assert!(build.process(self.db, &self.store, "test").await.unwrap(), "processed"); + builds::Model::find_by_id(self.db, id).await.unwrap() + } +} + +async fn world(ctx: &loco_rs::prelude::AppContext) -> Option> { + use loco_rs::prelude::*; + let store = BlobStore::from_context(ctx).ok()?; + if let Err(e) = store.ensure_bucket().await { + eprintln!("skipping: no blob store ({e})"); + return None; + } + let user = users::ActiveModel { + pid: Set(Uuid::new_v4()), + email: Set(format!("{}@example.com", Uuid::new_v4())), + password: Set(String::new()), + api_key: Set(format!("lo-{}", Uuid::new_v4())), + name: Set("admin".to_string()), + ..Default::default() + } + .insert(&ctx.db) + .await + .unwrap(); + let slug = format!("org-{}", &Uuid::new_v4().to_string()[..8]); + let org = organizations::Model::create_with_admin(&ctx.db, &slug, "Org", user.id).await.unwrap(); + let project = projects::Model::create(&ctx.db, org.id, "web", "Web").await.unwrap(); + let token = project_tokens::Model::generate(&ctx.db, project.id, "test").await.unwrap().1; + Some(World { db: &ctx.db, store, project, token }) +} + +#[tokio::test] +#[serial] +async fn a_builds_changed_images_download_as_one_archive() { + request::(|request, ctx| async move { + let Some(w) = world(&ctx).await else { return }; + w.build("A", &[], &[("web/a", RED), ("web/b", BLUE), ("other/c", RED)]).await; + let b = w.build("B", &["A"], &[("web/a", GREEN), ("web/b", BLUE), ("other/c", BLUE)]).await; + let auth = format!("Bearer {}", w.token); + + // The changed snapshots under web/, by build number: the worker runs inline in tests + let r = request + .post(&format!("/api/v1/builds/{}/downloads", b.number)) + .add_header("authorization", auth.clone()) + .json(&serde_json::json!({ "glob": "web/**", "sides": ["head", "regions"] })) + .await; + assert_eq!(r.status_code(), 200, "{}", r.text()); + let first: serde_json::Value = r.json(); + assert_eq!(first["state"], "ready", "{first}"); + assert_eq!(first["summary"]["snapshots"], 1, "only web/a changed under web/: {first}"); + assert_eq!(first["files"], 3, "head, regions and the manifest: {first}"); + + let bytes = reqwest::get(first["url"].as_str().unwrap()).await.unwrap().bytes().await.unwrap(); + let dir = tempfile::tempdir().unwrap(); + let written = visualci_core::bundle::unpack(bytes.as_ref(), dir.path()).unwrap(); + assert_eq!(written.len(), 3, "{written:?}"); + assert_eq!(std::fs::read(dir.path().join("web/a/head.png")).unwrap(), png(GREEN)); + let regions = image::open(dir.path().join("web/a/regions.png")).unwrap(); + assert!(regions.width() < 200 && regions.height() < 150, "cropped to the change"); + let manifest: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.path().join("manifest.json")).unwrap()).unwrap(); + assert_eq!(manifest["snapshots"][0]["name"], "web/a"); + assert_eq!(manifest["snapshots"][0]["pages"][0]["files"].as_array().unwrap().len(), 2); + + // The same filter within the hour: the same download, not built again + let again: serde_json::Value = request + .post(&format!("/api/v1/builds/{}/downloads", b.number)) + .add_header("authorization", auth.clone()) + .json(&serde_json::json!({ "glob": "web/**", "sides": ["regions", "head"] })) + .await + .json(); + assert_eq!(again["id"], first["id"]); + let shown: serde_json::Value = request + .get(&format!("/api/v1/downloads/{}", first["id"].as_str().unwrap())) + .add_header("authorization", auth.clone()) + .await + .json(); + assert_eq!(shown["state"], "ready"); + + // A filter it doesn't know is refused, saying why + let r = request + .post(&format!("/api/v1/builds/{}/downloads", b.number)) + .add_header("authorization", auth) + .json(&serde_json::json!({ "state": "new" })) + .await; + assert_eq!(r.status_code(), 400, "{}", r.text()); + assert!(r.text().contains("state must be one of"), "{}", r.text()); + + // After a day, retention deletes the download and its archive + let d = downloads::Model::find_by_pid(w.db, first["id"].as_str().unwrap().parse().unwrap()).await.unwrap(); + let key = d.object_key.clone().unwrap(); + let mut active = d.into_active_model(); + active.created_at = Set((chrono::Utc::now() - chrono::Duration::hours(25)).into()); + active.update(w.db).await.unwrap(); + assert_eq!(downloads::Model::prune(w.db, Some(&w.store)).await.unwrap(), 1); + let gone = reqwest::get(w.store.object_url(&key)).await.unwrap(); + assert_eq!(gone.status().as_u16(), 404); + }) + .await; +} + +#[tokio::test] +#[serial] +async fn another_projects_token_can_not_download_a_build() { + request::(|request, ctx| async move { + let Some(w) = world(&ctx).await else { return }; + let b = w.build("A", &[], &[("web/a", RED)]).await; + let other = world(&ctx).await.unwrap(); + let r = request + .post(&format!("/api/v1/builds/{}/downloads", b.pid)) + .add_header("authorization", format!("Bearer {}", other.token)) + .json(&serde_json::json!({})) + .await; + assert_eq!(r.status_code(), 404, "{}", r.text()); + }) + .await; +} diff --git a/server/tests/requests/mod.rs b/server/tests/requests/mod.rs index 74b4246b..496547a8 100644 --- a/server/tests/requests/mod.rs +++ b/server/tests/requests/mod.rs @@ -7,6 +7,7 @@ mod changeset; mod comments; mod demo; mod device_login; +mod downloads; mod emails; mod forge_webhooks; mod gallery; diff --git a/skills/visualci-review/SKILL.md b/skills/visualci-review/SKILL.md index e6a43ad5..b0a3212f 100644 --- a/skills/visualci-review/SKILL.md +++ b/skills/visualci-review/SKILL.md @@ -215,6 +215,7 @@ failing in the repository instead of sending them. - `get_build`: a build's status and the snapshots that need attention, each with its link, 30 at a time (`offset` and `limit`); a longer list also comes grouped by state and name prefix. - `get_snapshot`: one snapshot's comparison, page by page, with images scaled to 1200 pixels wide (`max_width`), or cropped to what changed (`crop: changed`). The platform can be left out when the name is on one platform only. - `contact_sheet`: many snapshots at a glance, as one grid of thumbnails with the list of what's in it, for checking a build with many new snapshots in a few calls. +- `download_build`: a build's images as one tar.zst, for a close look at a big build or for checks of your own (pixel counts, OCR, a script over every page). Filter by `state` (`changed` by default), `sides` (`base`, `head`, `diff`, `regions`: the head cropped to the changes) and a `glob` on snapshot names. It returns a link that lasts an hour and a summary, never the images. The archive has `[@platform][/page-N]/{base,head,diff,regions}.png` and a `manifest.json` with each snapshot's state, pages, changed fraction and regions. With a big build (thousands of pages), scan it with `contact_sheet`, then download the changed images and look at them on disk. Free. - `snapshot_history`: one snapshot across recent builds. - `list_comments`, `post_comment`, `update_comment`, `resolve_comment`, `delete_comment`: comment threads pinned to snapshots. - `get_pr_changeset`: a pull request's (or branch's) changes across all its builds, against its fork point.