//! Live updates: a change counter per topic, and the server-sent event stream that carries it to //! the browser. //! //! A write that changes what a page shows calls [`LiveHub::bump`] after it commits. A stream that //! subscribed to that topic wakes and sends one `changed` event without data. The browser then //! fetches the page again (`nav.js`), so an event carries no state and a missed one cannot leave the //! page wrong for long. Nothing polls, and a topic nobody listens to is dropped. //! //! The hub is not a queue and not an authorisation check. Each route that opens a stream //! authenticates and authorises first, then calls [`stream_changes`]. //! //! Every stream ends when the process stops (the stop flag in [`AppState`]), so a shutdown does not wait //! for a browser to close its connection. No stream lives longer than [`MAX_STREAM_LIFE`]: the browser //! reconnects, and each new connection authenticates again. use std::collections::HashMap; use std::future::Future; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::Duration; use futures_util::{Stream, StreamExt, future::select_all, stream}; use im_core::store::Store; use tokio::sync::{OwnedSemaphorePermit, watch}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::sse::{Event, KeepAlive, Sse}; use topcoat::router::response::{IntoResponse, Response}; use topcoat::router::{HeaderValue, StatusCode, route}; use crate::api::api_error; use crate::api::directory::{SlotGuard, StreamSlots}; use crate::auth::current_user; use crate::state::AppState; /// How long a client waits before it reconnects when a stream ends. Sent once, at the start. pub const STREAM_RETRY: Duration = Duration::from_millis(1000); /// Silence after which the server sends a keep-alive comment, so proxies keep the stream open. pub const KEEP_ALIVE: Duration = Duration::from_secs(30); /// Longest a stream lives, whatever happens on it. The browser reconnects after it, and a reconnect /// authenticates and authorises again, so a session that ended or lost its role is not kept by a stream. pub const MAX_STREAM_LIFE: Duration = Duration::from_secs(60 * 60); /// How often an idle `changed` stream runs its fingerprint anyway, so a viewer who signed out or lost /// access is noticed even when no topic of the stream changes. pub const RECHECK: Duration = Duration::from_secs(15); /// Anonymous `/-/alive` streams open at once, across the whole process. A further one gets `429`. pub const MAX_ANONYMOUS_STREAMS: usize = 256; /// Signed-in `/-/alive` streams one user may hold open at once, across all their browsers and tabs. A further /// one gets `429`. pub const MAX_ALIVE_STREAMS_PER_USER: usize = 16; /// What a live page follows. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Topic { /// A user's own settings, sessions or sign-ins. Keyed by user id. Streamed only to that user. Account(String), /// Anything an administrator page shows: users, invitations, clients, mail, keys, settings, audit /// entries, health. Bumped by every administrator write. Streamed only to administrators. Admin, } /// The change counters of all open topics. Cheap to share: every clone of the app state holds the /// same `Arc`. #[derive(Default)] pub struct LiveHub { topics: Mutex>>, } impl LiveHub { /// Locks the map. A panic in another holder must not stop every live page, so a poisoned lock /// is used as it is. fn topics(&self) -> MutexGuard<'_, HashMap>> { self.topics.lock().unwrap_or_else(PoisonError::into_inner) } /// Subscribes to `topic`. The receiver starts as seen, so a bump after this call wakes it. /// Subscribe before reading the state: a change between the two is then not lost. Topics that /// nobody holds any more are dropped here, so the map stays small. pub fn subscribe(&self, topic: &Topic) -> watch::Receiver { let mut topics = self.topics(); topics.retain(|_, sender| sender.receiver_count() > 0); topics .entry(topic.clone()) .or_insert_with(|| watch::channel(0).0) .subscribe() } /// The change counter of `topic` now. It moves on every bump, so a stream that compares it with the /// value it sent last sends one event per change. Zero when nobody listens. pub fn generation(&self, topic: &Topic) -> u64 { self.topics() .get(topic) .map_or(0, |sender| *sender.borrow()) } /// Wakes the subscribers of `topic`. Does nothing when nobody listens. pub fn bump(&self, topic: &Topic) { let mut topics = self.topics(); let Some(sender) = topics.get(topic) else { return; }; sender.send_modify(|generation| *generation = generation.wrapping_add(1)); if sender.receiver_count() == 0 { topics.remove(topic); } } } /// The state a stream carries between wakes. struct Follow { wakes: Vec>, stop: watch::Receiver, /// When the stream ends, whatever else happened ([`MAX_STREAM_LIFE`]). until: tokio::time::Instant, fingerprint: F, last: String, } /// Opens the `changed` stream for `topics`. The stream sends an event only when `fingerprint` /// differs from the value it last sent, so a bump that changes nothing the viewer sees sends /// nothing. Nothing is sent on connect: the page already shows the state that `fingerprint` read. /// /// `fingerprint` must be cheap and must describe everything the page shows. It runs on every wake, before /// anything is sent, so it is also the place to check the viewer again: an error (a read that fails, or a /// viewer who may no longer see the page) ends the stream, and the browser reconnects and is refused. pub async fn stream_changes( cx: &Cx, hub: &LiveHub, topics: &[Topic], fingerprint: F, ) -> Result where F: Fn() -> Fut + Send + 'static, Fut: Future> + Send, { // Subscribed before the first read, so a change in between still wakes the stream. let wakes: Vec> = topics.iter().map(|topic| hub.subscribe(topic)).collect(); let last = fingerprint().await?; let follow = Follow { wakes, stop: app_context::(cx).stop.clone(), until: tokio::time::Instant::now() + MAX_STREAM_LIFE, fingerprint, last, }; let events = stream::unfold(follow, |mut follow| async move { loop { let woke = tokio::select! { woke = wait_any(&mut follow.wakes) => woke, () = stopped(&mut follow.stop) => false, () = tokio::time::sleep_until(follow.until) => false, () = tokio::time::sleep(RECHECK) => true, }; if !woke { return None; } match (follow.fingerprint)().await { Ok(now) if now != follow.last => { follow.last = now; return Some((changed_event(), follow)); } Ok(_) => continue, Err(error) => { tracing::error!(error = %error, "live: could not read the page state"); return None; } } } }); events_response(cx, events) } /// The data-less `changed` event. fn changed_event() -> Result { Ok(Event::new().event("changed").data("1")) } /// Resolves when the stop flag is set. A flag whose sender is gone never resolves, so the stream is not /// ended by mistake. pub async fn stopped(stop: &mut watch::Receiver) { if stop.wait_for(|stopped| *stopped).await.is_err() { std::future::pending::<()>().await; } } /// Resolves when one of `wakes` changes. False when that topic is gone, which ends the stream. /// With no topics at all it never resolves: the stream then only sends keep-alives. async fn wait_any(wakes: &mut [watch::Receiver]) -> bool { if wakes.is_empty() { std::future::pending::<()>().await; } let waits = wakes.iter_mut().map(|wake| Box::pin(wake.changed())); let (result, _, _) = select_all(waits).await; result.is_ok() } /// The response of a live stream: `retry` once, then the events, with keep-alives while idle. /// `X-Accel-Buffering: no` stops a reverse proxy from holding the events back. pub fn events_response( cx: &Cx, events: impl Stream> + Send + 'static, ) -> Result { let retry = stream::once(std::future::ready(Ok(Event::new().retry(STREAM_RETRY)))); let stream = Sse::new(retry.chain(events)) .keep_alive(KeepAlive::new().interval(KEEP_ALIVE).text("keepalive")); let mut response = stream.into_response(cx)?; response .headers_mut() .insert("x-accel-buffering", HeaderValue::from_static("no")); Ok(response) } /// The state of a viewer's `/-/alive` stream between two wakes. struct AccountFollow { /// Woken by every change of the viewer's account (sessions, security). wake: watch::Receiver, /// Set when the process stops. The stream then ends. stop: watch::Receiver, /// When the stream ends, whatever else happened ([`MAX_STREAM_LIFE`]). until: tokio::time::Instant, /// Checks that the session of this stream still exists. store: Store, /// The session the stream was opened with. session_id: String, /// Set after `signed_out` was sent, so the stream ends right after it. done: bool, /// The user's slot. Held for the life of the stream, so the number of them is capped per user. _slot: SlotGuard, } /// `GET /-/alive`. Every page holds this stream, so the browser learns when the server stops and /// starts again. /// /// An anonymous viewer gets keep-alives only. A signed-in viewer also gets an `account` event each /// time their account changes (the page then refreshes), and a `signed_out` event when their session /// is gone. The session is checked every [`RECHECK`] too, so an idle stream notices an expiry. After `signed_out` the browser goes to the sign-in page, and the stream ends. #[route(GET "/-/alive")] async fn alive(cx: &Cx) -> Result { let state = app_context::(cx); let Some(viewer) = current_user(cx).await? else { // Anonymous: no events, but the stream still ends when the process stops or its time is up. The // slot is held for the life of the stream, so the number of these is capped for the process. let Ok(slot) = Arc::clone(&state.anonymous_streams).try_acquire_owned() else { return Ok(api_error( StatusCode::TOO_MANY_REQUESTS, "rate_limited", "Too many open streams. Try again shortly.", None, )); }; let events = stream::unfold((state.stop.clone(), slot), |(mut stop, _slot)| async move { tokio::select! { () = stopped(&mut stop) => {} () = tokio::time::sleep(MAX_STREAM_LIFE) => {} } None::<(Result, (watch::Receiver, OwnedSemaphorePermit))> }); return events_response(cx, events); }; let Some(slot) = StreamSlots::acquire( &state.stream_slots, &format!("user:{}", viewer.user.id), MAX_ALIVE_STREAMS_PER_USER, ) else { return Ok(api_error( StatusCode::TOO_MANY_REQUESTS, "rate_limited", "Too many open streams. Try again shortly.", None, )); }; let follow = AccountFollow { wake: state .live .subscribe(&Topic::Account(viewer.user.id.clone())), stop: state.stop.clone(), until: tokio::time::Instant::now() + MAX_STREAM_LIFE, store: state.store.clone(), session_id: viewer.session.id.clone(), done: false, _slot: slot, }; let events = stream::unfold(follow, |mut follow| async move { loop { if follow.done { return None; } // An account change is announced. A recheck tick only looks at the session: a session that // expired by idle or age policy ends the stream, and a live one sends nothing. let account_changed = tokio::select! { changed = follow.wake.changed() => { if changed.is_err() { return None; } true } () = stopped(&mut follow.stop) => return None, () = tokio::time::sleep_until(follow.until) => return None, () = tokio::time::sleep(RECHECK) => false, }; match follow.store.session_is_live(&follow.session_id).await { Ok(true) if account_changed => { return Some((Ok(Event::new().event("account").data("1")), follow)); } Ok(true) => {} Ok(false) => { follow.done = true; return Some((Ok(Event::new().event("signed_out").data("1")), follow)); } Err(error) => { tracing::error!(error = %error, "alive: could not check the session"); return None; } } } }); events_response(cx, events) } #[cfg(test)] mod tests { use std::time::Duration; use super::*; #[tokio::test] async fn a_bump_wakes_only_the_subscribers_of_its_topic() { let hub = LiveHub::default(); let mine = Topic::Account("user-a".to_owned()); let other = Topic::Account("user-b".to_owned()); let mut wake_mine = hub.subscribe(&mine); let wake_other = hub.subscribe(&other); hub.bump(&mine); tokio::time::timeout(Duration::from_secs(1), wake_mine.changed()) .await .expect("woken") .expect("open"); assert!(!wake_other.has_changed().expect("open")); } }