forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

directory.rs361 lines, 13.8 KiBHistoryRawDownload
1//! The people directory of `im` (`docs/contracts.md` section 3): the full listing, and the change stream
2//! that follows it.
3//!
4//! The listing and its cursor are read in one step (`Store::directory_snapshot`), so the cursor is exactly
5//! the state of the members. The stream resumes from `Last-Event-ID` (or `?cursor=`). A cursor that is not
6//! a non-negative integer, that is ahead of the feed, or that is older than the oldest kept row gets one
7//! `resync` event and the stream closes: the client then reads the listing again. Otherwise every row after
8//! the cursor is sent (`member` with the current record, or `deleted`), and the stream then waits on the
9//! feed's watch channel. It ends when the token expires (or after 50 minutes), when the calling client is
10//! disabled or removed, or when the client's stream is cut at the per-client cap (four at once, 429 beyond).
11
12use std::collections::{HashMap, VecDeque};
13use std::sync::{Arc, Mutex, PoisonError};
14use std::time::Duration;
15
16use futures_util::{Stream, stream};
17use http::header::HeaderValue;
18use im_core::model::User;
19use im_core::store::Store;
20use im_core::store::directory::{Change, ChangeKind};
21use im_core::time::unix_now;
22use serde_json::{Value, json};
23use tokio::sync::watch;
24use tokio::time::{Instant, Interval};
25use topcoat::Result;
26use topcoat::context::{Cx, app_context};
27use topcoat::router::content::sse::{Event, KeepAlive, Sse, last_event_id};
28use topcoat::router::request::uri;
29use topcoat::router::response::{IntoResponse, Response};
30use topcoat::router::{StatusCode, route};
31
32use super::machine_auth::{DIRECTORY_READ, Machine, require};
33use super::{api_error, json_response};
34use crate::oidc::parse_pairs;
35use crate::state::AppState;
36
37/// Most streams one client may hold open at once. A further one is refused with `429`.
38pub const MAX_STREAMS_PER_CLIENT: usize = 4;
39
40/// Longest a stream lives, in seconds of wall time, whatever the token's expiry says (contracts 3.2).
41pub const STREAM_MAX_LIFE: Duration = Duration::from_secs(50 * 60);
42
43/// Silence after which a keep-alive comment is sent (contracts 3.2 says every 30 s; 25 s keeps a margin).
44pub const KEEP_ALIVE: Duration = Duration::from_secs(25);
45
46/// Rows read from the feed in one batch.
47const BATCH: i64 = 200;
48
49/// How long a `Retry-After` the refused client is given, in seconds.
50const RETRY_AFTER_SECS: &str = "5";
51
52/// The open streams of each key: a machine client for the directory feed, a user for `/-/alive`. Shared by
53/// every request, so each cap holds across connections.
54#[derive(Default)]
55pub struct StreamSlots {
56 open: Mutex<HashMap<String, usize>>,
57}
58
59/// One open stream of a key. Dropping it frees the slot, so a stream that ends for any reason gives its
60/// slot back.
61pub struct SlotGuard {
62 slots: Arc<StreamSlots>,
63 key: String,
64}
65
66impl StreamSlots {
67 /// Takes a slot for `key`, or `None` when the key already holds `max` streams.
68 pub fn acquire(this: &Arc<Self>, key: &str, max: usize) -> Option<SlotGuard> {
69 let mut open = this.open.lock().unwrap_or_else(PoisonError::into_inner);
70 let count = open.entry(key.to_owned()).or_insert(0);
71 if *count >= max {
72 return None;
73 }
74 *count += 1;
75 Some(SlotGuard {
76 slots: Arc::clone(this),
77 key: key.to_owned(),
78 })
79 }
80}
81
82impl Drop for SlotGuard {
83 fn drop(&mut self) {
84 let mut open = self
85 .slots
86 .open
87 .lock()
88 .unwrap_or_else(PoisonError::into_inner);
89 if let Some(count) = open.get_mut(&self.key) {
90 *count = count.saturating_sub(1);
91 if *count == 0 {
92 open.remove(&self.key);
93 }
94 }
95 }
96}
97
98/// The wire form of one member (contracts 3.1).
99pub fn member_json(user: &User) -> Value {
100 json!({
101 "sub": user.id,
102 "email": user.email,
103 "name": user.name,
104 "admin": user.is_admin,
105 "disabled": user.is_disabled(),
106 "locale": user.locale,
107 "zoneinfo": user.zoneinfo,
108 "picture_version": user.picture_version,
109 "updated_at": user.updated_at,
110 })
111}
112
113/// `GET /api/v1/directory`: every account, disabled ones included, and the cursor of this state.
114#[route(GET "/api/v1/directory")]
115async fn directory(cx: &Cx) -> Result<Response> {
116 let app = app_context::<AppState>(cx);
117 let machine = match require(app, cx, DIRECTORY_READ).await? {
118 Ok(machine) => machine,
119 Err(refusal) => return Ok(refusal),
120 };
121 tracing::debug!(caller = %machine.caller, "directory: listing");
122 let (head, users) = app.store.directory_snapshot().await?;
123 let members: Vec<Value> = users.iter().map(member_json).collect();
124 Ok(json_response(
125 StatusCode::OK,
126 &json!({"members": members, "cursor": head.to_string()}),
127 ))
128}
129
130/// `GET /api/v1/directory/stream`: the change stream, as `text/event-stream`.
131#[route(GET "/api/v1/directory/stream")]
132async fn directory_stream(cx: &Cx) -> Result<Response> {
133 let app = app_context::<AppState>(cx);
134 let machine = match require(app, cx, DIRECTORY_READ).await? {
135 Ok(machine) => machine,
136 Err(refusal) => return Ok(refusal),
137 };
138 let Some(slot) = StreamSlots::acquire(
139 &app.stream_slots,
140 &machine.client_id,
141 MAX_STREAMS_PER_CLIENT,
142 ) else {
143 let mut response = api_error(
144 StatusCode::TOO_MANY_REQUESTS,
145 "rate_limited",
146 "This client already has the maximum number of directory streams open.",
147 None,
148 );
149 response
150 .headers_mut()
151 .insert("retry-after", HeaderValue::from_static(RETRY_AFTER_SECS));
152 return Ok(response);
153 };
154 // Subscribed before the feed is read, so a change made in between still wakes the stream.
155 let wake = app.store.directory_watch();
156 let head = app.store.directory_head().await?;
157 let oldest = app.store.directory_oldest().await?;
158 let requested = requested_cursor(cx);
159 let Some(start) = resume_point(requested.as_deref(), head, oldest) else {
160 return sse(cx, stream::iter(vec![Ok(resync_event())]));
161 };
162 let deadline = Instant::now() + stream_life(&machine);
163 let follow = Follow {
164 stop: app.stop.clone(),
165 store: app.store.clone(),
166 client_id: machine.client_id.clone(),
167 cursor: start,
168 wake,
169 check: tokio::time::interval_at(Instant::now() + KEEP_ALIVE, KEEP_ALIVE),
170 deadline,
171 pending: VecDeque::new(),
172 _slot: slot,
173 };
174 sse(cx, follow_events(follow))
175}
176
177/// The state of one stream between two events.
178struct Follow {
179 /// Set when the process stops: the stream then ends, so the server can drain.
180 stop: watch::Receiver<bool>,
181 store: Store,
182 client_id: String,
183 /// The last sequence number sent.
184 cursor: i64,
185 /// Woken by every committed directory change.
186 wake: watch::Receiver<u64>,
187 /// Checks, every [`KEEP_ALIVE`], that the calling client is still enabled.
188 check: Interval,
189 /// The stream ends at this time (the token's expiry or the 50-minute cap).
190 deadline: Instant,
191 /// Events read but not yet sent.
192 pending: VecDeque<Event>,
193 /// Holds the client's slot for as long as the stream lives.
194 _slot: SlotGuard,
195}
196
197/// The events of a stream from its cursor on. It ends on a store failure, a disabled client, the
198/// deadline, or a closed feed; the browser or consumer reconnects with its last cursor.
199fn follow_events(follow: Follow) -> impl Stream<Item = topcoat::Result<Event>> + Send + 'static {
200 stream::unfold(follow, |mut follow| async move {
201 loop {
202 if let Some(event) = follow.pending.pop_front() {
203 return Some((Ok(event), follow));
204 }
205 match follow
206 .store
207 .directory_changes_after(follow.cursor, BATCH)
208 .await
209 {
210 Ok(changes) if !changes.is_empty() => {
211 for change in changes {
212 match change_event(&follow.store, &change).await {
213 Ok(event) => follow.pending.push_back(event),
214 Err(error) => {
215 tracing::error!(error = %error, "directory stream: a change could not be read");
216 return None;
217 }
218 }
219 follow.cursor = change.seq;
220 }
221 continue;
222 }
223 Ok(_) => {}
224 Err(error) => {
225 tracing::error!(error = %error, "directory stream: the feed could not be read");
226 return None;
227 }
228 }
229 tokio::select! {
230 changed = follow.wake.changed() => {
231 if changed.is_err() {
232 return None;
233 }
234 }
235 _ = follow.check.tick() => {
236 match follow.store.client_by_id(&follow.client_id).await {
237 Ok(Some(client)) if !client.is_disabled() => {}
238 _ => return None,
239 }
240 }
241 () = stopped(&mut follow.stop) => return None,
242 () = tokio::time::sleep_until(follow.deadline) => return None,
243 }
244 }
245 })
246}
247
248/// Resolves when the stop flag is set. A flag whose sender is gone never resolves, so a stream is not
249/// ended by a test state that has no server behind it.
250async fn stopped(stop: &mut watch::Receiver<bool>) {
251 if stop.wait_for(|stopped| *stopped).await.is_err() {
252 std::future::pending::<()>().await;
253 }
254}
255
256/// The event of one change row, with the row's sequence number as its id. A member row is sent with the
257/// person's current record; if the person is gone by then, the event is `deleted`.
258async fn change_event(store: &Store, change: &Change) -> im_core::Result<Event> {
259 let user = match change.kind {
260 ChangeKind::Member => store.user_by_id(&change.sub).await?,
261 ChangeKind::Deleted => None,
262 };
263 let event = match user {
264 Some(user) => Event::new()
265 .event("member")
266 .data(member_json(&user).to_string()),
267 None => Event::new()
268 .event("deleted")
269 .data(json!({"sub": change.sub}).to_string()),
270 };
271 Ok(event.id(change.seq.to_string()))
272}
273
274/// The one `resync` event: the cursor is unusable, so the consumer reads the listing again.
275fn resync_event() -> Event {
276 Event::new().event("resync").data("{}")
277}
278
279/// The cursor the client asked to resume from: `Last-Event-ID`, else `?cursor=`. A repeated `cursor`
280/// parameter is treated as garbage, which means resync.
281fn requested_cursor(cx: &Cx) -> Option<String> {
282 if let Some(id) = last_event_id(cx).filter(|id| !id.is_empty()) {
283 return Some(id.to_owned());
284 }
285 let query = uri(cx).query()?;
286 let pairs = parse_pairs(query.as_bytes())?;
287 match crate::oidc::single(&pairs, "cursor") {
288 crate::oidc::Single::Absent => None,
289 crate::oidc::Single::One(value) => Some(value.to_owned()),
290 crate::oidc::Single::Repeated => Some(String::new()),
291 }
292}
293
294/// Where a stream starts, or `None` when it must resync. No cursor starts at the head (the consumer reads
295/// the listing first). A cursor must be digits only, not ahead of the head, and not older than the oldest
296/// kept row: the rows between it and that row were pruned, so they cannot be replayed.
297pub fn resume_point(requested: Option<&str>, head: i64, oldest: Option<i64>) -> Option<i64> {
298 let Some(text) = requested else {
299 return Some(head);
300 };
301 if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
302 return None;
303 }
304 let cursor: i64 = text.parse().ok()?;
305 if cursor > head {
306 return None;
307 }
308 if let Some(oldest) = oldest
309 && cursor.saturating_add(1) < oldest
310 {
311 return None;
312 }
313 Some(cursor)
314}
315
316/// How long a stream of this caller may live: until the token expires, and at most [`STREAM_MAX_LIFE`].
317fn stream_life(machine: &Machine) -> Duration {
318 let until_expiry = u64::try_from(machine.expires_at - unix_now()).unwrap_or(0);
319 Duration::from_secs(until_expiry).min(STREAM_MAX_LIFE)
320}
321
322/// The response of a stream: the events, with a keep-alive comment while idle. `X-Accel-Buffering: no`
323/// stops a reverse proxy from holding the events back.
324fn sse(
325 cx: &Cx,
326 events: impl Stream<Item = topcoat::Result<Event>> + Send + 'static,
327) -> Result<Response> {
328 let mut response = Sse::new(events)
329 .keep_alive(KeepAlive::new().interval(KEEP_ALIVE).text("keepalive"))
330 .into_response(cx)?;
331 response
332 .headers_mut()
333 .insert("x-accel-buffering", HeaderValue::from_static("no"));
334 Ok(response)
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340
341 #[test]
342 fn a_cursor_resumes_only_inside_the_kept_range() {
343 // No cursor: start at the head.
344 assert_eq!(resume_point(None, 7, Some(3)), Some(7));
345 // Inside the range, and at the head.
346 assert_eq!(resume_point(Some("5"), 7, Some(3)), Some(5));
347 assert_eq!(resume_point(Some("7"), 7, Some(3)), Some(7));
348 // Ahead of the head, negative, empty, signed or not a number: resync.
349 assert_eq!(resume_point(Some("8"), 7, Some(3)), None);
350 assert_eq!(resume_point(Some("-1"), 7, Some(3)), None);
351 assert_eq!(resume_point(Some("+1"), 7, Some(3)), None);
352 assert_eq!(resume_point(Some(""), 7, Some(3)), None);
353 assert_eq!(resume_point(Some("abc"), 7, Some(3)), None);
354 // Rows 1 and 2 were pruned, so row 3 is the oldest kept. A cursor of 1 still needs row 2: resync.
355 // A cursor of 2 needs only rows from 3 on: fine.
356 assert_eq!(resume_point(Some("1"), 7, Some(3)), None);
357 assert_eq!(resume_point(Some("2"), 7, Some(3)), Some(2));
358 // Empty feed: cursor 0 is at the head.
359 assert_eq!(resume_point(Some("0"), 0, None), Some(0));
360 }
361}