From 47a234161aceccc75bde2c230d6221fc1d336ab6 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:05:49 +1300 Subject: [PATCH] =?UTF-8?q?app/:=20live=20updates=20for=20the=20web=20app?= =?UTF-8?q?=20(sc-8897,=20sc-8900):=20a=20project=20page=20and=20a=20build?= =?UTF-8?q?=20page=20each=20follow=20a=20server-sent=20event=20stream=20(G?= =?UTF-8?q?ET=20=E2=80=A6/projects/{project}/live=20and=20=E2=80=A6/builds?= =?UTF-8?q?/{number}/live)=20and=20read=20their=20data=20again=20when=20it?= =?UTF-8?q?=20says=20changed;=20the=20streams=20carry=20no=20data=20of=20t?= =?UTF-8?q?heir=20own,=20are=20open=20to=20the=20project's=20members=20(an?= =?UTF-8?q?yone=20for=20a=20public=20project,=20a=20404=20otherwise,=20as?= =?UTF-8?q?=20the=20pages),=20gather=20a=20burst=20of=20notifications=20in?= =?UTF-8?q?to=20one=20event,=20say=20changed=20after=20a=20reconnection=20?= =?UTF-8?q?or=20when=20they=20fell=20behind,=20and=20end=20after=2030=20mi?= =?UTF-8?q?nutes=20so=20the=20browser=20reconnects=20and=20access=20is=20c?= =?UTF-8?q?hecked=20again;=20BuildChanged,=20a=20new=20build=20and=20a=20b?= =?UTF-8?q?uild=20starting=20to=20process=20notify=20build:=20and=20pr?= =?UTF-8?q?oject:;=20the=20frontend's=20useLive=20hook=20invalidates?= =?UTF-8?q?=20the=20page's=20queries=20and=20the=20pages=20poll=20only=20w?= =?UTF-8?q?hile=20no=20stream=20is=20open=20(today's=20server=20has=20none?= =?UTF-8?q?);=20design=20doc?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/src/http/api/builds.rs | 2 + app/src/http/live.rs | 155 ++++++++++++++++++++ app/src/http/mod.rs | 1 + app/src/lib.rs | 5 +- app/tests/live_pages.rs | 95 ++++++++++++ docs/design.md | 6 + server/frontend/src/__tests__/live.test.tsx | 90 ++++++++++++ server/frontend/src/api/hooks.ts | 17 ++- server/frontend/src/api/live.ts | 33 +++++ 9 files changed, 400 insertions(+), 4 deletions(-) create mode 100644 app/src/http/live.rs create mode 100644 app/tests/live_pages.rs create mode 100644 server/frontend/src/__tests__/live.test.tsx create mode 100644 server/frontend/src/api/live.ts diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index a0b33441..4a65e998 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, + #[env("VISUALCI_LIVE_STREAM_SECONDS")] + pub seconds: Option, +} + +pub fn routes(route: &mut Router) { + route.get("/api/ui/orgs/{org}/projects/{project}/live", project_live); + route.get("/api/ui/orgs/{org}/projects/{project}/builds/{number}/live", build_live); +} + +/// The topic of a project's builds list. +#[must_use] +pub fn project_topic(project_id: i64) -> String { + format!("project:{project_id}") +} + +/// The topic of one build. +#[must_use] +pub fn build_topic(build_id: i64) -> String { + format!("build:{build_id}") +} + +/// `GET /api/ui/orgs/{org}/projects/{project}/live` +pub async fn project_live( + Params((org, project)): Params<(String, String)>, + live: laravel::config::Section, + request: Request, +) -> laravel::Result { + let project = readable(&request, &org, &project).await?; + stream_of(&live, vec![project_topic(project.id)]) +} + +/// `GET /api/ui/orgs/{org}/projects/{project}/builds/{number}/live` +pub async fn build_live( + Params((org, project, number)): Params<(String, String, i32)>, + live: laravel::config::Section, + request: Request, +) -> laravel::Result { + let project = readable(&request, &org, &project).await?; + 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 build = build.ok_or_else(|| laravel::abort(404))?; + stream_of(&live, vec![build_topic(build)]) +} + +/// The project, when the person (or a guest, for a public project) may read it; a 404 otherwise. +async fn readable(request: &Request, org: &str, project: &str) -> laravel::Result { + let project = crate::http::api::project_by_slugs(org, project).await?.ok_or_else(|| laravel::abort(404))?; + if project.public { + return Ok(project); + } + let Some(user) = request.user::().await? else { return Err(laravel::abort(404)) }; + let (org_id, user_id) = (project.organization_id, user.id); + let member: Option = db::query!( + "SELECT EXISTS (SELECT 1 FROM memberships WHERE organization_id = {org_id} AND user_id = {user_id})" + ) + .scalar() + .await?; + if member == Some(true) { Ok(project) } else { Err(laravel::abort(404)) } +} + +fn stream_of(live: &LiveStreams, topics: Vec) -> laravel::Result { + let url = live.database_url.as_deref().ok_or_else(|| laravel::abort_with(503, "live updates aren't set up"))?; + let rx = crate::live::subscribe(url); + let lifetime = live.seconds.map_or(LIFETIME, Duration::from_secs); + Ok(EventStream::new(changes(rx, topics, COALESCE, lifetime)).without_end_event()) +} + +/// A `changed` event for each burst of `topics` (or [`EVERYTHING`], or a missed stretch) that `rx` hears, until +/// `lifetime` has passed. +pub fn changes( + mut rx: broadcast::Receiver, + topics: Vec, + coalesce: Duration, + lifetime: Duration, +) -> impl Stream + Send + 'static { + stream! { + let until = tokio::time::Instant::now() + lifetime; + loop { + let relevant = match tokio::time::timeout_at(until, rx.recv()).await { + Err(_) | Ok(Err(RecvError::Closed)) => break, + Ok(Err(RecvError::Lagged(_))) => true, + Ok(Ok(topic)) => topic == EVERYTHING || topics.contains(&topic), + }; + if !relevant { + continue; + } + // 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() {} + yield Event::new("changed", "{}"); + } + } +} + +/// Tell open pages that something changed: the project's page, and the build's page when there's a build. Best +/// effort: a page that misses it reads again when its stream reconnects. +pub async fn tell_pages(project_id: i64, build_id: Option) { + let topics = build_id.map(build_topic).into_iter().chain([project_topic(project_id)]); + for topic in topics { + if let Err(e) = crate::live::notify(&topic).await { + tracing::warn!(error = %e, project_id, ?build_id, "live updates: couldn't notify open pages"); + } + } +} + +/// A build's state, review or snapshots changed: its page and its project's page read again. +#[laravel::event::listener] +pub async fn tell_open_pages(event: laravel::event::Event) -> laravel::Result<()> { + let build_id = event.build_id; + let project_id: Option = db::query!("SELECT project_id FROM builds WHERE id = {build_id}").scalar().await?; + if let Some(project_id) = project_id { + tell_pages(project_id, Some(build_id)).await; + } + Ok(()) +} diff --git a/app/src/http/mod.rs b/app/src/http/mod.rs index 02b9ee67..79321ab6 100644 --- a/app/src/http/mod.rs +++ b/app/src/http/mod.rs @@ -3,6 +3,7 @@ pub mod api; pub mod gallery; pub mod hosts; +pub mod live; pub mod renderer; pub mod status; diff --git a/app/src/lib.rs b/app/src/lib.rs index 77b131e4..3d067689 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -63,7 +63,10 @@ pub fn configure() -> ApplicationBuilder { }) .with_routing(|routing, _| { routing - .web(auth::routes) + .web(|route| { + auth::routes(route); + http::live::routes(route); + }) .api(http::api::routes) .routes(|route| { route.post("/webhooks/stripe", billing::webhook::handle); diff --git a/app/tests/live_pages.rs b/app/tests/live_pages.rs new file mode 100644 index 00000000..a88bc92e --- /dev/null +++ b/app/tests/live_pages.rs @@ -0,0 +1,95 @@ +//! The web app's live streams: who may follow a project or a build, and what a stream says. A notification never +//! arrives inside a test's rolled-back transaction, so what a stream sends is tested on its own channel. + +use std::time::Duration; + +use app::http::live::{build_topic, changes, project_topic}; +use app::models::{Build, User}; +use app::testing::fixtures; +use laravel::db; +use laravel::model::create; +use laravel::stream::StreamExt; +use laravel::testing::prelude::*; +use tokio::sync::broadcast; + +/// Streams of one second, so a request that's allowed to follow ends. +fn short_streams() -> Application { + app::testing::configure().with_env("VISUALCI_LIVE_STREAM_SECONDS", "1").create() +} + +async fn person(email: &str) -> laravel::Result { + create!(User { pid: laravel::str::uuid7(), name: "Ada", email: email, staff: false }).await +} + +#[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@example.com").await?; + fixtures::member(&org, &ada, "read").await?; + create!(Build { + pid: laravel::str::uuid7(), + project_id: project.id, + number: 1, + commit_sha: "c1", + branch: "main", + base_build_id: None, + }) + .await?; + + let followed = app.get("/api/ui/orgs/acme/projects/web/live").acting_as(&ada).await; + followed.assert_ok().assert_header("content-type", "text/event-stream"); + app.get("/api/ui/orgs/acme/projects/web/builds/1/live").acting_as(&ada).await.assert_ok(); + app.get("/api/ui/orgs/acme/projects/web/builds/2/live").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@example.com").await?; + app.get("/api/ui/orgs/acme/projects/web/live").acting_as(&eve).await.assert_status(404); + app.get("/api/ui/orgs/acme/projects/web/live").header("accept", "application/json").await.assert_status(404); + app.get("/api/ui/orgs/acme/projects/nothing/live").acting_as(&eve).await.assert_status(404); + Ok(()) +} + +#[laravel::test(app = short_streams)] +async fn anyone_follows_a_public_project(app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let project = fixtures::project(&org, "demo").await?; + let id = project.id; + db::query!("UPDATE projects SET public = true WHERE id = {id}").update().await?; + app.get("/api/ui/orgs/acme/projects/demo/live").header("accept", "application/json").await.assert_ok(); + Ok(()) +} + +#[tokio::test] +async fn a_burst_of_changes_is_one_event_and_other_topics_are_not_heard() { + let (tx, rx) = broadcast::channel(16); + let events = changes(rx, vec![build_topic(7)], Duration::from_millis(50), Duration::from_millis(400)); + 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(app::live::EVERYTHING.to_string()).unwrap(); + }; + let (events, ()) = tokio::join!(events.collect::>(), sent); + assert_eq!(events.len(), 2, "one for the burst, one for the re-read; nothing for other topics"); +} + +#[tokio::test] +async fn a_stream_that_fell_behind_reads_again() { + let (tx, rx) = broadcast::channel(2); + for n in 0..5 { + tx.send(format!("build:{n}")).unwrap(); + } + let events: Vec<_> = + changes(rx, vec![build_topic(99)], Duration::from_millis(10), Duration::from_millis(200)).collect().await; + assert_eq!(events.len(), 1, "missed notifications might have been its own"); +} diff --git a/docs/design.md b/docs/design.md index fbcc5c47..e003425f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -497,6 +497,12 @@ DocSpring's own ops agents (triage, support) work on customers' issues through a - Backend: **Loco (Rust) + Postgres** (its own CNPG cluster: one instance, WAL and base backups to its own R2 bucket) + **Loco's pg queue**, matching Talira, so the deploy setup, monitoring and playbooks carry over. - Frontend: React + TanStack (Router, Query), from the original note, served by the backend or as static assets. +- 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`) and every replica passes it on to its + server-sent event streams: a project page and a build page each hold one stream (`…/live`) and read their data + again when it says `changed`. The streams carry no data of their own, so they show nobody more than the page's own + reads do. A page polls only while it has no open stream. LISTEN needs a direct or session-mode connection to + Postgres, not a transaction-mode PgBouncer. - Workers: the Rust diff worker 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/server/frontend/src/__tests__/live.test.tsx b/server/frontend/src/__tests__/live.test.tsx new file mode 100644 index 00000000..2eca28b5 --- /dev/null +++ b/server/frontend/src/__tests__/live.test.tsx @@ -0,0 +1,90 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { 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 last: FakeSource | null = null + readyState = FakeSource.CONNECTING + closed = false + listeners: Record void)[]> = {} + constructor(readonly url: string) { + FakeSource.last = this + } + 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())) + } +} +vi.stubGlobal('EventSource', FakeSource) + +afterEach(() => { + FakeSource.last = null +}) + +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 } +} + +describe('a page following its live stream', () => { + it('reads its data again on each change, and after a reconnection', () => { + const { invalidate, view } = setup('/api/ui/orgs/acme/projects/web/live') + const source = FakeSource.last! + expect(source.url).toBe('/api/ui/orgs/acme/projects/web/live') + expect(view.container.textContent).toBe('polling') + + source.fire('open', FakeSource.OPEN) + expect(view.container.textContent).toBe('live') + expect(invalidate).not.toHaveBeenCalled() + + source.fire('changed') + expect(invalidate.mock.calls.map((c) => c[0]?.queryKey)).toEqual([ + ['project', 'acme', 'web'], + ['pull', 'acme', 'web'], + ]) + + invalidate.mockClear() + source.fire('error', FakeSource.CONNECTING) + expect(view.container.textContent).toBe('polling') + source.fire('open', FakeSource.OPEN) + expect(invalidate).toHaveBeenCalledTimes(2) + expect(view.container.textContent).toBe('live') + + view.unmount() + expect(source.closed).toBe(true) + }) + + it('keeps polling when the server has no live updates', () => { + const { view } = setup('/api/ui/orgs/acme/projects/web/live') + FakeSource.last!.fire('error', FakeSource.CLOSED) + expect(view.container.textContent).toBe('polling') + }) + + it('opens nothing without a path', () => { + setup(null) + expect(FakeSource.last).toBeNull() + }) +}) diff --git a/server/frontend/src/api/hooks.ts b/server/frontend/src/api/hooks.ts index 423be142..b7c36837 100644 --- a/server/frontend/src/api/hooks.ts +++ b/server/frontend/src/api/hooks.ts @@ -1,5 +1,6 @@ import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { ApiError, del, get, patch, post, request } from './client' +import { useLive } from './live' import type { EmailPreview, FailedEmail, @@ -79,11 +80,14 @@ export function useOrg(org: string) { const live = (state: string | undefined) => state === 'receiving' || state === 'processing' 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 ? `${projectPath(org, project)}/live` : 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) => (!streaming && q.state.data?.builds.some((b) => live(b.state)) ? 4000 : false), }) } @@ -91,11 +95,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(`${buildPath(org, project, n)}/live`, [ + 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) => (!streaming && live(q.state.data?.build.state) ? 3000 : IMAGE_URL_TTL), }) } diff --git a/server/frontend/src/api/live.ts b/server/frontend/src/api/live.ts new file mode 100644 index 00000000..7fda6a56 --- /dev/null +++ b/server/frontend/src/api/live.ts @@ -0,0 +1,33 @@ +import { type QueryKey, useQueryClient } from '@tanstack/react-query' +import { useEffect, useState } from 'react' + +/** + * Follow a page's live stream (`…/live`, server-sent events): read `keys` again whenever the server says `changed`, + * and after each reconnection, since nothing missed meanwhile is replayed. Returns whether the stream is open, so the + * page polls only while it isn't (a server without live updates answers 404, and the browser stops trying). + */ +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 + const source = new EventSource(path) + let opened = false + const refresh = () => { + for (const queryKey of JSON.parse(id) as QueryKey[]) void qc.invalidateQueries({ queryKey }) + } + source.addEventListener('open', () => { + if (opened) refresh() + opened = true + setOpen(true) + }) + source.addEventListener('changed', refresh) + source.addEventListener('error', () => setOpen(source.readyState === EventSource.OPEN)) + return () => { + source.close() + setOpen(false) + } + }, [path, id, qc]) + return open +}