diff --git a/app/Cargo.lock b/app/Cargo.lock index 8ade652e..af0bece3 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -455,6 +455,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -1014,6 +1016,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" @@ -1960,6 +1972,16 @@ dependencies = [ "syn 2.0.119", ] +[[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" @@ -4202,6 +4224,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" @@ -4703,6 +4735,7 @@ dependencies = [ "hmac 0.12.1", "image", "include_dir", + "ipnet", "laravel-rust", "oauth-provider", "oauth-provider-laravel", @@ -4736,7 +4769,9 @@ dependencies = [ "sha2 0.10.9", "similar", "snapshot-diff", + "tar", "thiserror", + "zstd", ] [[package]] @@ -5243,6 +5278,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/app/Cargo.toml b/app/Cargo.toml index 805dbec1..107a1131 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -38,6 +38,7 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg", reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } rusty-s3 = "0.12" globset = "0.4" +ipnet = "2" schemars = "1" tracing = "0.1" include_dir = "0.7" @@ -47,7 +48,7 @@ tower = { version = "0.5", features = ["util"] } url = "2" regex = "1" # VisualCI's own crates, shared with the CLI. -visualci-core = { path = "../crates/visualci-core" } +visualci-core = { path = "../crates/visualci-core", features = ["bundle"] } snapshot-diff = { path = "../crates/snapshot-diff" } [dev-dependencies] diff --git a/app/database/migrations/2026_12_03_000300_render_uploads_blob_deleting_gallery_urls.rs b/app/database/migrations/2026_12_03_000300_render_uploads_blob_deleting_gallery_urls.rs new file mode 100644 index 00000000..27e7ee3a --- /dev/null +++ b/app/database/migrations/2026_12_03_000300_render_uploads_blob_deleting_gallery_urls.rs @@ -0,0 +1,41 @@ +//! Columns the renderer API, retention and the gallery need (#81's review): +//! +//! - `blobs.deleting`: retention marks a blob before deleting its object, and deletes the row only while it's still +//! marked. Registering the hash again clears the mark (and has the file uploaded again), so a build reusing a file +//! while a prune runs keeps it. +//! - `renders.uploads`: the PNGs a render uploaded through its own uploads, by hash: `"blob"` for one it uploaded to +//! the blob itself, `"proof"` for one already stored, which it uploaded to a proof key instead. Completing the render +//! may name only these as page images, so a renderer can't name another tenant's PNG by its hash. +//! - `renders.used_at`: when a snapshot last reused the render. Retention leaves a recently reused render's images and +//! texts alone, since the build reusing it isn't in the prune's keep sets. +//! - `projects.gallery_urls`: the gallery URLs last purged as published, so a screenshot that drops out of the gallery +//! is purged too. +//! - `gallery_purge_failures`: purges that used up their retries, counted in `/status`. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r" +ALTER TABLE blobs ADD COLUMN deleting boolean DEFAULT false NOT NULL; +CREATE INDEX blobs_deleting ON blobs USING btree (sha256) WHERE deleting; + +ALTER TABLE renders ADD COLUMN uploads jsonb DEFAULT '{}'::jsonb NOT NULL; +ALTER TABLE renders ADD COLUMN used_at timestamp with time zone; +CREATE INDEX renders_used_at ON renders USING btree (used_at) WHERE used_at IS NOT NULL; + +ALTER TABLE projects ADD COLUMN gallery_urls jsonb DEFAULT '[]'::jsonb NOT NULL; + +CREATE TABLE gallery_purge_failures ( + id bigserial PRIMARY KEY, + project_id bigint REFERENCES projects(id) ON DELETE CASCADE, + build_id bigint REFERENCES builds(id) ON DELETE SET NULL, + urls jsonb NOT NULL, + error text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); +CREATE INDEX gallery_purge_failures_created ON gallery_purge_failures USING btree (created_at); +"; diff --git a/app/database/migrations/2026_12_03_000400_diffs_used_at.rs b/app/database/migrations/2026_12_03_000400_diffs_used_at.rs new file mode 100644 index 00000000..be42b880 --- /dev/null +++ b/app/database/migrations/2026_12_03_000400_diffs_used_at.rs @@ -0,0 +1,14 @@ +//! `diffs.used_at`: when a comparison last reused the cached diff. Retention leaves the overlay of a diff reused in the +//! last day alone, since the build reusing it isn't in the prune's keep sets. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r" +ALTER TABLE diffs ADD COLUMN used_at timestamp with time zone; +CREATE INDEX diffs_used_at ON diffs USING btree (used_at) WHERE used_at IS NOT NULL; +"; diff --git a/app/src/config.rs b/app/src/config.rs index 635ffca6..91af7d8d 100644 --- a/app/src/config.rs +++ b/app/src/config.rs @@ -21,3 +21,70 @@ pub struct Storage { #[env("S3_SECRET_ACCESS_KEY", required)] pub secret_access_key: String, } + +/// The renderers' API (`/internal/renderer`): the shared token renderers claim work with, the metrics scraper's own +/// token, and the renderer image's version, part of every render's cache key. +#[derive(Clone, Debug, Section)] +pub struct Renderer { + /// Required: without it, nobody could claim renders, and an empty token would match nothing anyway. + #[env("RENDERER_TOKEN", required)] + pub token: String, + /// The renderer version documents are drawn with: part of the render cache key, and what a renderer's claim must + /// match exactly. Required: the app doesn't start without it. + #[env("RENDERER_VERSION", required)] + pub version: String, + /// Empty turns the metrics endpoint off (no token matches it). + #[env("METRICS_TOKEN", default = "")] + pub metrics_token: String, +} + +/// Cloudflare, for purging public gallery URLs after a change (`jobs::purge_gallery`). Empty in development: nothing is +/// purged. +#[derive(Clone, Debug, Section)] +pub struct Cloudflare { + #[env("VISUALCI_CLOUDFLARE_ZONE_ID", default = "")] + pub zone_id: String, + #[env("VISUALCI_CLOUDFLARE_PURGE_TOKEN", default = "")] + pub purge_token: String, +} + +/// Cloudflare's published edge ranges (https://www.cloudflare.com/ips/), for [`Gallery::cloudflare_ip_ranges`]. +pub const CLOUDFLARE_IP_RANGES: &str = "173.245.48.0/20,103.21.244.0/22,103.22.200.0/22,103.31.4.0/22,141.101.64.0/18,\ +108.162.192.0/18,190.93.240.0/20,188.114.96.0/20,197.234.240.0/22,198.41.128.0/17,162.158.0.0/15,104.16.0.0/13,\ +104.24.0.0/14,172.64.0.0/13,131.0.72.0/22,2400:cb00::/32,2606:4700::/32,2803:f800::/32,2405:b500::/32,2405:8100::/32,\ +2a06:98c0::/29,2c0f:f248::/32"; + +/// The public gallery (`http::gallery`). +#[derive(Clone, Debug, Section)] +pub struct Gallery { + /// The networks whose `cf-connecting-ip` header is believed: Cloudflare's edge, comma-separated. A request from + /// anywhere else is limited by its own address, so a client can't rotate the header to dodge the rate limit. + #[env("VISUALCI_CLOUDFLARE_IP_RANGES", default = "")] + pub cloudflare_ip_ranges: String, + /// The most gallery credits one project is charged in a day: images past it are served free. + #[env("VISUALCI_GALLERY_DAILY_CREDITS", default = 50_000)] + pub daily_credits: i64, +} + +impl Gallery { + /// The Cloudflare networks: the configured ones, else the published list. + #[must_use] + pub fn cloudflare_networks(&self) -> Vec { + let list = + if self.cloudflare_ip_ranges.trim().is_empty() { CLOUDFLARE_IP_RANGES } else { &self.cloudflare_ip_ranges }; + list.split(',').filter_map(|n| n.trim().parse().ok()).collect() + } +} + +/// The proxies in front of the app whose `X-Forwarded-For` is believed (`TRUSTED_PROXIES`, comma-separated; the +/// cluster's network by default). Behind them, a request's address is the nearest one that isn't a trusted proxy: +/// Cloudflare's edge, or a client that reached the ingress directly. +#[must_use] +pub fn trusted_proxies() -> Vec { + std::env::var("TRUSTED_PROXIES") + .unwrap_or_else(|_| "10.0.0.0/8".to_string()) + .split(',') + .map(|p| p.trim().to_string()) + .filter(|p| !p.is_empty()) + .collect() +} diff --git a/app/src/console/mod.rs b/app/src/console/mod.rs index 4da66664..294fe017 100644 --- a/app/src/console/mod.rs +++ b/app/src/console/mod.rs @@ -1,14 +1,18 @@ //! The schedule (`laravel schedule:run` every minute, in production a CronJob): the builds sweep every five minutes, -//! each run pushing its result to a heartbeat so a sweep that failed or stopped running alerts. +//! retention and the groups check daily, each run pushing its result to a heartbeat so a task that failed or stopped +//! running alerts. use laravel::schedule::{self, Schedule}; // The heartbeat every scheduled task pushes to (`crate::heartbeat`). pub use crate::heartbeat; +pub mod retention; #[schedule::tasks] fn schedule(schedule: &mut Schedule) { schedule.call(sweep_builds).name("builds-sweep").every_five_minutes().without_overlapping().on_one_runner(); + schedule.command("retention:prune").daily_at("03:00").without_overlapping().on_one_runner(); + schedule.command("groups:check").daily_at("04:00").without_overlapping().on_one_runner(); } /// [`crate::domain::processing::sweep`], with its heartbeat (`VISUALCI_BUILDS_SWEEP_HEARTBEAT_URL` and `_TOKEN`). diff --git a/app/src/console/retention.rs b/app/src/console/retention.rs new file mode 100644 index 00000000..959311de --- /dev/null +++ b/app/src/console/retention.rs @@ -0,0 +1,76 @@ +//! Retention's commands, run daily by the schedule (`console`), each pushing its result to its heartbeat. + +use laravel::console::{Console, clap, command}; + +use super::heartbeat; +use crate::domain::{downloads, retention}; +use crate::storage::BlobStore; + +/// `retention:prune`, daily: delete the images, PDFs, render rows and page texts nothing needs any more (see +/// `domain::retention` for what's kept), and bulk downloads older than a day (`domain::downloads`). Pushes its result +/// to `VISUALCI_RETENTION_HEARTBEAT_URL` (and `_TOKEN`): Gatus alerts on a failed run and on a day with no run. +#[derive(clap::Parser)] +#[command(name = "retention:prune")] +pub struct RetentionPrune { + /// Keep every build from this many days (at least 30). + #[arg(long, default_value_t = retention::RETENTION_DAYS)] + days: i32, + /// Only count what would go. + #[arg(long)] + dry_run: bool, +} + +#[command] +impl RetentionPrune { + async fn handle(self, console: &mut Console) -> laravel::Result<()> { + if self.days < 30 { + return Err(laravel::Error::msg("days must be at least 30")); + } + let store = BlobStore::current().await?; + let result = retention::prune(Some(&store), self.days, self.dry_run).await; + if self.dry_run { + console.line(format!("retention (dry run, {} days): would delete {}", self.days, result?)); + return Ok(()); + } + // Bulk downloads older than a day, and their archives. + let pruned = downloads::prune(Some(&store)).await; + let outcome = match (&result, &pruned) { + (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) = &pruned { + console.line(format!("downloads: deleted {n}")); + } + heartbeat::push("VISUALCI_RETENTION_HEARTBEAT", outcome.clone()).await; + console.line(format!("retention ({} days): deleted {}", self.days, result?)); + outcome.map_err(laravel::Error::msg) + } +} + +/// `groups:check`, nightly: every group a build reads from another build still has rows there +/// ([`retention::empty_groups`], docs/design-storage.md). A group that resolves to no rows shows its build with +/// snapshots missing, so any fails the run and its heartbeat (`VISUALCI_GROUPS_CHECK_HEARTBEAT_URL` and `_TOKEN`). +#[derive(clap::Parser)] +#[command(name = "groups:check")] +pub struct GroupsCheck; + +#[command] +impl GroupsCheck { + async fn handle(self, console: &mut Console) -> laravel::Result<()> { + let outcome = match retention::empty_groups().await { + Ok(empty) if empty.is_empty() => Ok(()), + Ok(empty) => { + let shown: Vec = + empty.iter().take(20).map(|(build, key)| format!("build {build} group {key:?}")).collect(); + Err(format!("{} groups resolve to no rows: {}", empty.len(), shown.join(", "))) + } + Err(e) => Err(e.to_string()), + }; + heartbeat::push("VISUALCI_GROUPS_CHECK_HEARTBEAT", outcome.clone()).await; + outcome.map_err(laravel::Error::msg)?; + console.line("groups:check: every sourced group has its rows"); + Ok(()) + } +} diff --git a/app/src/domain/blobs.rs b/app/src/domain/blobs.rs index c35324d7..64b050e8 100644 --- a/app/src/domain/blobs.rs +++ b/app/src/domain/blobs.rs @@ -7,14 +7,19 @@ use laravel::model::update; use crate::models::Blob; use crate::storage::BlobStore; -/// Record a blob a client or renderer is about to upload (or already has). Returns it. +/// Record a blob a client or renderer is about to upload (or already has). Returns it. A blob retention marked for +/// deletion loses the mark and counts as not uploaded, so the client uploads it again. Registering also renews +/// `updated_at` (at most hourly), and retention doesn't mark a blob registered in the last day, so a file a build is +/// about to name is never deleted under it. /// /// # Errors /// On a database error. pub async fn register(sha256: &str, size: i64, content_type: &str) -> laravel::Result { db::query!( "INSERT INTO blobs (sha256, size, content_type) VALUES ({sha256}, {size}, {content_type}) \ - ON CONFLICT (sha256) DO NOTHING" + ON CONFLICT (sha256) DO UPDATE SET deleting = false, updated_at = now(), \ + uploaded_at = CASE WHEN blobs.deleting THEN NULL ELSE blobs.uploaded_at END \ + WHERE blobs.deleting OR blobs.updated_at < now() - interval '1 hour'" ) .insert() .await?; @@ -23,7 +28,7 @@ pub async fn register(sha256: &str, size: i64, content_type: &str) -> laravel::R #[must_use] pub fn is_uploaded(blob: &Blob) -> bool { - blob.uploaded_at.is_some() + blob.uploaded_at.is_some() && !blob.deleting } /// Which of these blobs exist (retention deletes old ones). diff --git a/app/src/domain/credits.rs b/app/src/domain/credits.rs index d0acfa39..d3d217c7 100644 --- a/app/src/domain/credits.rs +++ b/app/src/domain/credits.rs @@ -321,32 +321,7 @@ pub async fn spend( build_id: Option, ) -> laravel::Result<()> { db::transaction(async |_| { - let plan: String = db::query!("SELECT plan FROM organizations WHERE id = {organization_id} FOR UPDATE") - .scalar() - .await? - .ok_or_else(|| laravel::Error::msg(format!("no organization {organization_id}")))?; - let plan = plan_by_id(&plan); - let from_pool = match spender { - Some(s) if s.open_source && credits > 0 => { - (OPEN_SOURCE_POOL - pool_used_this_month(organization_id).await?).clamp(0, credits) - } - _ => 0, - }; - let for_plan = credits - from_pool; - // Unlimited plans never touch pack credits; the transaction still records what was used. - let from_packs = if plan.unlimited { - 0 - } else { - let allowance_left = (plan.included_credits - used_this_month(organization_id).await?).max(0); - (for_plan - allowance_left).clamp(0, for_plan.max(0)) - }; - let balance: i64 = db::query!( - "UPDATE organizations SET credits_balance = credits_balance - {from_packs}, updated_at = now() \ - WHERE id = {organization_id} RETURNING credits_balance" - ) - .scalar() - .await? - .unwrap_or(0); + let (balance, from_pool) = take(organization_id, credits, spender).await?; let (amount, project_id) = (-credits, spender.map(|s| s.project_id)); db::query!( "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind, reference, project_id, \ @@ -360,6 +335,81 @@ pub async fn spend( .await } +/// Spend credits for gallery images served from VisualCI's own servers, as [`spend`] does, but added to one row per +/// project and UTC day (`kind = 'gallery'`, `day`), not one row per image: a busy public page would otherwise write a +/// row for every request. Kept even when the organization is out of credits, so a customer's page keeps working. Past +/// `daily_cap` credits in the project's day, nothing more is charged (`false`): a customer isn't billed without limit +/// for a page someone hammers. +/// +/// # Errors +/// On a database error. +pub async fn spend_gallery(project: &crate::models::Project, credits: i64, daily_cap: i64) -> laravel::Result { + let spender = Spender::of(project); + let (organization_id, project_id) = (project.organization_id, project.id); + // The day as allowances count time (`now`). + let day = now().in_tz("UTC").map_err(|e| laravel::Error::msg(e.to_string()))?.date(); + db::transaction(async |_| { + let today: i64 = db::query!( + "SELECT -amount FROM credit_transactions \ + WHERE organization_id = {organization_id} AND project_id = {project_id} AND day = {day} AND kind = 'gallery'" + ) + .scalar() + .await? + .unwrap_or(0); + if today + credits > daily_cap { + return Ok(false); + } + let (balance, from_pool) = take(organization_id, credits, Some(spender)).await?; + let amount = -credits; + db::query!( + "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind, project_id, \ + open_source_credits, day) \ + VALUES ({organization_id}, {amount}, {balance}, 'gallery', {project_id}, {from_pool}, {day}) \ + ON CONFLICT (organization_id, project_id, day) WHERE kind = 'gallery' DO UPDATE SET \ + amount = credit_transactions.amount + EXCLUDED.amount, balance_after = EXCLUDED.balance_after, \ + open_source_credits = credit_transactions.open_source_credits + EXCLUDED.open_source_credits, \ + updated_at = now()" + ) + .insert() + .await?; + Ok(true) + }) + .await +} + +/// Take credits from the organization, inside the caller's transaction: from the open source pool first (for an open +/// source project), then this month's allowance, then pack credits. Returns the pack balance after and how many came +/// from the pool. +async fn take(organization_id: i64, credits: i64, spender: Option) -> laravel::Result<(i64, i64)> { + let plan: String = db::query!("SELECT plan FROM organizations WHERE id = {organization_id} FOR UPDATE") + .scalar() + .await? + .ok_or_else(|| laravel::Error::msg(format!("no organization {organization_id}")))?; + let plan = plan_by_id(&plan); + let from_pool = match spender { + Some(s) if s.open_source && credits > 0 => { + (OPEN_SOURCE_POOL - pool_used_this_month(organization_id).await?).clamp(0, credits) + } + _ => 0, + }; + let for_plan = credits - from_pool; + // Unlimited plans never touch pack credits; the transaction still records what was used. + let from_packs = if plan.unlimited { + 0 + } else { + let allowance_left = (plan.included_credits - used_this_month(organization_id).await?).max(0); + (for_plan - allowance_left).clamp(0, for_plan.max(0)) + }; + let balance: i64 = db::query!( + "UPDATE organizations SET credits_balance = credits_balance - {from_packs}, updated_at = now() \ + WHERE id = {organization_id} RETURNING credits_balance" + ) + .scalar() + .await? + .unwrap_or(0); + Ok((balance, from_pool)) +} + /// Automatic reloads (pack purchases) this month. /// /// # Errors diff --git a/app/src/domain/diffs.rs b/app/src/domain/diffs.rs index 5760ac22..2ab1e0a1 100644 --- a/app/src/domain/diffs.rs +++ b/app/src/domain/diffs.rs @@ -31,6 +31,18 @@ async fn find(base_image: &str, head_image: &str, key: &str) -> laravel::Result< .await } +/// Note that a comparison reuses this diff now (at most once an hour): retention leaves its overlay alone for a day +/// after. +async fn mark_used(diff_id: i64) -> laravel::Result<()> { + db::query!( + "UPDATE diffs SET used_at = now() \ + WHERE id = {diff_id} AND (used_at IS NULL OR used_at < now() - interval '1 hour')" + ) + .update() + .await?; + Ok(()) +} + /// The diff of two images, computed (with its overlay stored as a blob) on first use. A diff whose overlay retention /// deleted is computed again, and keeps its row. /// @@ -44,7 +56,10 @@ pub async fn find_or_compute( ) -> laravel::Result { let key = options_key(&options); let stale = match find(base_image, head_image, &key).await? { - Some(diff) if diff.overlay_blob.is_some() || result(&diff).is_none_or(|r| r.is_identical()) => return Ok(diff), + Some(diff) if diff.overlay_blob.is_some() || result(&diff).is_none_or(|r| r.is_identical()) => { + mark_used(diff.id).await?; + return Ok(diff); + } other => other, }; let (base_bytes, head_bytes) = (store.get(base_image).await?, store.get(head_image).await?); diff --git a/app/src/domain/downloads.rs b/app/src/domain/downloads.rs new file mode 100644 index 00000000..b090ce67 --- /dev/null +++ b/app/src/domain/downloads.rs @@ -0,0 +1,550 @@ +//! 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 job 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. Snapshots are read through `effective_snapshots`, so a build that reads a group from an +//! earlier build downloads that group's images too. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use laravel::db; +use laravel::model::create; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use visualci_core::bundle; + +use super::pages; +use crate::models::{Build, Diff, Download, Snapshot}; +use crate::storage::BlobStore; + +/// 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: i32 = 60; +/// How long the archive stays in the bucket (the URL itself lasts an hour from each request). +pub const KEEP_HOURS: i32 = 24; +/// A download still building after this long has stopped (a worker restart): the next request starts another. +pub const STALE_MINUTES: i32 = 15; +/// How many downloads one project may have pending or building at once. +pub const MAX_BUILDING_PER_PROJECT: i64 = 3; +/// How long building one archive may take before it fails (an incomplete upload is cleared by the bucket's lifecycle +/// rule). +pub const BUILD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(14 * 60); +/// 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) -> 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)) + } +} + +/// Why a download wasn't started. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Refused { + /// The filter isn't valid. + Invalid(String), + /// The project already has [`MAX_BUILDING_PER_PROJECT`] downloads pending or building. + Busy(String), +} + +/// 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 job). A project has at most [`MAX_BUILDING_PER_PROJECT`] building at once. +/// +/// # Errors +/// `Ok(Err(_))` when it's refused; `Err` on a database error. +pub async fn request(build: &Build, filter: &Filter) -> laravel::Result> { + let filter = match filter.normalized() { + Ok(f) => f, + Err(m) => return Ok(Err(Refused::Invalid(m))), + }; + let key = filter.key(); + let (build_id, reuse, stale) = (build.id, REUSE_MINUTES, STALE_MINUTES); + let recent: Option = db::query!( + "SELECT * FROM downloads WHERE build_id = {build_id} AND filter_key = {key} AND ( \ + (state = 'ready' AND ready_at > now() - make_interval(mins => {reuse})) \ + OR (state IN ('pending', 'building') AND updated_at > now() - make_interval(mins => {stale}))) \ + ORDER BY created_at DESC LIMIT 1" + ) + .select_one_as() + .await?; + if let Some(d) = recent { + return Ok(Ok((d, false))); + } + let project_id = build.project_id; + let building: i64 = db::query!( + "SELECT COUNT(*) FROM downloads d JOIN builds b ON b.id = d.build_id \ + WHERE b.project_id = {project_id} AND d.state IN ('pending', 'building') \ + AND d.updated_at > now() - make_interval(mins => {stale})" + ) + .scalar() + .await? + .unwrap_or(0); + if building >= MAX_BUILDING_PER_PROJECT { + return Ok(Err(Refused::Busy(format!( + "{building} downloads are being built for this project: wait for one to finish (at most \ + {MAX_BUILDING_PER_PROJECT} at once)" + )))); + } + let filter = serde_json::to_value(&filter).unwrap_or_default(); + let created = create!(Download { + pid: laravel::str::uuid7(), + build_id: build_id, + filter: filter, + filter_key: key, + state: "pending", + }) + .await?; + Ok(Ok((created, true))) +} + +/// 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. +#[must_use] +pub fn to_json(download: &Download, store: &BlobStore) -> serde_json::Value { + let url = + (download.state == "ready").then(|| download.object_key.as_deref().map(|k| store.object_url(k))).flatten(); + json!({ + "id": download.pid, + "state": download.state, + "filter": download.filter, + "url": url, + "files": download.files, + "bytes": download.bytes, + "summary": download.summary, + "error": download.error, + }) +} + +/// 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(download: Download, store: &BlobStore) -> laravel::Result<()> { + let id = download.id; + // One conditional update: a second job for the same download (a retry, a duplicate dispatch) finds it taken. + let taken = + db::query!("UPDATE downloads SET state = 'building', updated_at = now() WHERE id = {id} AND state = 'pending'") + .update() + .await?; + if taken == 0 { + return Ok(()); + } + let key = format!("downloads/{}.tar.zst", download.pid); + let written = + tokio::time::timeout(BUILD_TIMEOUT, write_archive(store, &download, &key)).await.unwrap_or_else(|_| { + Err(format!( + "Building the archive took longer than {} minutes: download part of the build with a narrower glob", + BUILD_TIMEOUT.as_secs() / 60 + )) + }); + match written { + Ok((files, bytes, summary)) => { + let bytes = i64::try_from(bytes).unwrap_or(i64::MAX); + db::query!( + "UPDATE downloads SET state = 'ready', object_key = {key}, files = {files}, bytes = {bytes}, \ + summary = {summary}, ready_at = now(), updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + } + Err(e) => { + tracing::warn!(download = %download.pid, error = %e, "building a download failed"); + db::query!("UPDATE downloads SET state = 'failed', error = {e}, updated_at = now() WHERE id = {id}") + .update() + .await?; + } + } + Ok(()) +} + +/// Delete downloads older than [`KEEP_HOURS`] and their archives (retention 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(store: Option<&BlobStore>) -> laravel::Result { + let keep = KEEP_HOURS; + let old: Vec = + db::query!("SELECT * FROM downloads WHERE created_at < now() - make_interval(hours => {keep})") + .select_as() + .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; + } + let id = d.id; + db::query!("DELETE FROM downloads WHERE id = {id}").delete().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("/") +} + +/// The archive's paths so far, so every snapshot and page directory is one of its own. Names made safe can meet (`a:b` +/// and `a?b` are both `a_b`), a snapshot can be named like another's page (`x/page-2` beside page 2 of `x`), and a name +/// can be another's file (`x/head.png` beside `x`'s head image). A directory that would meet one already used, as a +/// directory or as a file, or whose files would meet a directory, is suffixed `~2`, `~3`… (the manifest names each +/// snapshot's paths). +#[derive(Default)] +struct Layout { + /// Snapshot and page directories handed out. + taken: std::collections::HashSet, + /// Every directory above a path handed out. + parents: std::collections::HashSet, + /// Files a directory handed out may hold: `/.`. + files: std::collections::HashSet, +} + +const EXTENSIONS: &[&str] = &["png", "jpg", "webp"]; + +fn ancestors(path: &str) -> impl Iterator { + path.char_indices().filter(|(_, c)| *c == '/').map(move |(i, _)| &path[..i]) +} + +impl Layout { + fn planned_files(dir: &str) -> impl Iterator + '_ { + SIDES.iter().flat_map(move |side| EXTENSIONS.iter().map(move |ext| format!("{dir}/{side}.{ext}"))) + } + + /// Whether `dir` can be handed out, holding files (`with_files`) or only page directories. + fn free(&self, dir: &str, with_files: bool) -> bool { + !self.taken.contains(dir) + && !self.files.contains(dir) + && !ancestors(dir).any(|a| self.files.contains(a)) + && (!with_files || Self::planned_files(dir).all(|f| !self.taken.contains(&f) && !self.parents.contains(&f))) + } + + /// Hand out `dir`, or the first `dir~N` that's free. + fn take(&mut self, dir: &str, with_files: bool) -> String { + let chosen = if self.free(dir, with_files) { + dir.to_string() + } else { + (2..).map(|n| format!("{dir}~{n}")).find(|d| self.free(d, with_files)).unwrap_or_else(|| dir.to_string()) + }; + self.parents.extend(ancestors(&chosen).map(str::to_string)); + if with_files { + self.files.extend(Self::planned_files(&chosen)); + } + self.taken.insert(chosen.clone()); + chosen + } +} + +fn extension(bytes: &[u8]) -> &'static str { + match image::guess_format(bytes) { + Ok(image::ImageFormat::Jpeg) => "jpg", + Ok(image::ImageFormat::WebP) => "webp", + _ => "png", + } +} + +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) + ) +} + +fn text(e: impl std::fmt::Display) -> String { + e.to_string() +} + +/// The snapshots the filter picks from the build: every one it holds or reads, but not its settings item or text +/// snapshots (they have no images). +async fn chosen(build: &Build, filter: &Filter) -> Result, String> { + let glob = + filter.glob.as_deref().map(|g| globset::Glob::new(g).map(|g| g.compile_matcher())).transpose().map_err(text)?; + let state = filter.state.clone().unwrap_or_else(|| "changed".to_string()); + Ok(super::snapshots::of_build(build.id) + .await + .map_err(text)? + .into_iter() + .filter(|s| s.platform != super::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()) +} + +/// Write the archive to the bucket. Returns its files, its compressed size and the manifest's summary. +async fn write_archive( + store: &BlobStore, + download: &Download, + key: &str, +) -> Result<(i32, u64, serde_json::Value), String> { + let filter: Filter = serde_json::from_value(download.filter.clone()).map_err(text)?; + let build = Build::find_or_fail(download.build_id).await.map_err(text)?; + let chosen = chosen(&build, &filter).await?; + let refs: Vec<&Snapshot> = chosen.iter().collect(); + let pages_of = pages::of_many(None, &refs).await.map_err(text)?; + let diff_ids: Vec = pages_of.values().flatten().filter_map(|p| p.diff_id).collect(); + let mut diffs: HashMap = HashMap::new(); + for chunk in diff_ids.chunks(10_000) { + for d in Diff::query().filter(Diff::id.is_in(chunk.to_vec())).get().await.map_err(text)? { + diffs.insert(d.id, d); + } + } + + let parts = Parts::default(); + let mut writer = bundle::Writer::new(parts.clone()).map_err(text)?; + let mut upload = store.start_multipart(key, "application/zstd").await.map_err(text)?; + let mut sent: u64 = 0; + let mut files = 0i32; + let mut entries = Vec::new(); + let result: Result<(), String> = async { + let mut layout = Layout::default(); + for s in &chosen { + let mut dir = path_part(&s.name); + if !s.platform.is_empty() { + dir = format!("{dir}@{}", path_part(&s.platform)); + } + let pages = pages_of.get(&s.id).map(Vec::as_slice).unwrap_or_default(); + let several = pages.len() > 1; + // A single page's files go in the snapshot's directory; several pages each get one beneath it. + let dir = layout.take(&dir, !several); + let mut listed = Vec::new(); + for p in pages { + let page_dir = + if several { layout.take(&format!("{dir}/page-{}", p.position + 1), true) } else { dir.clone() }; + let diff = p.diff_id.and_then(|id| diffs.get(&id)); + let result = diff.and_then(super::diffs::result); + let regions = result.as_ref().map(|r| r.regions.as_slice()).unwrap_or_default(); + 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(), + _ => diff.and_then(|d| d.overlay_blob.as_deref()), + }; + let Some(sha) = sha else { continue }; + if *side == "regions" && regions.is_empty() { + continue; + } + let mut bytes = store.get(sha).await.map_err(text)?; + 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(text)?; + 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(text)?; + } + } + listed.push(json!({ + "position": p.position, + "state": p.state, + "changed_fraction": result.as_ref().map(|r| r.changed_fraction), + "regions": result.as_ref().map(|r| &r.regions), + "files": written, + })); + } + entries.push(json!({ + "name": s.name, + "platform": s.platform, + "state": s.state, + "path": dir, + "pages": listed, + })); + } + 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(text)?).map_err(text)?; + writer.finish().map_err(text)?; + 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(text)?; + } + Ok::<_, String>(()) + } + .await; + if let Err(e) = finished { + upload.abort().await; + return Err(e); + } + upload.complete().await.map_err(text)?; + Ok((files + 1, sent, summary)) +} + +#[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 names_that_become_the_same_path_get_their_own_directories() { + let mut layout = Layout::default(); + let dirs: Vec = ["a:b", "a?b", "a_b", "c"].iter().map(|n| layout.take(&path_part(n), true)).collect(); + assert_eq!(dirs, ["a_b", "a_b~2", "a_b~3", "c"]); + } + + #[test] + fn a_snapshot_named_like_another_snapshots_page_gets_its_own_directory() { + // Page 2 of the two-page `x`, then a one-page snapshot named `x/page-2`. + let mut layout = Layout::default(); + let x = layout.take("x", false); + let pages: Vec = (1..=2).map(|n| layout.take(&format!("{x}/page-{n}"), true)).collect(); + assert_eq!(pages, ["x/page-1", "x/page-2"]); + assert_eq!(layout.take("x/page-2", true), "x/page-2~2"); + + // The other way round: the one-page `x/page-2` first, then the two-page `x`. + let mut layout = Layout::default(); + assert_eq!(layout.take("x/page-2", true), "x/page-2"); + let x = layout.take("x", false); + let pages: Vec = (1..=2).map(|n| layout.take(&format!("{x}/page-{n}"), true)).collect(); + assert_eq!(pages, ["x/page-1", "x/page-2~2"]); + } + + #[test] + fn a_snapshot_named_like_another_snapshots_file_gets_its_own_directory() { + // `x`'s head image is `x/head.png`: a snapshot named `x/head.png` can't be a directory there. + let mut layout = Layout::default(); + assert_eq!(layout.take("x", true), "x"); + assert_eq!(layout.take("x/head.png", true), "x/head.png~2"); + // And the other way round: once `x/head.png` is a directory, `x` can't hold a file of that name. + let mut layout = Layout::default(); + assert_eq!(layout.take("x/head.png", true), "x/head.png"); + assert_eq!(layout.take("x", true), "x~2"); + // Directories that only share a parent are fine. + assert_eq!(layout.take("x/other", true), "x/other"); + } + + #[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/app/src/domain/gallery.rs b/app/src/domain/gallery.rs new file mode 100644 index 00000000..d4ecc1ec --- /dev/null +++ b/app/src/domain/gallery.rs @@ -0,0 +1,380 @@ +//! Public galleries: the screenshots a project publishes (visualci.yml's `gallery`), each at a stable public URL that +//! always serves its approved version on the default branch. See "Public galleries" in docs/design.md. +//! +//! What's published is decided from the newest completed CI build of each suite on the default branch: its +//! visualci.yml names the groups, and each screenshot's approved state there (what the next default-branch build +//! would compare with) is the image served. A pending or rejected change keeps the old image, so a review is the +//! publish step. +//! +//! Each image the origin serves costs its organization a credit, added to one row per project and day +//! ([`super::credits::spend_gallery`]), and kept even when it's out of credits: a customer's page must keep working. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use laravel::db::{self, Json}; +use visualci_core::config::{Config, Gallery}; + +use crate::models::{Blob, Build, Organization, Project}; + +/// One published screenshot. +#[derive(Debug, Clone, serde::Serialize)] +pub struct Item { + pub group: String, + pub name: String, + pub platform: String, + /// Its path under the project's gallery: `screens/home-dark.png`, with `@` before the extension when + /// the name is published on more than one platform. + pub path: String, + #[serde(skip)] + pub sha256: String, + #[serde(skip)] + pub content_type: String, + pub width: Option, + pub height: Option, + /// When this version was approved (its snapshot was made): changes only when the image does. + pub since: String, +} + +/// A project's published gallery: its groups in order (name, title) and their items. +#[derive(Debug, Clone, Default)] +pub struct Published { + pub groups: Vec<(String, Option)>, + pub items: Vec, +} + +fn extension(content_type: &str) -> &'static str { + match content_type { + "image/jpeg" => "jpg", + "image/webp" => "webp", + "image/gif" => "gif", + "image/avif" => "avif", + _ => "png", + } +} + +/// 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 { + let micros = t.subsec_microsecond(); + let fraction = if micros == 0 { + String::new() + } else if micros % 1000 == 0 { + format!(".{:03}", micros / 1000) + } else { + format!(".{micros:06}") + }; + let utc = t.in_tz("UTC").map(|z| z.strftime("%Y-%m-%dT%H:%M:%S").to_string()).unwrap_or_default(); + 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> { + 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' \ + AND state = 'completed' ORDER BY id DESC" + ) + .select_as() + .await?; + let mut seen = HashSet::new(); + Ok(all.into_iter().filter(|b| seen.insert(b.name.clone())).collect()) +} + +/// The gallery a build's visualci.yml asks for, if any. +fn gallery_of(build: &Build) -> Option { + build.config.as_ref().and_then(|c| Config::from_json(c).ok()).and_then(|c| c.gallery) +} + +/// How long a computed gallery is reused when nothing it depends on changed. +const CACHE_FOR: std::time::Duration = std::time::Duration::from_secs(600); + +/// The galleries computed lately, by project pid: what they were computed from, when, and the result. +type Cache = std::collections::HashMap, String, std::time::Instant, Published)>; + +/// What a project's gallery depends on that changes when it may: its newest completed CI build and newest baseline (an +/// approval adds one). A cheap indexed read, so every web process sees a change at once. +async fn inputs(project: &Project) -> laravel::Result> { + let id = project.id; + let row = db::query!( + "SELECT (SELECT COALESCE(MAX(id), 0) FROM builds WHERE project_id = {id} AND mode = 'ci' AND state = 'completed') \ + AS build, \ + (SELECT COALESCE(MAX(id), 0) FROM baselines WHERE project_id = {id}) AS baseline" + ) + .select() + .await?; + let row = row.first().ok_or_else(|| laravel::Error::msg("no gallery inputs"))?; + Ok(vec![row.try_get::("build")?, row.try_get::("baseline")?]) +} + +/// Everything a project publishes. Empty when its gallery is off or no default-branch build has one. Cached per web +/// process while its inputs (the newest completed CI build, the newest baseline, the default branch) stay the same, +/// for at most [`CACHE_FOR`]: computing it resolves baselines, and the gallery is public. +/// +/// # Errors +/// On a database error. +pub async fn published(project: &Project) -> laravel::Result { + static CACHE: std::sync::OnceLock> = std::sync::OnceLock::new(); + if !project.gallery_enabled { + return Ok(Published::default()); + } + let cache = CACHE.get_or_init(|| std::sync::Mutex::new(Cache::new())); + let inputs = inputs(project).await?; + let hit = cache.lock().ok().and_then(|c| { + c.get(&project.pid) + .filter(|(i, branch, at, _)| *i == inputs && *branch == project.default_branch && at.elapsed() < CACHE_FOR) + .map(|(_, _, _, p)| p.clone()) + }); + if let Some(p) = hit { + return Ok(p); + } + let computed = compute(project).await?; + if let Ok(mut c) = cache.lock() { + if c.len() > 10_000 { + c.retain(|_, (_, _, at, _)| at.elapsed() < CACHE_FOR); + } + c.insert(project.pid, (inputs, project.default_branch.clone(), std::time::Instant::now(), computed.clone())); + } + Ok(computed) +} + +async fn compute(project: &Project) -> laravel::Result { + let mut out = Published::default(); + let mut found = Vec::new(); + for newest in newest_builds(project).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. + 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()); + next.environment = "ci".to_string(); + let (resolved, _) = super::baselines::resolve(&next, project).await?; + for ((name, _), r) in resolved { + if r.snapshot.kind != "image" || r.snapshot.environment != "ci" { + continue; + } + if let Some(group) = gallery.group_of(&name) { + found.push((group.name.clone(), r.snapshot)); + } + } + } + let shas: Vec = found.iter().filter_map(|(_, s)| s.source_blob.clone()).collect(); + let mut blobs: HashMap = HashMap::new(); + for chunk in shas.chunks(10_000) { + for b in Blob::query().filter(Blob::sha256.is_in(chunk.to_vec())).get().await? { + blobs.insert(b.sha256.clone(), b); + } + } + let mut platforms: BTreeMap = BTreeMap::new(); + for (_, s) in &found { + *platforms.entry(s.name.clone()).or_default() += 1; + } + for (group, s) in found { + let Some(blob) = s.source_blob.as_ref().and_then(|sha| blobs.get(sha)) else { continue }; + let ext = extension(&blob.content_type); + // A name that already ends in its extension (`home.png`) keeps it once. + let stem = s.name.strip_suffix(&format!(".{ext}")).unwrap_or(&s.name); + let path = if platforms.get(&s.name).copied().unwrap_or(0) > 1 && !s.platform.is_empty() { + format!("{stem}@{}.{ext}", s.platform) + } else { + format!("{stem}.{ext}") + }; + out.items.push(Item { + group, + name: s.name.clone(), + platform: s.platform.clone(), + path, + sha256: blob.sha256.clone(), + content_type: blob.content_type.clone(), + width: blob.width, + height: blob.height, + since: rfc3339(s.created_at), + }); + } + out.items.sort_by(|a, b| a.path.cmp(&b.path)); + Ok(out) +} + +/// The public URL of a project's manifest. +#[must_use] +pub fn manifest_url(app_url: &str, org: &str, project: &str) -> String { + format!("{app_url}/g/{org}/{project}.json") +} + +/// A path segment as today's server wrote it (the `url` crate's path segment set): controls, non-ASCII bytes, space +/// and `"#<>`?{}/%` are percent-encoded. +fn segment(s: &str) -> String { + s.bytes() + .map(|b| { + if !(0x20..0x7F).contains(&b) || b" \"#<>`?{}/%".contains(&b) { + format!("%{b:02X}") + } else { + (b as char).to_string() + } + }) + .collect() +} + +/// The public URL of one published screenshot. +#[must_use] +pub fn item_url(app_url: &str, org: &str, project: &str, path: &str) -> String { + let mut url = format!("{}/g/{}/{}", app_url.trim_end_matches('/'), segment(org), segment(project)); + for part in path.split('/') { + url.push('/'); + url.push_str(&segment(part)); + } + url +} + +impl Published { + /// The manifest: groups in order with their items, and nothing that changes unless the images do. + #[must_use] + pub fn manifest(&self, app_url: &str, org: &str, project: &str) -> serde_json::Value { + let groups: Vec = self + .groups + .iter() + .map(|(name, title)| { + let items: Vec = self + .items + .iter() + .filter(|i| &i.group == name) + .map(|i| { + serde_json::json!({ + "name": i.name, "platform": i.platform, "url": item_url(app_url, org, project, &i.path), + "width": i.width, "height": i.height, "sha256": i.sha256, "since": i.since, + }) + }) + .collect(); + serde_json::json!({ "name": name, "title": title, "items": items }) + }) + .collect(); + serde_json::json!({ "project": format!("{org}/{project}"), "groups": groups }) + } + + /// The item at a path, if it's published. + #[must_use] + pub fn find(&self, path: &str) -> Option<&Item> { + self.items.iter().find(|i| i.path == path) + } +} + +/// What a project makes public, for its settings: the manifest's URL and each published screenshot's. +/// +/// # Errors +/// On a database error. +pub async fn public_list(app_url: &str, org: &str, project: &Project) -> laravel::Result { + let published = published(project).await?; + let items: Vec = published + .groups + .iter() + .flat_map(|(group, _)| published.items.iter().filter(move |i| &i.group == group)) + .map(|i| { + serde_json::json!({ + "group": i.group, "name": i.name, "platform": i.platform, + "url": item_url(app_url, org, &project.slug, &i.path), + }) + }) + .collect(); + Ok(serde_json::json!({ + "enabled": project.gallery_enabled, + "manifest_url": (!items.is_empty()).then(|| manifest_url(app_url, org, &project.slug)), + "items": items, + })) +} + +/// The project at `/g//`, when its gallery is on. +/// +/// # Errors +/// On a database error. +pub async fn project_by_slugs(org: &str, project: &str) -> laravel::Result> { + let Some(organization) = Organization::query().filter(Organization::slug.eq(org)).first().await? else { + return Ok(None); + }; + let found = Project::query() + .filter(Project::organization_id.eq(organization.id) & Project::slug.eq(project)) + .first() + .await? + .filter(|p| p.gallery_enabled); + Ok(found.map(|p| (organization, p))) +} + +/// The URLs a build's change can make stale: its changed, added or removed published screenshots' (an unchanged one's +/// cached copy is still right, and purging it would only cost a credit), and the manifest. Empty when the build isn't +/// a CI build on the default branch or the project publishes nothing. +/// +/// # Errors +/// On a database error. +pub async fn stale_urls(app_url: &str, build: &Build) -> laravel::Result> { + let project = Project::find_or_fail(build.project_id).await?; + if build.mode != "ci" || build.branch != project.default_branch { + return Ok(vec![]); + } + let published = published(&project).await?; + if published.items.is_empty() { + return Ok(vec![]); + } + let org = Organization::find_or_fail(project.organization_id).await?; + let names: HashSet = super::snapshots::of_build(build.id) + .await? + .into_iter() + .filter(|s| s.state != "unchanged") + .map(|s| s.name) + .collect(); + let mut urls = vec![manifest_url(app_url, &org.slug, &project.slug)]; + urls.extend( + published + .items + .iter() + .filter(|i| names.contains(&i.name)) + .map(|i| item_url(app_url, &org.slug, &project.slug, &i.path)), + ); + Ok(urls) +} + +/// Purge every gallery URL a project publishes now or published at its last purge, in the background: call it before +/// the gallery is turned off. Does nothing when purges aren't configured. +/// +/// # Errors +/// On a database error, or when the job can't be queued. +pub async fn purge_project(project_id: i64) -> laravel::Result<()> { + if crate::jobs::purge_gallery::configured().is_none() { + return Ok(()); + } + let project = Project::find_or_fail(project_id).await?; + let urls = all_urls(&crate::http::api::builds::app_url(), &project).await?; + crate::jobs::purge_gallery::PurgeGallery { build_id: None, project_id: Some(project_id), urls }.dispatch().await?; + Ok(()) +} + +/// Every URL a project publishes now: what to purge before its gallery is turned off. +/// +/// # Errors +/// On a database error. +pub async fn all_urls(app_url: &str, project: &Project) -> laravel::Result> { + let published = published(project).await?; + if published.items.is_empty() { + return Ok(vec![]); + } + let org = Organization::find_or_fail(project.organization_id).await?; + let mut urls = vec![manifest_url(app_url, &org.slug, &project.slug)]; + urls.extend(published.items.iter().map(|i| item_url(app_url, &org.slug, &project.slug, &i.path))); + Ok(urls) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn item_urls_encode_each_segment() { + assert_eq!( + item_url("https://app.visualci.com/", "acme", "web", "screens/home page@ios.png"), + "https://app.visualci.com/g/acme/web/screens/home%20page@ios.png" + ); + assert_eq!(manifest_url("https://app.visualci.com", "acme", "web"), "https://app.visualci.com/g/acme/web.json"); + } +} diff --git a/app/src/domain/mod.rs b/app/src/domain/mod.rs index fc869178..00ec4344 100644 --- a/app/src/domain/mod.rs +++ b/app/src/domain/mod.rs @@ -11,8 +11,10 @@ pub mod compare; pub mod credits; pub mod detail; pub mod diffs; +pub mod downloads; pub mod environments; pub mod feedback; +pub mod gallery; pub mod groups; pub mod inherited; pub mod lenient; @@ -21,6 +23,7 @@ pub mod pages; pub mod processing; pub mod projects; pub mod renders; +pub mod retention; pub mod reviews; pub mod snapshots; pub mod summary; diff --git a/app/src/domain/renders.rs b/app/src/domain/renders.rs index 721f7db8..acb85651 100644 --- a/app/src/domain/renders.rs +++ b/app/src/domain/renders.rs @@ -66,7 +66,8 @@ pub async fn find_or_queue( db::query!( "INSERT INTO renders (project_id, source_fingerprint, renderer, source_blob) \ VALUES ({project_id}, {fingerprint}, {renderer}, {source_blob}) \ - ON CONFLICT (project_id, source_fingerprint, renderer) DO NOTHING" + ON CONFLICT (project_id, source_fingerprint, renderer) DO UPDATE SET used_at = now() \ + WHERE renders.used_at IS NULL OR renders.used_at < now() - interval '1 hour'" ) .insert() .await?; @@ -86,6 +87,21 @@ pub async fn find_or_queue( Ok(render) } +/// Note that a snapshot reuses this render now (at most once an hour): retention leaves its images and texts alone for +/// a day after. +/// +/// # Errors +/// On a database error. +pub async fn mark_used(render_id: i64) -> laravel::Result<()> { + db::query!( + "UPDATE renders SET used_at = now() \ + WHERE id = {render_id} AND (used_at IS NULL OR used_at < now() - interval '1 hour')" + ) + .update() + .await?; + Ok(()) +} + /// Record a render's pages: their texts go to `texts`, and the pages keep the hashes. /// /// # Errors @@ -113,3 +129,176 @@ pub async fn fail(mut render: Render, error: &str) -> laravel::Result { update!(render { state: "failed", error, completed_at: Some(now), render_ms }).await?; Ok(render) } + +/// The error a render gets when its claims ran out: every attempt was claimed and none finished. +pub const CLAIMS_RAN_OUT: &str = "the renderer stopped before finishing this PDF, on every attempt"; + +/// Renders whose last claim expired with no attempts left: they'd stay `rendering` forever. They fail, and the builds +/// waiting on them are processed again (their snapshots fail with the render). Run before each claim. Returns them. +/// +/// # Errors +/// On a database or queue error. +pub async fn fail_exhausted_claims() -> laravel::Result> { + let (timeout, attempts) = (CLAIM_TIMEOUT_SECONDS, MAX_ATTEMPTS); + let failed: Vec = db::query!( + "UPDATE renders SET state = 'failed', error = {CLAIMS_RAN_OUT}, completed_at = now(), updated_at = now(), \ + render_ms = (EXTRACT(EPOCH FROM (now() - claimed_at)) * 1000)::BIGINT, claim_token_hash = NULL \ + WHERE state = 'rendering' AND claimed_at < now() - make_interval(secs => {timeout}) \ + AND attempts >= {attempts} \ + RETURNING *" + ) + .select_as() + .await?; + for render in &failed { + wake_waiting(render).await?; + } + Ok(failed) +} + +/// Process again every build waiting on this render: renders are per project, so that's the project's processing builds +/// (the ones whose snapshots use it, and the ones waiting for their base's PDF to be drawn again with their own +/// renderer settings). Processing a build that's still waiting does nothing. +/// +/// # Errors +/// On a database or queue error. +pub async fn wake_waiting(render: &Render) -> laravel::Result<()> { + let render_id = render.id; + let rows = match render.project_id { + Some(project_id) => { + db::query!("SELECT id FROM builds WHERE project_id = {project_id} AND state = 'processing'") + .select() + .await? + } + None => { + db::query!( + "SELECT DISTINCT b.id FROM builds b JOIN snapshots s ON s.build_id = b.id \ + WHERE s.render_id = {render_id} AND b.state = 'processing'" + ) + .select() + .await? + } + }; + for build_id in rows.iter().filter_map(|r| r.try_get::("id").ok()) { + crate::jobs::process_build::ProcessBuild { build_id }.dispatch().await?; + } + Ok(()) +} + +/// Hand the oldest waiting render for `renderer_version` to a renderer, with the token its claim gets (the renderer +/// needs it to upload the render's pages and complete it), or `None` when there's nothing to do. Projects take turns: +/// the next render is the oldest from the project with the fewest being drawn now, so one account's flood of PDFs can't +/// hold the renderers from everyone else. A claim older than [`CLAIM_TIMEOUT_SECONDS`] is handed out again, until +/// [`MAX_ATTEMPTS`]; past that the render fails ([`fail_exhausted_claims`]). The version must match the render's +/// exactly (the last part of `engine/dpi/version`). +/// +/// # Errors +/// On a database error. +pub async fn claim(renderer_version: &str) -> laravel::Result> { + fail_exhausted_claims().await?; + let token = laravel::str::random(40); + let hash = visualci_core::sha256_hex(token.as_bytes()); + let (timeout, attempts) = (CLAIM_TIMEOUT_SECONDS, MAX_ATTEMPTS); + let render: Option = db::query!( + "UPDATE renders SET state = 'rendering', claimed_at = now(), attempts = attempts + 1, updated_at = now(), \ + claim_token_hash = {hash}, \ + wait_ms = COALESCE(wait_ms, (EXTRACT(EPOCH FROM (now() - created_at)) * 1000)::BIGINT) \ + WHERE id = (SELECT r.id FROM renders r \ + WHERE substring(r.renderer from '^[^/]*/[^/]*/(.*)$') = {renderer_version} \ + AND (r.state = 'queued' OR (r.state = 'rendering' AND r.claimed_at < now() - make_interval(secs => {timeout}))) \ + AND r.attempts < {attempts} \ + ORDER BY (SELECT COUNT(*) FROM renders o WHERE o.project_id IS NOT DISTINCT FROM r.project_id \ + AND o.state = 'rendering'), r.id \ + LIMIT 1 FOR UPDATE SKIP LOCKED) \ + RETURNING *" + ) + .select_one_as() + .await?; + Ok(render.map(|r| (r, token))) +} + +/// The most pages a render may report. +pub const MAX_PAGES: usize = 2000; +/// The most text one page may carry, in bytes. +pub const MAX_PAGE_TEXT_BYTES: usize = 256 * 1024; +/// The most entries one uploads request, and one render, may name. +pub const MAX_UPLOADS: usize = 5000; + +fn is_hex_sha256(s: &str) -> bool { + crate::storage::blobs::valid_sha256(s) +} + +/// Check a completed render's pages before anything is stored: a renderer runs untrusted PDFs, so a hostile one may +/// have taken it over. At most [`MAX_PAGES`] pages, each within the decoder's size limits, with hex fingerprints and at +/// most [`MAX_PAGE_TEXT_BYTES`] of text, and every image one of the PNGs this render uploaded itself (its `uploads`), +/// never another tenant's file named by its hash. +/// +/// # Errors +/// A message saying what's wrong. +pub fn validate_pages(render: &Render, pages: &[RenderPage]) -> Result<(), String> { + if pages.len() > MAX_PAGES { + return Err(format!("{} pages: a render has at most {MAX_PAGES}", pages.len())); + } + let uploads = render.uploads.as_object(); + for (i, p) in pages.iter().enumerate() { + let n = i + 1; + if p.width == 0 + || p.height == 0 + || p.width > visualci_core::image_hash::MAX_WIDTH + || p.height > visualci_core::image_hash::MAX_HEIGHT + { + return Err(format!("page {n}: {}x{} isn't a page size", p.width, p.height)); + } + if !is_hex_sha256(&p.fingerprint) || !is_hex_sha256(&p.image_fingerprint) { + return Err(format!("page {n}: fingerprints are 64 lowercase hex characters")); + } + if p.text.len() > MAX_PAGE_TEXT_BYTES { + return Err(format!("page {n}: more than {MAX_PAGE_TEXT_BYTES} bytes of text")); + } + if !uploads.is_some_and(|u| u.contains_key(&p.image)) { + return Err(format!("page {n}: image {:?} wasn't uploaded for this render", p.image)); + } + } + Ok(()) +} + +/// Record the PNGs a render's uploads named (`"blob"` or `"proof"`, see the migration), refusing past [`MAX_UPLOADS`]. +/// +/// # Errors +/// `Ok(Err(message))` past the limit; `Err` on a database error. +pub async fn record_uploads( + render_id: i64, + entries: &serde_json::Map, +) -> laravel::Result> { + let added = serde_json::Value::Object(entries.clone()); + let max = i64::try_from(MAX_UPLOADS).unwrap_or(i64::MAX); + let updated = db::query!( + "UPDATE renders SET uploads = uploads || {added}, updated_at = now() \ + WHERE id = {render_id} \ + AND (SELECT COUNT(*) FROM jsonb_object_keys(uploads || {added})) <= {max}" + ) + .update() + .await?; + Ok(if updated == 1 { Ok(()) } else { Err(format!("a render uploads at most {MAX_UPLOADS} images")) }) +} + +/// The proof key a render uploads an already stored PNG to: its bytes show the renderer drew it. +#[must_use] +pub fn proof_key(render_id: i64, sha256: &str) -> String { + format!("proofs/{render_id}/{sha256}") +} + +/// Whether `token` is this render's current claim's. +#[must_use] +pub fn claimed_with(render: &Render, token: &str) -> bool { + render.state == "rendering" + && render.claim_token_hash.as_deref().is_some_and(|h| h == visualci_core::sha256_hex(token.as_bytes())) +} + +/// The engine and DPI from the renderer key (`pdfbox/140dpi/`). +#[must_use] +pub fn engine_and_dpi(render: &Render) -> (String, u32) { + let mut parts = render.renderer.split('/'); + let engine = parts.next().unwrap_or("pdfbox").to_string(); + let dpi = parts.next().and_then(|d| d.trim_end_matches("dpi").parse().ok()).unwrap_or(140); + (engine, dpi) +} diff --git a/app/src/domain/retention.rs b/app/src/domain/retention.rs new file mode 100644 index 00000000..d700956b --- /dev/null +++ b/app/src/domain/retention.rs @@ -0,0 +1,417 @@ +//! Retention: deleting the images (and PDFs, render rows and page texts) that nothing needs any more. Build, snapshot, +//! page and diff rows stay, so history, counts and diff regions remain; their images show as expired. See "Retention +//! and garbage collection" in docs/design-storage.md. +//! +//! Kept: +//! - everything a build from the retention window (90 days) uses, plus its base build's, +//! - builds still receiving or processing, +//! - the newest completed CI build of each project and build name on the default branch, +//! - every build a kept build reads groups from (`build_groups.source_build_id`): their rows are the kept build's +//! unchanged snapshots, +//! - every current baseline: the newest baseline row per snapshot name on the default branch, and on each branch with +//! a build in the window, +//! - the snapshots those builds compared against (`base_snapshot_id`), +//! - renders those snapshots use, and any render made in the window or not finished, +//! - variants' images, and any blob created in the window (an upload a build hasn't claimed yet), +//! - page texts any page row or remaining render names, and any text from the last 24 hours (a comparison in flight). +//! +//! A build that registers snapshots while a prune runs isn't in its keep sets, so the prune leaves alone what any +//! snapshot touched in the last day names, and the images and texts of a render reused in the last day. A blob is +//! marked before its object goes, and registering it again clears the mark ([`prune`] has the steps). +//! +//! Ignored-change fingerprints are rows, not blobs, and are never deleted. Neither are build, snapshot or page rows: a +//! build other builds read groups from keeps its rows (deleting them would cascade, drop baselines and leave every +//! reader's groups empty), and its images too while any kept build reads from it. [`empty_groups`] is the nightly check +//! that no group lost its rows. + +use laravel::db; + +use crate::storage::BlobStore; + +/// How long a build's images are kept once nothing else needs them. +pub const RETENTION_DAYS: i32 = 90; +/// How old an unreferenced text must be before it's deleted. +pub const TEXT_GRACE_HOURS: i32 = 24; + +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Report { + pub renders: u64, + pub blobs: u64, + pub bytes: i64, + pub texts: u64, + /// Blob objects the store didn't delete (they stay as orphans; the rows are gone). + pub store_errors: u64, +} + +impl std::fmt::Display for Report { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + #[allow(clippy::cast_precision_loss)] + let mb = self.bytes as f64 / 1_000_000.0; + write!( + f, + "{} renders, {} blobs ({mb:.1} MB), {} texts{}", + self.renders, + self.blobs, + self.texts, + if self.store_errors > 0 { format!(", {} store deletes failed", self.store_errors) } else { String::new() } + ) + } +} + +/// Build the keep sets, as temporary tables dropped at the end of the transaction. +async fn keep_sets(days: i32) -> laravel::Result<()> { + // Left over when the caller's transaction is still open (a run inside a test's, or a dry run before a real one). + db::query!("DROP TABLE IF EXISTS keep_builds, keep_snapshots, keep_renders, keep_blobs, keep_texts") + .statement() + .await?; + db::query!("CREATE TEMP TABLE keep_builds (id BIGINT PRIMARY KEY) ON COMMIT DROP").statement().await?; + db::query!( + "INSERT INTO keep_builds \ + SELECT id FROM builds \ + WHERE COALESCE(completed_at, created_at) > now() - make_interval(days => {days}) \ + OR state IN ('receiving', 'processing') \ + UNION \ + SELECT id FROM ( \ + SELECT DISTINCT ON (b.project_id, b.name) b.id FROM builds b JOIN projects p ON p.id = b.project_id \ + WHERE b.branch = p.default_branch AND b.mode = 'ci' AND b.state = 'completed' \ + ORDER BY b.project_id, b.name, b.id DESC \ + ) newest \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + db::query!( + "INSERT INTO keep_builds \ + SELECT b.base_build_id FROM builds b JOIN keep_builds k ON k.id = b.id WHERE b.base_build_id IS NOT NULL \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + // The builds that hold the kept builds' sourced groups (one hop: a source is always a holder), base builds' + // included. Before snapshots, renders and blobs are kept from the set. + db::query!( + "INSERT INTO keep_builds \ + SELECT DISTINCT g.source_build_id FROM build_groups g JOIN keep_builds k ON k.id = g.build_id \ + WHERE g.source_build_id IS NOT NULL \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + + db::query!("CREATE TEMP TABLE keep_snapshots (id BIGINT PRIMARY KEY) ON COMMIT DROP").statement().await?; + db::query!("INSERT INTO keep_snapshots SELECT s.id FROM snapshots s JOIN keep_builds k ON k.id = s.build_id") + .statement() + .await?; + db::query!( + "INSERT INTO keep_snapshots \ + SELECT snapshot_id FROM ( \ + SELECT DISTINCT ON (bl.project_id, bl.build_name, bl.name, bl.platform, bl.environment, bl.branch) \ + bl.snapshot_id \ + FROM baselines bl JOIN projects p ON p.id = bl.project_id \ + WHERE bl.branch = p.default_branch OR EXISTS ( \ + SELECT 1 FROM builds b WHERE b.project_id = bl.project_id AND b.branch = bl.branch \ + AND b.created_at > now() - make_interval(days => {days})) \ + ORDER BY bl.project_id, bl.build_name, bl.name, bl.platform, bl.environment, bl.branch, bl.id DESC \ + ) current WHERE snapshot_id IS NOT NULL \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + db::query!( + "INSERT INTO keep_snapshots \ + SELECT s.base_snapshot_id FROM snapshots s JOIN keep_snapshots k ON k.id = s.id \ + WHERE s.base_snapshot_id IS NOT NULL \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + + db::query!("CREATE TEMP TABLE keep_renders (id BIGINT PRIMARY KEY) ON COMMIT DROP").statement().await?; + db::query!( + "INSERT INTO keep_renders \ + SELECT s.render_id FROM snapshots s JOIN keep_snapshots k ON k.id = s.id WHERE s.render_id IS NOT NULL \ + UNION \ + SELECT id FROM renders WHERE created_at > now() - make_interval(days => {days}) OR state <> 'done' \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + + db::query!("CREATE TEMP TABLE keep_blobs (sha256 TEXT PRIMARY KEY) ON COMMIT DROP").statement().await?; + db::query!( + "INSERT INTO keep_blobs \ + SELECT sha256 FROM blobs WHERE created_at > now() - make_interval(days => {days}) \ + UNION SELECT image FROM variants \ + 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 \ + WHERE p.head_image IS NOT NULL \ + UNION SELECT p.base_image FROM snapshot_pages p JOIN keep_snapshots k ON k.id = p.snapshot_id \ + WHERE p.base_image IS NOT NULL \ + UNION SELECT d.overlay_blob FROM snapshot_pages p JOIN keep_snapshots k ON k.id = p.snapshot_id \ + JOIN diffs d ON d.id = p.diff_id WHERE d.overlay_blob IS NOT NULL \ + UNION SELECT r.source_blob FROM renders r JOIN keep_renders k ON k.id = r.id \ + UNION SELECT pg->>'image' FROM renders r JOIN keep_renders k ON k.id = r.id, jsonb_array_elements(r.pages) pg \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + Ok(()) +} + +/// The texts still named after the renders go: every page row's, and every kept render's pages'. A temporary table, so +/// each source is scanned once rather than once per text. +async fn keep_texts() -> laravel::Result<()> { + db::query!("CREATE TEMP TABLE keep_texts (sha256 TEXT PRIMARY KEY) ON COMMIT DROP").statement().await?; + db::query!( + "INSERT INTO keep_texts \ + SELECT head_text_sha FROM snapshot_pages WHERE head_text_sha IS NOT NULL \ + UNION SELECT base_text_sha FROM snapshot_pages WHERE base_text_sha IS NOT NULL \ + UNION SELECT pg->>'text_sha' FROM renders r JOIN keep_renders k ON k.id = r.id, \ + jsonb_array_elements(r.pages) pg WHERE pg->>'text_sha' IS NOT NULL \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + Ok(()) +} + +/// How many renders, texts or blobs one transaction deletes. +pub const BATCH: usize = 1000; + +/// What a prune may delete, found in one pass over the keep sets. +struct Candidates { + renders: Vec, + texts: Vec, + blobs: Vec<(String, i64)>, +} + +/// Find what nothing keeps, in one read-only transaction (the keep sets are its temporary tables). +async fn candidates(days: i32) -> laravel::Result { + let grace = TEXT_GRACE_HOURS; + db::transaction(async |_| { + keep_sets(days).await?; + keep_texts().await?; + let renders = db::query!( + "SELECT id FROM renders WHERE NOT EXISTS (SELECT 1 FROM keep_renders k WHERE k.id = renders.id) ORDER BY id" + ) + .select() + .await? + .iter() + .filter_map(|r| r.try_get::("id").ok()) + .collect(); + let texts = db::query!( + "SELECT sha256 FROM texts WHERE created_at < now() - make_interval(hours => {grace}) \ + AND NOT EXISTS (SELECT 1 FROM keep_texts k WHERE k.sha256 = texts.sha256) ORDER BY sha256" + ) + .select() + .await? + .iter() + .filter_map(|r| r.try_get::("sha256").ok()) + .collect(); + let blobs = db::query!( + "SELECT sha256, size FROM blobs WHERE NOT EXISTS (SELECT 1 FROM keep_blobs k WHERE k.sha256 = blobs.sha256) \ + ORDER BY sha256" + ) + .select() + .await? + .iter() + .filter_map(|r| Some((r.try_get::("sha256").ok()?, r.try_get::("size").ok()?))) + .collect(); + // Gone with the transaction anyway, unless the caller's is still open (a test's). + db::query!("DROP TABLE IF EXISTS keep_builds, keep_snapshots, keep_renders, keep_blobs, keep_texts") + .statement() + .await?; + Ok(Candidates { renders, texts, blobs }) + }) + .await +} + +/// Delete what nothing needs, a batch of [`BATCH`] at a time, each batch in its own transaction, so a large prune never +/// holds locks across the whole database. The candidates come from one pass over the keep sets; each batch checks +/// again what may have changed since (a build registering now isn't in the keep sets): +/// +/// - a render goes only once no snapshot names it, and its snapshots' links go only when they're over a day old; +/// - a text goes only while it's over a day old (storing it again renews that) and no render reused in the last day +/// names it; +/// - an overlay goes only when its diff wasn't reused in the last day; +/// - a blob is marked `deleting` (rows locked, skipping any a registration holds) unless something registered it in the +/// last day or anything names it, then its object is deleted and the row with it, under the row's lock, only while +/// it's still marked and still unnamed. Registering the hash clears the mark and has the file uploaded again +/// ([`super::blobs::register`]), so a build reusing the file keeps it. Marks left over (a skipped row, a store that +/// refused) are cleared at the end of the batch, and any from a run that stopped are cleared at the start: no mark +/// outlives its run. +/// +/// With `dry_run`, only count. +/// +/// # Errors +/// On a database error. A failed store delete is counted in the report, not returned: the blob stays, and the next +/// prune tries again. +pub async fn prune(store: Option<&BlobStore>, days: i32, dry_run: bool) -> laravel::Result { + let grace = TEXT_GRACE_HOURS; + // Marks a run that stopped part way left behind (prunes never overlap: the schedule runs one at a time). + if !dry_run { + db::query!("UPDATE blobs SET deleting = false WHERE deleting").update().await?; + } + let found = candidates(days).await?; + let mut report = Report::default(); + if dry_run { + report.renders = found.renders.len() as u64; + report.texts = found.texts.len() as u64; + report.blobs = found.blobs.len() as u64; + report.bytes = found.blobs.iter().map(|(_, size)| size).sum(); + return Ok(report); + } + + for chunk in found.renders.chunks(BATCH) { + let ids = chunk.to_vec(); + report.renders += db::transaction(async |_| { + db::query!( + "UPDATE snapshots SET render_id = NULL \ + WHERE render_id IN ({...ids}) AND updated_at < now() - make_interval(hours => {grace})" + ) + .update() + .await?; + db::query!( + "DELETE FROM renders WHERE id IN ({...ids}) \ + AND (used_at IS NULL OR used_at < now() - make_interval(hours => {grace})) \ + AND NOT EXISTS (SELECT 1 FROM snapshots s WHERE s.render_id = renders.id)" + ) + .delete() + .await + }) + .await?; + } + + for chunk in found.texts.chunks(BATCH) { + let shas = chunk.to_vec(); + report.texts += db::query!( + "DELETE FROM texts WHERE sha256 IN ({...shas}) AND created_at < now() - make_interval(hours => {grace}) \ + 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->>'text_sha' = texts.sha256)" + ) + .delete() + .await?; + } + + for chunk in found.blobs.chunks(BATCH) { + let shas: Vec = chunk.iter().map(|(s, _)| s.clone()).collect(); + let marked: Vec<(String, i64)> = db::transaction(async |_| { + db::query!( + "UPDATE snapshots SET source_blob = NULL \ + WHERE source_blob IN ({...shas}) AND updated_at < now() - make_interval(hours => {grace})" + ) + .update() + .await?; + db::query!( + "UPDATE diffs SET overlay_blob = NULL \ + WHERE overlay_blob IN ({...shas}) AND (used_at IS NULL OR used_at < now() - make_interval(hours => {grace}))" + ) + .update() + .await?; + let rows = db::query!( + "UPDATE blobs SET deleting = true, updated_at = now() WHERE sha256 IN ( \ + SELECT b.sha256 FROM blobs b WHERE b.sha256 IN ({...shas}) \ + AND b.updated_at < now() - make_interval(hours => {grace}) \ + AND NOT EXISTS (SELECT 1 FROM snapshots s WHERE s.source_blob = b.sha256) \ + 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 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) \ + RETURNING sha256, size" + ) + .select() + .await?; + Ok(rows + .iter() + .filter_map(|r| Some((r.try_get::("sha256").ok()?, r.try_get::("size").ok()?))) + .collect()) + }) + .await?; + for (sha256, size) in &marked { + match delete_marked(store, sha256).await? { + Deleted::Yes => { + report.blobs += 1; + report.bytes += size; + } + Deleted::KeptForNow => {} + Deleted::StoreFailed => report.store_errors += 1, + } + } + // No mark outlives its run: what wasn't deleted (named again, locked by a registration, or the store refused) + // is a blob like any other again. Waits for a registration holding a row. + let left: Vec = marked.into_iter().map(|(s, _)| s).collect(); + for chunk in left.chunks(BATCH) { + let chunk = chunk.to_vec(); + db::query!("UPDATE blobs SET deleting = false WHERE sha256 IN ({...chunk}) AND deleting").update().await?; + } + } + Ok(report) +} + +enum Deleted { + Yes, + /// Registered again since it was marked, or a registration holds its row: it stays. + KeptForNow, + /// The store refused: it stays marked. + StoreFailed, +} + +/// Delete a marked blob's object and then its row, holding the row's lock throughout, and only while it's still +/// marked. A registration of the same hash waits for the lock and then inserts a fresh row (to be uploaded again), or, +/// when it came first, has cleared the mark and this leaves it alone. +async fn delete_marked(store: Option<&BlobStore>, sha256: &str) -> laravel::Result { + db::transaction(async |_| { + let locked: Option = + db::query!("SELECT sha256 FROM blobs WHERE sha256 = {sha256} AND deleting FOR UPDATE SKIP LOCKED") + .scalar() + .await?; + if locked.is_none() { + return Ok(Deleted::KeptForNow); + } + // Named since it was marked (a snapshot or diff committed after a registration that found it uploaded, or a page + // image of a render reused since): it stays. + let named: Option = db::query!( + "SELECT 1::BIGINT WHERE EXISTS (SELECT 1 FROM snapshots WHERE source_blob = {sha256}) \ + OR EXISTS (SELECT 1 FROM renders WHERE source_blob = {sha256}) \ + OR EXISTS (SELECT 1 FROM diffs WHERE overlay_blob = {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})" + ) + .scalar() + .await?; + if named.is_some() { + return Ok(Deleted::KeptForNow); + } + if let Some(store) = store + && let Err(e) = store.delete(sha256).await + { + tracing::warn!(sha256, error = %e, "retention: store delete failed"); + return Ok(Deleted::StoreFailed); + } + db::query!("DELETE FROM blobs WHERE sha256 = {sha256} AND deleting").delete().await?; + Ok(Deleted::Yes) + }) + .await +} + +/// Every group a build reads from another build that has no rows there: `(build id, group key)`. Each should be none; +/// one means a build shows with snapshots missing (docs/design-storage.md, "no group resolves to zero rows"). +/// +/// # Errors +/// On a database error. +pub async fn empty_groups() -> laravel::Result> { + let rows = db::query!( + "SELECT g.build_id, g.key FROM build_groups g \ + WHERE g.source_build_id IS NOT NULL AND NOT EXISTS ( \ + SELECT 1 FROM snapshots s WHERE s.build_id = g.source_build_id AND s.group_key = g.key) \ + ORDER BY g.build_id, g.key" + ) + .select() + .await?; + Ok(rows + .iter() + .filter_map(|r| Some((r.try_get::("build_id").ok()?, r.try_get::("key").ok()?))) + .collect()) +} diff --git a/app/src/domain/snapshots.rs b/app/src/domain/snapshots.rs index 435cea7f..6265e571 100644 --- a/app/src/domain/snapshots.rs +++ b/app/src/domain/snapshots.rs @@ -127,7 +127,7 @@ pub struct Registration { /// # Errors /// On a database error. pub async fn usable_render(project_id: i64, fingerprint: &str, renderer: &str) -> laravel::Result> { - Render::query() + let found = Render::query() .filter( Render::project_id.eq(project_id) & Render::source_fingerprint.eq(fingerprint) @@ -135,7 +135,12 @@ pub async fn usable_render(project_id: i64, fingerprint: &str, renderer: &str) - & Render::state.ne("failed"), ) .first() - .await + .await?; + // Reused: retention leaves its images and texts alone while this build is new. + if let Some(r) = &found { + super::renders::mark_used(r.id).await?; + } + Ok(found) } /// Record a snapshot in a build (replacing one with the same name and platform), and say whether its file must be diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index 6967c417..a0b33441 100644 --- a/app/src/http/api/builds.rs +++ b/app/src/http/api/builds.rs @@ -23,10 +23,10 @@ pub fn routes(route: &mut Router) { route.get("/v1/builds/{pid}/snapshots", list_snapshots); } -/// The renderer version documents are drawn with: part of the render cache key. +/// The renderer version documents are drawn with: part of the render cache key (`RENDERER_VERSION`, required). #[must_use] pub fn renderer_version() -> String { - std::env::var("RENDERER_VERSION").unwrap_or_else(|_| "1".to_string()) + laravel::config().section::().version.clone() } /// The web app's address, for links (`APP_URL`). diff --git a/app/src/http/api/downloads.rs b/app/src/http/api/downloads.rs new file mode 100644 index 00000000..28363d56 --- /dev/null +++ b/app/src/http/api/downloads.rs @@ -0,0 +1,80 @@ +//! Bulk downloads 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. + +use axum::response::Response; +use laravel::prelude::*; +use laravel::str::Uuid; + +use super::{ApiError, ApiProject, Body}; +use crate::domain::downloads::{self, Filter, Refused}; +use crate::jobs::build_download::BuildDownload; +use crate::models::{Build, Download, Project}; +use crate::storage::BlobStore; + +pub fn routes(route: &mut Router) { + route.post("/v1/builds/{build}/downloads", request); + route.get("/v1/downloads/{pid}", show); +} + +fn respond(result: Result) -> Response { + match result { + Ok(body) => axum::response::IntoResponse::into_response(axum::Json(body)), + Err(e) => axum::response::IntoResponse::into_response(e), + } +} + +/// The project's build with this id, or this number (`12` or `#12`). +async fn find_build(project: &Project, build: &str) -> Result { + let query = Build::query().filter(Build::project_id.eq(project.id)); + let found = match build.parse::() { + Ok(pid) => query.filter(Build::pid.eq(pid)).first().await?, + Err(_) => { + let number: i32 = build.trim_start_matches('#').parse().map_err(|_| ApiError::not_found())?; + query.filter(Build::number.eq(number)).first().await? + } + }; + found.ok_or_else(ApiError::not_found) +} + +/// `POST /api/v1/builds/{id or number}/downloads`. +pub async fn request( + auth: Result, + Params(build): Params, + Body(filter): Body, +) -> Response { + respond( + async { + let ApiProject { project, .. } = auth?; + let build = find_build(&project, &build).await?; + let (mut download, new) = downloads::request(&build, &filter).await?.map_err(|r| match r { + Refused::Invalid(m) => ApiError::bad_request(m), + Refused::Busy(m) => ApiError::too_many_requests(m), + })?; + if new { + BuildDownload { download_id: download.id }.dispatch().await?; + // A job that runs inline (or quickly) has already finished it. + download = Download::find_or_fail(download.id).await?; + } + Ok(downloads::to_json(&download, &BlobStore::current().await?)) + } + .await, + ) +} + +/// `GET /api/v1/downloads/{id}`. +pub async fn show(auth: Result, Params(pid): Params) -> Response { + respond( + async { + let ApiProject { project, .. } = auth?; + let download = + Download::query().filter(Download::pid.eq(pid)).first().await?.ok_or_else(ApiError::not_found)?; + let build = Build::find_or_fail(download.build_id).await?; + if build.project_id != project.id { + return Err(ApiError::not_found()); + } + Ok(downloads::to_json(&download, &BlobStore::current().await?)) + } + .await, + ) +} diff --git a/app/src/http/api/mod.rs b/app/src/http/api/mod.rs index 766117f8..d127accf 100644 --- a/app/src/http/api/mod.rs +++ b/app/src/http/api/mod.rs @@ -3,6 +3,7 @@ //! is a 422 `{"error": "invalid body: …"}`. pub mod builds; +pub mod downloads; pub mod support; use axum::extract::FromRequestParts; @@ -21,6 +22,7 @@ pub fn routes(route: &mut Router) { route.get("/v1/whoami", crate::auth::whoami); builds::routes(route); route.post("/v1/support/feedback", support::feedback); + downloads::routes(route); route.fallback(async || laravel::abort(404)); } @@ -42,6 +44,14 @@ impl ApiError { Self { status: StatusCode::CONFLICT, body: json!({ "error": "conflict", "description": message.into() }) } } + #[must_use] + pub fn too_many_requests(message: impl Into) -> Self { + Self { + status: StatusCode::TOO_MANY_REQUESTS, + body: json!({ "error": "too_many_requests", "description": message.into() }), + } + } + #[must_use] pub fn unauthorized(message: impl Into) -> Self { Self { diff --git a/app/src/http/gallery.rs b/app/src/http/gallery.rs new file mode 100644 index 00000000..4d9c2e2c --- /dev/null +++ b/app/src/http/gallery.rs @@ -0,0 +1,190 @@ +//! Public galleries on the app host: `/g//.json` (the manifest) and `/g///` (one +//! published screenshot, always its approved default-branch version). See `domain::gallery`. +//! +//! Cloudflare caches both for a day (`s-maxage`) and VisualCI purges a URL when an approval changes it +//! (`jobs::purge_gallery`), so the origin sees only misses. Each image the origin serves costs its organization one +//! credit, added to the project's row for the day and recorded even when it's out of credits: a customer's page must +//! keep working. Nothing else is served: no query parameters, no other variants, and a per-address rate limit, so the +//! URLs can't be used to bill a customer for junk or as free image hosting. Every answer may be read from any origin. + +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use std::net::IpAddr; + +use axum::http::{HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use laravel::http::Request; +use laravel::prelude::*; + +use crate::domain::gallery; +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"; +/// Requests per address per minute, per web process. +const PER_MINUTE: u32 = 120; + +pub fn routes(route: &mut Router) { + route.get("/g/{org}/{file}", manifest); + route.get("/g/{org}/{project}/{*path}", image); +} + +/// The caller's address, for the rate limit. `hop` is the address that reached our ingress (the kernel reads it from +/// the trusted proxies' `X-Forwarded-For`): when it's Cloudflare's edge, the client is the one Cloudflare names in +/// `cf-connecting-ip`; from anywhere else that header is the client's own claim, so the hop itself is the caller. +#[must_use] +pub fn caller(hop: IpAddr, cf_connecting_ip: Option<&str>, cloudflare: &[ipnet::IpNet]) -> String { + let from_cloudflare = cloudflare.iter().any(|n| n.contains(&hop)); + match cf_connecting_ip.map(str::trim).and_then(|v| v.parse::().ok()) { + Some(client) if from_cloudflare => client.to_string(), + _ => hop.to_string(), + } +} + +/// Whether this address may make another request now. +fn allowed(address: &str) -> bool { + static WINDOWS: OnceLock>> = OnceLock::new(); + let mut windows = WINDOWS.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap_or_else(|e| e.into_inner()); + let now = Instant::now(); + if windows.len() > 50_000 { + windows.retain(|_, (start, _)| now.duration_since(*start) < Duration::from_secs(60)); + } + let entry = windows.entry(address.to_string()).or_insert((now, 0)); + if now.duration_since(entry.0) >= Duration::from_secs(60) { + *entry = (now, 0); + } + entry.1 += 1; + entry.1 <= PER_MINUTE +} + +/// Any page may read a gallery answer: an image in an ``, the manifest with `fetch`. +fn public(mut r: Response) -> Response { + let h = r.headers_mut(); + h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*")); + h.insert(header::HeaderName::from_static("cross-origin-resource-policy"), HeaderValue::from_static("cross-origin")); + r +} + +/// A refusal (404) is never cached: a screenshot published a minute later must show up at once, and the approval's +/// purge only knows the URLs it published. The rate limit keeps junk URLs off the origin instead. +fn status(code: StatusCode, message: &'static str) -> Response { + let mut r = (code, message).into_response(); + r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + public(r) +} + +fn server(e: &laravel::Error) -> Response { + tracing::error!(error = %e, "gallery request failed"); + status(StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error") +} + +fn guard(request: &Request) -> Option { + if request.uri().query().is_some() { + return Some(status(StatusCode::NOT_FOUND, "not found")); + } + let settings = laravel::config(); + let networks = settings.section::().cloudflare_networks(); + if !allowed(&caller(request.ip(), request.header("cf-connecting-ip"), &networks)) { + let mut r = status(StatusCode::TOO_MANY_REQUESTS, "slow down"); + r.headers_mut().insert(header::RETRY_AFTER, HeaderValue::from_static("60")); + return Some(r); + } + None +} + +/// `/g//.json` +pub async fn manifest(Params((org, file)): Params<(String, String)>, request: Request) -> Response { + if let Some(r) = guard(&request) { + return r; + } + let Some(slug) = file.strip_suffix(".json") else { return status(StatusCode::NOT_FOUND, "not found") }; + let published = async { + let Some((_, project)) = gallery::project_by_slugs(&org, slug).await? else { return Ok(None) }; + Ok::<_, laravel::Error>(Some(gallery::published(&project).await?)) + } + .await; + match published { + Ok(Some(p)) if !p.items.is_empty() => { + let body = p.manifest(&crate::http::api::builds::app_url(), &org, slug); + let mut r = axum::Json(body).into_response(); + r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE)); + public(r) + } + Ok(_) => status(StatusCode::NOT_FOUND, "no public gallery"), + Err(e) => server(&e), + } +} + +/// `/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) { + return r; + } + match serve(&org, &slug, &path, request.header(header::IF_NONE_MATCH)).await { + Ok(r) => r, + Err(e) => server(&e), + } +} + +async fn serve(org: &str, slug: &str, path: &str, if_none_match: Option<&str>) -> laravel::Result { + let Some((_, project)) = gallery::project_by_slugs(org, slug).await? else { + return Ok(status(StatusCode::NOT_FOUND, "not found")); + }; + let published = gallery::published(&project).await?; + let Some(item) = published.find(path) else { return Ok(status(StatusCode::NOT_FOUND, "not found")) }; + let etag = format!("\"{}\"", item.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)); + return Ok(public(r)); + } + let bytes = BlobStore::current().await?.get(&item.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", + Ok(image::ImageFormat::Jpeg) => "image/jpeg", + Ok(image::ImageFormat::WebP) => "image/webp", + _ => return Ok(status(StatusCode::NOT_FOUND, "not found")), + }; + // 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?; + 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)); + if let Ok(v) = HeaderValue::from_str(&etag) { + h.insert(header::ETAG, v); + } + Ok(public(r)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cloudflare_names_the_client_only_when_the_request_came_from_cloudflare() { + let cloudflare: Vec = vec!["173.245.48.0/20".parse().unwrap(), "2606:4700::/32".parse().unwrap()]; + let edge: IpAddr = "173.245.48.7".parse().unwrap(); + let elsewhere: IpAddr = "203.0.113.9".parse().unwrap(); + assert_eq!(caller(edge, Some("198.51.100.4"), &cloudflare), "198.51.100.4"); + assert_eq!(caller("2606:4700::1".parse().unwrap(), Some("2001:db8::5"), &cloudflare), "2001:db8::5"); + // A client that reaches the origin directly can't pick its own address, however it rotates the header. + assert_eq!(caller(elsewhere, Some("198.51.100.4"), &cloudflare), "203.0.113.9"); + assert_eq!(caller(elsewhere, Some("198.51.100.5"), &cloudflare), "203.0.113.9"); + assert_eq!(caller(edge, Some("not an address"), &cloudflare), "173.245.48.7"); + assert_eq!(caller(edge, None, &cloudflare), "173.245.48.7"); + } + + #[test] + fn the_published_cloudflare_ranges_parse() { + let gallery = crate::config::Gallery { cloudflare_ip_ranges: String::new(), daily_credits: 1 }; + assert_eq!(gallery.cloudflare_networks().len(), crate::config::CLOUDFLARE_IP_RANGES.split(',').count()); + } +} diff --git a/app/src/http/mod.rs b/app/src/http/mod.rs index e405da68..ca4bdcfc 100644 --- a/app/src/http/mod.rs +++ b/app/src/http/mod.rs @@ -1,5 +1,7 @@ //! HTTP handlers. pub mod api; +pub mod gallery; pub mod hosts; +pub mod renderer; pub mod status; diff --git a/app/src/http/renderer.rs b/app/src/http/renderer.rs new file mode 100644 index 00000000..6593246f --- /dev/null +++ b/app/src/http/renderer.rs @@ -0,0 +1,396 @@ +//! The renderer API (`/internal/renderer`). Renderers run in a sandbox with no database access: they claim a render +//! here, download the PDF from a presigned URL, upload page images to presigned URLs and report the pages. +//! +//! Every route checks its token itself, whatever the request's Host: the routes are reachable from any host the host +//! routing doesn't know (the cluster address the renderers use), and a client chooses its Host header. Claiming, +//! uploading and completing take the shared renderer token; uploading a render's pages and completing it also need the +//! token its claim was given (`X-Render-Token`), so a renderer acts only on the render it claimed. The metrics take the +//! scraper's own token: a renderer (which runs untrusted PDFs) can't read metrics, and the scraper can't claim renders. + +use axum::http::{HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use laravel::db; +use laravel::prelude::*; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +use crate::config::Renderer; +use crate::domain::renders::{self, RenderPage}; +use crate::models::Render; +use crate::storage::BlobStore; + +pub fn routes(route: &mut Router) { + route.prefix("/internal/renderer").group(|route| { + route.get("/metrics", metrics); + route.post("/claim", claim); + route.post("/renders/{id}/uploads", uploads); + route.post("/renders/{id}/complete", complete); + }); +} + +fn error(status: StatusCode, kind: &str, description: impl Into) -> Response { + (status, axum::Json(json!({ "error": kind, "description": description.into() }))).into_response() +} + +fn unauthorized(description: &str) -> Response { + error(StatusCode::UNAUTHORIZED, "unauthorized", description) +} + +fn server(e: &laravel::Error) -> Response { + tracing::error!(error = %e, "renderer API request failed"); + error(StatusCode::INTERNAL_SERVER_ERROR, "internal_server_error", "Internal Server Error") +} + +fn bearer(headers: &HeaderMap) -> &str { + headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .unwrap_or_default() +} + +/// A constant-time comparison; an empty expected secret matches nothing. +fn same_secret(given: &str, expected: &str) -> bool { + let expected = expected.as_bytes(); + !expected.is_empty() + && given.len() == expected.len() + && given.bytes().zip(expected).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0 +} + +/// `Err` with the 401 when the request doesn't carry the renderer token. +fn renderer_token(headers: &HeaderMap) -> Result<(), Response> { + let settings = laravel::config(); + let config = settings.section::(); + if same_secret(bearer(headers), &config.token) { Ok(()) } else { Err(unauthorized("invalid renderer token")) } +} + +/// The render `id`, when the request carries its current claim's token (`X-Render-Token`). +async fn claimed_render(headers: &HeaderMap, id: i64) -> Result { + let token = headers.get("x-render-token").and_then(|v| v.to_str().ok()).unwrap_or_default(); + let render = Render::find(id) + .await + .map_err(|e| server(&e))? + .ok_or_else(|| error(StatusCode::NOT_FOUND, "not_found", "Resource was not found"))?; + if renders::claimed_with(&render, token) { Ok(render) } else { Err(unauthorized("not this render's claim")) } +} + +#[derive(Debug, Deserialize)] +pub struct ClaimParams { + /// The renderer image's version; only renders keyed to it are handed out. + renderer_version: String, +} + +#[derive(Debug, Serialize)] +struct Job { + id: i64, + engine: String, + dpi: u32, + source_url: String, + source_sha256: String, + /// This claim's token: `X-Render-Token` on this render's uploads and completion. + token: String, +} + +/// `POST /internal/renderer/claim`: the next render to draw, or `{"job": null}`. +pub async fn claim(headers: HeaderMap, body: axum::body::Bytes) -> Response { + if let Err(r) = renderer_token(&headers) { + return r; + } + let params: ClaimParams = match serde_json::from_slice(&body) { + Ok(p) => p, + Err(e) => return error(StatusCode::UNPROCESSABLE_ENTITY, "invalid body", e.to_string()), + }; + let result = async { + let store = BlobStore::current().await?; + let Some((render, token)) = renders::claim(¶ms.renderer_version).await? else { + return Ok(json!({ "job": null })); + }; + let (engine, dpi) = renders::engine_and_dpi(&render); + let job = Job { + id: render.id, + engine, + dpi, + source_url: store.download_url(&render.source_blob)?, + source_sha256: render.source_blob.clone(), + token, + }; + Ok::<_, laravel::Error>(json!({ "job": job })) + } + .await; + match result { + Ok(body) => axum::Json(body).into_response(), + Err(e) => server(&e), + } +} + +#[derive(Debug, Deserialize)] +struct UploadFile { + sha256: String, + size: i64, + content_type: String, +} + +#[derive(Debug, Deserialize)] +struct UploadsParams { + files: Vec, +} + +/// `POST /internal/renderer/renders/{id}/uploads`: upload URLs for a render's page images (PNGs only). +pub async fn uploads(Params(id): Params, headers: HeaderMap, body: axum::body::Bytes) -> Response { + if let Err(r) = renderer_token(&headers) { + return r; + } + if let Err(r) = claimed_render(&headers, id).await { + return r; + } + let params: UploadsParams = match serde_json::from_slice(&body) { + Ok(p) => p, + Err(e) => return error(StatusCode::UNPROCESSABLE_ENTITY, "invalid body", e.to_string()), + }; + if params.files.len() > renders::MAX_UPLOADS { + return error( + StatusCode::BAD_REQUEST, + "Bad Request", + format!("{} files: a request names at most {}", params.files.len(), renders::MAX_UPLOADS), + ); + } + let max = i64::try_from(crate::storage::blobs::MAX_BLOB_BYTES).unwrap_or(i64::MAX); + for f in ¶ms.files { + // Page images only: a render uploads PNGs, never a type a browser would run. + if f.content_type != "image/png" + || f.size <= 0 + || f.size > max + || !crate::storage::blobs::valid_sha256(&f.sha256) + { + return error( + StatusCode::BAD_REQUEST, + "Bad Request", + format!("{}: page images are PNGs of at most 64 MiB", f.sha256), + ); + } + } + let result = async { + let store = BlobStore::current().await?; + let mut urls = serde_json::Map::new(); + let mut kinds = serde_json::Map::new(); + for f in ¶ms.files { + let blob = crate::domain::blobs::register(&f.sha256, f.size, &f.content_type).await?; + if crate::domain::blobs::is_uploaded(&blob) { + // Already stored (perhaps another tenant's): the renderer shows it drew the same PNG by uploading the + // bytes to a key of this render's own, checked when it completes. The URL takes exactly the declared + // size. + let size = u64::try_from(f.size).unwrap_or_default(); + urls.insert( + f.sha256.clone(), + store.upload_url_for_key(&renders::proof_key(id, &f.sha256), size).into(), + ); + kinds.insert(f.sha256.clone(), "proof".into()); + } else { + urls.insert(f.sha256.clone(), store.upload_url(&f.sha256)?.into()); + kinds.insert(f.sha256.clone(), "blob".into()); + } + } + if let Err(m) = renders::record_uploads(id, &kinds).await? { + return Ok(Err(m)); + } + Ok::<_, laravel::Error>(Ok(json!({ "upload_urls": urls }))) + } + .await; + match result { + Ok(Ok(body)) => axum::Json(body).into_response(), + Ok(Err(m)) => error(StatusCode::BAD_REQUEST, "Bad Request", m), + Err(e) => server(&e), + } +} + +/// Check that every page image is a PNG this render uploaded: a blob it uploaded (confirmed against its hash), or a +/// proof of one already stored (its bytes hash to it; the proof object is deleted). Returns what's wrong, if anything. +async fn check_images(store: &BlobStore, render: &Render, pages: &[RenderPage]) -> laravel::Result> { + let kinds = render.uploads.as_object().cloned().unwrap_or_default(); + let mut blobs = Vec::new(); + let mut proofs = Vec::new(); + for p in pages { + match kinds.get(&p.image).and_then(|k| k.as_str()) { + Some("proof") => proofs.push(p.image.clone()), + _ => blobs.push(p.image.clone()), + } + } + blobs.sort(); + blobs.dedup(); + proofs.sort(); + proofs.dedup(); + let missing = crate::domain::blobs::confirm_uploads(store, &blobs).await?; + if !missing.is_empty() { + return Ok(Some(format!("page images not uploaded: {}", missing.join(", ")))); + } + for sha in &proofs { + let key = renders::proof_key(render.id, sha); + let proven = store.verify_object(&key, sha).await?.is_some(); + store.delete_object(&key).await?; + if !proven { + return Ok(Some(format!("page image {sha} wasn't uploaded for this render"))); + } + } + let all: Vec = blobs.iter().chain(&proofs).cloned().collect(); + for chunk in all.chunks(1000) { + let wrong = crate::models::Blob::query() + .filter( + crate::models::Blob::sha256.is_in(chunk.to_vec()) & crate::models::Blob::content_type.ne("image/png"), + ) + .first() + .await?; + if let Some(b) = wrong { + return Ok(Some(format!("page image {} isn't a PNG", b.sha256))); + } + } + Ok(None) +} + +#[derive(Debug, Deserialize)] +struct CompleteParams { + #[serde(default)] + pages: Vec, + error: Option, +} + +/// `POST /internal/renderer/renders/{id}/complete`: the render's pages (their images uploaded first), or its error. +/// Every build waiting on it is processed again. +pub async fn complete(Params(id): Params, headers: HeaderMap, body: axum::body::Bytes) -> Response { + if let Err(r) = renderer_token(&headers) { + return r; + } + let render = match claimed_render(&headers, id).await { + Ok(r) => r, + Err(r) => return r, + }; + let params: CompleteParams = match serde_json::from_slice(&body) { + Ok(p) => p, + Err(e) => return error(StatusCode::UNPROCESSABLE_ENTITY, "invalid body", e.to_string()), + }; + let result = async { + let store = BlobStore::current().await?; + if params.error.is_none() + && let Err(m) = renders::validate_pages(&render, ¶ms.pages) + { + // A renderer that sends this has been taken over by its PDF, or is broken: the render fails. + let failed = renders::fail(render, &m).await?; + renders::wake_waiting(&failed).await?; + return Ok(Err(m)); + } + let result = if let Some(error) = params.error { + renders::fail(render, &error).await? + } else if params.pages.is_empty() { + renders::fail(render, "the renderer produced no pages").await? + } else if let Some(problem) = check_images(&store, &render, ¶ms.pages).await? { + renders::fail(render, &problem).await? + } else { + renders::complete(render, ¶ms.pages).await? + }; + renders::wake_waiting(&result).await?; + Ok::<_, laravel::Error>(Ok(json!({ "state": result.state }))) + } + .await; + match result { + Ok(Ok(body)) => axum::Json(body).into_response(), + Ok(Err(m)) => error(StatusCode::BAD_REQUEST, "Bad Request", m), + Err(e) => server(&e), + } +} + +/// `GET /internal/renderer/metrics`: Prometheus metrics for the renderers, from the last 24 hours of renders: seconds +/// per page and queue wait (quantiles), renders finished by state, pages drawn, and what's queued or rendering now. +/// Scraped with the metrics token. +pub async fn metrics(headers: HeaderMap) -> Response { + let settings = laravel::config(); + let config = settings.section::(); + if !same_secret(bearer(&headers), &config.metrics_token) { + return unauthorized("invalid metrics token"); + } + match metrics_text().await { + Ok(out) => ([(axum::http::header::CONTENT_TYPE, "text/plain; version=0.0.4")], out).into_response(), + Err(e) => server(&e), + } +} + +async fn metrics_text() -> laravel::Result { + let row = db::query!( + "WITH recent AS (SELECT * FROM renders WHERE completed_at > now() - interval '24 hours'), \ + done AS (SELECT render_ms / 1000.0 / GREATEST(jsonb_array_length(pages), 1) AS per_page, \ + jsonb_array_length(pages) AS pages, wait_ms / 1000.0 AS wait \ + FROM recent WHERE state = 'done' AND render_ms IS NOT NULL) \ + SELECT \ + (SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY per_page) FROM done)::FLOAT8 AS page_p50, \ + (SELECT percentile_cont(0.9) WITHIN GROUP (ORDER BY per_page) FROM done)::FLOAT8 AS page_p90, \ + (SELECT percentile_cont(0.99) WITHIN GROUP (ORDER BY per_page) FROM done)::FLOAT8 AS page_p99, \ + (SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY wait) FROM done)::FLOAT8 AS wait_p50, \ + (SELECT percentile_cont(0.9) WITHIN GROUP (ORDER BY wait) FROM done)::FLOAT8 AS wait_p90, \ + (SELECT percentile_cont(0.99) WITHIN GROUP (ORDER BY wait) FROM done)::FLOAT8 AS wait_p99, \ + (SELECT COUNT(*) FROM done)::BIGINT AS done_count, \ + (SELECT COALESCE(SUM(per_page), 0) FROM done)::FLOAT8 AS page_sum, \ + (SELECT COALESCE(SUM(wait), 0) FROM done)::FLOAT8 AS wait_sum, \ + (SELECT COALESCE(SUM(pages), 0) FROM done)::BIGINT AS pages, \ + (SELECT COUNT(*) FROM recent WHERE state = 'failed')::BIGINT AS failed_count, \ + (SELECT COUNT(*) FROM renders WHERE state = 'queued')::BIGINT AS queued, \ + (SELECT COUNT(*) FROM renders WHERE state = 'rendering')::BIGINT AS rendering, \ + (SELECT COUNT(*) FROM gallery_purge_failures WHERE created_at > now() - interval '7 days')::BIGINT \ + AS gallery_purges_failed" + ) + .select_one() + .await? + .ok_or_else(|| laravel::Error::msg("no metrics row"))?; + let f = |name: &str| row.try_get::>(name).ok().flatten(); + let n = |name: &str| row.try_get::(name).unwrap_or(0); + let mut out = String::new(); + // Quantiles appear once a render has finished in the window; _sum and _count always do. Every web pod reports the + // same database's numbers, so dashboards take max across pods, not sum. + let mut summary = |metric: &str, help: &str, values: [(&str, Option); 3], sum: f64, count: i64| { + out.push_str(&format!("# HELP {metric} {help}\n# TYPE {metric} summary\n")); + for (q, v) in values { + if let Some(v) = v { + out.push_str(&format!("{metric}{{quantile=\"{q}\"}} {v}\n")); + } + } + out.push_str(&format!("{metric}_sum {sum}\n{metric}_count {count}\n")); + }; + summary( + "visualci_render_page_seconds", + "Seconds from claim to completion per page drawn, renders finished in the last 24 hours.", + [("0.5", f("page_p50")), ("0.9", f("page_p90")), ("0.99", f("page_p99"))], + f("page_sum").unwrap_or(0.0), + n("done_count"), + ); + summary( + "visualci_render_queue_wait_seconds", + "Seconds a render waited in the queue before a renderer claimed it, renders finished in the last 24 hours.", + [("0.5", f("wait_p50")), ("0.9", f("wait_p90")), ("0.99", f("wait_p99"))], + f("wait_sum").unwrap_or(0.0), + n("done_count"), + ); + let gauge = |out: &mut String, metric: &str, help: &str, lines: &[(&str, i64)]| { + out.push_str(&format!("# HELP {metric} {help}\n# TYPE {metric} gauge\n")); + for (labels, v) in lines { + out.push_str(&format!("{metric}{labels} {v}\n")); + } + }; + gauge( + &mut out, + "visualci_renders_finished_24h", + "Renders finished in the last 24 hours, by state.", + &[("{state=\"done\"}", n("done_count")), ("{state=\"failed\"}", n("failed_count"))], + ); + gauge(&mut out, "visualci_render_pages_24h", "Pages drawn in the last 24 hours.", &[("", n("pages"))]); + // Alerted on a rise (a warning: Cloudflare may serve a stale public-gallery screenshot until its cache expires). + gauge( + &mut out, + "visualci_gallery_purges_failed_7d", + "Public gallery purges that used up their retries in the last 7 days.", + &[("", n("gallery_purges_failed"))], + ); + gauge( + &mut out, + "visualci_renders_now", + "Renders queued or being drawn now.", + &[("{state=\"queued\"}", n("queued")), ("{state=\"rendering\"}", n("rendering"))], + ); + Ok(out) +} diff --git a/app/src/http/status.rs b/app/src/http/status.rs index 750b397d..ecd82964 100644 --- a/app/src/http/status.rs +++ b/app/src/http/status.rs @@ -25,7 +25,12 @@ pub async fn status() -> laravel::Result> { AS last_render_seconds_ago, \ COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(GREATEST(b.updated_at, COALESCE((SELECT MAX(s.updated_at) \ FROM snapshots s WHERE s.build_id = b.id), b.created_at)))) FROM builds b WHERE b.state = 'receiving'), 0)::BIGINT \ - AS oldest_receiving_seconds" + AS oldest_receiving_seconds, \ + (SELECT COUNT(*) FROM build_groups g WHERE g.source_build_id IS NOT NULL AND NOT EXISTS ( \ + SELECT 1 FROM snapshots s WHERE s.build_id = g.source_build_id AND s.group_key = g.key))::BIGINT \ + AS empty_groups, \ + (SELECT COUNT(*) FROM gallery_purge_failures WHERE created_at > now() - interval '7 days')::BIGINT \ + AS gallery_purges_failed" ) .select_one() .await? @@ -43,5 +48,9 @@ pub async fn status() -> laravel::Result> { "last_render_seconds_ago": get("last_render_seconds_ago")?, // A build left receiving: the sweep fails it after an hour without uploads, so past two hours it has stopped. "oldest_receiving_seconds": get("oldest_receiving_seconds")?, + // Groups a build reads from another build that has no rows for them (`groups:check`): always 0. + "empty_groups": get("empty_groups")?, + // Gallery purges that used up their retries in the last week: Cloudflare may serve stale screenshots. + "gallery_purges_failed": get("gallery_purges_failed")?, }))) } diff --git a/app/src/jobs/build_download.rs b/app/src/jobs/build_download.rs new file mode 100644 index 00000000..9e68bf7f --- /dev/null +++ b/app/src/jobs/build_download.rs @@ -0,0 +1,22 @@ +//! Builds a bulk download's archive (sc-8869, `domain::downloads`). Queued 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 job that stopped is replaced +//! on the next request after `downloads::STALE_MINUTES`. + +use laravel::queue::{Queueable, job}; + +use crate::domain::downloads; +use crate::models::Download; +use crate::storage::BlobStore; + +#[derive(Queueable)] +pub struct BuildDownload { + pub download_id: i64, +} + +#[job(name = "downloads.build")] +impl BuildDownload { + async fn handle(self) -> laravel::Result<()> { + let Some(download) = Download::find(self.download_id).await? else { return Ok(()) }; + downloads::build(download, &BlobStore::current().await?).await + } +} diff --git a/app/src/jobs/mod.rs b/app/src/jobs/mod.rs index 68e2b123..ac591519 100644 --- a/app/src/jobs/mod.rs +++ b/app/src/jobs/mod.rs @@ -1,3 +1,5 @@ //! Queued jobs. +pub mod build_download; pub mod process_build; +pub mod purge_gallery; diff --git a/app/src/jobs/purge_gallery.rs b/app/src/jobs/purge_gallery.rs new file mode 100644 index 00000000..d85428ed --- /dev/null +++ b/app/src/jobs/purge_gallery.rs @@ -0,0 +1,141 @@ +//! Purges Cloudflare's copies of public gallery URLs (`domain::gallery`): after a CI build changes (processed, approved, +//! rejected: the `BuildChanged` listener queues it), each published screenshot it changed and the project's manifest, +//! and every URL the project published at its last purge that it doesn't publish now (a screenshot removed, a group +//! dropped, the gallery turned off); or a list of URLs as they are (`gallery::purge_project`). One URL per screenshot, so +//! a purge is exact. Without `VISUALCI_CLOUDFLARE_ZONE_ID` and `VISUALCI_CLOUDFLARE_PURGE_TOKEN` (development) nothing is +//! queued. A failed purge is tried again; one that used up its tries is logged as an error and recorded in +//! `gallery_purge_failures`, which `/status` counts (`gallery_purges_failed`). + +use std::collections::BTreeSet; + +use laravel::db; +use laravel::queue::{Queueable, job}; + +use crate::config::Cloudflare; +use crate::domain::gallery; +use crate::models::{Build, Project}; + +#[derive(Queueable)] +pub struct PurgeGallery { + /// The build whose change may have made gallery URLs stale. + pub build_id: Option, + /// The project, when there's no build (`gallery::purge_project`). + pub project_id: Option, + /// URLs to purge as they are. + pub urls: Vec, +} + +/// Whether purges are configured: Cloudflare's zone and a token that may purge it. +#[must_use] +pub fn configured() -> Option { + let settings = laravel::config(); + let c = settings.section::().clone(); + (!c.zone_id.is_empty() && !c.purge_token.is_empty()).then_some(c) +} + +/// Ask Cloudflare to drop these URLs, 30 at a time (its limit per call). A client per purge: an HTTP client held +/// across the application's runtimes breaks. +async fn purge(cloudflare: &Cloudflare, urls: &[String]) -> laravel::Result<()> { + let client = reqwest::Client::new(); + for batch in urls.chunks(30) { + let response = client + .post(format!("https://api.cloudflare.com/client/v4/zones/{}/purge_cache", cloudflare.zone_id)) + .bearer_auth(&cloudflare.purge_token) + .json(&serde_json::json!({ "files": batch })) + .timeout(std::time::Duration::from_secs(20)) + .send() + .await + .map_err(|e| laravel::Error::msg(format!("Cloudflare purge: {e}")))?; + if !response.status().is_success() { + let status = response.status(); + let body = response.text().await.unwrap_or_default(); + return Err(laravel::Error::msg(format!( + "Cloudflare purge: HTTP {status}: {}", + body.chars().take(300).collect::() + ))); + } + } + Ok(()) +} + +/// What a purge does: the URLs to purge, and the project with what it publishes now (recorded once the purge worked). +pub struct Plan { + pub urls: Vec, + pub project: Option, + pub current: Vec, +} + +impl PurgeGallery { + /// Work out what to purge: the URLs given, the build's stale ones, and those published at the last purge but not + /// now. + /// + /// # Errors + /// On a database error. + pub async fn plan(&self) -> laravel::Result { + let app_url = crate::http::api::builds::app_url(); + let mut urls: BTreeSet = self.urls.iter().cloned().collect(); + let build = match self.build_id { + Some(id) => Build::find(id).await?, + None => None, + }; + let project_id = self.project_id.or(build.as_ref().map(|b| b.project_id)); + let project = match project_id { + Some(id) => Project::find(id).await?, + None => None, + }; + if let Some(build) = &build { + urls.extend(gallery::stale_urls(&app_url, build).await?); + } + let mut current = Vec::new(); + if let Some(project) = &project { + current = gallery::all_urls(&app_url, project).await?; + let previous: Vec = serde_json::from_value(project.gallery_urls.clone()).unwrap_or_default(); + urls.extend(previous.into_iter().filter(|u| !current.contains(u))); + } + Ok(Plan { urls: urls.into_iter().collect(), project, current }) + } + + /// Record a purge that used up its tries: an error in the log, and a row `/status` counts. + /// + /// # Errors + /// On a database error. + pub async fn record_failure(&self, error: &str) -> laravel::Result<()> { + tracing::error!(build_id = self.build_id, project_id = self.project_id, error, "gallery purge failed for good"); + let project_id = match (self.project_id, self.build_id) { + (Some(id), _) => Some(id), + (None, Some(build_id)) => Build::find(build_id).await?.map(|b| b.project_id), + (None, None) => None, + }; + let (build_id, urls) = (self.build_id, serde_json::json!(self.urls)); + db::query!( + "INSERT INTO gallery_purge_failures (project_id, build_id, urls, error) \ + VALUES ({project_id}, {build_id}, {urls}, {error})" + ) + .insert() + .await?; + Ok(()) + } +} + +#[job(name = "gallery.purge", tries = 5, backoff = [1.minutes(), 5.minutes(), 15.minutes(), 1.hours()])] +impl PurgeGallery { + async fn handle(self) -> laravel::Result<()> { + let Some(cloudflare) = configured() else { return Ok(()) }; + let plan = self.plan().await?; + if !plan.urls.is_empty() { + purge(&cloudflare, &plan.urls).await?; + tracing::info!(build_id = self.build_id, purged = plan.urls.len(), "gallery purged"); + } + if let Some(project) = plan.project { + let (id, current) = (project.id, serde_json::json!(plan.current)); + db::query!("UPDATE projects SET gallery_urls = {current} WHERE id = {id}").update().await?; + } + Ok(()) + } + + async fn failed(self, error: &laravel::Error) { + if let Err(e) = self.record_failure(&error.to_string()).await { + tracing::error!(error = %e, "recording a failed gallery purge failed"); + } + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index f68e2118..f763f2e6 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -49,6 +49,9 @@ pub fn configure() -> ApplicationBuilder { Ok(()) }) .with_middleware(|middleware, _| { + if let Err(e) = middleware.try_trust_proxies(config::trusted_proxies()) { + tracing::error!(error = %e, "TRUSTED_PROXIES: trusting no proxies"); + } middleware.prepend(http::hosts::route_by_host); // The site's signed-in hint is read by its script: plain, not encrypted middleware.replace(laravel::cookie::EncryptCookies::except([auth::sign_in::SIGNED_IN_HINT])); @@ -68,6 +71,12 @@ pub fn configure() -> ApplicationBuilder { // or project token. route.any("/mcp", mcp::handle); }) + .routes(http::renderer::routes) + .routes(http::gallery::routes) .health("/up"); }) + .with_commands(|commands, _| { + commands.add::(); + commands.add::(); + }) } diff --git a/app/src/listeners/mod.rs b/app/src/listeners/mod.rs index 9fa846c0..97ccbb14 100644 --- a/app/src/listeners/mod.rs +++ b/app/src/listeners/mod.rs @@ -1,4 +1,4 @@ -//! Listeners for the auth side's events (sc-8900). +//! Listeners for the domain's and the auth side's events (sc-8900). use laravel::event::{Event, listener}; @@ -12,3 +12,20 @@ pub async fn give_new_users_an_organization(event: Event) -> laravel:: Organization::create_personal(&user).await?; Ok(()) } + +/// A default-branch CI build changed: Cloudflare's copies of the gallery URLs it touches are purged in the background, +/// when purges are configured. +#[listener] +pub async fn purge_the_gallery(event: Event) -> laravel::Result<()> { + if crate::jobs::purge_gallery::configured().is_none() { + return Ok(()); + } + let Some(build) = crate::models::Build::find(event.build_id).await? else { return Ok(()) }; + if build.mode != "ci" { + return Ok(()); + } + crate::jobs::purge_gallery::PurgeGallery { build_id: Some(build.id), project_id: None, urls: vec![] } + .dispatch() + .await?; + Ok(()) +} diff --git a/app/src/models/blobs.rs b/app/src/models/blobs.rs index 2be81aa2..1576d24e 100644 --- a/app/src/models/blobs.rs +++ b/app/src/models/blobs.rs @@ -14,4 +14,7 @@ pub struct Blob { pub height: Option, pub created_at: Timestamp, pub updated_at: Timestamp, + /// Marked by retention before it deletes the object; registering the hash again clears it. + #[default] + pub deleting: bool, } diff --git a/app/src/models/diffs.rs b/app/src/models/diffs.rs index 784795b5..0643fe17 100644 --- a/app/src/models/diffs.rs +++ b/app/src/models/diffs.rs @@ -16,4 +16,6 @@ pub struct Diff { pub overlay_blob: Option, pub created_at: Timestamp, pub updated_at: Timestamp, + /// When a comparison last reused it (retention leaves its overlay alone for a day after). + pub used_at: Option, } diff --git a/app/src/models/projects.rs b/app/src/models/projects.rs index 8cd0bcb9..2906a66d 100644 --- a/app/src/models/projects.rs +++ b/app/src/models/projects.rs @@ -48,6 +48,9 @@ pub struct Project { #[default] pub tokens_can_approve: bool, pub repository_id: Option, + /// The gallery URLs last purged as published (`jobs::purge_gallery`). + #[default] + pub gallery_urls: serde_json::Value, } impl crate::auth::InProject for Project { diff --git a/app/src/models/renders.rs b/app/src/models/renders.rs index 8b4e2932..207a4360 100644 --- a/app/src/models/renders.rs +++ b/app/src/models/renders.rs @@ -23,4 +23,9 @@ pub struct Render { pub render_ms: Option, pub project_id: Option, pub claim_token_hash: Option, + /// The PNGs this render's claims uploaded through its own uploads: the only page images completing it may name. + #[default] + pub uploads: serde_json::Value, + /// When a snapshot last reused it (retention leaves its images and texts alone for a day after). + pub used_at: Option, } diff --git a/app/src/storage/blobs.rs b/app/src/storage/blobs.rs index 35db6c83..a5c3eb13 100644 --- a/app/src/storage/blobs.rs +++ b/app/src/storage/blobs.rs @@ -129,14 +129,27 @@ impl BlobStore { /// # Errors /// When the store can't be reached. pub async fn verify(&self, sha256: &str) -> Result> { + let found = self.verify_object(&key(sha256)?, sha256).await?; + if found.is_none() { + self.delete(sha256).await?; + } + Ok(found) + } + + /// The size of the object at `key` when it's there, no larger than [`MAX_BLOB_BYTES`], and its bytes hash to + /// `sha256`; else `None`. Nothing is deleted. + /// + /// # Errors + /// When the store can't be reached. + pub async fn verify_object(&self, key: &str, sha256: &str) -> Result> { use sha2::Digest; - let url = self.bucket.get_object(Some(&self.credentials), &key(sha256)?).sign(URL_TTL); + let url = self.bucket.get_object(Some(&self.credentials), key).sign(URL_TTL); let mut response = self.http.get(url).send().await.map_err(|e| error(e.to_string()))?; if response.status().as_u16() == 404 { return Ok(None); } if !response.status().is_success() { - return Err(error(format!("blob {sha256}: HTTP {}", response.status()))); + return Err(error(format!("{key}: HTTP {}", response.status()))); } let limit = MAX_BLOB_BYTES; let mut hasher = sha2::Sha256::new(); @@ -147,11 +160,17 @@ impl BlobStore { too_big = read > limit; hasher.update(&chunk); } - if !too_big && hex::encode(hasher.finalize()) == sha256 { - return Ok(Some(read)); - } - self.delete(sha256).await?; - Ok(None) + Ok((!too_big && hex::encode(hasher.finalize()) == sha256).then_some(read)) + } + + /// A URL a client can PUT an object other than a blob to (a renderer's proof that it holds a PNG), for minutes. The + /// size is part of the signature (`Content-Length`), so the URL takes exactly that many bytes and nothing larger. + #[must_use] + pub fn upload_url_for_key(&self, key: &str, size: u64) -> String { + let length = size.to_string(); + let mut action = self.public_bucket.put_object(Some(&self.credentials), key); + action.headers_mut().insert("content-length", length.as_str()); + action.sign(UPLOAD_TTL).to_string() } /// Store bytes under their SHA-256 and return it. @@ -190,6 +209,48 @@ impl BlobStore { } } + /// A URL a client can GET a stored object other than a blob from (a bulk download's archive), 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(e.to_string()))?; + let status = response.status(); + if status.is_success() || status.as_u16() == 404 { + Ok(()) + } else { + Err(error(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(e.to_string()))?; + if !response.status().is_success() { + return Err(error(format!("starting upload of {key}: HTTP {}", response.status()))); + } + let body = response.text().await.map_err(|e| error(e.to_string()))?; + let parsed = rusty_s3::actions::CreateMultipartUpload::parse_response(&body) + .map_err(|e| error(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 @@ -215,6 +276,72 @@ impl BlobStore { } } +/// An upload in parts ([`BlobStore::start_multipart`]): every part but the last 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("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(e.to_string()))?; + if !response.status().is_success() { + return Err(error(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(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(e.to_string()))?; + if !response.status().is_success() { + return Err(error(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"); + } + } +} + /// The store's factory: the container builds it once per application. #[laravel::container::singleton] async fn blob_store(config: laravel::config::Section) -> laravel::Result { diff --git a/app/src/storage/texts.rs b/app/src/storage/texts.rs index 897b0377..7435c897 100644 --- a/app/src/storage/texts.rs +++ b/app/src/storage/texts.rs @@ -30,9 +30,15 @@ pub async fn store(bodies: &[&str]) -> laravel::Result> { let rows: Vec = unique.into_iter().map(|(s, b)| Row { sha256: s.to_string(), body: b.to_string() }).collect(); // Two parameters a row, well under PostgreSQL's 65,535. for chunk in rows.chunks(10_000) { - db::query!("INSERT INTO texts (sha256, body) VALUES {...chunk(sha256, body)} ON CONFLICT DO NOTHING") - .insert() - .await?; + // A text stored again that's older than a day gets a new `created_at`: retention deletes only texts older than + // a day that nothing names, and the page or render naming it now may not be in its keep sets. + db::query!( + "INSERT INTO texts (sha256, body) VALUES {...chunk(sha256, body)} \ + ON CONFLICT (sha256) DO UPDATE SET created_at = now() \ + WHERE texts.created_at < now() - interval '12 hours'" + ) + .insert() + .await?; } Ok(shas) } diff --git a/app/src/testing.rs b/app/src/testing.rs index db01bf8f..3b9a7f39 100644 --- a/app/src/testing.rs +++ b/app/src/testing.rs @@ -36,6 +36,9 @@ pub fn configure() -> ApplicationBuilder { ("S3_ACCESS_KEY_ID", "visualci"), ("S3_SECRET_ACCESS_KEY", "visualci-dev-secret"), ("APP_URL", "https://app.visualci.test"), + ("RENDERER_TOKEN", "renderer-test-token"), + ("RENDERER_VERSION", "1"), + ("METRICS_TOKEN", "metrics-test-token"), ]) .with_env("DATABASE_URL", url) .refresh_database() diff --git a/app/tests/downloads.rs b/app/tests/downloads.rs new file mode 100644 index 00000000..4a1d3ace --- /dev/null +++ b/app/tests/downloads.rs @@ -0,0 +1,235 @@ +//! Bulk downloads (sc-8869): a build's images as one tar.zst, filtered by state, sides and glob, reused within the +//! hour, deleted by retention after a day, and only for the build's own project. + +use app::domain::downloads; +use app::models::Download; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +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]; + +async fn project_token() -> laravel::Result { + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(token) +} + +/// A finished build of these images on main. +async fn build(app: &Application, token: &str, commit: &str, parents: &[&str], files: &[(&str, [u8; 3])]) -> Value { + let auth = format!("Bearer {token}"); + let created = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": commit, "branch": "main", "parent_commits": parents })) + .await + .json() + .clone(); + let id = created["id"].as_str().unwrap().to_string(); + let mut list = Vec::new(); + let mut bodies = Vec::new(); + for (name, rgb) in files { + let bytes = png(*rgb); + let sha = visualci_core::sha256_hex(&bytes); + list.push(json!({ + "name": name, "kind": "image", "sha256": sha, "size": bytes.len(), "content_type": "image/png", + "fingerprint": visualci_core::image_hash::fingerprint_bytes(&bytes).unwrap(), + })); + bodies.push(bytes); + } + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": list })) + .await; + registered.assert_ok(); + let registered = registered.json().clone(); + for (s, bytes) in registered["snapshots"].as_array().unwrap().iter().zip(bodies) { + if let Some(url) = s["upload_url"].as_str() { + let r = + reqwest::Client::new().put(url).header("content-type", "image/png").body(bytes).send().await.unwrap(); + assert!(r.status().is_success()); + } + } + let done = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await.json().clone(); + assert_eq!(done["state"], "completed", "{done}"); + done +} + +#[laravel::test] +async fn a_builds_changed_images_download_as_one_archive(app: Application) -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + let token = project_token().await?; + let auth = format!("Bearer {token}"); + build(&app, &token, "A", &[], &[("web/a", RED), ("web/b", BLUE), ("other/c", RED)]).await; + let b = build(&app, &token, "B", &["A"], &[("web/a", GREEN), ("web/b", BLUE), ("other/c", BLUE)]).await; + + // The changed snapshots under web/, by build number: the job runs inline in tests. + let r = app + .post(format!("/api/v1/builds/{}/downloads", b["number"])) + .header("authorization", &auth) + .json(json!({ "glob": "web/**", "sides": ["head", "regions"] })) + .await; + r.assert_ok(); + let first = r.json().clone(); + 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}"); + assert_eq!(first["filter"], json!({ "state": "changed", "sides": ["head", "regions"], "glob": "web/**" })); + + let bytes = reqwest::get(first["url"].as_str().unwrap()).await.unwrap().bytes().await.unwrap(); + let mut files = std::collections::BTreeMap::new(); + visualci_core::bundle::for_each_entry(bytes.as_ref(), 64 << 20, |path, bytes| { + files.insert(path.to_string(), bytes); + Ok::<_, ()>(()) + }) + .unwrap(); + assert_eq!(files.keys().collect::>(), ["manifest.json", "web/a/head.png", "web/a/regions.png"]); + assert_eq!(files["web/a/head.png"], png(GREEN)); + let regions = image::load_from_memory(&files["web/a/regions.png"]).unwrap(); + assert!(regions.width() < 200 && regions.height() < 150, "cropped to the change"); + let manifest: Value = serde_json::from_slice(&files["manifest.json"]).unwrap(); + assert_eq!(manifest["snapshots"][0]["name"], "web/a"); + assert_eq!(manifest["snapshots"][0]["pages"][0]["files"].as_array().unwrap().len(), 2); + assert!(manifest["snapshots"][0]["pages"][0]["changed_fraction"].as_f64().unwrap() > 0.0, "{manifest}"); + + // Every unchanged snapshot, by id: base, head and no diff. + let unchanged = app + .post(format!("/api/v1/builds/{}/downloads", b["id"].as_str().unwrap())) + .header("authorization", &auth) + .json(json!({ "state": "unchanged" })) + .await + .json() + .clone(); + assert_eq!( + (unchanged["summary"]["snapshots"].clone(), unchanged["files"].clone()), + (json!(1), json!(3)), + "{unchanged}" + ); + + // The same filter within the hour: the same download, not built again. + let again = app + .post(format!("/api/v1/builds/%23{}/downloads", b["number"])) + .header("authorization", &auth) + .json(json!({ "glob": "web/**", "sides": ["regions", "head"] })) + .await + .json() + .clone(); + assert_eq!(again["id"], first["id"]); + let shown = + app.get(format!("/api/v1/downloads/{}", first["id"].as_str().unwrap())).header("authorization", &auth).await; + shown.assert_ok(); + assert_eq!(shown.json()["state"], "ready"); + + // A filter it doesn't know is refused, saying why. + let r = app + .post(format!("/api/v1/builds/{}/downloads", b["number"])) + .header("authorization", &auth) + .json(json!({ "state": "new" })) + .await; + r.assert_status(400); + assert!(r.text().contains("state must be one of"), "{}", r.text()); + + // After a day, retention deletes the download and its archive. + let pid: laravel::str::Uuid = first["id"].as_str().unwrap().parse().unwrap(); + let d = Download::query().filter(Download::pid.eq(pid)).first().await?.unwrap(); + let (id, key) = (d.id, d.object_key.clone().unwrap()); + db::query!("UPDATE downloads SET created_at = now() - interval '25 hours' WHERE id = {id}").update().await?; + assert_eq!(downloads::prune(Some(&store)).await?, 1); + assert_eq!(reqwest::get(store.object_url(&key)).await.unwrap().status().as_u16(), 404); + Ok(()) +} + +#[laravel::test] +async fn another_projects_token_can_not_download_a_build(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let b = build(&app, &token, "A", &[], &[("web/a", RED)]).await; + let other = project_token().await?; + let auth = format!("Bearer {other}"); + let r = app + .post(format!("/api/v1/builds/{}/downloads", b["id"].as_str().unwrap())) + .header("authorization", &auth) + .json(json!({})) + .await; + r.assert_status(404); + let r = app + .post(format!("/api/v1/builds/{}/downloads", b["number"])) + .header("authorization", &auth) + .json(json!({})) + .await; + r.assert_status(404); + Ok(()) +} + +/// A project builds at most three downloads at once, and a download is built once even when its job runs twice. +#[laravel::test] +async fn downloads_are_limited_per_project_and_built_once(app: Application) -> laravel::Result<()> { + Box::pin(limited_and_once(app)).await +} + +async fn limited_and_once(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let auth = format!("Bearer {token}"); + let b = build(&app, &token, "A", &[], &[("web/a", RED)]).await; + let number = b["number"].clone(); + + // Ready now (the job runs inline): building it again does nothing. + let first = app + .post(format!("/api/v1/builds/{number}/downloads")) + .header("authorization", &auth) + .json(json!({ "state": "all" })) + .await; + assert_eq!(first.json()["state"], "ready"); + let pid: laravel::str::Uuid = first.json()["id"].as_str().unwrap().parse().unwrap(); + let mut d = Download::query().filter(Download::pid.eq(pid)).first().await?.unwrap(); + d.state = "pending".to_string(); + downloads::build(d, &app::storage::BlobStore::current().await?).await?; + let again = Download::query().filter(Download::pid.eq(pid)).first().await?.unwrap(); + assert_eq!((again.state.as_str(), again.files), ("ready", first.json()["files"].as_i64().unwrap() as i32)); + + // Three still building: a fourth waits. + let build_id = Download::query().filter(Download::pid.eq(pid)).first().await?.unwrap().build_id; + for i in 0..3 { + let key = format!("busy-{i}"); + db::query!( + "INSERT INTO downloads (pid, build_id, filter, filter_key, state) \ + VALUES (gen_random_uuid(), {build_id}, '{{}}', {key}, 'building')" + ) + .insert() + .await?; + } + let r = app + .post(format!("/api/v1/builds/{number}/downloads")) + .header("authorization", &auth) + .json(json!({ "state": "added" })) + .await; + r.assert_status(429); + assert!(r.text().contains("at most 3 at once"), "{}", r.text()); + Ok(()) +} diff --git a/app/tests/gallery.rs b/app/tests/gallery.rs new file mode 100644 index 00000000..d7d77340 --- /dev/null +++ b/app/tests/gallery.rs @@ -0,0 +1,275 @@ +//! Public galleries: only the approved default-branch version of a screenshot a `gallery` group includes is served, +//! at one stable URL each, with a manifest that doesn't change unless the images do. Each image served adds a credit +//! to its project's row for the day; a 304, a 404 or a URL with a query costs nothing. + +use app::domain::{gallery, reviews}; +use app::models::{Build, CreditTransaction, Organization, Project}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +fn png(rgb: [u8; 3]) -> Vec { + let img = image::RgbImage::from_pixel(8, 6, 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]; +const PURPLE: [u8; 3] = [128, 0, 128]; + +struct World { + org: Organization, + project: Project, + token: String, +} + +async fn world() -> laravel::Result { + fixtures::blob_store().await?; + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(World { org, project, token }) +} + +impl World { + /// A finished CI build of these images, with a visualci.yml that publishes `web/**`. + async fn build( + &self, + app: &Application, + commit: &str, + branch: &str, + parents: &[&str], + files: &[(&str, [u8; 3])], + ) -> Build { + // Boxed: the test's own future would otherwise outgrow a test thread's stack. + Box::pin(self.build_inner(app, commit, branch, parents, files)).await + } + + async fn build_inner( + &self, + app: &Application, + commit: &str, + branch: &str, + parents: &[&str], + files: &[(&str, [u8; 3])], + ) -> Build { + let auth = format!("Bearer {}", self.token); + let created = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ + "commit": commit, "branch": branch, "parent_commits": parents, + "config": { "gallery": { "groups": [{ "name": "Web", "include": ["web/**"] }] } }, + })) + .await; + created.assert_ok(); + let id = created.json()["id"].as_str().unwrap().to_string(); + let mut list = Vec::new(); + let mut bodies = Vec::new(); + for (name, rgb) in files { + let bytes = png(*rgb); + let sha = visualci_core::sha256_hex(&bytes); + list.push(json!({ + "name": name, "kind": "image", "sha256": sha, "size": bytes.len(), "content_type": "image/png", + "fingerprint": visualci_core::image_hash::fingerprint_bytes(&bytes).unwrap(), + })); + bodies.push(bytes); + } + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": list })) + .await; + registered.assert_ok(); + for (s, bytes) in registered.json()["snapshots"].as_array().unwrap().iter().zip(bodies) { + if let Some(url) = s["upload_url"].as_str() { + let r = reqwest::Client::new() + .put(url) + .header("content-type", "image/png") + .body(bytes) + .send() + .await + .unwrap(); + assert!(r.status().is_success()); + } + } + let done = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await; + assert_eq!(done.json()["state"], "completed", "{}", done.text()); + let pid: laravel::str::Uuid = id.parse().unwrap(); + Build::query().filter(Build::pid.eq(pid)).first().await.unwrap().unwrap() + } + + async fn review(&self, build: Build, action: &str) -> Build { + Box::pin(reviews::review(build, None, &reviews::Via::default(), action, None, None)).await.unwrap().unwrap() + } + + /// The project's gallery rows: (rows, credits). + async fn gallery_credits(&self) -> (usize, i64) { + let rows = CreditTransaction::query() + .filter(CreditTransaction::organization_id.eq(self.org.id) & CreditTransaction::kind.eq("gallery")) + .get() + .await + .unwrap(); + (rows.len(), rows.iter().map(|r| -r.amount).sum()) + } +} + +fn header(r: &laravel::testing::TestResponse, name: &str) -> String { + r.header(name).unwrap_or_default().to_string() +} + +/// The ETag an image is served with: its SHA-256. +fn etag(rgb: [u8; 3]) -> String { + format!("\"{}\"", visualci_core::sha256_hex(&png(rgb))) +} + +#[laravel::test] +async fn only_approved_default_branch_screenshots_in_a_group_are_served(app: Application) -> laravel::Result<()> { + // On the heap: this test's future is larger than a test thread's stack. + Box::pin(only_approved_served(app)).await +} + +async fn only_approved_served(app: Application) -> laravel::Result<()> { + let w = world().await?; + let base = format!("/g/{}/web", w.org.slug); + w.build(&app, "A", "main", &[], &[("web/home", RED), ("web/about", GREEN), ("private/x", BLUE)]).await; + + // The manifest: the group with its two screenshots, nothing outside the globs, cacheable and readable anywhere. + let m = app.get(format!("{base}.json")).await; + m.assert_ok(); + assert_eq!(header(&m, "cache-control"), "public, max-age=300, s-maxage=86400"); + assert_eq!(header(&m, "access-control-allow-origin"), "*"); + assert_eq!(header(&m, "cross-origin-resource-policy"), "cross-origin"); + let manifest: Value = m.json().clone(); + let urls: Vec = manifest["groups"][0]["items"] + .as_array() + .unwrap() + .iter() + .map(|i| i["url"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(manifest["groups"][0]["name"], "Web"); + assert_eq!(manifest["project"], format!("{}/web", w.org.slug)); + assert_eq!(urls.len(), 2, "{manifest}"); + assert!(urls.iter().all(|u| u.contains("/web/web/")), "{urls:?}"); + assert!(manifest["groups"][0]["items"][0]["since"].as_str().unwrap().ends_with("+00:00"), "{manifest}"); + assert_eq!(app.get(format!("{base}.json")).await.text(), m.text(), "the manifest is stable"); + + // An image: its bytes, a credit, and an ETag that answers a revalidation for free. + let home = app.get(format!("{base}/web/home.png")).await; + home.assert_ok(); + assert_eq!(header(&home, "etag"), etag(RED)); + assert_eq!(header(&home, "content-length"), png(RED).len().to_string()); + assert_eq!(header(&home, "content-type"), "image/png"); + assert_eq!(w.gallery_credits().await, (1, 1)); + let again = app.get(format!("{base}/web/home.png")).header("if-none-match", header(&home, "etag")).await; + again.assert_status(304); + + // Outside the globs, unknown, or with a query: 404, and free. + for path in ["private/x.png", "web/missing.png", "web/home.jpg"] { + app.get(format!("{base}/{path}")).await.assert_status(404); + } + app.get(format!("{base}/web/home.png?width=10")).await.assert_status(404); + assert_eq!(header(&app.get(format!("{base}/private/x.png")).await, "cache-control"), "no-store", "never cached"); + app.get(format!("/g/{}/nope.json", w.org.slug)).await.assert_status(404); + assert_eq!(w.gallery_credits().await, (1, 1)); + + // More images the same day add to the project's one row for the day. + app.get(format!("{base}/web/about.png")).await.assert_ok(); + app.get(format!("{base}/web/home.png")).await.assert_ok(); + assert_eq!(w.gallery_credits().await, (1, 3), "one row for the day"); + + // A pending change keeps the approved image; approving it publishes the new one. + let b = w.build(&app, "B", "main", &["A"], &[("web/home", BLUE), ("web/about", GREEN), ("private/x", BLUE)]).await; + assert_eq!(header(&app.get(format!("{base}/web/home.png")).await, "etag"), etag(RED)); + let b = w.review(b, "approve").await; + assert_eq!(header(&app.get(format!("{base}/web/home.png")).await, "etag"), etag(BLUE)); + // The approval purges exactly the published URLs of its screenshots, and the manifest. + let mut stale = gallery::stale_urls("https://app.visualci.com", &b).await?; + stale.sort(); + let at = format!("https://app.visualci.com/g/{}/web", w.org.slug); + assert_eq!(stale, vec![format!("{at}.json"), format!("{at}/web/home.png")], "not the unchanged about.png"); + + // A rejected change keeps it too, and so does a change on another branch. + let c = w + .build(&app, "C", "main", &["B", "A"], &[("web/home", PURPLE), ("web/about", GREEN), ("private/x", BLUE)]) + .await; + w.review(c, "reject").await; + w.build(&app, "F", "feature", &["B", "A"], &[("web/home", GREEN), ("web/about", GREEN)]).await; + assert_eq!(header(&app.get(format!("{base}/web/home.png")).await, "etag"), etag(BLUE)); + + // Turned off, nothing is served. + let id = w.project.id; + db::query!("UPDATE projects SET gallery_enabled = false WHERE id = {id}").update().await?; + app.get(format!("{base}.json")).await.assert_status(404); + app.get(format!("{base}/web/home.png")).await.assert_status(404); + Ok(()) +} + +/// The gallery serves from the app's own origin, so an image goes out only as the image its bytes are, never as the +/// content type a client declared: an image declared as HTML would run script there, as anyone who opens the link. +#[laravel::test] +async fn an_image_is_served_as_its_bytes_never_as_a_declared_html_type(app: Application) -> laravel::Result<()> { + let w = world().await?; + w.build(&app, "A", "main", &[], &[("web/home", RED)]).await; + let sha = visualci_core::sha256_hex(&png(RED)); + db::query!("UPDATE blobs SET content_type = 'text/html' WHERE sha256 = {sha}").update().await?; + let home = app.get(format!("/g/{}/web/web/home.png", w.org.slug)).await; + home.assert_ok(); + assert_eq!(header(&home, "content-type"), "image/png"); + assert_eq!(header(&home, "x-content-type-options"), "nosniff"); + assert_eq!(header(&home, "access-control-allow-origin"), "*"); + assert!(header(&home, "content-security-policy").contains("sandbox")); + Ok(()) +} + +/// A project's gallery credits stop at the day's cap; a purge covers what dropped out of the gallery since the last +/// one; and a purge that used up its tries is counted in `/status`. +#[laravel::test] +async fn credits_stop_at_the_cap_and_purges_cover_what_dropped_out(app: Application) -> laravel::Result<()> { + Box::pin(cap_and_dropouts(app)).await +} + +async fn cap_and_dropouts(app: Application) -> laravel::Result<()> { + use app::jobs::purge_gallery::PurgeGallery; + let w = world().await?; + w.build(&app, "A", "main", &[], &[("web/home", RED), ("web/about", GREEN)]).await; + let project = Project::find_or_fail(w.project.id).await?; + + for _ in 0..3 { + assert!(app::domain::credits::spend_gallery(&project, 1, 3).await?); + } + assert!(!app::domain::credits::spend_gallery(&project, 1, 3).await?, "past the cap: served free"); + assert_eq!(w.gallery_credits().await, (1, 3)); + + // The first purge records what's published: the manifest and two screenshots. + let first = PurgeGallery { build_id: None, project_id: Some(project.id), urls: vec![] }.plan().await?; + assert_eq!(first.current.len(), 3, "{:?}", first.current); + let (id, current) = (project.id, json!(first.current)); + db::query!("UPDATE projects SET gallery_urls = {current} WHERE id = {id}").update().await?; + + // about.png leaves the gallery (removed, and the removal approved): the next purge includes it. + let b = w.build(&app, "B", "main", &["A"], &[("web/home", RED)]).await; + let b = w.review(b, "approve").await; + let plan = PurgeGallery { build_id: Some(b.id), project_id: None, urls: vec![] }.plan().await?; + let about = format!("https://app.visualci.test/g/{}/web/web/about.png", w.org.slug); + assert!(plan.urls.contains(&about), "{:?}", plan.urls); + assert!(!plan.current.contains(&about), "{:?}", plan.current); + + // A purge that used up its tries. + PurgeGallery { build_id: Some(b.id), project_id: None, urls: vec![about] } + .record_failure("Cloudflare purge: HTTP 500") + .await?; + assert_eq!(app.get("/status").await.json()["gallery_purges_failed"], 1); + Ok(()) +} diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index 4787f8c1..20311864 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -43,6 +43,8 @@ fn in_production() -> laravel::foundation::ApplicationBuilder { ("S3_BUCKET", "visualci-test"), ("S3_ACCESS_KEY_ID", "visualci"), ("S3_SECRET_ACCESS_KEY", "visualci-dev-secret"), + ("RENDERER_TOKEN", "renderer-test-token"), + ("RENDERER_VERSION", "1"), ]) } diff --git a/app/tests/renderer.rs b/app/tests/renderer.rs new file mode 100644 index 00000000..6e4cb04c --- /dev/null +++ b/app/tests/renderer.rs @@ -0,0 +1,344 @@ +//! The renderer API: tokens on every route whatever the Host, claiming, uploading pages and completing a render, which +//! wakes the build waiting on it. + +use app::models::{Build, Render, Snapshot}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +const RENDERER: &str = "Bearer renderer-test-token"; + +async fn project_token() -> laravel::Result { + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "docs").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(token) +} + +fn png() -> Vec { + png_of([10, 20, 30, 255]) +} + +fn png_of(rgba: [u8; 4]) -> Vec { + let image = image::RgbaImage::from_pixel(8, 8, image::Rgba(rgba)); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +async fn put(url: &str, bytes: Vec, content_type: &str) { + let r = reqwest::Client::new().put(url).header("content-type", content_type).body(bytes).send().await.unwrap(); + assert!(r.status().is_success(), "uploading: {}", r.status()); +} + +#[laravel::test] +async fn every_renderer_route_needs_its_token_whatever_the_host(app: Application) -> laravel::Result<()> { + for host in ["renderer.cluster.local", "api.visualci.test", "evil.example.com"] { + app.post("/internal/renderer/claim") + .header("host", host) + .json(json!({ "renderer_version": "1" })) + .await + .assert_status(401); + app.post("/internal/renderer/renders/1/uploads") + .header("host", host) + .json(json!({ "files": [] })) + .await + .assert_status(401); + app.post("/internal/renderer/renders/1/complete") + .header("host", host) + .json(json!({ "pages": [] })) + .await + .assert_status(401); + app.get("/internal/renderer/metrics").header("host", host).await.assert_status(401); + } + // The renderer token doesn't read metrics, and the metrics token doesn't claim renders. + app.get("/internal/renderer/metrics").header("authorization", RENDERER).await.assert_status(401); + app.post("/internal/renderer/claim") + .header("authorization", "Bearer metrics-test-token") + .json(json!({ "renderer_version": "1" })) + .await + .assert_status(401); + let metrics = app.get("/internal/renderer/metrics").header("authorization", "Bearer metrics-test-token").await; + metrics.assert_ok(); + assert!(metrics.text().contains("visualci_renders_now{state=\"queued\"} 0"), "{}", metrics.text()); + assert!(metrics.text().contains("visualci_gallery_purges_failed_7d 0"), "{}", metrics.text()); + Ok(()) +} + +/// A build on main with one PDF, waiting for its render. Returns the build's id. +async fn waiting_build(app: &Application, token: &str, commit: &str) -> String { + let auth = format!("Bearer {token}"); + let build = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": commit, "branch": "main", "parent_commits": [] })) + .await + .json() + .clone(); + let id = build["id"].as_str().unwrap().to_string(); + let pdf = format!("%PDF-1.4 renderer test {id}").into_bytes(); + let sha = visualci_core::sha256_hex(&pdf); + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": [{ + "name": "invoice", "kind": "document", "fingerprint": sha, "sha256": sha, "size": pdf.len(), + "content_type": "application/pdf" + }]})) + .await + .json() + .clone(); + put(registered["snapshots"][0]["upload_url"].as_str().unwrap(), pdf, "application/pdf").await; + let waiting = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await.json().clone(); + assert_eq!(waiting["state"], "processing", "waiting for its render"); + id +} + +/// Claim the next render: its id and the claim's token. +async fn claim(app: &Application) -> (i64, String) { + let claimed = app + .post("/internal/renderer/claim") + .header("authorization", RENDERER) + .json(json!({ "renderer_version": "1" })) + .await; + claimed.assert_ok(); + let job: Value = claimed.json()["job"].clone(); + (job["id"].as_i64().unwrap(), job["token"].as_str().unwrap().to_string()) +} + +/// Ask for upload URLs for these PNGs: the answer's `upload_urls`. +async fn uploads(app: &Application, render_id: i64, claim: &str, pngs: &[&[u8]]) -> Value { + let files: Vec = pngs + .iter() + .map(|b| json!({ "sha256": visualci_core::sha256_hex(b), "size": b.len(), "content_type": "image/png" })) + .collect(); + let r = app + .post(format!("/internal/renderer/renders/{render_id}/uploads")) + .header("authorization", RENDERER) + .header("x-render-token", claim) + .json(json!({ "files": files })) + .await; + r.assert_ok(); + r.json()["upload_urls"].clone() +} + +/// A page as a renderer reports it. +fn page(png: &[u8], text: &str) -> Value { + json!({ + "image": visualci_core::sha256_hex(png), "image_fingerprint": visualci_core::image_hash::fingerprint_bytes(png).unwrap(), + "fingerprint": "f".repeat(64), "width": 8, "height": 8, "text": text, + }) +} + +async fn complete(app: &Application, render_id: i64, claim: &str, pages: Value) -> laravel::testing::TestResponse { + app.post(format!("/internal/renderer/renders/{render_id}/complete")) + .header("authorization", RENDERER) + .header("x-render-token", claim) + .json(json!({ "pages": pages })) + .await +} + +#[laravel::test] +async fn a_render_is_claimed_drawn_and_completed_and_its_build_finishes(app: Application) -> laravel::Result<()> { + Box::pin(claimed_drawn_completed(app)).await +} + +async fn claimed_drawn_completed(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + waiting_build(&app, &token, "c1").await; + + // A renderer claims it, uploads its page and completes it. + let claimed = app + .post("/internal/renderer/claim") + .header("authorization", RENDERER) + .json(json!({ "renderer_version": "1" })) + .await; + let job: Value = claimed.json()["job"].clone(); + assert_eq!((job["engine"].as_str(), job["dpi"].as_u64()), (Some("pdfbox"), Some(140))); + let (render_id, claim) = (job["id"].as_i64().unwrap(), job["token"].as_str().unwrap().to_string()); + let page_png = png(); + let page_sha = visualci_core::sha256_hex(&page_png); + // Another claim's token can't upload. + app.post(format!("/internal/renderer/renders/{render_id}/uploads")) + .header("authorization", RENDERER) + .header("x-render-token", "not-the-claim") + .json(json!({ "files": [{ "sha256": page_sha, "size": page_png.len(), "content_type": "image/png" }] })) + .await + .assert_status(401); + let urls = uploads(&app, render_id, &claim, &[&page_png]).await; + put(urls[&page_sha].as_str().unwrap(), page_png.clone(), "image/png").await; + let done = complete(&app, render_id, &claim, json!([page(&page_png, "Invoice 42")])).await; + done.assert_ok(); + assert_eq!(done.json()["state"], "done"); + + // The render keeps its text by hash, and the build that waited on it finished. + let render = Render::find_or_fail(render_id).await?; + assert_eq!(render.pages[0]["text_sha"], visualci_core::sha256_hex(b"Invoice 42")); + assert!(render.pages[0].get("text").is_none(), "{}", render.pages); + let build = Build::query().filter(Build::number.eq(1)).first().await?.unwrap(); + assert_eq!(build.state, "completed"); + let snapshot = Snapshot::query().filter(Snapshot::build_id.eq(build.id)).first().await?.unwrap(); + assert_eq!(snapshot.state, "added"); + Ok(()) +} + +/// A render whose claims all expired would stay `rendering` forever: the next claim fails it, and its build goes on. +#[laravel::test] +async fn a_render_out_of_attempts_fails_and_its_build_finishes(app: Application) -> laravel::Result<()> { + Box::pin(out_of_attempts(app)).await +} + +async fn out_of_attempts(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let build_id = waiting_build(&app, &token, "c1").await; + let (render_id, _) = claim(&app).await; + db::query!("UPDATE renders SET attempts = 3, claimed_at = now() - interval '1 hour' WHERE id = {render_id}") + .update() + .await?; + + let next = app + .post("/internal/renderer/claim") + .header("authorization", RENDERER) + .json(json!({ "renderer_version": "1" })) + .await; + assert_eq!(next.json()["job"], Value::Null, "nothing else to draw"); + let render = Render::find_or_fail(render_id).await?; + assert_eq!(render.state, "failed"); + assert_eq!(render.error.as_deref(), Some(app::domain::renders::CLAIMS_RAN_OUT)); + let pid: laravel::str::Uuid = build_id.parse().unwrap(); + let build = Build::query().filter(Build::pid.eq(pid)).first().await?.unwrap(); + assert_ne!(build.state, "processing", "the build stopped waiting"); + Ok(()) +} + +/// A claim's version must match a render's exactly: never a pattern. +#[laravel::test] +async fn a_claim_matches_the_renderer_version_exactly(app: Application) -> laravel::Result<()> { + Box::pin(version_exactly(app)).await +} + +async fn version_exactly(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + waiting_build(&app, &token, "c1").await; + for version in ["%", "_", "", "2", "pdfbox/140dpi/1"] { + let r = app + .post("/internal/renderer/claim") + .header("authorization", RENDERER) + .json(json!({ "renderer_version": version })) + .await; + assert_eq!(r.json()["job"], Value::Null, "{version:?} claims nothing"); + } + claim(&app).await; + Ok(()) +} + +/// A renderer runs untrusted PDFs, so completion trusts nothing it sends: page counts, sizes, fingerprints and text are +/// bounded, and a page image must be a PNG this render uploaded itself, never another tenant's file named by its hash. +#[laravel::test] +async fn a_completion_is_checked_before_anything_is_stored(app: Application) -> laravel::Result<()> { + Box::pin(completion_checked(app)).await +} + +async fn completion_checked(app: Application) -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + let token = project_token().await?; + + // Another tenant's PNG, already stored. + let theirs = png_of([200, 1, 1, 255]); + let their_sha = store.put(theirs.clone(), "image/png").await?; + app::domain::blobs::register(&their_sha, i64::try_from(theirs.len()).unwrap(), "image/png").await?; + db::query!("UPDATE blobs SET uploaded_at = now() WHERE sha256 = {their_sha}").update().await?; + + let refused = |r: &laravel::testing::TestResponse, what: &str| { + assert_eq!(r.status().as_u16(), 400, "{what}: {}", r.text()); + }; + let mut commit = 0; + let mut fresh = async || { + commit += 1; + let c = format!("c{commit}"); + db::query!("UPDATE renders SET state = 'done' WHERE state IN ('queued', 'rendering')").update().await.unwrap(); + waiting_build(&app, &token, &c).await; + claim(&app).await + }; + + // Named without uploading it: refused, and the render fails. + let (render_id, claim_token) = fresh().await; + let r = complete(&app, render_id, &claim_token, json!([page(&theirs, "")])).await; + refused(&r, "another tenant's PNG"); + assert!(r.text().contains("wasn't uploaded for this render"), "{}", r.text()); + assert_eq!(Render::find_or_fail(render_id).await?.state, "failed"); + + // Named through the uploads, but its bytes never sent to the proof key: the render fails. + let (render_id, claim_token) = fresh().await; + let urls = uploads(&app, render_id, &claim_token, &[&theirs]).await; + assert!(urls[&their_sha].as_str().unwrap().contains(&format!("proofs/{render_id}/")), "{urls}"); + let r = complete(&app, render_id, &claim_token, json!([page(&theirs, "")])).await; + r.assert_ok(); + assert_eq!(r.json()["state"], "failed"); + + // Drawn for real (the same PNG, uploaded to the proof key): done. The proof URL takes exactly the declared size. + let (render_id, claim_token) = fresh().await; + let urls = uploads(&app, render_id, &claim_token, &[&theirs]).await; + let mut larger = theirs.clone(); + larger.extend_from_slice(&[0; 1024]); + let refused_upload = reqwest::Client::new() + .put(urls[&their_sha].as_str().unwrap()) + .header("content-type", "image/png") + .body(larger) + .send() + .await + .unwrap(); + assert!(!refused_upload.status().is_success(), "a larger body is refused: {}", refused_upload.status()); + put(urls[&their_sha].as_str().unwrap(), theirs.clone(), "image/png").await; + let r = complete(&app, render_id, &claim_token, json!([page(&theirs, "")])).await; + assert_eq!(r.json()["state"], "done", "{}", r.text()); + + // Bounds: pages, size, fingerprints, text. + let mine = png_of([1, 2, 200, 255]); + let mut bad: Vec<(&str, Value)> = Vec::new(); + bad.push(("too many pages", Value::Array(vec![page(&mine, ""); 2001]))); + let mut wide = page(&mine, ""); + wide["width"] = json!(1_000_000); + bad.push(("a page too wide", json!([wide]))); + let mut zero = page(&mine, ""); + zero["height"] = json!(0); + bad.push(("a page with no height", json!([zero]))); + let mut fingerprint = page(&mine, ""); + fingerprint["fingerprint"] = json!("../../not-hex"); + bad.push(("a fingerprint that isn't hex", json!([fingerprint]))); + bad.push(("too much text", json!([page(&mine, &"x".repeat(300 * 1024))]))); + for (what, pages) in bad { + let (render_id, claim_token) = fresh().await; + let urls = uploads(&app, render_id, &claim_token, &[&mine]).await; + if let Some(url) = urls[visualci_core::sha256_hex(&mine)].as_str() { + put(url, mine.clone(), "image/png").await; + } + let r = complete(&app, render_id, &claim_token, pages).await; + refused(&r, what); + assert_eq!(Render::find_or_fail(render_id).await?.state, "failed", "{what}"); + } + + // More than 5,000 upload entries are refused, not cut short. + let (render_id, claim_token) = fresh().await; + let files: Vec = + (0..5001).map(|i| json!({ "sha256": format!("{i:064x}"), "size": 1, "content_type": "image/png" })).collect(); + let r = app + .post(format!("/internal/renderer/renders/{render_id}/uploads")) + .header("authorization", RENDERER) + .header("x-render-token", &claim_token) + .json(json!({ "files": files })) + .await; + refused(&r, "5,001 uploads"); + Ok(()) +} diff --git a/app/tests/retention.rs b/app/tests/retention.rs new file mode 100644 index 00000000..df9f962b --- /dev/null +++ b/app/tests/retention.rs @@ -0,0 +1,345 @@ +//! Retention and expiry: what retention keeps (the builds a kept build reads groups from, referenced texts, recent +//! texts) and deletes, and the scheduled `builds:expire` and `retention:prune` commands. + +use app::domain::retention; +use app::models::{Blob, Build, Snapshot}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::json; + +fn png(rgb: [u8; 3]) -> Vec { + let img = image::RgbImage::from_pixel(8, 6, image::Rgb(rgb)); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() +} + +async fn project_token() -> laravel::Result { + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(token) +} + +/// A finished build of one image, on its own branch. +async fn build(app: &Application, token: &str, branch: &str, rgb: [u8; 3]) -> Build { + Box::pin(build_inner(app, token, branch, rgb)).await +} + +async fn build_inner(app: &Application, token: &str, branch: &str, rgb: [u8; 3]) -> Build { + let auth = format!("Bearer {token}"); + let created = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": &visualci_core::sha256_hex(branch.as_bytes())[..40], "branch": branch, "parent_commits": [] })) + .await; + created.assert_ok(); + let id = created.json()["id"].as_str().unwrap().to_string(); + let bytes = png(rgb); + let sha = visualci_core::sha256_hex(&bytes); + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": [{ + "name": "web/home", "kind": "image", "sha256": sha, "size": bytes.len(), "content_type": "image/png", + "fingerprint": visualci_core::image_hash::fingerprint_bytes(&bytes).unwrap(), + }]})) + .await; + registered.assert_ok(); + if let Some(url) = registered.json()["snapshots"][0]["upload_url"].as_str() { + reqwest::Client::new().put(url).header("content-type", "image/png").body(bytes).send().await.unwrap(); + } + let done = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await; + assert_eq!(done.json()["state"], "completed", "{}", done.text()); + let pid: laravel::str::Uuid = id.parse().unwrap(); + Build::query().filter(Build::pid.eq(pid)).first().await.unwrap().unwrap() +} + +/// Make a build and its blobs older than the retention window, and nothing anyone needs: off the default branch, no +/// base, no baselines. +async fn age(build: &Build) -> laravel::Result<()> { + let (id, project_id) = (build.id, build.project_id); + db::query!( + "UPDATE builds SET created_at = now() - interval '200 days', completed_at = now() - interval '200 days', \ + base_build_id = NULL WHERE id = {id}" + ) + .update() + .await?; + db::query!( + "UPDATE blobs SET created_at = now() - interval '200 days', updated_at = now() - interval '200 days' \ + WHERE sha256 IN (SELECT source_blob FROM snapshots WHERE build_id = {id})" + ) + .update() + .await?; + db::query!("UPDATE snapshots SET updated_at = now() - interval '200 days' WHERE build_id = {id}").update().await?; + db::query!("DELETE FROM baselines WHERE project_id = {project_id}").delete().await?; + Ok(()) +} + +async fn blob_of(build: &Build) -> Option { + let snapshot = Snapshot::query().filter(Snapshot::build_id.eq(build.id)).first().await.unwrap().unwrap(); + let sha = snapshot.source_blob?; + Blob::query().filter(Blob::sha256.eq(sha)).first().await.unwrap() +} + +#[laravel::test] +async fn retention_keeps_the_builds_a_kept_build_reads_groups_from(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let holder = build(&app, &token, "old-holder", [255, 0, 0]).await; + let forgotten = build(&app, &token, "old-forgotten", [0, 0, 255]).await; + let reader = build(&app, &token, "recent", [0, 255, 0]).await; + age(&holder).await?; + age(&forgotten).await?; + // The recent build reads a group from the old one: the old build's rows are its unchanged snapshots. + let (reader_id, holder_id) = (reader.id, holder.id); + let key: String = + db::query!("SELECT group_key FROM snapshots WHERE build_id = {holder_id}").scalar().await?.unwrap(); + db::query!( + "INSERT INTO build_groups (build_id, key, hash, snapshot_count, source_build_id) \ + VALUES ({reader_id}, {key}, 'h', 1, {holder_id})" + ) + .insert() + .await?; + let read = |id: i64| async move { + db::query!("SELECT COUNT(*) FROM effective_snapshots WHERE build_id = {id} AND sourced").scalar::().await + }; + assert_eq!(read(reader_id).await?, Some(1), "the reader reads the holder's row"); + + let counted = retention::prune(None, retention::RETENTION_DAYS, true).await?; + assert!(blob_of(&forgotten).await.is_some(), "a dry run deletes nothing"); + assert!(counted.blobs >= 1, "{counted}"); + + retention::prune(None, retention::RETENTION_DAYS, false).await?; + assert!(blob_of(&holder).await.is_some(), "the source build's image stays"); + assert!(blob_of(&reader).await.is_some(), "the recent build's image stays"); + assert!(blob_of(&forgotten).await.is_none(), "an old build nothing reads loses its image"); + // The holder's rows stay, so the reader still reads its group, and no group resolves to no rows. + assert_eq!(read(reader_id).await?, Some(1), "the reader still reads the holder's row"); + assert!(retention::empty_groups().await?.is_empty()); + Ok(()) +} + +#[laravel::test] +async fn retention_deletes_only_unreferenced_texts_older_than_a_day(_app: Application) -> laravel::Result<()> { + let texts = ["referenced by a render", "old and unreferenced", "new and unreferenced"] + .map(|t| (visualci_core::sha256_hex(t.as_bytes()), t)); + for (i, (sha, body)) in texts.iter().enumerate() { + let body: &str = body; + let hours = if i == 2 { 1 } else { 48 }; + db::query!( + "INSERT INTO texts (sha256, body, created_at) VALUES ({sha}, {body}, now() - make_interval(hours => {hours}))" + ) + .insert() + .await?; + } + // A render from today names the first text on its page. + let pages = json!([{ "image": "", "fingerprint": "f", "width": 1, "height": 1, "text_sha": texts[0].0 }]); + let source = "a".repeat(64); + db::query!("INSERT INTO blobs (sha256, size, content_type) VALUES ({source}, 1, 'application/pdf')") + .insert() + .await?; + db::query!( + "INSERT INTO renders (source_fingerprint, renderer, source_blob, state, pages) \ + VALUES ('fp', 'pdfbox/140dpi/1', {source}, 'done', {pages})" + ) + .insert() + .await?; + + let report = retention::prune(None, retention::RETENTION_DAYS, false).await?; + let left: Vec = db::query!("SELECT body FROM texts ORDER BY body") + .select() + .await? + .iter() + .filter_map(|r| r.try_get::("body").ok()) + .collect(); + assert_eq!(left, ["new and unreferenced", "referenced by a render"]); + assert_eq!(report.texts, 1, "{report}"); + Ok(()) +} + +#[laravel::test] +async fn the_nightly_check_finds_groups_that_resolve_to_no_rows(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let holder = build(&app, &token, "holder", [1, 2, 3]).await; + let reader = build(&app, &token, "reader", [4, 5, 6]).await; + app.command("groups:check").await.assert_successful(); + + // A group the reader reads from the holder under a key the holder has no rows for. + let (reader_id, holder_id) = (reader.id, holder.id); + db::query!( + "INSERT INTO build_groups (build_id, key, hash, snapshot_count, source_build_id) \ + VALUES ({reader_id}, 'gone/', 'h', 1, {holder_id})" + ) + .insert() + .await?; + assert_eq!(retention::empty_groups().await?, vec![(reader_id, "gone/".to_string())]); + app.command("groups:check").await.assert_failed().assert_error_output_contains("1 groups resolve to no rows"); + assert_eq!(app.get("/status").await.json()["empty_groups"], 1, "and /status counts it"); + + // Retention's command: a dry run counts, and fewer than 30 days is refused. + app.command("retention:prune --dry-run").await.assert_successful().assert_output_contains("would delete"); + app.command("retention:prune --days 7").await.assert_failed(); + Ok(()) +} + +/// A build registering snapshots while a prune runs isn't in the prune's keep sets: what a snapshot touched in the last +/// day names stays, its file and its render alike. +#[laravel::test] +async fn retention_keeps_what_a_snapshot_registered_now_names(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let old = build(&app, &token, "old", [10, 20, 30]).await; + age(&old).await?; + // The same file, just registered again by a build the keep sets don't know about yet (here: the old build's own + // row, touched now). + let id = old.id; + db::query!("UPDATE snapshots SET updated_at = now() WHERE build_id = {id}").update().await?; + retention::prune(None, retention::RETENTION_DAYS, false).await?; + let snapshot = Snapshot::query().filter(Snapshot::build_id.eq(id)).first().await?.expect("the snapshot"); + assert!(snapshot.source_blob.is_some(), "its file is still named"); + assert!(blob_of(&old).await.is_some(), "and still there"); + Ok(()) +} + +/// A file a new build registers while a prune has it marked for deletion keeps its row, and the build is asked to +/// upload it again: the prune deletes only rows still marked, and never what a new snapshot names. +#[laravel::test] +async fn a_blob_registered_again_while_marked_is_uploaded_again_and_kept(app: Application) -> laravel::Result<()> { + Box::pin(registered_while_marked(app)).await +} + +async fn registered_while_marked(app: Application) -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + let token = project_token().await?; + let old = build(&app, &token, "old", [9, 9, 9]).await; + age(&old).await?; + let sha = visualci_core::sha256_hex(&png([9, 9, 9])); + // The prune's first step: marked for deletion. + db::query!("UPDATE blobs SET deleting = true WHERE sha256 = {sha}").update().await?; + + // A new build registers the same file: the mark goes, and the build is asked to upload it again. + let auth = format!("Bearer {token}"); + let created = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": "0123456789abcdef", "branch": "again", "parent_commits": [] })) + .await; + let id = created.json()["id"].as_str().unwrap().to_string(); + let bytes = png([9, 9, 9]); + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": [{ + "name": "web/home", "kind": "image", "sha256": sha, "size": bytes.len(), "content_type": "image/png", + "fingerprint": visualci_core::image_hash::fingerprint_bytes(&bytes).unwrap(), + }]})) + .await; + registered.assert_ok(); + assert!(registered.json()["snapshots"][0]["upload_url"].is_string(), "uploaded again: {}", registered.text()); + let blob = Blob::query().filter(Blob::sha256.eq(sha.clone())).first().await?.unwrap(); + assert!(!blob.deleting && blob.uploaded_at.is_none(), "the mark is gone, and the file is awaited"); + + // The prune leaves it: a new snapshot names it, and it's no longer marked. + retention::prune(Some(&store), retention::RETENTION_DAYS, false).await?; + assert!(Blob::query().filter(Blob::sha256.eq(sha.clone())).first().await?.is_some(), "the row stays"); + assert!(store.exists(&sha).await?, "and the object"); + Ok(()) +} + +/// A prune works through more than one batch, each in its own transaction. +#[laravel::test] +async fn a_prune_deletes_in_batches(_app: Application) -> laravel::Result<()> { + let n = i64::try_from(retention::BATCH).unwrap() + 5; + db::query!( + "INSERT INTO blobs (sha256, size, content_type, created_at, updated_at) \ + SELECT encode(sha256(i::text::bytea), 'hex'), 1, 'image/png', now() - interval '200 days', \ + now() - interval '200 days' \ + FROM generate_series(1, {n}) i" + ) + .insert() + .await?; + let counted = retention::prune(None, retention::RETENTION_DAYS, true).await?; + assert_eq!(counted.blobs, u64::try_from(n).unwrap(), "{counted}"); + let report = retention::prune(None, retention::RETENTION_DAYS, false).await?; + assert_eq!(report.blobs, u64::try_from(n).unwrap(), "{report}"); + let left: Option = db::query!("SELECT COUNT(*) FROM blobs").scalar().await?; + assert_eq!(left, Some(0)); + Ok(()) +} + +/// An old blob, unnamed by any kept build: `n` picks its hash. +async fn old_blob(n: u32) -> laravel::Result { + let sha = visualci_core::sha256_hex(format!("old blob {n}").as_bytes()); + db::query!( + "INSERT INTO blobs (sha256, size, content_type, created_at, updated_at) \ + VALUES ({sha}, 1, 'image/png', now() - interval '200 days', now() - interval '200 days')" + ) + .insert() + .await?; + Ok(sha) +} + +/// A cached diff a comparison reused in the last day keeps its overlay (the build reusing it isn't in the keep sets); +/// one nobody reused loses it. +#[laravel::test] +async fn a_recently_reused_diff_keeps_its_overlay(_app: Application) -> laravel::Result<()> { + let (used, unused) = (old_blob(1).await?, old_blob(2).await?); + for (n, overlay, used_at) in [(1, &used, "now()"), (2, &unused, "NULL")] { + let (base, head) = (format!("base{n}"), format!("head{n}")); + let recent = used_at == "now()"; + db::query!( + "INSERT INTO diffs (base_image, head_image, options_key, changed_pixels, changed_fraction, size_changed, \ + result, overlay_blob, used_at) \ + VALUES ({base}, {head}, 'k', 1, 0.1, false, '{{}}', {overlay}, CASE WHEN {recent} THEN now() END)" + ) + .insert() + .await?; + } + retention::prune(None, retention::RETENTION_DAYS, false).await?; + let overlays: Vec> = db::query!("SELECT overlay_blob FROM diffs ORDER BY base_image") + .select() + .await? + .iter() + .map(|r| r.try_get::>("overlay_blob").unwrap()) + .collect(); + assert_eq!(overlays, [Some(used.clone()), None]); + assert!(Blob::query().filter(Blob::sha256.eq(used)).first().await?.is_some(), "the reused overlay stays"); + assert!(Blob::query().filter(Blob::sha256.eq(unused)).first().await?.is_none(), "the other goes"); + Ok(()) +} + +/// No mark outlives its run: a mark a stopped run left behind is cleared, and so is one on a blob that turns out to be +/// kept; a blob registered in the last day isn't marked at all. +#[laravel::test] +async fn no_deleting_mark_outlives_its_prune(app: Application) -> laravel::Result<()> { + Box::pin(no_mark_outlives(app)).await +} + +async fn no_mark_outlives(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + // A kept build's blob, marked by a run that stopped. + let kept = build(&app, &token, "kept", [7, 7, 7]).await; + let kept_sha = blob_of(&kept).await.unwrap().sha256; + db::query!("UPDATE blobs SET deleting = true WHERE sha256 = {kept_sha}").update().await?; + // An old blob a client registered just now (the snapshot naming it not yet committed). + let registered = old_blob(3).await?; + app::domain::blobs::register(®istered, 1, "image/png").await?; + + retention::prune(None, retention::RETENTION_DAYS, false).await?; + let marked: Option = db::query!("SELECT COUNT(*) FROM blobs WHERE deleting").scalar().await?; + assert_eq!(marked, Some(0), "no mark left"); + assert!(blob_of(&kept).await.is_some_and(|b| b.uploaded_at.is_some()), "the kept blob is still uploaded"); + assert!(Blob::query().filter(Blob::sha256.eq(registered)).first().await?.is_some(), "registered just now: kept"); + Ok(()) +}