From 5d4be6f969a4dcd17bf3e7a53d9b20d55e14d178 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:48:47 +1300 Subject: [PATCH 1/3] app/: live updates' transport (sc-8897, sc-8900): Postgres LISTEN/NOTIFY on one channel, one listener per process (started by the first subscriber, reconnecting with backoff) fanning topics out to subscribers; notify() is delivered on commit; topics only say 'look again', so a missed one costs a moment and payloads carry no data; CheckLive notifies itself every minute and pushes VISUALCI_LIVE_HEARTBEAT only when it arrives --- app/Cargo.lock | 1 + app/Cargo.toml | 1 + app/src/lib.rs | 1 + app/src/live.rs | 121 ++++++++++++++++++++++++++++++++++++++++++++++ app/tests/live.rs | 39 +++++++++++++++ 5 files changed, 163 insertions(+) create mode 100644 app/src/live.rs create mode 100644 app/tests/live.rs diff --git a/app/Cargo.lock b/app/Cargo.lock index 8c808fac..7a9f970c 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -4751,6 +4751,7 @@ dependencies = [ "serde_json", "sha2 0.10.9", "snapshot-diff", + "sqlx", "tokio", "tracing", "visualci-core", diff --git a/app/Cargo.toml b/app/Cargo.toml index a27a2155..69caf13b 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -40,6 +40,7 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg", reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } rusty-s3 = "0.12" globset = "0.4" +sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "tls-rustls-ring", "postgres"] } tracing = "0.1" # VisualCI's own crates, shared with the CLI. visualci-core = { path = "../crates/visualci-core" } diff --git a/app/src/lib.rs b/app/src/lib.rs index 1df75144..e0dbbcbd 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -8,6 +8,7 @@ pub mod forge; pub mod heartbeat; pub mod http; pub mod listeners; +pub mod live; pub mod models; pub mod notify; #[path = "../database/seeders/mod.rs"] diff --git a/app/src/live.rs b/app/src/live.rs new file mode 100644 index 00000000..0f597056 --- /dev/null +++ b/app/src/live.rs @@ -0,0 +1,121 @@ +//! Live updates between replicas (sc-8897, sc-8900): Postgres LISTEN/NOTIFY, fanned out in each process to whoever is +//! streaming server-sent events (`EventStream`) to a browser or the CLI's `--wait`. No WebSockets and no broadcaster +//! service: the database every replica already shares carries the signal. +//! +//! - [`notify`] sends a topic, such as `build:42`. Inside a transaction, Postgres delivers it on commit, so nobody is +//! told about a change they can't read yet. +//! - [`subscribe`] gets every topic sent from now on, from any replica. One connection per process LISTENs; it starts +//! with the first subscriber and reconnects by itself after an error. +//! - A notification only says "look again": the stream's handler reads the current state, so a missed one costs a +//! moment, never a wrong answer, and payloads never carry data a subscriber mightn't be allowed to see. +//! +//! [`CheckLive`] sends itself a notification every minute and pushes `VISUALCI_LIVE_HEARTBEAT` only when it arrives, +//! so a listener that's connected but deaf fails the heartbeat. + +use std::sync::OnceLock; +use std::time::Duration; + +use laravel::db; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; +use tokio::sync::broadcast; + +/// The one Postgres channel; topics travel as its payloads. +pub const CHANNEL: &str = "visualci_live"; + +/// Where the listener connects: the application's database. +#[derive(Clone, laravel::config::Section)] +pub struct LiveDatabase { + #[env("DATABASE_URL")] + pub url: Option, +} + +/// Tell every replica's subscribers that `topic` changed (`build:42`, `project:7`). On commit, inside a transaction. +/// +/// # Errors +/// On a database error. +pub async fn notify(topic: &str) -> laravel::Result<()> { + db::query!("SELECT pg_notify({CHANNEL}, {topic})").statement().await?; + Ok(()) +} + +static HUB: OnceLock> = OnceLock::new(); + +/// Every topic sent from now on. The first call starts this process's listener on `database_url`. +pub fn subscribe(database_url: &str) -> broadcast::Receiver { + HUB.get_or_init(|| { + let (tx, _) = broadcast::channel(1024); + tokio::spawn(listen(database_url.to_string(), tx.clone())); + tx + }) + .subscribe() +} + +/// LISTEN, forwarding each payload; on any error wait a moment and connect again, for as long as the process runs. +async fn listen(url: String, tx: broadcast::Sender) { + let mut wait = Duration::from_millis(500); + loop { + match sqlx::postgres::PgListener::connect(&url).await { + Ok(mut listener) => match listener.listen(CHANNEL).await { + Ok(()) => { + wait = Duration::from_millis(500); + loop { + match listener.recv().await { + // No subscribers right now is fine: `send` only fails then + Ok(n) => drop(tx.send(n.payload().to_string())), + Err(e) => { + tracing::warn!(error = %e, "live updates: the listener lost its connection"); + break; + } + } + } + } + Err(e) => tracing::warn!(error = %e, "live updates: LISTEN failed"), + }, + Err(e) => tracing::warn!(error = %e, "live updates: can't connect"), + } + tokio::time::sleep(wait).await; + wait = (wait * 2).min(Duration::from_secs(30)); + } +} + +/// Wait up to `within` for `topic` on `rx`, skipping others. `false` when it doesn't come (or the hub closed). +pub async fn arrives(rx: &mut broadcast::Receiver, topic: &str, within: Duration) -> bool { + tokio::time::timeout(within, async { + loop { + match rx.recv().await { + Ok(t) if t == topic => return true, + Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {} + Err(broadcast::error::RecvError::Closed) => return false, + } + } + }) + .await + .unwrap_or(false) +} + +/// Every minute: notify a probe topic and check this process's listener hears it, then push the heartbeat. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct CheckLive; + +#[job] +impl CheckLive { + async fn handle(self, database: laravel::config::Section) -> laravel::Result<()> { + let Some(url) = database.url.as_deref().filter(|u| !u.is_empty()) else { return Ok(()) }; + let mut rx = subscribe(url); + let probe = format!("probe:{}", laravel::str::random(12)); + let sent = notify(&probe).await; + let health = match sent { + Err(e) => Err(e.to_string()), + Ok(()) if arrives(&mut rx, &probe, Duration::from_secs(10)).await => Ok(()), + Ok(()) => Err("a notification didn't arrive within 10 seconds".to_string()), + }; + crate::heartbeat::push("VISUALCI_LIVE_HEARTBEAT", health.clone()).await; + health.map_err(laravel::Error::msg) + } +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(CheckLive).every_minute().without_overlapping(); +} diff --git a/app/tests/live.rs b/app/tests/live.rs new file mode 100644 index 00000000..b96a544f --- /dev/null +++ b/app/tests/live.rs @@ -0,0 +1,39 @@ +//! Live updates: a topic notified from any connection reaches every subscriber in this process, and only once it's +//! committed. Run against the database itself, outside a test's rolled-back transaction, where NOTIFY never arrives. + +use std::time::Duration; + +use sqlx::Connection; + +/// The test server's `postgres` database: LISTEN and NOTIFY only need both sides on one database, and the tests' own +/// databases are per-test copies. +fn database() -> String { + let url = std::env::var("VISUALCI_APP_TEST_DATABASE_URL") + .unwrap_or_else(|_| "postgres://loco:loco@127.0.0.1:55433/visualci_app_test".to_string()); + let server = url.rsplit_once('/').map_or(url.as_str(), |(server, _)| server); + format!("{server}/postgres") +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_committed_notification_reaches_subscribers() { + let url = database(); + let mut rx = app::live::subscribe(&url); + let mut other = sqlx::PgConnection::connect(&url).await.expect("the test database"); + // Give the listener a moment to LISTEN before anything is sent + let mut tries = 0; + loop { + sqlx::query("SELECT pg_notify($1, 'probe:ready')").bind(app::live::CHANNEL).execute(&mut other).await.unwrap(); + if app::live::arrives(&mut rx, "probe:ready", Duration::from_millis(500)).await { + break; + } + tries += 1; + assert!(tries < 20, "the listener never started"); + } + + // Inside a transaction: nothing until it commits + let mut tx = other.begin().await.unwrap(); + sqlx::query("SELECT pg_notify($1, 'build:42')").bind(app::live::CHANNEL).execute(&mut *tx).await.unwrap(); + assert!(!app::live::arrives(&mut rx, "build:42", Duration::from_millis(300)).await, "not before the commit"); + tx.commit().await.unwrap(); + assert!(app::live::arrives(&mut rx, "build:42", Duration::from_secs(5)).await, "after the commit"); +} From 21ed9c8b2ce756f24ae77aa9e91b7ae30731775c Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:25:42 +1300 Subject: [PATCH 2/3] Live updates, review fixes: the listener uses try_recv, and after each fresh LISTEN and each silent reconnect tells subscribers to re-read everything (*), as they must on Lagged too; every process probes its own listener each minute over a separate connection and restarts it when the probe doesn't come back in ten seconds (a half-open connection), with live::healthy() for its health check; the queue worker's heartbeat waits for the listener to be ready before probing; topics are capped well under Postgres's 8000 bytes; documented: LISTEN needs a direct or session-mode connection, not a transaction-mode PgBouncer --- app/src/live.rs | 161 ++++++++++++++++++++++++++++++++++++++-------- app/tests/live.rs | 13 +--- 2 files changed, 136 insertions(+), 38 deletions(-) diff --git a/app/src/live.rs b/app/src/live.rs index 0f597056..e12b3d12 100644 --- a/app/src/live.rs +++ b/app/src/live.rs @@ -5,23 +5,38 @@ //! - [`notify`] sends a topic, such as `build:42`. Inside a transaction, Postgres delivers it on commit, so nobody is //! told about a change they can't read yet. //! - [`subscribe`] gets every topic sent from now on, from any replica. One connection per process LISTENs; it starts -//! with the first subscriber and reconnects by itself after an error. -//! - A notification only says "look again": the stream's handler reads the current state, so a missed one costs a -//! moment, never a wrong answer, and payloads never carry data a subscriber mightn't be allowed to see. +//! with the first subscriber. +//! - A notification only says "look again": the stream's handler reads the current state, so payloads never carry data +//! a subscriber mightn't be allowed to see. Whenever notifications may have been missed, subscribers get +//! [`EVERYTHING`] and must re-read everything they show: after the listener (re)connects, and when a subscriber falls +//! behind (`RecvError::Lagged`). +//! - Each process checks its own listener every minute: it notifies a probe topic over a separate connection and, when +//! the probe doesn't come back within ten seconds (a half-open connection that hears nothing), restarts the listener. +//! [`healthy`] says whether the last probe came back, for the process's health check; [`CheckLive`] pushes +//! `VISUALCI_LIVE_HEARTBEAT` from the queue worker the same way. //! -//! [`CheckLive`] sends itself a notification every minute and pushes `VISUALCI_LIVE_HEARTBEAT` only when it arrives, -//! so a listener that's connected but deaf fails the heartbeat. +//! The connection must reach Postgres directly or through a session-mode pooler: LISTEN doesn't work through a +//! transaction-mode PgBouncer. use std::sync::OnceLock; +use std::sync::atomic::{AtomicI64, Ordering}; use std::time::Duration; use laravel::db; use laravel::queue::{Queueable, job}; use laravel::schedule::{self, Schedule}; -use tokio::sync::broadcast; +use sqlx::Connection; +use tokio::sync::{broadcast, watch}; /// The one Postgres channel; topics travel as its payloads. pub const CHANNEL: &str = "visualci_live"; +/// What subscribers get when they may have missed something: re-read everything. +pub const EVERYTHING: &str = "*"; +/// Postgres refuses payloads of 8000 bytes or more; topics are far shorter. +pub const MAX_TOPIC: usize = 1000; +/// How often each process probes its listener, and how long a probe may take. +const PROBE_EVERY: Duration = Duration::from_secs(60); +const PROBE_WITHIN: Duration = Duration::from_secs(10); /// Where the listener connects: the application's database. #[derive(Clone, laravel::config::Section)] @@ -33,52 +48,138 @@ pub struct LiveDatabase { /// Tell every replica's subscribers that `topic` changed (`build:42`, `project:7`). On commit, inside a transaction. /// /// # Errors -/// On a database error. +/// On a database error, or a topic longer than [`MAX_TOPIC`]. pub async fn notify(topic: &str) -> laravel::Result<()> { + if topic.len() > MAX_TOPIC { + return Err(laravel::Error::msg(format!("a live topic of {} bytes; topics name what changed", topic.len()))); + } db::query!("SELECT pg_notify({CHANNEL}, {topic})").statement().await?; Ok(()) } -static HUB: OnceLock> = OnceLock::new(); +struct Hub { + tx: broadcast::Sender, + ready: watch::Receiver, +} -/// Every topic sent from now on. The first call starts this process's listener on `database_url`. -pub fn subscribe(database_url: &str) -> broadcast::Receiver { +static HUB: OnceLock = OnceLock::new(); +/// When this process's last probe came back (Unix seconds); 0 before the first. +static LAST_PROBE_OK: AtomicI64 = AtomicI64::new(0); + +fn hub(database_url: &str) -> &'static Hub { HUB.get_or_init(|| { let (tx, _) = broadcast::channel(1024); - tokio::spawn(listen(database_url.to_string(), tx.clone())); - tx + let (ready_tx, ready) = watch::channel(false); + tokio::spawn(supervise(database_url.to_string(), tx.clone(), ready_tx)); + Hub { tx, ready } }) - .subscribe() } -/// LISTEN, forwarding each payload; on any error wait a moment and connect again, for as long as the process runs. -async fn listen(url: String, tx: broadcast::Sender) { +/// Every topic sent from now on. The first call starts this process's listener on `database_url`. +pub fn subscribe(database_url: &str) -> broadcast::Receiver { + hub(database_url).tx.subscribe() +} + +/// Wait up to `within` for this process's listener to be LISTENing. `false` when it isn't by then. +pub async fn ready(database_url: &str, within: Duration) -> bool { + let mut ready = hub(database_url).ready.clone(); + tokio::time::timeout(within, ready.wait_for(|r| *r)).await.is_ok_and(|r| r.is_ok()) +} + +/// Whether this process's listener answered its last probe within the last three minutes. +#[must_use] +pub fn healthy() -> bool { + let last = LAST_PROBE_OK.load(Ordering::Relaxed); + last > 0 && laravel::now().timestamp().as_second() - last < 180 +} + +/// 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 { + let listener = tokio::spawn(listen(url.clone(), tx.clone(), ready.clone())); + let mut probes = tokio::time::interval(PROBE_EVERY); + probes.tick().await; + loop { + probes.tick().await; + if listener.is_finished() { + break; + } + if probe(&url, &tx).await { + LAST_PROBE_OK.store(laravel::now().timestamp().as_second(), Ordering::Relaxed); + } else { + tracing::warn!("live updates: a probe didn't come back; restarting the listener"); + break; + } + } + listener.abort(); + let _ = ready.send(false); + tokio::time::sleep(Duration::from_secs(1)).await; + } +} + +/// LISTEN, forwarding each payload. Tells subscribers to re-read everything after each (re)connection, since +/// notifications sent meanwhile are gone. Returns when the connection can't be used; `supervise` starts it again. +async fn listen(url: String, tx: broadcast::Sender, ready: watch::Sender) { let mut wait = Duration::from_millis(500); loop { - match sqlx::postgres::PgListener::connect(&url).await { + let connected = match sqlx::postgres::PgListener::connect(&url).await { Ok(mut listener) => match listener.listen(CHANNEL).await { Ok(()) => { wait = Duration::from_millis(500); + let _ = ready.send(true); + let _ = tx.send(EVERYTHING.to_string()); loop { - match listener.recv().await { + match listener.try_recv().await { // No subscribers right now is fine: `send` only fails then - Ok(n) => drop(tx.send(n.payload().to_string())), + Ok(Some(n)) => drop(tx.send(n.payload().to_string())), + // The connection dropped and sqlx reconnected and LISTENs again: anything sent in between + // is lost + Ok(None) => drop(tx.send(EVERYTHING.to_string())), Err(e) => { - tracing::warn!(error = %e, "live updates: the listener lost its connection"); + tracing::warn!(error = %e, "live updates: the listener failed"); break; } } } + true + } + Err(e) => { + tracing::warn!(error = %e, "live updates: LISTEN failed"); + false } - Err(e) => tracing::warn!(error = %e, "live updates: LISTEN failed"), }, - Err(e) => tracing::warn!(error = %e, "live updates: can't connect"), + Err(e) => { + tracing::warn!(error = %e, "live updates: can't connect"); + false + } + }; + let _ = ready.send(false); + if connected { + return; } tokio::time::sleep(wait).await; wait = (wait * 2).min(Duration::from_secs(30)); } } +/// Notify a fresh probe topic over a connection of its own and wait for this process's listener to hear it. +async fn probe(url: &str, tx: &broadcast::Sender) -> bool { + let mut rx = tx.subscribe(); + let topic = format!("probe:{}", laravel::str::random(12)); + let sent = async { + let mut connection = sqlx::PgConnection::connect(url).await?; + sqlx::query("SELECT pg_notify($1, $2)").bind(CHANNEL).bind(&topic).execute(&mut connection).await?; + connection.close().await + }; + match sent.await { + Ok(()) => arrives(&mut rx, &topic, PROBE_WITHIN).await, + Err(e) => { + tracing::warn!(error = %e, "live updates: the probe couldn't be sent"); + false + } + } +} + /// Wait up to `within` for `topic` on `rx`, skipping others. `false` when it doesn't come (or the hub closed). pub async fn arrives(rx: &mut broadcast::Receiver, topic: &str, within: Duration) -> bool { tokio::time::timeout(within, async { @@ -94,7 +195,8 @@ pub async fn arrives(rx: &mut broadcast::Receiver, topic: &str, within: .unwrap_or(false) } -/// Every minute: notify a probe topic and check this process's listener hears it, then push the heartbeat. +/// Every minute in the queue worker: wait for its listener to be ready, notify a probe topic through the application's +/// database, check the listener hears it, and push the heartbeat. #[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct CheckLive; @@ -103,12 +205,15 @@ impl CheckLive { async fn handle(self, database: laravel::config::Section) -> laravel::Result<()> { let Some(url) = database.url.as_deref().filter(|u| !u.is_empty()) else { return Ok(()) }; let mut rx = subscribe(url); - let probe = format!("probe:{}", laravel::str::random(12)); - let sent = notify(&probe).await; - let health = match sent { - Err(e) => Err(e.to_string()), - Ok(()) if arrives(&mut rx, &probe, Duration::from_secs(10)).await => Ok(()), - Ok(()) => Err("a notification didn't arrive within 10 seconds".to_string()), + let health = if ready(url, PROBE_WITHIN).await { + let probe = format!("probe:{}", laravel::str::random(12)); + match notify(&probe).await { + Err(e) => Err(e.to_string()), + Ok(()) if arrives(&mut rx, &probe, PROBE_WITHIN).await => Ok(()), + Ok(()) => Err("a notification didn't arrive within 10 seconds".to_string()), + } + } else { + Err("the listener isn't LISTENing".to_string()) }; crate::heartbeat::push("VISUALCI_LIVE_HEARTBEAT", health.clone()).await; health.map_err(laravel::Error::msg) diff --git a/app/tests/live.rs b/app/tests/live.rs index b96a544f..594e5e06 100644 --- a/app/tests/live.rs +++ b/app/tests/live.rs @@ -18,17 +18,10 @@ fn database() -> String { async fn a_committed_notification_reaches_subscribers() { let url = database(); let mut rx = app::live::subscribe(&url); + assert!(app::live::ready(&url, Duration::from_secs(10)).await, "the listener LISTENs"); + // Connecting tells subscribers to re-read everything, since anything sent before is gone + assert!(app::live::arrives(&mut rx, app::live::EVERYTHING, Duration::from_secs(5)).await); let mut other = sqlx::PgConnection::connect(&url).await.expect("the test database"); - // Give the listener a moment to LISTEN before anything is sent - let mut tries = 0; - loop { - sqlx::query("SELECT pg_notify($1, 'probe:ready')").bind(app::live::CHANNEL).execute(&mut other).await.unwrap(); - if app::live::arrives(&mut rx, "probe:ready", Duration::from_millis(500)).await { - break; - } - tries += 1; - assert!(tries < 20, "the listener never started"); - } // Inside a transaction: nothing until it commits let mut tx = other.begin().await.unwrap(); From 8f8c8a32edd95751869a663bbe383b70ad071804 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 05:00:43 +1300 Subject: [PATCH 3/3] Rebased on main: Cargo.lock resolved from main's, and the boot checks and dependencies merged --- app/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Cargo.toml b/app/Cargo.toml index 69caf13b..949af111 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -35,7 +35,7 @@ jsonwebtoken = "9" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" -tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } rusty-s3 = "0.12"