//! The people directory of `im` (`docs/contracts.md` section 3): the full listing, and the change stream //! that follows it. //! //! The listing and its cursor are read in one step (`Store::directory_snapshot`), so the cursor is exactly //! the state of the members. The stream resumes from `Last-Event-ID` (or `?cursor=`). A cursor that is not //! a non-negative integer, that is ahead of the feed, or that is older than the oldest kept row gets one //! `resync` event and the stream closes: the client then reads the listing again. Otherwise every row after //! the cursor is sent (`member` with the current record, or `deleted`), and the stream then waits on the //! feed's watch channel. It ends when the token expires (or after 50 minutes), when the calling client is //! disabled or removed, or when the client's stream is cut at the per-client cap (four at once, 429 beyond). use std::collections::{HashMap, VecDeque}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; use futures_util::{Stream, stream}; use http::header::HeaderValue; use im_core::model::User; use im_core::store::Store; use im_core::store::directory::{Change, ChangeKind}; use im_core::time::unix_now; use serde_json::{Value, json}; use tokio::sync::watch; use tokio::time::{Instant, Interval}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::sse::{Event, KeepAlive, Sse, last_event_id}; use topcoat::router::request::uri; use topcoat::router::response::{IntoResponse, Response}; use topcoat::router::{StatusCode, route}; use super::machine_auth::{DIRECTORY_READ, Machine, require}; use super::{api_error, json_response}; use crate::oidc::parse_pairs; use crate::state::AppState; /// Most streams one client may hold open at once. A further one is refused with `429`. pub const MAX_STREAMS_PER_CLIENT: usize = 4; /// Longest a stream lives, in seconds of wall time, whatever the token's expiry says (contracts 3.2). pub const STREAM_MAX_LIFE: Duration = Duration::from_secs(50 * 60); /// Silence after which a keep-alive comment is sent (contracts 3.2 says every 30 s; 25 s keeps a margin). pub const KEEP_ALIVE: Duration = Duration::from_secs(25); /// Rows read from the feed in one batch. const BATCH: i64 = 200; /// How long a `Retry-After` the refused client is given, in seconds. const RETRY_AFTER_SECS: &str = "5"; /// The open streams of each key: a machine client for the directory feed, a user for `/-/alive`. Shared by /// every request, so each cap holds across connections. #[derive(Default)] pub struct StreamSlots { open: Mutex>, } /// One open stream of a key. Dropping it frees the slot, so a stream that ends for any reason gives its /// slot back. pub struct SlotGuard { slots: Arc, key: String, } impl StreamSlots { /// Takes a slot for `key`, or `None` when the key already holds `max` streams. pub fn acquire(this: &Arc, key: &str, max: usize) -> Option { let mut open = this.open.lock().unwrap_or_else(PoisonError::into_inner); let count = open.entry(key.to_owned()).or_insert(0); if *count >= max { return None; } *count += 1; Some(SlotGuard { slots: Arc::clone(this), key: key.to_owned(), }) } } impl Drop for SlotGuard { fn drop(&mut self) { let mut open = self .slots .open .lock() .unwrap_or_else(PoisonError::into_inner); if let Some(count) = open.get_mut(&self.key) { *count = count.saturating_sub(1); if *count == 0 { open.remove(&self.key); } } } } /// The wire form of one member (contracts 3.1). pub fn member_json(user: &User) -> Value { json!({ "sub": user.id, "email": user.email, "name": user.name, "admin": user.is_admin, "disabled": user.is_disabled(), "locale": user.locale, "zoneinfo": user.zoneinfo, "picture_version": user.picture_version, "updated_at": user.updated_at, }) } /// `GET /api/v1/directory`: every account, disabled ones included, and the cursor of this state. #[route(GET "/api/v1/directory")] async fn directory(cx: &Cx) -> Result { let app = app_context::(cx); let machine = match require(app, cx, DIRECTORY_READ).await? { Ok(machine) => machine, Err(refusal) => return Ok(refusal), }; tracing::debug!(caller = %machine.caller, "directory: listing"); let (head, users) = app.store.directory_snapshot().await?; let members: Vec = users.iter().map(member_json).collect(); Ok(json_response( StatusCode::OK, &json!({"members": members, "cursor": head.to_string()}), )) } /// `GET /api/v1/directory/stream`: the change stream, as `text/event-stream`. #[route(GET "/api/v1/directory/stream")] async fn directory_stream(cx: &Cx) -> Result { let app = app_context::(cx); let machine = match require(app, cx, DIRECTORY_READ).await? { Ok(machine) => machine, Err(refusal) => return Ok(refusal), }; let Some(slot) = StreamSlots::acquire( &app.stream_slots, &machine.client_id, MAX_STREAMS_PER_CLIENT, ) else { let mut response = api_error( StatusCode::TOO_MANY_REQUESTS, "rate_limited", "This client already has the maximum number of directory streams open.", None, ); response .headers_mut() .insert("retry-after", HeaderValue::from_static(RETRY_AFTER_SECS)); return Ok(response); }; // Subscribed before the feed is read, so a change made in between still wakes the stream. let wake = app.store.directory_watch(); let head = app.store.directory_head().await?; let oldest = app.store.directory_oldest().await?; let requested = requested_cursor(cx); let Some(start) = resume_point(requested.as_deref(), head, oldest) else { return sse(cx, stream::iter(vec![Ok(resync_event())])); }; let deadline = Instant::now() + stream_life(&machine); let follow = Follow { stop: app.stop.clone(), store: app.store.clone(), client_id: machine.client_id.clone(), cursor: start, wake, check: tokio::time::interval_at(Instant::now() + KEEP_ALIVE, KEEP_ALIVE), deadline, pending: VecDeque::new(), _slot: slot, }; sse(cx, follow_events(follow)) } /// The state of one stream between two events. struct Follow { /// Set when the process stops: the stream then ends, so the server can drain. stop: watch::Receiver, store: Store, client_id: String, /// The last sequence number sent. cursor: i64, /// Woken by every committed directory change. wake: watch::Receiver, /// Checks, every [`KEEP_ALIVE`], that the calling client is still enabled. check: Interval, /// The stream ends at this time (the token's expiry or the 50-minute cap). deadline: Instant, /// Events read but not yet sent. pending: VecDeque, /// Holds the client's slot for as long as the stream lives. _slot: SlotGuard, } /// The events of a stream from its cursor on. It ends on a store failure, a disabled client, the /// deadline, or a closed feed; the browser or consumer reconnects with its last cursor. fn follow_events(follow: Follow) -> impl Stream> + Send + 'static { stream::unfold(follow, |mut follow| async move { loop { if let Some(event) = follow.pending.pop_front() { return Some((Ok(event), follow)); } match follow .store .directory_changes_after(follow.cursor, BATCH) .await { Ok(changes) if !changes.is_empty() => { for change in changes { match change_event(&follow.store, &change).await { Ok(event) => follow.pending.push_back(event), Err(error) => { tracing::error!(error = %error, "directory stream: a change could not be read"); return None; } } follow.cursor = change.seq; } continue; } Ok(_) => {} Err(error) => { tracing::error!(error = %error, "directory stream: the feed could not be read"); return None; } } tokio::select! { changed = follow.wake.changed() => { if changed.is_err() { return None; } } _ = follow.check.tick() => { match follow.store.client_by_id(&follow.client_id).await { Ok(Some(client)) if !client.is_disabled() => {} _ => return None, } } () = stopped(&mut follow.stop) => return None, () = tokio::time::sleep_until(follow.deadline) => return None, } } }) } /// Resolves when the stop flag is set. A flag whose sender is gone never resolves, so a stream is not /// ended by a test state that has no server behind it. async fn stopped(stop: &mut watch::Receiver) { if stop.wait_for(|stopped| *stopped).await.is_err() { std::future::pending::<()>().await; } } /// The event of one change row, with the row's sequence number as its id. A member row is sent with the /// person's current record; if the person is gone by then, the event is `deleted`. async fn change_event(store: &Store, change: &Change) -> im_core::Result { let user = match change.kind { ChangeKind::Member => store.user_by_id(&change.sub).await?, ChangeKind::Deleted => None, }; let event = match user { Some(user) => Event::new() .event("member") .data(member_json(&user).to_string()), None => Event::new() .event("deleted") .data(json!({"sub": change.sub}).to_string()), }; Ok(event.id(change.seq.to_string())) } /// The one `resync` event: the cursor is unusable, so the consumer reads the listing again. fn resync_event() -> Event { Event::new().event("resync").data("{}") } /// The cursor the client asked to resume from: `Last-Event-ID`, else `?cursor=`. A repeated `cursor` /// parameter is treated as garbage, which means resync. fn requested_cursor(cx: &Cx) -> Option { if let Some(id) = last_event_id(cx).filter(|id| !id.is_empty()) { return Some(id.to_owned()); } let query = uri(cx).query()?; let pairs = parse_pairs(query.as_bytes())?; match crate::oidc::single(&pairs, "cursor") { crate::oidc::Single::Absent => None, crate::oidc::Single::One(value) => Some(value.to_owned()), crate::oidc::Single::Repeated => Some(String::new()), } } /// Where a stream starts, or `None` when it must resync. No cursor starts at the head (the consumer reads /// the listing first). A cursor must be digits only, not ahead of the head, and not older than the oldest /// kept row: the rows between it and that row were pruned, so they cannot be replayed. pub fn resume_point(requested: Option<&str>, head: i64, oldest: Option) -> Option { let Some(text) = requested else { return Some(head); }; if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) { return None; } let cursor: i64 = text.parse().ok()?; if cursor > head { return None; } if let Some(oldest) = oldest && cursor.saturating_add(1) < oldest { return None; } Some(cursor) } /// How long a stream of this caller may live: until the token expires, and at most [`STREAM_MAX_LIFE`]. fn stream_life(machine: &Machine) -> Duration { let until_expiry = u64::try_from(machine.expires_at - unix_now()).unwrap_or(0); Duration::from_secs(until_expiry).min(STREAM_MAX_LIFE) } /// The response of a stream: the events, with a keep-alive comment while idle. `X-Accel-Buffering: no` /// stops a reverse proxy from holding the events back. fn sse( cx: &Cx, events: impl Stream> + Send + 'static, ) -> Result { let mut response = Sse::new(events) .keep_alive(KeepAlive::new().interval(KEEP_ALIVE).text("keepalive")) .into_response(cx)?; response .headers_mut() .insert("x-accel-buffering", HeaderValue::from_static("no")); Ok(response) } #[cfg(test)] mod tests { use super::*; #[test] fn a_cursor_resumes_only_inside_the_kept_range() { // No cursor: start at the head. assert_eq!(resume_point(None, 7, Some(3)), Some(7)); // Inside the range, and at the head. assert_eq!(resume_point(Some("5"), 7, Some(3)), Some(5)); assert_eq!(resume_point(Some("7"), 7, Some(3)), Some(7)); // Ahead of the head, negative, empty, signed or not a number: resync. assert_eq!(resume_point(Some("8"), 7, Some(3)), None); assert_eq!(resume_point(Some("-1"), 7, Some(3)), None); assert_eq!(resume_point(Some("+1"), 7, Some(3)), None); assert_eq!(resume_point(Some(""), 7, Some(3)), None); assert_eq!(resume_point(Some("abc"), 7, Some(3)), None); // Rows 1 and 2 were pruned, so row 3 is the oldest kept. A cursor of 1 still needs row 2: resync. // A cursor of 2 needs only rows from 3 on: fine. assert_eq!(resume_point(Some("1"), 7, Some(3)), None); assert_eq!(resume_point(Some("2"), 7, Some(3)), Some(2)); // Empty feed: cursor 0 is at the head. assert_eq!(resume_point(Some("0"), 0, None), Some(0)); } }