forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

live.rs346 lines, 13.9 KiBHistoryRawDownload
1//! Live updates: a change counter per topic, and the server-sent event stream that carries it to
2//! the browser.
3//!
4//! A write that changes what a page shows calls [`LiveHub::bump`] after it commits. A stream that
5//! subscribed to that topic wakes and sends one `changed` event without data. The browser then
6//! fetches the page again (`nav.js`), so an event carries no state and a missed one cannot leave the
7//! page wrong for long. Nothing polls, and a topic nobody listens to is dropped.
8//!
9//! The hub is not a queue and not an authorisation check. Each route that opens a stream
10//! authenticates and authorises first, then calls [`stream_changes`].
11//!
12//! Every stream ends when the process stops (the stop flag in [`AppState`]), so a shutdown does not wait
13//! for a browser to close its connection. No stream lives longer than [`MAX_STREAM_LIFE`]: the browser
14//! reconnects, and each new connection authenticates again.
15
16use std::collections::HashMap;
17use std::future::Future;
18use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
19use std::time::Duration;
20
21use futures_util::{Stream, StreamExt, future::select_all, stream};
22use im_core::store::Store;
23use tokio::sync::{OwnedSemaphorePermit, watch};
24use topcoat::Result;
25use topcoat::context::{Cx, app_context};
26use topcoat::router::content::sse::{Event, KeepAlive, Sse};
27use topcoat::router::response::{IntoResponse, Response};
28use topcoat::router::{HeaderValue, StatusCode, route};
29
30use crate::api::api_error;
31use crate::api::directory::{SlotGuard, StreamSlots};
32use crate::auth::current_user;
33use crate::state::AppState;
34
35/// How long a client waits before it reconnects when a stream ends. Sent once, at the start.
36pub const STREAM_RETRY: Duration = Duration::from_millis(1000);
37
38/// Silence after which the server sends a keep-alive comment, so proxies keep the stream open.
39pub const KEEP_ALIVE: Duration = Duration::from_secs(30);
40
41/// Longest a stream lives, whatever happens on it. The browser reconnects after it, and a reconnect
42/// authenticates and authorises again, so a session that ended or lost its role is not kept by a stream.
43pub const MAX_STREAM_LIFE: Duration = Duration::from_secs(60 * 60);
44/// How often an idle `changed` stream runs its fingerprint anyway, so a viewer who signed out or lost
45/// access is noticed even when no topic of the stream changes.
46pub const RECHECK: Duration = Duration::from_secs(15);
47
48/// Anonymous `/-/alive` streams open at once, across the whole process. A further one gets `429`.
49pub const MAX_ANONYMOUS_STREAMS: usize = 256;
50
51/// Signed-in `/-/alive` streams one user may hold open at once, across all their browsers and tabs. A further
52/// one gets `429`.
53pub const MAX_ALIVE_STREAMS_PER_USER: usize = 16;
54
55/// What a live page follows.
56#[derive(Clone, Debug, PartialEq, Eq, Hash)]
57pub enum Topic {
58 /// A user's own settings, sessions or sign-ins. Keyed by user id. Streamed only to that user.
59 Account(String),
60 /// Anything an administrator page shows: users, invitations, clients, mail, keys, settings, audit
61 /// entries, health. Bumped by every administrator write. Streamed only to administrators.
62 Admin,
63}
64
65/// The change counters of all open topics. Cheap to share: every clone of the app state holds the
66/// same `Arc<LiveHub>`.
67#[derive(Default)]
68pub struct LiveHub {
69 topics: Mutex<HashMap<Topic, watch::Sender<u64>>>,
70}
71
72impl LiveHub {
73 /// Locks the map. A panic in another holder must not stop every live page, so a poisoned lock
74 /// is used as it is.
75 fn topics(&self) -> MutexGuard<'_, HashMap<Topic, watch::Sender<u64>>> {
76 self.topics.lock().unwrap_or_else(PoisonError::into_inner)
77 }
78
79 /// Subscribes to `topic`. The receiver starts as seen, so a bump after this call wakes it.
80 /// Subscribe before reading the state: a change between the two is then not lost. Topics that
81 /// nobody holds any more are dropped here, so the map stays small.
82 pub fn subscribe(&self, topic: &Topic) -> watch::Receiver<u64> {
83 let mut topics = self.topics();
84 topics.retain(|_, sender| sender.receiver_count() > 0);
85 topics
86 .entry(topic.clone())
87 .or_insert_with(|| watch::channel(0).0)
88 .subscribe()
89 }
90
91 /// The change counter of `topic` now. It moves on every bump, so a stream that compares it with the
92 /// value it sent last sends one event per change. Zero when nobody listens.
93 pub fn generation(&self, topic: &Topic) -> u64 {
94 self.topics()
95 .get(topic)
96 .map_or(0, |sender| *sender.borrow())
97 }
98
99 /// Wakes the subscribers of `topic`. Does nothing when nobody listens.
100 pub fn bump(&self, topic: &Topic) {
101 let mut topics = self.topics();
102 let Some(sender) = topics.get(topic) else {
103 return;
104 };
105 sender.send_modify(|generation| *generation = generation.wrapping_add(1));
106 if sender.receiver_count() == 0 {
107 topics.remove(topic);
108 }
109 }
110}
111
112/// The state a stream carries between wakes.
113struct Follow<F> {
114 wakes: Vec<watch::Receiver<u64>>,
115 stop: watch::Receiver<bool>,
116 /// When the stream ends, whatever else happened ([`MAX_STREAM_LIFE`]).
117 until: tokio::time::Instant,
118 fingerprint: F,
119 last: String,
120}
121
122/// Opens the `changed` stream for `topics`. The stream sends an event only when `fingerprint`
123/// differs from the value it last sent, so a bump that changes nothing the viewer sees sends
124/// nothing. Nothing is sent on connect: the page already shows the state that `fingerprint` read.
125///
126/// `fingerprint` must be cheap and must describe everything the page shows. It runs on every wake, before
127/// anything is sent, so it is also the place to check the viewer again: an error (a read that fails, or a
128/// viewer who may no longer see the page) ends the stream, and the browser reconnects and is refused.
129pub async fn stream_changes<F, Fut>(
130 cx: &Cx,
131 hub: &LiveHub,
132 topics: &[Topic],
133 fingerprint: F,
134) -> Result<Response>
135where
136 F: Fn() -> Fut + Send + 'static,
137 Fut: Future<Output = Result<String>> + Send,
138{
139 // Subscribed before the first read, so a change in between still wakes the stream.
140 let wakes: Vec<watch::Receiver<u64>> =
141 topics.iter().map(|topic| hub.subscribe(topic)).collect();
142 let last = fingerprint().await?;
143 let follow = Follow {
144 wakes,
145 stop: app_context::<AppState>(cx).stop.clone(),
146 until: tokio::time::Instant::now() + MAX_STREAM_LIFE,
147 fingerprint,
148 last,
149 };
150 let events = stream::unfold(follow, |mut follow| async move {
151 loop {
152 let woke = tokio::select! {
153 woke = wait_any(&mut follow.wakes) => woke,
154 () = stopped(&mut follow.stop) => false,
155 () = tokio::time::sleep_until(follow.until) => false,
156 () = tokio::time::sleep(RECHECK) => true,
157 };
158 if !woke {
159 return None;
160 }
161 match (follow.fingerprint)().await {
162 Ok(now) if now != follow.last => {
163 follow.last = now;
164 return Some((changed_event(), follow));
165 }
166 Ok(_) => continue,
167 Err(error) => {
168 tracing::error!(error = %error, "live: could not read the page state");
169 return None;
170 }
171 }
172 }
173 });
174 events_response(cx, events)
175}
176
177/// The data-less `changed` event.
178fn changed_event() -> Result<Event> {
179 Ok(Event::new().event("changed").data("1"))
180}
181
182/// Resolves when the stop flag is set. A flag whose sender is gone never resolves, so the stream is not
183/// ended by mistake.
184pub async fn stopped(stop: &mut watch::Receiver<bool>) {
185 if stop.wait_for(|stopped| *stopped).await.is_err() {
186 std::future::pending::<()>().await;
187 }
188}
189
190/// Resolves when one of `wakes` changes. False when that topic is gone, which ends the stream.
191/// With no topics at all it never resolves: the stream then only sends keep-alives.
192async fn wait_any(wakes: &mut [watch::Receiver<u64>]) -> bool {
193 if wakes.is_empty() {
194 std::future::pending::<()>().await;
195 }
196 let waits = wakes.iter_mut().map(|wake| Box::pin(wake.changed()));
197 let (result, _, _) = select_all(waits).await;
198 result.is_ok()
199}
200
201/// The response of a live stream: `retry` once, then the events, with keep-alives while idle.
202/// `X-Accel-Buffering: no` stops a reverse proxy from holding the events back.
203pub fn events_response(
204 cx: &Cx,
205 events: impl Stream<Item = Result<Event>> + Send + 'static,
206) -> Result<Response> {
207 let retry = stream::once(std::future::ready(Ok(Event::new().retry(STREAM_RETRY))));
208 let stream = Sse::new(retry.chain(events))
209 .keep_alive(KeepAlive::new().interval(KEEP_ALIVE).text("keepalive"));
210 let mut response = stream.into_response(cx)?;
211 response
212 .headers_mut()
213 .insert("x-accel-buffering", HeaderValue::from_static("no"));
214 Ok(response)
215}
216
217/// The state of a viewer's `/-/alive` stream between two wakes.
218struct AccountFollow {
219 /// Woken by every change of the viewer's account (sessions, security).
220 wake: watch::Receiver<u64>,
221 /// Set when the process stops. The stream then ends.
222 stop: watch::Receiver<bool>,
223 /// When the stream ends, whatever else happened ([`MAX_STREAM_LIFE`]).
224 until: tokio::time::Instant,
225 /// Checks that the session of this stream still exists.
226 store: Store,
227 /// The session the stream was opened with.
228 session_id: String,
229 /// Set after `signed_out` was sent, so the stream ends right after it.
230 done: bool,
231 /// The user's slot. Held for the life of the stream, so the number of them is capped per user.
232 _slot: SlotGuard,
233}
234
235/// `GET /-/alive`. Every page holds this stream, so the browser learns when the server stops and
236/// starts again.
237///
238/// An anonymous viewer gets keep-alives only. A signed-in viewer also gets an `account` event each
239/// time their account changes (the page then refreshes), and a `signed_out` event when their session
240/// 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.
241#[route(GET "/-/alive")]
242async fn alive(cx: &Cx) -> Result<Response> {
243 let state = app_context::<AppState>(cx);
244 let Some(viewer) = current_user(cx).await? else {
245 // Anonymous: no events, but the stream still ends when the process stops or its time is up. The
246 // slot is held for the life of the stream, so the number of these is capped for the process.
247 let Ok(slot) = Arc::clone(&state.anonymous_streams).try_acquire_owned() else {
248 return Ok(api_error(
249 StatusCode::TOO_MANY_REQUESTS,
250 "rate_limited",
251 "Too many open streams. Try again shortly.",
252 None,
253 ));
254 };
255 let events = stream::unfold((state.stop.clone(), slot), |(mut stop, _slot)| async move {
256 tokio::select! {
257 () = stopped(&mut stop) => {}
258 () = tokio::time::sleep(MAX_STREAM_LIFE) => {}
259 }
260 None::<(Result<Event>, (watch::Receiver<bool>, OwnedSemaphorePermit))>
261 });
262 return events_response(cx, events);
263 };
264 let Some(slot) = StreamSlots::acquire(
265 &state.stream_slots,
266 &format!("user:{}", viewer.user.id),
267 MAX_ALIVE_STREAMS_PER_USER,
268 ) else {
269 return Ok(api_error(
270 StatusCode::TOO_MANY_REQUESTS,
271 "rate_limited",
272 "Too many open streams. Try again shortly.",
273 None,
274 ));
275 };
276 let follow = AccountFollow {
277 wake: state
278 .live
279 .subscribe(&Topic::Account(viewer.user.id.clone())),
280 stop: state.stop.clone(),
281 until: tokio::time::Instant::now() + MAX_STREAM_LIFE,
282 store: state.store.clone(),
283 session_id: viewer.session.id.clone(),
284 done: false,
285 _slot: slot,
286 };
287 let events = stream::unfold(follow, |mut follow| async move {
288 loop {
289 if follow.done {
290 return None;
291 }
292 // An account change is announced. A recheck tick only looks at the session: a session that
293 // expired by idle or age policy ends the stream, and a live one sends nothing.
294 let account_changed = tokio::select! {
295 changed = follow.wake.changed() => {
296 if changed.is_err() {
297 return None;
298 }
299 true
300 }
301 () = stopped(&mut follow.stop) => return None,
302 () = tokio::time::sleep_until(follow.until) => return None,
303 () = tokio::time::sleep(RECHECK) => false,
304 };
305 match follow.store.session_is_live(&follow.session_id).await {
306 Ok(true) if account_changed => {
307 return Some((Ok(Event::new().event("account").data("1")), follow));
308 }
309 Ok(true) => {}
310 Ok(false) => {
311 follow.done = true;
312 return Some((Ok(Event::new().event("signed_out").data("1")), follow));
313 }
314 Err(error) => {
315 tracing::error!(error = %error, "alive: could not check the session");
316 return None;
317 }
318 }
319 }
320 });
321 events_response(cx, events)
322}
323
324#[cfg(test)]
325mod tests {
326 use std::time::Duration;
327
328 use super::*;
329
330 #[tokio::test]
331 async fn a_bump_wakes_only_the_subscribers_of_its_topic() {
332 let hub = LiveHub::default();
333 let mine = Topic::Account("user-a".to_owned());
334 let other = Topic::Account("user-b".to_owned());
335 let mut wake_mine = hub.subscribe(&mine);
336 let wake_other = hub.subscribe(&other);
337
338 hub.bump(&mine);
339
340 tokio::time::timeout(Duration::from_secs(1), wake_mine.changed())
341 .await
342 .expect("woken")
343 .expect("open");
344 assert!(!wake_other.has_changed().expect("open"));
345 }
346}