diff --git a/Cargo.lock b/Cargo.lock index d7e8d5f0..c134c0d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5023,7 +5023,7 @@ dependencies = [ [[package]] name = "visualci-cli" -version = "0.2.22" +version = "0.2.23" dependencies = [ "anyhow", "base64 0.22.1", @@ -5040,7 +5040,7 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.22" +version = "0.2.23" dependencies = [ "globset", "hex", @@ -5060,7 +5060,7 @@ dependencies = [ [[package]] name = "visualci-renderer" -version = "0.2.22" +version = "0.2.23" dependencies = [ "anyhow", "image", @@ -5075,7 +5075,7 @@ dependencies = [ [[package]] name = "visualci-wasm" -version = "0.2.22" +version = "0.2.23" dependencies = [ "image", "serde", diff --git a/Cargo.toml b/Cargo.toml index a6edf347..697051eb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ resolver = "3" members = ["crates/*", "app"] [workspace.package] -version = "0.2.22" +version = "0.2.23" edition = "2024" license = "Apache-2.0" repository = "https://github.com/DocSpring/visualci" diff --git a/app/.env.example b/app/.env.example index 7cde582c..f70ca7c8 100644 --- a/app/.env.example +++ b/app/.env.example @@ -174,6 +174,23 @@ VISUALCI_STRIPE_WEBHOOK_SECRET= # The most gallery credits one project is charged in a day: images past it are served free. # VISUALCI_GALLERY_DAILY_CREDITS=50000 +###################################################################################################################### +# Live updates +###################################################################################################################### + +# The most streams one web process keeps open at once. +# VISUALCI_LIVE_MAX_STREAMS=2000 + +# The most streams one person, project token or visitor's address keeps open in one web process. +# VISUALCI_LIVE_MAX_STREAMS_PER_PRINCIPAL=30 + +# The most streams following one build in one web process. +# VISUALCI_LIVE_MAX_STREAMS_PER_BUILD=100 + +# How long one stream lasts, in seconds. It then ends, and the browser or the CLI connects again, so access is checked +# again. +# VISUALCI_LIVE_STREAM_SECONDS=1800 + ###################################################################################################################### # Heartbeats ###################################################################################################################### diff --git a/app/src/config.rs b/app/src/config.rs index d68bc35b..17693c0f 100644 --- a/app/src/config.rs +++ b/app/src/config.rs @@ -45,6 +45,8 @@ pub struct Config { #[settings(nested)] pub gallery: Gallery, #[settings(nested)] + pub live: Live, + #[settings(nested)] pub heartbeats: Heartbeats, } @@ -252,6 +254,27 @@ pub struct Gallery { pub daily_credits: i64, } +/// The server-sent event streams the build and project pages and the CLI's `--wait` follow. The limits are each web +/// process's own: a stream past one is refused with a 429, and the page or the CLI reads on its own instead. A stream +/// holds no database connection while it waits. +#[derive(Clone, Settings)] +#[settings(title = "Live updates")] +pub struct Live { + /// The most streams one web process keeps open at once. + #[env("VISUALCI_LIVE_MAX_STREAMS", default = 2000)] + pub max_streams: usize, + /// The most streams one person, project token or visitor's address keeps open in one web process. + #[env("VISUALCI_LIVE_MAX_STREAMS_PER_PRINCIPAL", default = 30)] + pub max_streams_per_principal: usize, + /// The most streams following one build in one web process. + #[env("VISUALCI_LIVE_MAX_STREAMS_PER_BUILD", default = 100)] + pub max_streams_per_build: usize, + /// How long one stream lasts, in seconds. It then ends, and the browser or the CLI connects again, so access is + /// checked again. + #[env("VISUALCI_LIVE_STREAM_SECONDS", default = 1800)] + pub stream_seconds: u64, +} + /// Each scheduled job pushes its result to a [Gatus](https://gatus.io) external endpoint, so a run that failed, or no /// run at all, alerts. Each pair is the endpoint's URL and its token; a job without a URL pushes nothing. #[derive(Clone, Settings)] @@ -461,6 +484,7 @@ pub fn install(config: &mut laravel::config::Config, env: &laravel::config::Env) .set(settings.stripe.clone()) .set(settings.cloudflare.clone()) .set(settings.gallery.clone()) + .set(settings.live.clone()) .set(settings.heartbeats.clone()) .set(settings); } diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index d6666023..8fb837e5 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -212,7 +212,11 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la } match result { Ok(true) => finished(id, build.project_id).await?, - Ok(false) => tracing::debug!(build_id = id, "build waiting for renders"), + Ok(false) => { + tracing::debug!(build_id = id, "build waiting for renders"); + // Some of its snapshots may have been compared: its page shows the progress + crate::live::tell(build.project_id, Some(id)).await; + } Err(e) if e.is::() => { tracing::info!(build_id = id, "another run is processing the build; it runs it again when it's done"); } diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index e7599ea8..820b382c 100644 --- a/app/src/http/api/builds.rs +++ b/app/src/http/api/builds.rs @@ -143,6 +143,7 @@ pub async fn create(auth: Result, Body(params): Body/mcp` with the `mcp` scope). A project token follows +//! only its own project's builds. A public project's pages can be followed by anyone, as they can be read; on the API, +//! a public project's builds by any person (as MCP's `get_build`), never by another project's token. Anything else is +//! a 404. +//! +//! Limits ([`crate::config::Live`], per web process): open streams per principal (or visitor's address), per build, +//! and in all. One past a limit is refused with a 429 and `Retry-After`, before the stream starts; the pages then poll +//! and the CLI polls. A stream holds no database connection while it waits: it reads only when it sends (the CLI's +//! events), at most [`READS`] at once, each on a pooled connection it gives back. It ends when the client goes away (the +//! response body is dropped, and its slot with it), after `VISUALCI_LIVE_STREAM_SECONDS` (the client reconnects, and +//! access is checked again), or at shutdown. A comment every [`KEEP_ALIVE`] keeps idle proxies from closing it. +//! +//! Proxies: the responses say `Cache-Control: no-cache, no-transform` (Cloudflare and Envoy don't compress or hold +//! them) and `X-Accel-Buffering: no`. The paths share the `/api/ui/live` and `/api/v1/live` prefixes, so a proxy can +//! give them a route without a response timeout. + +use std::collections::HashMap; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::Duration; + +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use laravel::context::Context; +use laravel::db; +use laravel::http::sse::{Event, EventStream}; +use laravel::http::{IntoResponse, Request, Response}; +use laravel::prelude::*; +use laravel::str::Uuid; +use laravel::stream::{Stream, stream}; +use serde_json::json; +use tokio::sync::broadcast::{self, error::RecvError, error::TryRecvError}; +use tokio::time::Instant; + +use crate::auth::Principal; +use crate::config::Live; +use crate::live::{EVERYTHING, build_topic, project_topic}; +use crate::models::{Build, Organization, Project}; + +/// How long a burst of changes is gathered into one event. +pub const COALESCE: Duration = Duration::from_millis(300); +/// How often a quiet stream sends a comment (seconds), so idle proxies don't close it. +pub const KEEP_ALIVE: i64 = 15; +/// The most streams reading the database at once in one process: a burst that reaches every stream (the listener +/// reconnected) reads a few at a time instead of taking the web pool's connections. +pub const READS: usize = 4; +/// How long a client refused for a limit waits before it tries again. +pub const RETRY_AFTER_SECONDS: u32 = 30; + +static READING: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(READS); + +/// The web app's streams, on the app host behind the session. +pub fn ui_routes(route: &mut Router) { + route.get("/api/ui/live/orgs/{org}/projects/{project}", project_page); + route.get("/api/ui/live/orgs/{org}/projects/{project}/builds/{number}", build_page); +} + +/// The CLI's stream, under the API group (`/api`). +pub fn api_routes(route: &mut Router) { + route.get("/v1/live/builds/{pid}", build_for_cli); +} + +fn limits() -> Live { + laravel::config().section::().clone() +} + +fn lifetime(limits: &Live) -> Duration { + Duration::from_secs(limits.stream_seconds.max(1)) +} + +/// `GET /api/ui/live/orgs/{org}/projects/{project}` +pub async fn project_page( + principal: Result, + Params((org, project)): Params<(String, String)>, + request: Request, +) -> laravel::Result { + let Some(project) = page_project(principal.as_ref().ok(), &org, &project).await? else { return Ok(ui_not_found()) }; + let limits = limits(); + let slot = match STREAMS.take(&limits, &who(principal.as_ref().ok(), &request), None) { + Ok(slot) => slot, + Err(refused) => return Ok(too_many(&refused, ui_error)), + }; + let rx = subscribe()?; + Ok(sse(page_stream(rx, vec![project_topic(project.id)], COALESCE, lifetime(&limits), slot))) +} + +/// `GET /api/ui/live/orgs/{org}/projects/{project}/builds/{number}` +pub async fn build_page( + principal: Result, + Params((org, project, number)): Params<(String, String, i32)>, + request: Request, +) -> laravel::Result { + let Some(project) = page_project(principal.as_ref().ok(), &org, &project).await? else { return Ok(ui_not_found()) }; + let project_id = project.id; + let build: Option = + db::query!("SELECT id FROM builds WHERE project_id = {project_id} AND number = {number}").scalar().await?; + let Some(build) = build else { return Ok(ui_not_found()) }; + let limits = limits(); + let slot = match STREAMS.take(&limits, &who(principal.as_ref().ok(), &request), Some(build)) { + Ok(slot) => slot, + Err(refused) => return Ok(too_many(&refused, ui_error)), + }; + let rx = subscribe()?; + Ok(sse(page_stream(rx, vec![build_topic(build)], COALESCE, lifetime(&limits), slot))) +} + +/// `GET /api/v1/live/builds/{id}`: the build as `GET /api/v1/builds/{id}` answers it, now (`snapshot`) and after +/// each change (`build`). +pub async fn build_for_cli( + principal: Result, + headers: HeaderMap, + Params(pid): Params, +) -> laravel::Result { + use crate::http::api::ApiError; + let api = |e: ApiError| Response::new(axum::response::IntoResponse::into_response(e)); + let principal = match principal { + Ok(principal) => principal, + // An MCP client's OAuth token, for its own resource + Err(_) => match crate::mcp::oauth_principal(bearer(&headers)).await { + Some(Ok(principal)) => principal, + Some(Err(_)) => return Ok(api(ApiError::unauthorized("invalid OAuth access token"))), + None if bearer(&headers).is_some() => return Ok(api(ApiError::unauthorized("invalid token"))), + None => return Ok(api(ApiError::unauthorized("missing token"))), + }, + }; + let Some(build) = Build::query().filter(Build::pid.eq(pid)).first().await? else { + return Ok(api(ApiError::not_found())); + }; + let Some(project) = Project::find(build.project_id).await? else { return Ok(api(ApiError::not_found())) }; + if !cli_may_read(&principal, &project).await? { + return Ok(api(ApiError::not_found())); + } + let Some(organization) = Organization::find(project.organization_id).await? else { + return Ok(api(ApiError::not_found())); + }; + let limits = limits(); + let slot = match STREAMS.take(&limits, &principal_key(&principal), Some(build.id)) { + Ok(slot) => slot, + Err(refused) => return Ok(too_many(&refused, |m| api(ApiError::too_many_requests(m)))), + }; + let rx = subscribe()?; + let context = Context::current().ok_or_else(|| laravel::Error::msg("no application context"))?; + Ok(sse(cli_stream(rx, build.id, project, organization, context, lifetime(&limits), slot))) +} + +/// A page's project, when the person may read it: a member's, or a public one for anyone (as the pages themselves). +async fn page_project(principal: Option<&Principal>, org: &str, slug: &str) -> laravel::Result> { + let Some(project) = crate::http::api::project_by_slugs(org, slug).await? else { return Ok(None) }; + if project.public { + return Ok(Some(project)); + } + match principal { + Some(p) if p.role_in(&project).await?.is_some() => Ok(Some(project)), + _ => Ok(None), + } +} + +/// Whether a CLI's principal may follow a build of `project`: its own project's token, a member, or any person for a +/// public project. +async fn cli_may_read(principal: &Principal, project: &Project) -> laravel::Result { + if principal.role_in(project).await?.is_some() { + return Ok(true); + } + Ok(project.public && principal.user().is_some()) +} + +fn bearer(headers: &HeaderMap) -> Option { + oauth_provider::bearer(headers.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok())).map(str::to_string) +} + +/// Who a stream counts against: the person, the project token, or for a visitor the address they come from. +fn who(principal: Option<&Principal>, request: &Request) -> String { + principal.map_or_else(|| format!("guest:{}", request.ip()), principal_key) +} + +fn principal_key(principal: &Principal) -> String { + match principal { + Principal::User { user, .. } => format!("user:{}", user.id), + Principal::Project { token_id, .. } => format!("project-token:{token_id}"), + } +} + +fn ui_not_found() -> Response { + ui_error_status(StatusCode::NOT_FOUND, "not_found", "Resource was not found") +} + +fn ui_error(message: String) -> Response { + ui_error_status(StatusCode::TOO_MANY_REQUESTS, "too_many_requests", &message) +} + +fn ui_error_status(status: StatusCode, kind: &str, description: &str) -> Response { + Response::new(axum::response::IntoResponse::into_response(( + status, + axum::Json(json!({ "error": kind, "description": description })), + ))) +} + +/// A 429 with `Retry-After`, in the endpoint's error format. +fn too_many(refused: &Refused, respond: impl FnOnce(String) -> Response) -> Response { + tracing::info!(limit = refused.limit, "live updates: a stream refused at its limit"); + let mut response = respond(refused.message()); + response.headers_mut().insert(header::RETRY_AFTER, HeaderValue::from(RETRY_AFTER_SECONDS)); + response +} + +/// This process's listener, started by the first stream. +fn subscribe() -> laravel::Result> { + let url = crate::live::database_url(&laravel::config()) + .ok_or_else(|| laravel::abort_with(503, "live updates aren't set up"))?; + Ok(crate::live::subscribe(&url)) +} + +/// The stream as a response: no caching or transforming by proxies (Cloudflare and Envoy compress nothing marked +/// `no-transform`), no buffering (`X-Accel-Buffering: no`, which the framework sets), a comment every [`KEEP_ALIVE`] s, +/// and no end event, so the client reconnects when it ends. +fn sse + 'static>(events: impl Stream + Send + 'static) -> Response { + use laravel::time::ToSpan; + let stream = EventStream::new(events).without_end_event().keep_alive(KEEP_ALIVE.seconds()); + let mut response = stream.into_response(); + response.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache, no-transform")); + response +} + +/// Wait for the next burst of `topics` on `rx` (or of [`EVERYTHING`], or a stretch `rx` missed), and gather the rest +/// of it for `coalesce`. `false` once `until` has passed or the listener is gone. +pub async fn next_burst( + rx: &mut broadcast::Receiver, + topics: &[String], + coalesce: Duration, + until: Instant, +) -> bool { + loop { + let relevant = match tokio::time::timeout_at(until, rx.recv()).await { + Err(_) | Ok(Err(RecvError::Closed)) => return false, + Ok(Err(RecvError::Lagged(_))) => true, + Ok(Ok(topic)) => topic == EVERYTHING || topics.contains(&topic), + }; + if relevant { + break; + } + } + // Gather the rest of the burst: whatever else arrives meanwhile is covered by this one event + tokio::time::sleep(coalesce).await; + while let Ok(_) | Err(TryRecvError::Lagged(_)) = rx.try_recv() {} + true +} + +/// A page's stream: `snapshot` at once, then `changed` for each burst, until `lifetime` has passed. It carries no data +/// of its own: the page reads its data again, and each read checks access as usual. +pub fn page_stream( + mut rx: broadcast::Receiver, + topics: Vec, + coalesce: Duration, + lifetime: Duration, + slot: Slot, +) -> impl Stream + Send + 'static { + stream! { + let _slot = slot; + let until = Instant::now() + lifetime; + yield Event::new("snapshot", "{}"); + while next_burst(&mut rx, &topics, coalesce, until).await { + yield Event::new("changed", "{}"); + } + } +} + +/// The CLI's stream: the build now (`snapshot`), then after each burst (`build`), until `lifetime` has passed. Ends +/// early when the build is gone or can't be read. +fn cli_stream( + mut rx: broadcast::Receiver, + build_id: i64, + project: Project, + organization: Organization, + context: Context, + lifetime: Duration, + slot: Slot, +) -> impl Stream + Send + 'static { + stream! { + let _slot = slot; + let until = Instant::now() + lifetime; + let topics = vec![build_topic(build_id)]; + let mut name = "snapshot"; + loop { + let read = context.clone().scope(build_json(build_id, &project, &organization)); + match read.await { + Ok(Some(json)) => yield Event::new(name, json), + Ok(None) => break, + Err(e) => { + tracing::warn!(error = %e, build_id, "live updates: couldn't read a build for its stream"); + break; + } + } + name = "build"; + if !next_burst(&mut rx, &topics, COALESCE, until).await { + break; + } + } + } +} + +/// The build as the CI API answers it, as JSON; `None` once it's gone. +async fn build_json(build_id: i64, project: &Project, organization: &Organization) -> laravel::Result> { + let _permit = READING.acquire().await.map_err(|e| laravel::Error::msg(e.to_string()))?; + let Some(build) = Build::find(build_id).await? else { return Ok(None) }; + let response = crate::http::api::builds::BuildResponse::new(&build, project, organization) + .with_blocked(&build, project, organization) + .await?; + Ok(Some(serde_json::to_string(&response).map_err(|e| laravel::Error::msg(e.to_string()))?)) +} + +/// Open streams in one process, for the limits. +#[derive(Clone, Default)] +pub struct Streams(Arc>); + +#[derive(Default)] +struct Open { + total: usize, + principals: HashMap, + builds: HashMap, +} + +/// This process's streams. +pub static STREAMS: LazyLock = LazyLock::new(Streams::default); + +/// Which limit refused a stream. +#[derive(Debug, PartialEq, Eq)] +pub struct Refused { + pub limit: &'static str, + pub max: usize, +} + +impl Refused { + fn message(&self) -> String { + let what = match self.limit { + "principal" => "you already have", + "build" => "this build already has", + _ => "the server already has", + }; + format!("{what} {} live streams open: try again later, or poll", self.max) + } +} + +/// One open stream's place in [`Streams`], given back when it's dropped (the stream ended or the client went away). +pub struct Slot { + streams: Streams, + principal: String, + build: Option, +} + +impl Streams { + /// A slot for a stream of `principal`'s (following `build`, if it's a build's), unless a limit is reached. + /// + /// # Errors + /// The limit that refused it. + pub fn take(&self, limits: &Live, principal: &str, build: Option) -> Result { + let mut open = self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if open.total >= limits.max_streams { + return Err(Refused { limit: "total", max: limits.max_streams }); + } + if open.principals.get(principal).copied().unwrap_or(0) >= limits.max_streams_per_principal { + return Err(Refused { limit: "principal", max: limits.max_streams_per_principal }); + } + if let Some(b) = build + && open.builds.get(&b).copied().unwrap_or(0) >= limits.max_streams_per_build + { + return Err(Refused { limit: "build", max: limits.max_streams_per_build }); + } + open.total += 1; + *open.principals.entry(principal.to_string()).or_default() += 1; + if let Some(b) = build { + *open.builds.entry(b).or_default() += 1; + } + Ok(Slot { streams: self.clone(), principal: principal.to_string(), build }) + } + + /// How many streams are open. + #[must_use] + pub fn open(&self) -> usize { + self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).total + } +} + +impl Drop for Slot { + fn drop(&mut self) { + let mut open = self.streams.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + open.total = open.total.saturating_sub(1); + if let Some(n) = open.principals.get_mut(&self.principal) { + *n -= 1; + if *n == 0 { + open.principals.remove(&self.principal); + } + } + if let Some(b) = self.build + && let Some(n) = open.builds.get_mut(&b) + { + *n -= 1; + if *n == 0 { + open.builds.remove(&b); + } + } + } +} diff --git a/app/src/http/mod.rs b/app/src/http/mod.rs index e6badc34..d6008673 100644 --- a/app/src/http/mod.rs +++ b/app/src/http/mod.rs @@ -4,6 +4,7 @@ pub mod api; pub mod app_shell; pub mod gallery; pub mod hosts; +pub mod live; pub mod renderer; pub mod status; pub mod ui; diff --git a/app/src/http/status.rs b/app/src/http/status.rs index 32426e38..f743e667 100644 --- a/app/src/http/status.rs +++ b/app/src/http/status.rs @@ -85,5 +85,10 @@ async fn numbers() -> laravel::Result> { // 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")?, + // This process's live update streams (the pages' and the CLI's `--wait`), and its LISTEN connection: `stale` when + // its probes stopped coming back for three minutes, so open pages and waits hear nothing (they then poll only + // on a reconnection). `idle` until the first stream starts it. + "live_streams_open": super::live::STREAMS.open(), + "live_listener": crate::live::listener_state(), }))) } diff --git a/app/src/http/ui/mod.rs b/app/src/http/ui/mod.rs index 25474493..265c8164 100644 --- a/app/src/http/ui/mod.rs +++ b/app/src/http/ui/mod.rs @@ -25,6 +25,7 @@ pub fn routes(route: &mut Router) { projects::routes(route); builds::routes(route); comments::routes(route); + super::live::ui_routes(route); } /// An error as today's server answered it: `{"error": kind, "description": message}` with its status. diff --git a/app/src/listeners/mod.rs b/app/src/listeners/mod.rs index 5ea01952..1b5dbe14 100644 --- a/app/src/listeners/mod.rs +++ b/app/src/listeners/mod.rs @@ -13,6 +13,19 @@ pub async fn give_new_users_an_organization(event: Event) -> laravel:: Ok(()) } +/// A build's state, review or snapshots changed: its live streams (the build's page and its project's, the CLI's +/// `--wait`) read it again. +#[listener] +pub async fn tell_the_live_streams(event: Event) -> laravel::Result<()> { + let build_id = event.build_id; + let project_id: Option = + laravel::db::query!("SELECT project_id FROM builds WHERE id = {build_id}").scalar().await?; + if let Some(project_id) = project_id { + crate::live::tell(project_id, Some(build_id)).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] diff --git a/app/src/live.rs b/app/src/live.rs index 0c252824..a38ccf55 100644 --- a/app/src/live.rs +++ b/app/src/live.rs @@ -63,6 +63,8 @@ pub async fn notify(topic: &str) -> laravel::Result<()> { struct Hub { tx: broadcast::Sender, ready: watch::Receiver, + /// When the listener started (Unix seconds). + started: i64, } static HUB: OnceLock = OnceLock::new(); @@ -74,7 +76,7 @@ fn hub(database_url: &str) -> &'static Hub { let (tx, _) = broadcast::channel(1024); let (ready_tx, ready) = watch::channel(false); tokio::spawn(supervise(database_url.to_string(), tx.clone(), ready_tx)); - Hub { tx, ready } + Hub { tx, ready, started: unix_seconds() } }) } @@ -96,6 +98,50 @@ pub fn healthy() -> bool { last > 0 && laravel::now().timestamp().as_second() - last < 180 } +/// This process's listener, for `/status`: `idle` before anything subscribed (nothing to hear yet), `starting` in its +/// first three minutes before a probe came back, `ok` while probes come back, `stale` when none has for three minutes +/// (streams then hear nothing, and pages and `--wait` fall back on their own reads). +#[must_use] +pub fn listener_state() -> &'static str { + let Some(hub) = HUB.get() else { return "idle" }; + if healthy() { + "ok" + } else if LAST_PROBE_OK.load(Ordering::Relaxed) == 0 && unix_seconds() - hub.started < 180 { + "starting" + } else { + "stale" + } +} + +/// Now, in Unix seconds, from the system clock: the hub starts outside any request, where Laravel's clock isn't set. +fn unix_seconds() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) +} + +/// The topic of a project's builds list: a build was created, or one of its builds changed. +#[must_use] +pub fn project_topic(project_id: i64) -> String { + format!("project:{project_id}") +} + +/// The topic of one build: its state, review, counts or snapshots changed. +#[must_use] +pub fn build_topic(build_id: i64) -> String { + format!("build:{build_id}") +} + +/// Tell every replica's streams that a project's builds changed, and the build itself when there's one. Best effort: a +/// stream that misses it says so on its next reconnection, which starts with the current state. +pub async fn tell(project_id: i64, build_id: Option) { + for topic in build_id.map(build_topic).into_iter().chain([project_topic(project_id)]) { + if let Err(e) = notify(&topic).await { + tracing::warn!(error = %e, project_id, ?build_id, "live updates: couldn't notify the streams"); + } + } +} + /// Keep a listener running, restarting it when it stops or when a probe doesn't come back. async fn supervise(url: String, tx: broadcast::Sender, ready: watch::Sender) { loop { diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index 92df6787..2a1b3426 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -2327,7 +2327,7 @@ async fn is_access_token(token: &str) -> bool { /// The person an OAuth access token (a request's bearer token) acts for on `/mcp`: `None` when it isn't one, `Some(Err)` with /// why a token was refused. -async fn oauth_principal(token: Option) -> Option> { +pub(crate) async fn oauth_principal(token: Option) -> Option> { let token = token?; if !is_access_token(&token).await { return None; diff --git a/app/tests/live_limits.rs b/app/tests/live_limits.rs new file mode 100644 index 00000000..42e11bae --- /dev/null +++ b/app/tests/live_limits.rs @@ -0,0 +1,80 @@ +//! The limits on open live streams, through the endpoints. In a test binary of its own: the limits count every stream +//! in the process, and other tests' streams (whose row IDs repeat across test databases) would count against these. + +use app::config::Live; +use app::http::live::STREAMS; +use app::models::{Build, Project, User}; +use app::testing::fixtures; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +/// Short streams, and at most one stream per principal and two per build. +fn tight_limits() -> Application { + app::testing::configure() + .with_env("VISUALCI_LIVE_STREAM_SECONDS", "1") + .with_env("VISUALCI_LIVE_MAX_STREAMS_PER_PRINCIPAL", "1") + .with_env("VISUALCI_LIVE_MAX_STREAMS_PER_BUILD", "2") + .create() +} + +async fn person(name: &str) -> laravel::Result { + let email = format!("{name}-{}@example.com", laravel::str::uuid7().simple()); + create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await +} + +async fn project_token(project: &Project) -> laravel::Result { + 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 cli(app: &Application, build: &Build, token: &str) -> laravel::testing::TestRequest { + app.get(format!("/api/v1/live/builds/{}", build.pid)).header("authorization", format!("Bearer {token}")) +} + +#[laravel::test(app = tight_limits)] +async fn a_stream_past_a_limit_is_refused(app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let project = fixtures::project(&org, "web").await?; + let token = project_token(&project).await?; + let b = create!(Build { + pid: laravel::str::uuid7(), + project_id: project.id, + number: 1, + commit_sha: "c1", + branch: "main", + base_build_id: None, + }) + .await?; + let principal: Option = db::query!("SELECT id FROM project_tokens ORDER BY id DESC LIMIT 1").scalar().await?; + let principal = principal.expect("the token"); + let limits = laravel::config().section::().clone(); + + // The token already has its one stream open + let held = STREAMS.take(&limits, &format!("project-token:{principal}"), None).expect("a first slot"); + let refused = cli(&app, &b, &token).await; + refused.assert_status(429).assert_header("retry-after", "30"); + assert_eq!(refused.json()["error"], "too_many_requests"); + drop(held); + cli(&app, &b, &token).await.assert_ok(); + + // The build already has its two + let held = [ + STREAMS.take(&limits, "user:someone", Some(b.id)).expect("slot 1"), + STREAMS.take(&limits, "user:someone-else", Some(b.id)).expect("slot 2"), + ]; + cli(&app, &b, &token).await.assert_status(429); + let ada = person("ada").await?; + fixtures::member(&org, &ada, "read").await?; + let page = app.get("/api/ui/live/orgs/acme/projects/web/builds/1").acting_as(&ada).await; + page.assert_status(429).assert_header("retry-after", "30"); + drop(held); + Ok(()) +} diff --git a/app/tests/live_streams.rs b/app/tests/live_streams.rs new file mode 100644 index 00000000..e7924546 --- /dev/null +++ b/app/tests/live_streams.rs @@ -0,0 +1,340 @@ +//! Live update streams (`app::http::live`): who may follow a project or a build, that every stream starts with the +//! current state, the limits on open streams, and what a stream says when notifications arrive. A notification never +//! arrives inside a test's rolled-back transaction, so what a stream sends after its snapshot is tested on its own +//! channel. + +mod oauth_client; + +use std::time::Duration; + +use app::config::Live; +use app::http::live::{Streams, next_burst, page_stream}; +use app::live::{EVERYTHING, build_topic, project_topic}; +use app::models::{Build, Project, User}; +use app::testing::fixtures; +use laravel::db; +use laravel::model::create; +use laravel::stream::StreamExt; +use laravel::testing::TestResponse; +use laravel::testing::prelude::*; +use oauth_client::{admin_resource, connect, mcp_resource, token_of}; +use serde_json::Value; +use tokio::sync::broadcast; + +/// Streams of one second, so a request that's allowed to follow ends and its body can be read. +fn short_streams() -> Application { + app::testing::configure().with_env("VISUALCI_LIVE_STREAM_SECONDS", "1").create() +} + +async fn person(name: &str, staff: bool) -> laravel::Result { + let email = format!("{name}-{}@example.com", laravel::str::uuid7().simple()); + create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: staff }).await +} + +async fn project_token(project: &Project) -> laravel::Result { + 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) +} + +async fn build(project: &Project, number: i32) -> laravel::Result { + create!(Build { + pid: laravel::str::uuid7(), + project_id: project.id, + number: number, + commit_sha: "c1", + branch: "main", + base_build_id: None, + }) + .await +} + +async fn set_state(build: &Build, state: &str, conclusion: Option<&str>) -> laravel::Result<()> { + let id = build.id; + db::query!("UPDATE builds SET state = {state}, conclusion = {conclusion} WHERE id = {id}").update().await?; + Ok(()) +} + +async fn make_public(project: &Project) -> laravel::Result<()> { + let id = project.id; + db::query!("UPDATE projects SET public = true WHERE id = {id}").update().await?; + Ok(()) +} + +/// The events of a stream's body, as (name, data). +fn events(response: &TestResponse) -> Vec<(String, String)> { + let mut out = Vec::new(); + for block in response.text().split("\n\n") { + let mut name = String::new(); + let mut data = Vec::new(); + for line in block.lines() { + if let Some(n) = line.strip_prefix("event:") { + name = n.trim().to_string(); + } else if let Some(d) = line.strip_prefix("data:") { + data.push(d.trim_start().to_string()); + } + } + if !name.is_empty() { + out.push((name, data.join("\n"))); + } + } + out +} + +/// The first event, which every stream starts with: its name and data as JSON. +#[track_caller] +fn snapshot(response: &TestResponse) -> Value { + let events = events(response); + let (name, data) = events.first().unwrap_or_else(|| panic!("an event: {}", response.text())); + assert_eq!(name, "snapshot", "{events:?}"); + serde_json::from_str(data).unwrap_or_else(|e| panic!("JSON ({e}): {data}")) +} + +fn cli(app: &Application, build: &Build, token: &str) -> laravel::testing::TestRequest { + app.get(format!("/api/v1/live/builds/{}", build.pid)).header("authorization", format!("Bearer {token}")) +} + +#[laravel::test(app = short_streams)] +async fn members_follow_their_projects_and_builds(app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let project = fixtures::project(&org, "web").await?; + let ada = person("ada", false).await?; + fixtures::member(&org, &ada, "read").await?; + build(&project, 1).await?; + + let followed = app.get("/api/ui/live/orgs/acme/projects/web").acting_as(&ada).await; + followed + .assert_ok() + .assert_header("content-type", "text/event-stream") + .assert_header("cache-control", "no-cache, no-transform") + .assert_header("x-accel-buffering", "no"); + assert_eq!(snapshot(&followed), serde_json::json!({}), "a page's snapshot says read again"); + let page = app.get("/api/ui/live/orgs/acme/projects/web/builds/1").acting_as(&ada).await; + page.assert_ok(); + snapshot(&page); + app.get("/api/ui/live/orgs/acme/projects/web/builds/2").acting_as(&ada).await.assert_status(404); + Ok(()) +} + +#[laravel::test(app = short_streams)] +async fn nobody_else_follows_a_private_project(app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + fixtures::project(&org, "web").await?; + let eve = person("eve", false).await?; + app.get("/api/ui/live/orgs/acme/projects/web").acting_as(&eve).await.assert_status(404); + app.get("/api/ui/live/orgs/acme/projects/web").header("accept", "application/json").await.assert_status(404); + app.get("/api/ui/live/orgs/acme/projects/nothing").acting_as(&eve).await.assert_status(404); + Ok(()) +} + +#[laravel::test(app = short_streams)] +async fn anyone_follows_a_public_projects_pages(app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let project = fixtures::project(&org, "demo").await?; + make_public(&project).await?; + let followed = app.get("/api/ui/live/orgs/acme/projects/demo").header("accept", "application/json").await; + followed.assert_ok(); + snapshot(&followed); + Ok(()) +} + +#[laravel::test(app = short_streams)] +async fn a_stream_opened_after_the_build_finished_has_its_final_state_at_once(app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let project = fixtures::project(&org, "web").await?; + let token = project_token(&project).await?; + let b = build(&project, 1).await?; + set_state(&b, "completed", Some("unchanged")).await?; + + let streamed = cli(&app, &b, &token).await; + streamed.assert_ok().assert_header("content-type", "text/event-stream"); + let state = snapshot(&streamed); + assert_eq!(state["id"], b.pid.to_string()); + assert_eq!(state["state"], "completed"); + assert_eq!(state["passed"], true, "{state}"); + // The same answer as the build's own endpoint + let shown = app.get(format!("/api/v1/builds/{}", b.pid)).header("authorization", format!("Bearer {token}")).await; + assert_eq!(shown.json()["passed"], state["passed"]); + assert_eq!(shown.json()["state"], state["state"]); + Ok(()) +} + +#[laravel::test(app = short_streams)] +async fn a_reconnection_starts_with_the_current_state(app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let project = fixtures::project(&org, "web").await?; + let token = project_token(&project).await?; + let b = build(&project, 1).await?; + set_state(&b, "processing", None).await?; + + let first = cli(&app, &b, &token).await; + assert_eq!(snapshot(&first)["state"], "processing"); + assert_eq!(snapshot(&first)["passed"], Value::Null); + // It changed while the client was away (no notification reaches it): the next stream starts with the change + set_state(&b, "failed", None).await?; + let again = cli(&app, &b, &token).await; + assert_eq!(snapshot(&again)["state"], "failed"); + assert_eq!(snapshot(&again)["passed"], false); + Ok(()) +} + +#[laravel::test(app = short_streams)] +async fn a_project_token_follows_only_its_own_projects_builds(app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let web = fixtures::project(&org, "web").await?; + let docs = fixtures::project(&org, "docs").await?; + let demo = fixtures::project(&org, "demo").await?; + make_public(&demo).await?; + let token = project_token(&web).await?; + let own = build(&web, 1).await?; + let other = build(&docs, 1).await?; + let public = build(&demo, 1).await?; + + cli(&app, &own, &token).await.assert_ok(); + cli(&app, &other, &token).await.assert_status(404); + cli(&app, &public, &token).await.assert_status(404); + // The UI streams by the same principal + app.get("/api/ui/live/orgs/acme/projects/docs/builds/1") + .header("authorization", format!("Bearer {token}")) + .await + .assert_status(404); + app.get(format!("/api/v1/live/builds/{}", own.pid)).await.assert_status(401); + cli(&app, &own, "vci_nope").await.assert_status(401); + Ok(()) +} + +#[laravel::test(app = short_streams)] +async fn people_follow_their_organizations_builds_and_public_ones(app: Application) -> laravel::Result<()> { + let acme = fixtures::organization("acme").await?; + let web = fixtures::project(&acme, "web").await?; + let other = fixtures::organization("other").await?; + let private = fixtures::project(&other, "secret").await?; + let demo = fixtures::project(&other, "demo").await?; + make_public(&demo).await?; + let ada = person("ada", false).await?; + fixtures::member(&acme, &ada, "read").await?; + let personal = format!("vcu_{}", laravel::str::uuid7().simple()); + let (hash, uid) = (app::models::token_hash(&personal), ada.id); + db::query!( + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({uid}, 'laptop', {hash}, 'vcu_ab', now(), now())" + ) + .insert() + .await?; + + cli(&app, &build(&web, 1).await?, &personal).await.assert_ok(); + cli(&app, &build(&demo, 1).await?, &personal).await.assert_ok(); + cli(&app, &build(&private, 1).await?, &personal).await.assert_status(404); + Ok(()) +} + +#[laravel::test(app = short_streams)] +async fn an_mcp_clients_oauth_token_follows_on_its_own_resource(app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let project = fixtures::project(&org, "web").await?; + let grace = person("grace", true).await?; + fixtures::member(&org, &grace, "member").await?; + let b = build(&project, 1).await?; + set_state(&b, "completed", Some("unchanged")).await?; + + let mcp = token_of(connect(&app, &grace, &mcp_resource(), "mcp").await); + assert!(mcp.starts_with("vca_"), "{mcp}"); + let streamed = cli(&app, &b, &mcp).await; + streamed.assert_ok(); + assert_eq!(snapshot(&streamed)["passed"], true); + + // A token for another resource (the admin endpoint's) isn't one for this + let admin = token_of(connect(&app, &grace, &admin_resource(), "admin").await); + cli(&app, &b, &admin).await.assert_status(401); + // Nor once it's revoked + let oauth = laravel::container::resolve::().await?; + oauth.disconnect_all(&oauth_provider_laravel::subject(&grace)).await?; + cli(&app, &b, &mcp).await.assert_status(401); + Ok(()) +} + +fn limits(total: usize, per_principal: usize, per_build: usize) -> Live { + Live { + max_streams: total, + max_streams_per_principal: per_principal, + max_streams_per_build: per_build, + stream_seconds: 1800, + } +} + +#[test] +fn each_limit_refuses_the_next_stream_and_a_closed_stream_frees_its_place() { + let streams = Streams::default(); + let per_principal = limits(10, 2, 10); + let a = streams.take(&per_principal, "user:1", None).unwrap(); + let _b = streams.take(&per_principal, "user:1", Some(7)).unwrap(); + assert_eq!(streams.take(&per_principal, "user:1", None).err().map(|r| r.limit), Some("principal")); + assert!(streams.take(&per_principal, "user:2", None).is_ok(), "another principal isn't counted with them"); + drop(a); + let _c = streams.take(&per_principal, "user:1", None).expect("the closed stream's place"); + + let per_build = limits(10, 10, 1); + let streams = Streams::default(); + let _d = streams.take(&per_build, "user:1", Some(7)).unwrap(); + assert_eq!(streams.take(&per_build, "user:2", Some(7)).err().map(|r| r.limit), Some("build")); + assert!(streams.take(&per_build, "user:2", Some(8)).is_ok()); + + let total = limits(2, 10, 10); + let streams = Streams::default(); + let _e = streams.take(&total, "user:1", None).unwrap(); + let _f = streams.take(&total, "user:2", None).unwrap(); + assert_eq!(streams.take(&total, "user:3", None).err().map(|r| r.limit), Some("total")); + assert_eq!(streams.open(), 2); +} + +#[tokio::test] +async fn a_stream_starts_with_a_snapshot_and_a_burst_of_changes_is_one_event() { + let (tx, rx) = broadcast::channel(16); + let slot = Streams::default().take(&limits(10, 10, 10), "user:1", None).unwrap(); + let events = page_stream(rx, vec![build_topic(7)], Duration::from_millis(50), Duration::from_millis(400), slot); + let sent = async { + tx.send(build_topic(8)).unwrap(); + tx.send(project_topic(7)).unwrap(); + tokio::time::sleep(Duration::from_millis(20)).await; + for _ in 0..5 { + tx.send(build_topic(7)).unwrap(); + } + tokio::time::sleep(Duration::from_millis(150)).await; + tx.send(EVERYTHING.to_string()).unwrap(); + }; + let (events, ()) = tokio::join!(events.collect::>(), sent); + let names: Vec = events.iter().map(|e| format!("{e:?}")).collect(); + assert_eq!(events.len(), 3, "the snapshot, one for the burst, one for the re-read; nothing for others: {names:?}"); + assert!(names[0].contains("snapshot") && names[1].contains("changed"), "{names:?}"); +} + +#[tokio::test] +async fn a_stream_that_fell_behind_reads_again() { + let (tx, mut rx) = broadcast::channel(2); + for n in 0..5 { + tx.send(format!("build:{n}")).unwrap(); + } + let until = tokio::time::Instant::now() + Duration::from_millis(200); + assert!(next_burst(&mut rx, &[build_topic(99)], Duration::from_millis(10), until).await, "missed ones count"); + assert!(!next_burst(&mut rx, &[build_topic(99)], Duration::from_millis(10), until).await, "then nothing"); +} + +#[tokio::test] +async fn a_closed_stream_gives_its_place_back() { + let streams = Streams::default(); + let (_tx, rx) = broadcast::channel::(4); + let slot = streams.take(&limits(10, 10, 10), "user:1", Some(1)).unwrap(); + let events = page_stream(rx, vec![build_topic(1)], Duration::from_millis(10), Duration::from_secs(60), slot); + let mut events = Box::pin(events); + assert!(events.next().await.is_some(), "the snapshot"); + assert_eq!(streams.open(), 1); + // The client went away: the server drops the response body, and the stream with it + drop(events); + assert_eq!(streams.open(), 0); +} diff --git a/app/tests/mcp_admin.rs b/app/tests/mcp_admin.rs index 78aeeb9a..f793ec62 100644 --- a/app/tests/mcp_admin.rs +++ b/app/tests/mcp_admin.rs @@ -3,6 +3,7 @@ //! Each tool's answer is checked against tests/golden/mcp_admin. mod golden; +mod oauth_client; use std::collections::HashMap; use std::sync::Mutex; @@ -12,109 +13,9 @@ use laravel::db; use laravel::model::create; use laravel::testing::TestResponse; use laravel::testing::prelude::*; +use oauth_client::{CHALLENGE, Connected, REDIRECT, admin_resource, connect, form, mcp_resource, token_of}; use serde_json::{Value, json}; -const REDIRECT: &str = "http://127.0.0.1:9999/cb"; -const VERIFIER: &str = "visualci-test-verifier-0123456789-abcdefghijklmnopqrstuvwxyz"; -// The S256 challenge of VERIFIER. -const CHALLENGE: &str = "v8yzKoHOTGkBq15_ikEfQ4vLdOS_IW3B3JIsz5GmKUc"; - -fn mcp_resource() -> String { - format!("{}/mcp", laravel::config().app.url.trim_end_matches('/')) -} - -fn admin_resource() -> String { - format!("{}/admin", mcp_resource()) -} - -fn form(pairs: &[(&str, &str)]) -> String { - url::form_urlencoded::Serializer::new(String::new()).extend_pairs(pairs).finish() -} - -/// An HTML attribute's value as text. -fn unescape(s: &str) -> String { - [("/", "/"), ("/", "/"), ("'", "'"), ("'", "'"), (""", "\""), ("<", "<"), (">", ">")] - .into_iter() - .fold(s.to_string(), |s, (from, to)| s.replace(from, to)) - .replace("&", "&") -} - -/// What connecting got: the access token, or the consent step's status and page when it refused. -enum Connected { - Token(String), - Refused(u16, String), -} - -/// `user` connects a new MCP client for `resource`, asking for `scope`, as an MCP client and its person would: dynamic -/// registration, the consent page, approving it, then the code for tokens. -async fn connect(app: &Application, user: &User, resource: &str, scope: &str) -> Connected { - let registered = app - .post("/oauth/register") - .json(json!({ "client_name": "Ops agent", "redirect_uris": [REDIRECT], "token_endpoint_auth_method": "none" })) - .await; - registered.assert_status(201); - let client_id = registered.json()["client_id"].as_str().unwrap().to_string(); - let params = [ - ("response_type", "code"), - ("client_id", client_id.as_str()), - ("redirect_uri", REDIRECT), - ("state", "st"), - ("code_challenge", CHALLENGE), - ("code_challenge_method", "S256"), - ("resource", resource), - ("scope", scope), - ]; - let page = app.get(format!("/oauth/authorize?{}", form(¶ms))).acting_as(user).await; - if page.status() != 200 { - return Connected::Refused(page.status().as_u16(), page.text()); - } - // The consent form's own fields, as the page asks for them (the scope it grants) - let html = page.text(); - let hidden = regex::Regex::new(r#""#).unwrap(); - let decoded: Vec<(String, String)> = - hidden.captures_iter(&html).map(|c| (c[1].to_string(), unescape(&c[2]))).collect(); - assert!(decoded.iter().any(|(k, _)| k == "client_id"), "the consent page's form: {html}"); - let mut fields: Vec<(&str, &str)> = decoded.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); - fields.push(("decision", "approve")); - let approved = app - .post("/oauth/authorize") - .header("content-type", "application/x-www-form-urlencoded") - .header("sec-fetch-site", "same-origin") - .body(form(&fields)) - .acting_as(user) - .await; - if approved.status() != 303 { - return Connected::Refused(approved.status().as_u16(), approved.text()); - } - let location = approved.headers()["location"].to_str().unwrap().to_string(); - let back: HashMap = url::Url::parse(&location).unwrap().query_pairs().into_owned().collect(); - let token = app - .post("/oauth/token") - .header("content-type", "application/x-www-form-urlencoded") - .body(form(&[ - ("grant_type", "authorization_code"), - ("client_id", client_id.as_str()), - ("code", back["code"].as_str()), - ("code_verifier", VERIFIER), - ("redirect_uri", REDIRECT), - ("resource", resource), - ])) - .await; - let body = token.json().clone(); - Connected::Token(body["access_token"].as_str().unwrap_or_else(|| panic!("an access token: {body}")).to_string()) -} - -#[track_caller] -fn token_of(connected: Connected) -> String { - match connected { - Connected::Token(t) => t, - Connected::Refused(status, page) => { - let message = page.split("

").nth(1).unwrap_or(&page).to_string(); - panic!("refused ({status}): {message}") - } - } -} - /// The scopes a token was granted. async fn scopes(token: &str, resource: &str) -> Vec { let oauth = laravel::container::resolve::().await.unwrap(); diff --git a/app/tests/oauth_client/mod.rs b/app/tests/oauth_client/mod.rs new file mode 100644 index 00000000..cdae7ab8 --- /dev/null +++ b/app/tests/oauth_client/mod.rs @@ -0,0 +1,111 @@ +//! An MCP client connecting over OAuth in a test, as a real one does: dynamic registration, the consent page, +//! approving it, then the code for tokens. Shared by the tests that need a `vca_` access token. + +#![allow(dead_code)] + +use std::collections::HashMap; + +use app::models::User; +use laravel::testing::prelude::*; +use serde_json::json; + +pub const REDIRECT: &str = "http://127.0.0.1:9999/cb"; +pub const VERIFIER: &str = "visualci-test-verifier-0123456789-abcdefghijklmnopqrstuvwxyz"; +// The S256 challenge of VERIFIER. +pub const CHALLENGE: &str = "v8yzKoHOTGkBq15_ikEfQ4vLdOS_IW3B3JIsz5GmKUc"; + +pub fn mcp_resource() -> String { + format!("{}/mcp", laravel::config().app.url.trim_end_matches('/')) +} + +pub fn admin_resource() -> String { + format!("{}/admin", mcp_resource()) +} + +pub fn form(pairs: &[(&str, &str)]) -> String { + url::form_urlencoded::Serializer::new(String::new()).extend_pairs(pairs).finish() +} + +/// An HTML attribute's value as text. +pub fn unescape(s: &str) -> String { + [("/", "/"), ("/", "/"), ("'", "'"), ("'", "'"), (""", "\""), ("<", "<"), (">", ">")] + .into_iter() + .fold(s.to_string(), |s, (from, to)| s.replace(from, to)) + .replace("&", "&") +} + +/// What connecting got: the access token, or the consent step's status and page when it refused. +pub enum Connected { + Token(String), + Refused(u16, String), +} + +/// `user` connects a new MCP client for `resource`, asking for `scope`, as an MCP client and its person would: dynamic +/// registration, the consent page, approving it, then the code for tokens. +pub async fn connect(app: &Application, user: &User, resource: &str, scope: &str) -> Connected { + let registered = app + .post("/oauth/register") + .json(json!({ "client_name": "Ops agent", "redirect_uris": [REDIRECT], "token_endpoint_auth_method": "none" })) + .await; + registered.assert_status(201); + let client_id = registered.json()["client_id"].as_str().unwrap().to_string(); + let params = [ + ("response_type", "code"), + ("client_id", client_id.as_str()), + ("redirect_uri", REDIRECT), + ("state", "st"), + ("code_challenge", CHALLENGE), + ("code_challenge_method", "S256"), + ("resource", resource), + ("scope", scope), + ]; + let page = app.get(format!("/oauth/authorize?{}", form(¶ms))).acting_as(user).await; + if page.status() != 200 { + return Connected::Refused(page.status().as_u16(), page.text()); + } + // The consent form's own fields, as the page asks for them (the scope it grants) + let html = page.text(); + let hidden = regex::Regex::new(r#""#).unwrap(); + let decoded: Vec<(String, String)> = + hidden.captures_iter(&html).map(|c| (c[1].to_string(), unescape(&c[2]))).collect(); + assert!(decoded.iter().any(|(k, _)| k == "client_id"), "the consent page's form: {html}"); + let mut fields: Vec<(&str, &str)> = decoded.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); + fields.push(("decision", "approve")); + let approved = app + .post("/oauth/authorize") + .header("content-type", "application/x-www-form-urlencoded") + .header("sec-fetch-site", "same-origin") + .body(form(&fields)) + .acting_as(user) + .await; + if approved.status() != 303 { + return Connected::Refused(approved.status().as_u16(), approved.text()); + } + let location = approved.headers()["location"].to_str().unwrap().to_string(); + let back: HashMap = url::Url::parse(&location).unwrap().query_pairs().into_owned().collect(); + let token = app + .post("/oauth/token") + .header("content-type", "application/x-www-form-urlencoded") + .body(form(&[ + ("grant_type", "authorization_code"), + ("client_id", client_id.as_str()), + ("code", back["code"].as_str()), + ("code_verifier", VERIFIER), + ("redirect_uri", REDIRECT), + ("resource", resource), + ])) + .await; + let body = token.json().clone(); + Connected::Token(body["access_token"].as_str().unwrap_or_else(|| panic!("an access token: {body}")).to_string()) +} + +#[track_caller] +pub fn token_of(connected: Connected) -> String { + match connected { + Connected::Token(t) => t, + Connected::Refused(status, page) => { + let message = page.split("

").nth(1).unwrap_or(&page).to_string(); + panic!("refused ({status}): {message}") + } + } +} diff --git a/crates/visualci-cli/src/client.rs b/crates/visualci-cli/src/client.rs index cb398533..9e34a318 100644 --- a/crates/visualci-cli/src/client.rs +++ b/crates/visualci-cli/src/client.rs @@ -354,19 +354,218 @@ impl Client { } } - /// Poll until the build passes or fails under its CI mode, or until the timeout. + /// Wait until the build passes or fails under its CI mode, or until the timeout, and answer it as it is then. + /// Follows the build's live stream (`GET /api/v1/live/builds/{id}`, server-sent events), which starts with the + /// build as it is now; polls instead when the server has no stream (an older server), refuses one (its limits), or + /// a proxy holds it back (no first event within [`WaitTiming::first_event`]). pub fn wait(&self, id: &str, timeout: Duration) -> Result { - let start = Instant::now(); + self.wait_with(id, timeout, WaitTiming::default()) + } + + fn wait_with(&self, id: &str, timeout: Duration, timing: WaitTiming) -> Result { + let deadline = Instant::now() + timeout; + // Streams that end without saying anything (the server going away mid-deploy): after three, poll + let mut silent_ends = 0; + while Instant::now() < deadline && silent_ends < 3 { + match self.follow(id, deadline, timing) { + Followed::Decided(build) => return Ok(*build), + Followed::Ended { heard } => { + silent_ends = if heard { 0 } else { silent_ends + 1 }; + if verbose() { + eprintln!("visualci: the live stream ended; connecting again"); + } + std::thread::sleep(timing.reconnect.min(deadline.saturating_duration_since(Instant::now()))); + } + Followed::Unavailable(why) => { + if verbose() { + eprintln!("visualci: no live updates ({why}); polling"); + } + break; + } + } + } + // Polling, and a last read at the deadline loop { let build = self.build(id)?; - if build.passed.is_some() || start.elapsed() > timeout { + let now = Instant::now(); + if build.passed.is_some() || now >= deadline { return Ok(build); } - std::thread::sleep(Duration::from_secs(2)); + std::thread::sleep(timing.poll_every.min(deadline - now)); + } + } + + /// Follow the build's live stream until it's decided, the stream ends or stalls, or the deadline. + fn follow(&self, id: &str, deadline: Instant, timing: WaitTiming) -> Followed { + let path = format!("/api/v1/live/builds/{id}"); + let request = self + .authed(self.http.get(format!("{}{path}", self.api_url))) + .header("accept", "text/event-stream") + .timeout(deadline.saturating_duration_since(Instant::now()) + Duration::from_secs(5)); + let events = live_events(request); + let opened = Instant::now(); + let mut heard_from = opened; + let mut heard = false; + let mut read_at = opened; + loop { + let now = Instant::now(); + if now >= deadline { + return Followed::Ended { heard }; + } + // A stream that only sends comments may have stopped hearing about changes (the server's listener lost + // its connection): read the build now and then too + if heard && now >= read_at + timing.backstop { + read_at = now; + if let Ok(build) = self.build(id) + && build.passed.is_some() + { + return Followed::Decided(Box::new(build)); + } + } + // Before the first event: a proxy holding the stream back. After it: a stalled connection (the server + // sends a comment every 15 seconds). + let limit = if heard { + (heard_from + timing.silence).min(read_at + timing.backstop) + } else { + opened + timing.first_event + }; + match events.recv_timeout(limit.min(deadline).saturating_duration_since(now)) { + Ok(LiveMessage::Refused(why)) => return Followed::Unavailable(why), + Ok(LiveMessage::Comment) => heard_from = Instant::now(), + Ok(LiveMessage::Event { name, data }) => { + heard_from = Instant::now(); + if name != "snapshot" && name != "build" { + continue; + } + match serde_json::from_str::(&data) { + Ok(build) if build.passed.is_some() => return Followed::Decided(Box::new(build)), + Ok(_) => heard = true, + Err(e) => return Followed::Unavailable(format!("an event it couldn't read: {e}")), + } + } + Ok(LiveMessage::End) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { + return Followed::Ended { heard }; + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) if Instant::now() >= deadline => { + return Followed::Ended { heard }; + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) if heard => { + if Instant::now() >= heard_from + timing.silence { + return Followed::Ended { heard }; + } + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + return Followed::Unavailable(format!( + "nothing within {} s: a proxy may be holding the stream back", + timing.first_event.as_secs() + )); + } + } } } } +/// How `wait` follows a build. +#[derive(Clone, Copy, Debug)] +struct WaitTiming { + /// How long a new stream may take to send its first event before `wait` polls instead. + first_event: Duration, + /// How long an open stream may stay silent (it sends a comment every 15 s) before `wait` connects again. + silence: Duration, + /// How long `wait` waits before connecting again after a stream ended. + reconnect: Duration, + /// How often `wait` also reads the build while it follows the stream, in case the stream stopped hearing. + backstop: Duration, + /// How often `wait` reads the build when it polls. + poll_every: Duration, +} + +impl Default for WaitTiming { + fn default() -> Self { + Self { + first_event: Duration::from_secs(10), + silence: Duration::from_secs(45), + reconnect: Duration::from_secs(1), + backstop: Duration::from_secs(60), + poll_every: Duration::from_secs(2), + } + } +} + +/// How following a stream went. +enum Followed { + /// The build passed or failed. + Decided(Box), + /// The stream ended or stalled; `heard` when it sent the build first. + Ended { heard: bool }, + /// No stream to follow: poll instead. + Unavailable(String), +} + +/// What the thread reading a live stream passes on. +enum LiveMessage { + /// The server answered something other than an event stream. + Refused(String), + Event { + name: String, + data: String, + }, + /// A keep-alive comment. + Comment, + End, +} + +/// Send `request` and read its server-sent events on a thread of their own, so the caller can give up on a stream that +/// says nothing. The thread ends with the stream, or at its next line once the receiver is gone. +fn live_events(request: reqwest::blocking::RequestBuilder) -> std::sync::mpsc::Receiver { + use std::io::BufRead; + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let response = match request.send() { + Ok(response) => response, + Err(e) => { + let _ = tx.send(LiveMessage::Refused(e.to_string())); + return; + } + }; + let status = response.status(); + let content_type = + response.headers().get(reqwest::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or_default(); + if !status.is_success() || !content_type.starts_with("text/event-stream") { + let _ = tx.send(LiveMessage::Refused(format!("HTTP {status}, {content_type}"))); + return; + } + let (mut name, mut data) = (String::new(), Vec::::new()); + for line in std::io::BufReader::new(response).lines() { + let Ok(line) = line else { break }; + let message = if line.is_empty() { + if data.is_empty() { + name.clear(); + continue; + } + let event = if name.is_empty() { "message".to_string() } else { std::mem::take(&mut name) }; + LiveMessage::Event { name: event, data: std::mem::take(&mut data).join("\n") } + } else if line.starts_with(':') { + LiveMessage::Comment + } else { + let (field, value) = line.split_once(':').unwrap_or((line.as_str(), "")); + let value = value.strip_prefix(' ').unwrap_or(value); + match field { + "event" => name = value.to_string(), + "data" => data.push(value.to_string()), + _ => {} + } + continue; + }; + if tx.send(message).is_err() { + return; + } + } + let _ = tx.send(LiveMessage::End); + }); + rx +} + fn read(response: reqwest::blocking::Response, path: &str) -> Result { let status = response.status(); let text = response.text()?; @@ -746,6 +945,197 @@ mod tests { Client { api_url: String::new(), token: String::new(), project: None, http: reqwest::blocking::Client::new() } } + /// A VisualCI server for one test: `/api/v1/live/builds/b1` answers what `live` writes (after the status line), + /// `/api/v1/builds/b1` the build as `polled` says. Counts the requests to each. + fn api( + live: fn(&mut std::net::TcpStream), + polled: Option, + ) -> (String, std::sync::Arc<[std::sync::atomic::AtomicUsize; 2]>) { + use std::io::{BufRead, BufReader}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let counts = + std::sync::Arc::new([std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0)]); + let seen = counts.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let mut stream = stream.unwrap(); + let seen = seen.clone(); + std::thread::spawn(move || { + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut first = String::new(); + reader.read_line(&mut first).unwrap(); + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line == "\r\n" || line.is_empty() { + break; + } + } + if first.contains("/api/v1/live/builds/b1") { + seen[0].fetch_add(1, std::sync::atomic::Ordering::SeqCst); + live(&mut stream); + } else { + seen[1].fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let body = build_json(polled); + let _ = write!( + stream, + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ); + } + }); + } + }); + (url, counts) + } + + use std::io::Write; + + fn build_json(passed: Option) -> String { + let state = if passed.is_some() { "completed" } else { "processing" }; + json!({ + "id": "b1", "number": 1, "project": "acme/web", "state": state, "review_state": "unreviewed", + "conclusion": null, "ci_mode": "wait", "passed": passed, "stats": {}, "error": null, + "url": "https://app.visualci.test/acme/web/builds/1", + }) + .to_string() + } + + fn event_stream_head(stream: &mut std::net::TcpStream) { + let _ = write!(stream, "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncache-control: no-cache\r\n\r\n"); + let _ = stream.flush(); + } + + fn api_client(url: &str) -> Client { + Client { + api_url: url.to_string(), + token: "vci_test".into(), + project: None, + http: reqwest::blocking::Client::new(), + } + } + + fn quick() -> WaitTiming { + WaitTiming { + first_event: Duration::from_millis(300), + silence: Duration::from_secs(2), + reconnect: Duration::from_millis(10), + backstop: Duration::from_secs(60), + poll_every: Duration::from_millis(50), + } + } + + use std::time::Duration; + + #[test] + fn wait_follows_the_live_stream_until_the_build_is_decided() { + let (url, counts) = api( + |s| { + event_stream_head(s); + let _ = write!(s, ": keep-alive\n\nevent: snapshot\ndata: {}\n\n", build_json(None)); + let _ = s.flush(); + std::thread::sleep(Duration::from_millis(100)); + let _ = write!(s, "event: build\ndata: {}\n\n", build_json(Some(false))); + let _ = s.flush(); + std::thread::sleep(Duration::from_secs(5)); + }, + None, + ); + let build = api_client(&url).wait_with("b1", Duration::from_secs(10), quick()).unwrap(); + assert_eq!(build.passed, Some(false), "exit code 1 follows from it"); + assert_eq!(counts[1].load(std::sync::atomic::Ordering::SeqCst), 0, "no polling"); + } + + #[test] + fn a_wait_that_starts_after_the_build_finished_returns_at_once() { + let (url, counts) = api( + |s| { + event_stream_head(s); + let _ = write!(s, "event: snapshot\ndata: {}\n\n", build_json(Some(true))); + let _ = s.flush(); + std::thread::sleep(Duration::from_secs(5)); + }, + None, + ); + let start = std::time::Instant::now(); + let build = api_client(&url).wait_with("b1", Duration::from_secs(10), WaitTiming::default()).unwrap(); + assert_eq!(build.passed, Some(true)); + assert!(start.elapsed() < Duration::from_secs(2), "{:?}", start.elapsed()); + assert_eq!(counts[1].load(std::sync::atomic::Ordering::SeqCst), 0); + } + + #[test] + fn wait_polls_when_the_server_has_no_live_stream() { + let (url, counts) = api( + |s| { + let _ = write!(s, "HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"); + }, + Some(true), + ); + let build = api_client(&url).wait_with("b1", Duration::from_secs(10), quick()).unwrap(); + assert_eq!(build.passed, Some(true)); + assert_eq!(counts[0].load(std::sync::atomic::Ordering::SeqCst), 1, "one try at the stream"); + assert_eq!(counts[1].load(std::sync::atomic::Ordering::SeqCst), 1, "then a read"); + } + + #[test] + fn wait_polls_when_a_proxy_holds_the_stream_back() { + let (url, counts) = api( + |s| { + event_stream_head(s); + // A buffering proxy: the events never arrive + std::thread::sleep(Duration::from_secs(5)); + }, + Some(true), + ); + let start = std::time::Instant::now(); + let build = api_client(&url).wait_with("b1", Duration::from_secs(10), quick()).unwrap(); + assert_eq!(build.passed, Some(true)); + assert!(start.elapsed() < Duration::from_secs(3), "{:?}", start.elapsed()); + assert_eq!(counts[1].load(std::sync::atomic::Ordering::SeqCst), 1); + } + + #[test] + fn wait_reads_the_build_when_the_stream_only_keeps_alive() { + let (url, counts) = api( + |s| { + event_stream_head(s); + let _ = write!(s, "event: snapshot\ndata: {}\n\n", build_json(None)); + let _ = s.flush(); + // The server's listener stopped hearing: comments, never the change + for _ in 0..50 { + std::thread::sleep(Duration::from_millis(100)); + let _ = write!(s, ": keep-alive\n\n"); + let _ = s.flush(); + } + }, + Some(true), + ); + let timing = WaitTiming { backstop: Duration::from_millis(300), ..quick() }; + let start = std::time::Instant::now(); + let build = api_client(&url).wait_with("b1", Duration::from_secs(10), timing).unwrap(); + assert_eq!(build.passed, Some(true)); + assert!(start.elapsed() < Duration::from_secs(3), "{:?}", start.elapsed()); + assert_eq!(counts[0].load(std::sync::atomic::Ordering::SeqCst), 1, "still the first stream"); + } + + #[test] + fn wait_answers_the_undecided_build_at_its_timeout() { + let (url, counts) = api( + |s| { + event_stream_head(s); + let _ = write!(s, "event: snapshot\ndata: {}\n\n", build_json(None)); + let _ = s.flush(); + std::thread::sleep(Duration::from_secs(5)); + }, + None, + ); + let build = api_client(&url).wait_with("b1", Duration::from_millis(500), quick()).unwrap(); + assert_eq!(build.passed, None, "exit code 3 follows from it"); + assert_eq!(counts[1].load(std::sync::atomic::Ordering::SeqCst), 1, "a last read at the deadline"); + } + #[test] fn a_refused_upload_is_tried_again() { let (url, seen) = store(vec![429, 503]); diff --git a/docs/design.md b/docs/design.md index da251b0b..a0abfa83 100644 --- a/docs/design.md +++ b/docs/design.md @@ -577,6 +577,16 @@ DocSpring's own ops agents (triage, support) work on customers' issues through a fails when they differ). - Frontend: React + TanStack (Router, Query), from the original note, in `frontend`: app/ serves its build as `public/`, and visualci.com is its static build. +- Live updates (sc-8897): Postgres LISTEN/NOTIFY on one channel (`app/src/live.rs`), with no WebSockets and no + broadcaster service. A change notifies a topic (`build:42`, `project:7`: `BuildChanged`, a new build, a build + starting to process or making progress) and each web process passes it on to its server-sent event streams + (`app/src/http/live.rs`): the project and build pages (`/api/ui/live/...`, which say "read again") and the CLI's + `--wait` (`/api/v1/live/builds/{id}`, which carries the build). Every stream starts with a `snapshot`, so a reconnection + or a late start never waits for the next change. Streams authorize with the same `Principal` as the API and MCP, are + capped per principal, per build and per process (`VISUALCI_LIVE_*`, a 429 past them), hold no database connection + while idle, and end after 30 minutes so access is checked again. The pages poll and the CLI polls whenever there's no + stream. LISTEN needs a direct or session-mode connection to Postgres, not a transaction-mode PgBouncer. Behind + Envoy, the `/api/ui/live` and `/api/v1/live` prefixes need a route without a response timeout. - Workers: app/'s queue worker (diffs) on products-1, and the renderer images (PDFBox/mutool, Chromium) on render-1 with gVisor. - Storage: R2 bucket `visualci` in the DocSpring Products account, presigned uploads straight from CI. diff --git a/frontend/content/docs/reference/api.md b/frontend/content/docs/reference/api.md index cc09c8e0..14a4bf7a 100644 --- a/frontend/content/docs/reference/api.md +++ b/frontend/content/docs/reference/api.md @@ -75,6 +75,10 @@ A name (with its platform) is one snapshot per build. Registering it again with | `error` | Why the build failed, when it did. | | `blocked` | Set when the build can't be compared because the organization is out of credits: `reason` (`out_of_credits`), `credits_used`, `credits_limit`, `pack_credits`, `renews_at`, `fixes` (each an `action` such as `upgrade`, `buy_pack` or `turn_on_auto_buy`, a `label` and the billing `url`) and `message`, one line to show a person. On a build still receiving files too. `resolved: true` once the organization has credits again. | +### Follow a build + +`GET /api/v1/live/builds/{id}` follows the build as [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) instead of polling. The first event, `snapshot`, is the build as `GET /api/v1/builds/{id}` returns it now, so a client that connects after the build finished has the result at once. Each `build` event after that is the build again after it changed. A comment arrives every 15 seconds while nothing changes. The stream ends after 30 minutes: connect again, and the new stream starts with a `snapshot`. Too many open streams get a 429 with `Retry-After`; poll `GET /api/v1/builds/{id}` meanwhile. Personal tokens and MCP clients' OAuth tokens may follow any build of their organizations' projects. + `GET /api/v1/builds/{id}/snapshots` lists the build's snapshots: `id`, `name`, `platform`, `kind`, `state`, `review` and `error`. Add `?state=changes` for the changed, added and removed ones, or any single state. ## Download a build's images diff --git a/frontend/content/docs/self-hosting/environment-variables.md b/frontend/content/docs/self-hosting/environment-variables.md index 9af60336..eac73c03 100644 --- a/frontend/content/docs/self-hosting/environment-variables.md +++ b/frontend/content/docs/self-hosting/environment-variables.md @@ -137,6 +137,17 @@ Public galleries. | --- | --- | --- | --- | | `VISUALCI_GALLERY_DAILY_CREDITS` | integer | `50000` | The most gallery credits one project is charged in a day: images past it are served free. | +## Live updates + +The server-sent event streams the build and project pages and the CLI's `--wait` follow. The limits are each web process's own: a stream past one is refused with a 429, and the page or the CLI reads on its own instead. A stream holds no database connection while it waits. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_LIVE_MAX_STREAMS` | integer | `2000` | The most streams one web process keeps open at once. | +| `VISUALCI_LIVE_MAX_STREAMS_PER_PRINCIPAL` | integer | `30` | The most streams one person, project token or visitor's address keeps open in one web process. | +| `VISUALCI_LIVE_MAX_STREAMS_PER_BUILD` | integer | `100` | The most streams following one build in one web process. | +| `VISUALCI_LIVE_STREAM_SECONDS` | integer | `1800` | How long one stream lasts, in seconds. It then ends, and the browser or the CLI connects again, so access is checked again. | + ## Heartbeats Each scheduled job pushes its result to a [Gatus](https://gatus.io) external endpoint, so a run that failed, or no run at all, alerts. Each pair is the endpoint's URL and its token; a job without a URL pushes nothing. diff --git a/frontend/src/__tests__/live.test.tsx b/frontend/src/__tests__/live.test.tsx new file mode 100644 index 00000000..9dc1c196 --- /dev/null +++ b/frontend/src/__tests__/live.test.tsx @@ -0,0 +1,119 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, render } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { REOPEN_AFTER_MS, useLive } from '../api/live' + +// A stand-in for the browser's EventSource that the test drives. +class FakeSource { + static CONNECTING = 0 + static OPEN = 1 + static CLOSED = 2 + static all: FakeSource[] = [] + readyState = FakeSource.CONNECTING + closed = false + listeners: Record void)[]> = {} + constructor(readonly url: string) { + FakeSource.all.push(this) + } + static get last(): FakeSource | undefined { + return FakeSource.all[FakeSource.all.length - 1] + } + addEventListener(name: string, fn: () => void) { + ;(this.listeners[name] ??= []).push(fn) + } + close() { + this.closed = true + this.readyState = FakeSource.CLOSED + } + fire(name: string, state?: number) { + if (state !== undefined) this.readyState = state + act(() => this.listeners[name]?.forEach((fn) => fn())) + } +} + +beforeEach(() => { + vi.stubGlobal('EventSource', FakeSource) +}) + +afterEach(() => { + FakeSource.all = [] + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +function Page({ path }: { path: string | null }) { + const open = useLive(path, [ + ['project', 'acme', 'web'], + ['pull', 'acme', 'web'], + ]) + return

{open ? 'live' : 'polling'}

+} + +function setup(path: string | null) { + const qc = new QueryClient() + const invalidate = vi.spyOn(qc, 'invalidateQueries') + const view = render( + + + , + ) + return { invalidate, view } +} + +const keysOf = (invalidate: { mock: { calls: unknown[][] } }) => + invalidate.mock.calls.map((c) => (c[0] as { queryKey: unknown } | undefined)?.queryKey) + +describe('a page following its live stream', () => { + it('reads its data again on the opening snapshot and on each change', () => { + const { invalidate, view } = setup('/api/ui/live/orgs/acme/projects/web') + const source = FakeSource.last! + expect(source.url).toBe('/api/ui/live/orgs/acme/projects/web') + expect(view.container.textContent).toBe('polling') + + source.fire('open', FakeSource.OPEN) + expect(view.container.textContent).toBe('live') + source.fire('snapshot') + expect(keysOf(invalidate)).toEqual([ + ['project', 'acme', 'web'], + ['pull', 'acme', 'web'], + ]) + + invalidate.mockClear() + source.fire('changed') + expect(invalidate).toHaveBeenCalledTimes(2) + + view.unmount() + expect(source.closed).toBe(true) + }) + + it('polls while the browser reconnects, and reads again on the new snapshot', () => { + const { invalidate, view } = setup('/api/ui/live/orgs/acme/projects/web') + const source = FakeSource.last! + source.fire('open', FakeSource.OPEN) + source.fire('error', FakeSource.CONNECTING) + expect(view.container.textContent).toBe('polling') + source.fire('open', FakeSource.OPEN) + source.fire('snapshot') + expect(invalidate).toHaveBeenCalledTimes(2) + expect(view.container.textContent).toBe('live') + }) + + it('keeps polling when the server refuses the stream, and opens it again later', () => { + vi.useFakeTimers() + const { view } = setup('/api/ui/live/orgs/acme/projects/web') + FakeSource.last!.fire('error', FakeSource.CLOSED) + expect(view.container.textContent).toBe('polling') + expect(FakeSource.all).toHaveLength(1) + act(() => vi.advanceTimersByTime(REOPEN_AFTER_MS)) + expect(FakeSource.all).toHaveLength(2) + FakeSource.last!.fire('open', FakeSource.OPEN) + expect(view.container.textContent).toBe('live') + view.unmount() + expect(FakeSource.last!.closed).toBe(true) + }) + + it('opens nothing without a path', () => { + setup(null) + expect(FakeSource.all).toHaveLength(0) + }) +}) diff --git a/frontend/src/api/hooks.ts b/frontend/src/api/hooks.ts index 9d52fe44..83d2a457 100644 --- a/frontend/src/api/hooks.ts +++ b/frontend/src/api/hooks.ts @@ -1,6 +1,7 @@ import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { siteUrl } from '../lib/hosts' import { ApiError, del, get, patch, post, request } from './client' +import { useLive } from './live' import type { EmailPreview, FailedEmail, @@ -79,13 +80,22 @@ export function useOrg(org: string) { } const live = (state: string | undefined) => state === 'receiving' || state === 'processing' +// While a stream is open, an in-progress build is still read now and then, in case the stream stopped hearing. +const STREAM_BACKSTOP = 60_000 + +// Each page's live stream: the same path under /api/ui/live. +const livePath = (path: string) => path.replace(/^\/api\/ui\//, '/api/ui/live/') export function useProject(org: string, project: string, options: { enabled?: boolean } = {}) { + const enabled = options.enabled ?? true + // The project's stream says when its builds change; without one, poll while a build is in progress. + const streaming = useLive(enabled ? livePath(projectPath(org, project)) : null, [keys.project(org, project)]) return useQuery({ - enabled: options.enabled ?? true, + enabled, queryKey: keys.project(org, project), queryFn: () => get(projectPath(org, project)), - refetchInterval: (q) => (q.state.data?.builds.some((b) => live(b.state)) ? 4000 : false), + refetchInterval: (q) => + q.state.data?.builds.some((b) => live(b.state)) ? (streaming ? STREAM_BACKSTOP : 4000) : false, }) } @@ -93,11 +103,18 @@ export function useProject(org: string, project: string, options: { enabled?: bo const IMAGE_URL_TTL = 45 * 60_000 export function useBuild(org: string, project: string, n: number) { + // The build's stream says when it, its snapshots or its pull request's changes change; without one, poll while + // it's in progress. + const streaming = useLive(livePath(buildPath(org, project, n)), [ + keys.build(org, project, n), + ['snapshot', org, project, n], + ['pull', org, project], + ]) return useQuery({ queryKey: keys.build(org, project, n), queryFn: () => get(buildPath(org, project, n)), staleTime: 30_000, - refetchInterval: (q) => (live(q.state.data?.build.state) ? 3000 : IMAGE_URL_TTL), + refetchInterval: (q) => (live(q.state.data?.build.state) ? (streaming ? STREAM_BACKSTOP : 3000) : IMAGE_URL_TTL), }) } diff --git a/frontend/src/api/live.ts b/frontend/src/api/live.ts new file mode 100644 index 00000000..73b39d33 --- /dev/null +++ b/frontend/src/api/live.ts @@ -0,0 +1,50 @@ +import { type QueryKey, useQueryClient } from '@tanstack/react-query' +import { useEffect, useState } from 'react' + +/** How long a page waits before opening its stream again after the server refused it or closed it for good. */ +export const REOPEN_AFTER_MS = 30_000 + +/** + * Follow a page's live stream (server-sent events under `/api/ui/live`): read `keys` again when the stream opens (its + * first event, `snapshot`, so a reconnection never misses what changed meanwhile) and whenever it says `changed`. + * Returns whether the stream is open, so the page polls only while it isn't. When the server refuses the stream (a + * limit's 429, or an older server's 404) the browser gives up on it, and the page opens it again after + * {@link REOPEN_AFTER_MS}. + */ +export function useLive(path: string | null, keys: readonly QueryKey[]): boolean { + const qc = useQueryClient() + const [open, setOpen] = useState(false) + const id = JSON.stringify(keys) + useEffect(() => { + if (!path || typeof EventSource === 'undefined') return + let source: EventSource | null = null + let reopen: ReturnType | undefined + const refresh = () => { + for (const queryKey of JSON.parse(id) as QueryKey[]) void qc.invalidateQueries({ queryKey }) + } + const connect = () => { + const s = new EventSource(path) + source = s + s.addEventListener('open', () => setOpen(true)) + s.addEventListener('snapshot', refresh) + s.addEventListener('changed', refresh) + s.addEventListener('error', () => { + setOpen(s.readyState === EventSource.OPEN) + // CONNECTING: the browser reconnects by itself. CLOSED: it won't, so try again later. + if (s.readyState === EventSource.CLOSED && reopen === undefined) { + reopen = setTimeout(() => { + reopen = undefined + connect() + }, REOPEN_AFTER_MS) + } + }) + } + connect() + return () => { + clearTimeout(reopen) + source?.close() + setOpen(false) + } + }, [path, id, qc]) + return open +}