//! 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`]. //! //! The topics of the pages are listed on [`Topic`]. Every write that changes what a page shows bumps its //! topic after the commit. use std::collections::HashMap; use std::future::Future; use std::sync::{Mutex, MutexGuard, PoisonError}; use std::time::Duration; use futures_util::{Stream, StreamExt, future::select_all, stream}; use tokio::sync::watch; use topcoat::Result; use topcoat::context::Cx; use topcoat::router::content::sse::{Event, KeepAlive, Sse}; use topcoat::router::response::{IntoResponse, Response}; use topcoat::router::{HeaderValue, route}; /// 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); /// How often an idle `changed` stream checks its viewer anyway, so a viewer who signed out or lost access is /// noticed even when nothing the stream follows changes. const RECHECK: Duration = Duration::from_secs(15); /// The longest a `changed` stream lives. The browser then reconnects and is checked again from the start. const MAX_STREAM_LIFE: Duration = Duration::from_secs(60 * 60); /// What a live page follows. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Topic { /// A person's own account: sessions and preferences. Keyed by user sub. Streamed only to that person. Account(String), /// A person's own drive: folder listings and trash. Keyed by owner sub. Streamed only to the owner. Drive(String), /// Items shared with a person. Keyed by grantee sub. Streamed only to that person. Shared(String), /// The audit log: an entry was written. Global. Admin pages only. AdminAudit, /// A person's share links: made, revoked, reminted, or their targets changed. Keyed by owner sub. /// Streamed only to that person. Links(String), } /// 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() } /// 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>, 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. A read that fails ends /// the stream, and the browser reconnects. 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, fingerprint, last, }; let until = tokio::time::Instant::now() + MAX_STREAM_LIFE; let events = stream::unfold(follow, move |mut follow| async move { loop { // A tick runs the fingerprint too: it is where the viewer is checked again. let woke = tokio::select! { woke = wait_any(&mut follow.wakes) => woke, () = tokio::time::sleep(RECHECK) => true, () = tokio::time::sleep_until(until) => false, }; 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 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) } /// `GET /-/alive`. Every page holds this stream, so the browser learns when the server stops and /// starts again. Anonymous viewers may hold it, and it reveals nothing: for now it sends only the /// `retry` hint and keep-alives. #[route(GET "/-/alive")] async fn alive(cx: &Cx) -> Result { events_response(cx, stream::pending::>()) } #[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")); } }