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
1 change: 1 addition & 0 deletions app/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,12 @@ 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"
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" }
Expand Down
1 change: 1 addition & 0 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
226 changes: 226 additions & 0 deletions app/src/live.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
//! 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.
//! - 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.
//!
//! 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 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)]
pub struct LiveDatabase {
#[env("DATABASE_URL")]
pub url: Option<String>,
}

/// Tell every replica's subscribers that `topic` changed (`build:42`, `project:7`). On commit, inside a transaction.
///
/// # Errors
/// 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(())
}

struct Hub {
tx: broadcast::Sender<String>,
ready: watch::Receiver<bool>,
}

static HUB: OnceLock<Hub> = 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);
let (ready_tx, ready) = watch::channel(false);
tokio::spawn(supervise(database_url.to_string(), tx.clone(), ready_tx));
Hub { tx, ready }
})
}

/// 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<String> {
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<String>, ready: watch::Sender<bool>) {
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<String>, ready: watch::Sender<bool>) {
let mut wait = Duration::from_millis(500);
loop {
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.try_recv().await {
// No subscribers right now is fine: `send` only fails then
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 failed");
break;
}
}
}
true
}
Err(e) => {
tracing::warn!(error = %e, "live updates: LISTEN failed");
false
}
},
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<String>) -> 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<String>, 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 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;

#[job]
impl CheckLive {
async fn handle(self, database: laravel::config::Section<LiveDatabase>) -> laravel::Result<()> {
let Some(url) = database.url.as_deref().filter(|u| !u.is_empty()) else { return Ok(()) };
let mut rx = subscribe(url);
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)
}
}

#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
schedule.job(CheckLive).every_minute().without_overlapping();
}
32 changes: 32 additions & 0 deletions app/tests/live.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//! 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);
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");

// 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");
}
Loading