diff --git a/app/src/config.rs b/app/src/config.rs index 91af7d8d..16ee0e7c 100644 --- a/app/src/config.rs +++ b/app/src/config.rs @@ -88,3 +88,20 @@ pub fn trusted_proxies() -> Vec { .filter(|p| !p.is_empty()) .collect() } + +/// The database: `Database::from_env` (`DATABASE_URL`, `DB_MAX_CONNECTIONS`, default 10 per process), with a short wait +/// for a pooled connection (`DB_ACQUIRE_TIMEOUT`, seconds, default 5). A burst of CI builds that takes every +/// connection then answers 503 with Retry-After at once (`http::busy`), rather than holding each request for the +/// framework's default 30 seconds while the queue grows (today's server hung on 3 Dec 2026, 16:02-16:07 UTC). +#[laravel::config::section] +fn database(env: &laravel::config::Env) -> laravel::config::database::Database { + let mut database = laravel::config::database::Database::from_env(env); + let seconds: u64 = env.get("DB_ACQUIRE_TIMEOUT").unwrap_or(5); + let default = database.default.clone(); + if let Some(connection) = database.connections.remove(&default) { + let seconds = i64::try_from(seconds).unwrap_or(5); + let connection = connection.acquire_timeout(laravel::time::SignedDuration::from_secs(seconds)); + database.connections.insert(default, connection); + } + database +} diff --git a/app/src/console/mod.rs b/app/src/console/mod.rs index 947d50e8..aceb8069 100644 --- a/app/src/console/mod.rs +++ b/app/src/console/mod.rs @@ -17,7 +17,7 @@ fn schedule(schedule: &mut Schedule) { schedule.command("demo:reset").name("demo-reset").daily_at("05:00").without_overlapping().on_one_runner(); } -/// [`crate::domain::processing::sweep`], with its heartbeat (`VISUALCI_BUILDS_SWEEP_HEARTBEAT_URL` and `_TOKEN`). +/// [`crate::domain::processing::sweep`], with its heartbeat (`VISUALCI_BUILDS_EXPIRE_HEARTBEAT_URL` and `_TOKEN`). /// `/status` reports `oldest_processing_seconds` and `oldest_receiving_seconds`, which stay low while it runs. async fn sweep_builds() -> laravel::Result<()> { let outcome = crate::domain::processing::sweep().await; @@ -25,6 +25,7 @@ async fn sweep_builds() -> laravel::Result<()> { Ok(swept) => tracing::info!(?swept, "builds swept"), Err(e) => tracing::error!(error = %e, "sweeping builds failed"), } - heartbeat::push("VISUALCI_BUILDS_SWEEP_HEARTBEAT", outcome.as_ref().map(|_| ()).map_err(ToString::to_string)).await; + heartbeat::push("VISUALCI_BUILDS_EXPIRE_HEARTBEAT", outcome.as_ref().map(|_| ()).map_err(ToString::to_string)) + .await; outcome.map(|_| ()) } diff --git a/app/src/http/api/mod.rs b/app/src/http/api/mod.rs index d127accf..7d0c1efb 100644 --- a/app/src/http/api/mod.rs +++ b/app/src/http/api/mod.rs @@ -75,6 +75,13 @@ impl ApiError { #[must_use] pub fn server(e: &laravel::Error) -> Self { + if super::busy(e) { + tracing::warn!("API request: every database connection is busy"); + return Self { + status: StatusCode::SERVICE_UNAVAILABLE, + body: json!({ "error": "busy", "description": "VisualCI is busy right now: retry in a few seconds." }), + }; + } tracing::error!(error = %e, "API request failed"); Self { status: StatusCode::INTERNAL_SERVER_ERROR, @@ -101,7 +108,11 @@ impl From> for ApiError { impl axum::response::IntoResponse for ApiError { fn into_response(self) -> axum::response::Response { - axum::response::IntoResponse::into_response((self.status, axum::Json(self.body))) + let mut response = axum::response::IntoResponse::into_response((self.status, axum::Json(self.body))); + if self.status == StatusCode::SERVICE_UNAVAILABLE { + response.headers_mut().insert(axum::http::header::RETRY_AFTER, super::RETRY_AFTER_SECONDS.into()); + } + response } } diff --git a/app/src/http/mod.rs b/app/src/http/mod.rs index ca4bdcfc..02b9ee67 100644 --- a/app/src/http/mod.rs +++ b/app/src/http/mod.rs @@ -5,3 +5,13 @@ pub mod gallery; pub mod hosts; pub mod renderer; pub mod status; + +/// Whether a request failed because every pooled database connection was in use for `DB_ACQUIRE_TIMEOUT`: the +/// answer is a 503 with Retry-After, so clients (the CLI retries) back off instead of piling on. +#[must_use] +pub fn busy(e: &laravel::Error) -> bool { + matches!(e.downcast_ref::(), Some(laravel::db::sqlx::Error::PoolTimedOut)) +} + +/// How long a client should wait before retrying a 503, in seconds. +pub const RETRY_AFTER_SECONDS: u32 = 5; diff --git a/app/src/http/status.rs b/app/src/http/status.rs index ecd82964..81d8bb5f 100644 --- a/app/src/http/status.rs +++ b/app/src/http/status.rs @@ -12,7 +12,25 @@ pub const COMMIT: &str = match option_env!("BUILD_SHA") { None => "dev", }; -pub async fn status() -> laravel::Result> { +pub async fn status() -> axum::response::Response { + use axum::response::IntoResponse; + match numbers().await { + Ok(body) => body.into_response(), + // Every connection busy, or the database down: a fast 503 that Gatus alerts on, never a hang. + Err(e) => { + tracing::error!(error = %e, "status: the database didn't answer"); + let mut response = ( + axum::http::StatusCode::SERVICE_UNAVAILABLE, + Json(json!({ "ok": false, "commit": COMMIT, "database": if super::busy(&e) { "busy" } else { "error" } })), + ) + .into_response(); + response.headers_mut().insert(axum::http::header::RETRY_AFTER, super::RETRY_AFTER_SECONDS.into()); + response + } + } +} + +async fn numbers() -> laravel::Result> { let row = db::query!( "SELECT \ (SELECT COUNT(*) FROM renders WHERE state = 'queued')::BIGINT AS renders_queued, \ @@ -30,7 +48,9 @@ pub async fn status() -> laravel::Result> { 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" + AS gallery_purges_failed, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(synced_at)) FROM memberships \ + WHERE source = 'github' AND synced_at IS NOT NULL), 0)::BIGINT AS oldest_forge_sync_seconds" ) .select_one() .await? @@ -52,5 +72,8 @@ pub async fn status() -> laravel::Result> { "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")?, + // The longest any GitHub-derived membership has gone unchecked: subdomains' hourly forge sync keeps it under an + // hour. With the scheduler down, this, the receiving and processing ages are what still alert. + "oldest_forge_sync_seconds": get("oldest_forge_sync_seconds")?, }))) } diff --git a/app/tests/load.rs b/app/tests/load.rs new file mode 100644 index 00000000..e5e42de3 --- /dev/null +++ b/app/tests/load.rs @@ -0,0 +1,111 @@ +//! Load: the builds of a burst like the one before today's server hung (3 Dec 2026, about 20 builds of 331 snapshots +//! each in 30 minutes). Every build is unchanged, so the storage design writes no page rows for them, and all of them +//! finish within a bound on CI's Postgres. A pool that runs out answers 503 with Retry-After, never a hang. + +use std::time::{Duration, Instant}; + +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +const BUILDS: usize = 20; +const SNAPSHOTS: usize = 331; +/// The bound for the whole burst. Measured on docspring-dev and CI in a few seconds; the bound leaves room for a slow +/// runner while still catching a regression to per-snapshot work that grows with every build. +const WITHIN: Duration = Duration::from_secs(120); + +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) +} + +fn snapshots() -> Vec { + (0..SNAPSHOTS) + .map(|i| { + let text = format!("snapshot {i}\nline two\n"); + let sha = visualci_core::sha256_hex(text.as_bytes()); + json!({ + "name": format!("suite/{:03}", i), "kind": "text", "fingerprint": sha, "sha256": sha, + "size": text.len(), "content_type": "text/plain", + }) + }) + .collect() +} + +/// One CI build of every snapshot, sent the way the CLI sends it: create, register in one request, finalize. +async fn build(app: &Application, token: &str, commit: &str, parent: &str) -> Value { + let auth = format!("Bearer {token}"); + let created = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": commit, "branch": "main", "parent_commits": [parent] })) + .await; + created.assert_ok(); + let id = created.json()["id"].as_str().unwrap().to_string(); + app.post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": snapshots() })) + .await + .assert_ok(); + let done = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await; + done.assert_ok(); + done.json().clone() +} + +#[laravel::test] +async fn twenty_unchanged_builds_of_331_snapshots_finish_without_page_rows(app: Application) -> laravel::Result<()> { + Box::pin(burst(app)).await +} + +async fn burst(app: Application) -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + for i in 0..SNAPSHOTS { + let text = format!("snapshot {i}\nline two\n"); + app::domain::blobs::put(&store, text.into_bytes(), "text/plain").await?; + } + let token = project_token().await?; + let sha = |n: usize| format!("{n:040x}"); + let first = build(&app, &token, &sha(1000), &sha(999)).await; + assert_eq!(first["state"], "completed", "{first}"); + let pages_before: i64 = db::query!("SELECT COUNT(*) FROM snapshot_pages").scalar().await?.unwrap_or_default(); + + // One after another: a refreshed test database has one connection, so requests can't overlap here. The bound + // catches per-build work that grows (per-snapshot rows for unchanged groups); a pool that runs out is the 503 test + // below, and the concurrent burst is a benchmark against a dev server (see the PR). + let started = Instant::now(); + let mut done = Vec::with_capacity(BUILDS); + for n in 1..=BUILDS { + done.push(build(&app, &token, &sha(n), &sha(1000)).await); + } + let took = started.elapsed(); + + for b in &done { + assert_eq!(b["state"], "completed", "{b}"); + assert_eq!(b["conclusion"], "unchanged", "{b}"); + } + let pages_after: i64 = db::query!("SELECT COUNT(*) FROM snapshot_pages").scalar().await?.unwrap_or_default(); + assert_eq!(pages_after, pages_before, "unchanged builds store no page rows"); + println!("{BUILDS} builds of {SNAPSHOTS} unchanged snapshots in {took:?}"); + assert!(took < WITHIN, "{BUILDS} builds took {took:?}, over {WITHIN:?}"); + Ok(()) +} + +#[test] +fn a_pool_that_runs_out_answers_busy() { + let timed_out = laravel::Error::from(laravel::db::sqlx::Error::PoolTimedOut); + assert!(app::http::busy(&timed_out)); + assert!(!app::http::busy(&laravel::Error::msg("something else"))); + let response = axum::response::IntoResponse::into_response(app::http::api::ApiError::server(&timed_out)); + assert_eq!(response.status(), axum::http::StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(response.headers()[axum::http::header::RETRY_AFTER], "5"); +} diff --git a/app/tests/sweep.rs b/app/tests/sweep.rs index 5d568341..4c6b945b 100644 --- a/app/tests/sweep.rs +++ b/app/tests/sweep.rs @@ -55,6 +55,7 @@ async fn the_sweep_expires_closes_restarts_and_gives_up(app: Application) -> lar assert!(status["oldest_processing_seconds"].as_i64().unwrap() >= 7 * 3600, "{status}"); assert!(status["oldest_receiving_seconds"].as_i64().unwrap() >= 2 * 3600, "{status}"); assert_eq!(status["builds_processing"], 2); + assert_eq!(status["oldest_forge_sync_seconds"], 0, "no forge memberships: {status}"); let swept = processing::sweep().await?; assert_eq!(swept.expired, 1);