Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions app/src/http/api/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ pub async fn create(auth: Result<ApiProject, ApiError>, Body(params): Body<Creat
// task), so they don't sit "receiving" beside this one.
crate::domain::processing::expire_abandoned(Some(project.id)).await?;
let build = domain::create(&project, &params, creator).await.map_err(ApiError::from)?;
crate::http::live::tell_pages(project.id, None).await;
Ok(BuildResponse::new(&build, &project, &organization)
.with_blocked(&build, &project, &organization)
.await?)
Expand Down Expand Up @@ -267,6 +268,7 @@ pub async fn finalize(
let build =
if was_receiving { crate::domain::processing::stop_if_out_of_credits(build).await? } else { build };
if was_receiving && build.state == "processing" {
crate::http::live::tell_pages(project.id, Some(build.id)).await;
crate::jobs::process_build::ProcessBuild { build_id: build.id }.dispatch().await?;
} else if was_receiving && build.state == "failed" {
crate::events::BuildChanged { build_id: build.id }.dispatch().await?;
Expand Down
155 changes: 155 additions & 0 deletions app/src/http/live.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
//! The web app's live updates (sc-8897, sc-8900): a project page and a build page each hold one server-sent event
//! stream, and read their data again when it says `changed`. The stream carries no data of its own, only "look
//! again", so it can't show anyone more than the page's own reads do; each read checks access as usual.
//!
//! - `GET /api/ui/orgs/{org}/projects/{project}/live`: the project's builds list changed (a build was created, or a
//! build's state, review or counts changed).
//! - `GET /api/ui/orgs/{org}/projects/{project}/builds/{number}/live`: that build, its snapshots or its pull request's
//! changes changed.
//!
//! Anyone who can read the project can follow it: its members, and anyone for a public project. Others get a 404, as
//! the project's own pages do. A burst of changes (a build's pages finishing one by one) arrives as one `changed`
//! within [`COALESCE`]. When notifications may have been missed (the listener reconnected, or this stream fell
//! behind), the stream says `changed` too. Each stream ends after [`LIFETIME`] without an end event, so the browser
//! reconnects and access is checked again; the browser reads again after each reconnection (the `open` event), since
//! nothing is replayed.

use std::time::Duration;

use laravel::db;
use laravel::http::Request;
use laravel::http::sse::{Event, EventStream};
use laravel::prelude::*;
use laravel::stream::{Stream, stream};
use tokio::sync::broadcast::{self, error::RecvError, error::TryRecvError};

use crate::live::EVERYTHING;
use crate::models::{Project, User};

/// How long a burst of changes is gathered into one `changed`.
pub const COALESCE: Duration = Duration::from_millis(300);
/// How long one stream lasts before the browser reconnects (and access is checked again), unless
/// `VISUALCI_LIVE_STREAM_SECONDS` says otherwise.
pub const LIFETIME: Duration = Duration::from_secs(30 * 60);

/// Where the streams listen, and how long each lasts.
#[derive(Clone, laravel::config::Section)]
pub struct LiveStreams {
#[env("DATABASE_URL")]
pub database_url: Option<String>,
#[env("VISUALCI_LIVE_STREAM_SECONDS")]
pub seconds: Option<u64>,
}

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<LiveStreams>,
request: Request,
) -> laravel::Result<EventStream> {
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<LiveStreams>,
request: Request,
) -> laravel::Result<EventStream> {
let project = readable(&request, &org, &project).await?;
let project_id = project.id;
let build: Option<i64> =
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<Project> {
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::<User>().await? else { return Err(laravel::abort(404)) };
let (org_id, user_id) = (project.organization_id, user.id);
let member: Option<bool> = 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<String>) -> laravel::Result<EventStream> {
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<String>,
topics: Vec<String>,
coalesce: Duration,
lifetime: Duration,
) -> impl Stream<Item = Event> + 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<i64>) {
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<crate::events::BuildChanged>) -> laravel::Result<()> {
let build_id = event.build_id;
let project_id: Option<i64> = 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(())
}
1 change: 1 addition & 0 deletions app/src/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
pub mod api;
pub mod gallery;
pub mod hosts;
pub mod live;
pub mod renderer;
pub mod status;

Expand Down
5 changes: 4 additions & 1 deletion app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
95 changes: 95 additions & 0 deletions app/tests/live_pages.rs
Original file line number Diff line number Diff line change
@@ -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<User> {
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::<Vec<_>>(), 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");
}
6 changes: 6 additions & 0 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
90 changes: 90 additions & 0 deletions server/frontend/src/__tests__/live.test.tsx
Original file line number Diff line number Diff line change
@@ -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<string, (() => 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 <p>{open ? 'live' : 'polling'}</p>
}

function setup(path: string | null) {
const qc = new QueryClient()
const invalidate = vi.spyOn(qc, 'invalidateQueries')
const view = render(
<QueryClientProvider client={qc}>
<Page path={path} />
</QueryClientProvider>,
)
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()
})
})
Loading
Loading