forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

live.rs216 lines, 8.4 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//! The topics of the pages are listed on [`Topic`]. Every write that changes what a page shows bumps its
13//! topic after the commit.
14
15use std::collections::HashMap;
16use std::future::Future;
17use std::sync::{Mutex, MutexGuard, PoisonError};
18use std::time::Duration;
19
20use futures_util::{Stream, StreamExt, future::select_all, stream};
21use tokio::sync::watch;
22use topcoat::Result;
23use topcoat::context::Cx;
24use topcoat::router::content::sse::{Event, KeepAlive, Sse};
25use topcoat::router::response::{IntoResponse, Response};
26use topcoat::router::{HeaderValue, route};
27
28/// How long a client waits before it reconnects when a stream ends. Sent once, at the start.
29pub const STREAM_RETRY: Duration = Duration::from_millis(1000);
30
31/// Silence after which the server sends a keep-alive comment, so proxies keep the stream open.
32pub const KEEP_ALIVE: Duration = Duration::from_secs(30);
33
34/// How often an idle `changed` stream checks its viewer anyway, so a viewer who signed out or lost access is
35/// noticed even when nothing the stream follows changes.
36const RECHECK: Duration = Duration::from_secs(15);
37/// The longest a `changed` stream lives. The browser then reconnects and is checked again from the start.
38const MAX_STREAM_LIFE: Duration = Duration::from_secs(60 * 60);
39/// What a live page follows.
40#[derive(Clone, Debug, PartialEq, Eq, Hash)]
41pub enum Topic {
42 /// A person's own account: sessions and preferences. Keyed by user sub. Streamed only to that person.
43 Account(String),
44 /// A person's own drive: folder listings and trash. Keyed by owner sub. Streamed only to the owner.
45 Drive(String),
46 /// Items shared with a person. Keyed by grantee sub. Streamed only to that person.
47 Shared(String),
48 /// The audit log: an entry was written. Global. Admin pages only.
49 AdminAudit,
50 /// A person's share links: made, revoked, reminted, or their targets changed. Keyed by owner sub.
51 /// Streamed only to that person.
52 Links(String),
53}
54
55/// The change counters of all open topics. Cheap to share: every clone of the app state holds the
56/// same `Arc<LiveHub>`.
57#[derive(Default)]
58pub struct LiveHub {
59 topics: Mutex<HashMap<Topic, watch::Sender<u64>>>,
60}
61
62impl LiveHub {
63 /// Locks the map. A panic in another holder must not stop every live page, so a poisoned lock
64 /// is used as it is.
65 fn topics(&self) -> MutexGuard<'_, HashMap<Topic, watch::Sender<u64>>> {
66 self.topics.lock().unwrap_or_else(PoisonError::into_inner)
67 }
68
69 /// Subscribes to `topic`. The receiver starts as seen, so a bump after this call wakes it.
70 /// Subscribe before reading the state: a change between the two is then not lost. Topics that
71 /// nobody holds any more are dropped here, so the map stays small.
72 pub fn subscribe(&self, topic: &Topic) -> watch::Receiver<u64> {
73 let mut topics = self.topics();
74 topics.retain(|_, sender| sender.receiver_count() > 0);
75 topics
76 .entry(topic.clone())
77 .or_insert_with(|| watch::channel(0).0)
78 .subscribe()
79 }
80
81 /// Wakes the subscribers of `topic`. Does nothing when nobody listens.
82 pub fn bump(&self, topic: &Topic) {
83 let mut topics = self.topics();
84 let Some(sender) = topics.get(topic) else {
85 return;
86 };
87 sender.send_modify(|generation| *generation = generation.wrapping_add(1));
88 if sender.receiver_count() == 0 {
89 topics.remove(topic);
90 }
91 }
92}
93
94/// The state a stream carries between wakes.
95struct Follow<F> {
96 wakes: Vec<watch::Receiver<u64>>,
97 fingerprint: F,
98 last: String,
99}
100
101/// Opens the `changed` stream for `topics`. The stream sends an event only when `fingerprint`
102/// differs from the value it last sent, so a bump that changes nothing the viewer sees sends
103/// nothing. Nothing is sent on connect: the page already shows the state that `fingerprint` read.
104///
105/// `fingerprint` must be cheap and must describe everything the page shows. A read that fails ends
106/// the stream, and the browser reconnects.
107pub async fn stream_changes<F, Fut>(
108 cx: &Cx,
109 hub: &LiveHub,
110 topics: &[Topic],
111 fingerprint: F,
112) -> Result<Response>
113where
114 F: Fn() -> Fut + Send + 'static,
115 Fut: Future<Output = Result<String>> + Send,
116{
117 // Subscribed before the first read, so a change in between still wakes the stream.
118 let wakes: Vec<watch::Receiver<u64>> =
119 topics.iter().map(|topic| hub.subscribe(topic)).collect();
120 let last = fingerprint().await?;
121 let follow = Follow {
122 wakes,
123 fingerprint,
124 last,
125 };
126 let until = tokio::time::Instant::now() + MAX_STREAM_LIFE;
127 let events = stream::unfold(follow, move |mut follow| async move {
128 loop {
129 // A tick runs the fingerprint too: it is where the viewer is checked again.
130 let woke = tokio::select! {
131 woke = wait_any(&mut follow.wakes) => woke,
132 () = tokio::time::sleep(RECHECK) => true,
133 () = tokio::time::sleep_until(until) => false,
134 };
135 if !woke {
136 return None;
137 }
138 match (follow.fingerprint)().await {
139 Ok(now) if now != follow.last => {
140 follow.last = now;
141 return Some((changed_event(), follow));
142 }
143 Ok(_) => continue,
144 Err(error) => {
145 tracing::error!(error = %error, "live: could not read the page state");
146 return None;
147 }
148 }
149 }
150 });
151 events_response(cx, events)
152}
153
154/// The data-less `changed` event.
155fn changed_event() -> Result<Event> {
156 Ok(Event::new().event("changed").data("1"))
157}
158
159/// Resolves when one of `wakes` changes. False when that topic is gone, which ends the stream.
160/// With no topics at all it never resolves: the stream then only sends keep-alives.
161async fn wait_any(wakes: &mut [watch::Receiver<u64>]) -> bool {
162 if wakes.is_empty() {
163 std::future::pending::<()>().await;
164 }
165 let waits = wakes.iter_mut().map(|wake| Box::pin(wake.changed()));
166 let (result, _, _) = select_all(waits).await;
167 result.is_ok()
168}
169
170/// The response of a live stream: `retry` once, then the events, with keep-alives while idle.
171/// `X-Accel-Buffering: no` stops a reverse proxy from holding the events back.
172pub fn events_response(
173 cx: &Cx,
174 events: impl Stream<Item = Result<Event>> + Send + 'static,
175) -> Result<Response> {
176 let retry = stream::once(std::future::ready(Ok(Event::new().retry(STREAM_RETRY))));
177 let stream = Sse::new(retry.chain(events))
178 .keep_alive(KeepAlive::new().interval(KEEP_ALIVE).text("keepalive"));
179 let mut response = stream.into_response(cx)?;
180 response
181 .headers_mut()
182 .insert("x-accel-buffering", HeaderValue::from_static("no"));
183 Ok(response)
184}
185
186/// `GET /-/alive`. Every page holds this stream, so the browser learns when the server stops and
187/// starts again. Anonymous viewers may hold it, and it reveals nothing: for now it sends only the
188/// `retry` hint and keep-alives.
189#[route(GET "/-/alive")]
190async fn alive(cx: &Cx) -> Result<Response> {
191 events_response(cx, stream::pending::<Result<Event>>())
192}
193
194#[cfg(test)]
195mod tests {
196 use std::time::Duration;
197
198 use super::*;
199
200 #[tokio::test]
201 async fn a_bump_wakes_only_the_subscribers_of_its_topic() {
202 let hub = LiveHub::default();
203 let mine = Topic::Account("user-a".to_owned());
204 let other = Topic::Account("user-b".to_owned());
205 let mut wake_mine = hub.subscribe(&mine);
206 let wake_other = hub.subscribe(&other);
207
208 hub.bump(&mine);
209
210 tokio::time::timeout(Duration::from_secs(1), wake_mine.changed())
211 .await
212 .expect("woken")
213 .expect("open");
214 assert!(!wake_other.has_changed().expect("open"));
215 }
216}