Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
5c53c12
app/: renderer API: claim with per-project fairness, page uploads, co…
ndbroadbent Dec 2, 2026
2d4c614
app/: bulk downloads: the archive job, POST /api/v1/builds/{id or num…
ndbroadbent Dec 2, 2026
aa2c45f
app/: public gallery: the manifest and image routes, purges queued fr…
ndbroadbent Dec 2, 2026
0b258e5
app/: format the gallery's test and the routing
ndbroadbent Dec 2, 2026
84dcd62
app/: retention (keeps the builds kept builds read groups from, delet…
ndbroadbent Dec 2, 2026
76bff15
app/: retention's commands join the console schedule and its heartbea…
ndbroadbent Dec 2, 2026
42b3693
app/: Cargo.lock gains the bundle feature's tar and zstd; the gallery…
ndbroadbent Dec 2, 2026
97d0654
app/: retention leaves alone what a snapshot touched in the last day …
ndbroadbent Dec 2, 2026
8f640d2
app/: renderer review fixes for #81: completion checks pages (at most…
ndbroadbent Dec 2, 2026
8f5a8b1
app/: retention prunes in batches of 1,000, a transaction each; a blo…
ndbroadbent Dec 2, 2026
bf163a3
app/: downloads review fixes for #81: at most 3 pending or building p…
ndbroadbent Dec 2, 2026
983f9bd
app/: gallery review fixes for #81: cf-connecting-ip believed only fr…
ndbroadbent Dec 2, 2026
1523f63
app/: the host tests' production environment sets the renderer's toke…
ndbroadbent Dec 2, 2026
055c214
app/: retention follow-ups for #81: a cached diff reused in the last …
ndbroadbent Dec 2, 2026
0b63cb5
app/: a render's proof upload URL signs the declared size (Content-Le…
ndbroadbent Dec 2, 2026
3a59130
app/: download archives give every snapshot and page directory one of…
ndbroadbent Dec 2, 2026
7176a82
app/: retention leaves a blob that a render reused in the last day na…
ndbroadbent Dec 2, 2026
d7607f5
app/: the renderer metrics report visualci_gallery_purges_failed_7d, …
ndbroadbent Dec 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions app/Cargo.lock

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

3 changes: 2 additions & 1 deletion app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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]
Expand Down
Original file line number Diff line number Diff line change
@@ -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);
";
14 changes: 14 additions & 0 deletions app/database/migrations/2026_12_03_000400_diffs_used_at.rs
Original file line number Diff line number Diff line change
@@ -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;
";
67 changes: 67 additions & 0 deletions app/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ipnet::IpNet> {
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<String> {
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()
}
6 changes: 5 additions & 1 deletion app/src/console/mod.rs
Original file line number Diff line number Diff line change
@@ -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`).
Expand Down
76 changes: 76 additions & 0 deletions app/src/console/retention.rs
Original file line number Diff line number Diff line change
@@ -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<String> =
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(())
}
}
11 changes: 8 additions & 3 deletions app/src/domain/blobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Blob> {
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?;
Expand All @@ -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).
Expand Down
Loading
Loading