//! The members mirror: a local copy of the people directory of `im` (contracts section 3), kept current by //! a stream, so pages show a name or an avatar without calling `im`. //! //! The worker does a full fetch when it has no cursor yet, then follows the event stream from the cursor //! it stored in the `settings` table. A `resync` event means the cursor is too old: the next round does a //! full fetch. A `deleted` event, a `disabled` member, and a person missing from a full fetch all end the //! person's local sessions, which is the second of the two paths in contracts section 2.5. //! //! When the stream fails, the worker waits with exponential backoff from 1 s to 60 s, each wait a random //! point between half of the step and the whole step, so a restarted `im` is not hit all at once. A stream that ends //! on its own (the 50-minute close of contracts section 3.2) is reconnected after one second, provided it //! carried events or stayed open for a minute. A stream that closes at once without events is retried with //! the backoff, so a proxy that keeps closing connections cannot make the worker reconnect every second. use std::collections::HashSet; use std::time::{Duration, Instant}; use futures_util::StreamExt; use http::header::ACCEPT; use in_core::store::members::MemberFields; use in_core::time::now_stamp; use serde::Deserialize; use tokio::sync::watch; use crate::oidc::{OidcClient, OidcError, read_limited}; use crate::state::AppState; /// The `settings` key of the directory cursor. pub const CURSOR_KEY: &str = "directory_cursor"; /// The first wait after a failure. const BACKOFF_FIRST: Duration = Duration::from_secs(1); /// The longest wait between attempts after failures. const BACKOFF_MAX: Duration = Duration::from_secs(60); /// The pause after a stream that ended cleanly, before it is reconnected. const CLEAN_PAUSE: Duration = Duration::from_secs(1); /// How long a stream must stay open, with no event at all, to count as healthy. A quiet directory keeps /// a stream open for a long time without events, so that is not a failure. const QUIET_STREAM_HEALTHY: Duration = Duration::from_secs(60); /// The largest full listing the mirror reads. Matches the cap that `iz` uses for the same listing. const ROSTER_MAX_BYTES: usize = 8 * 1024 * 1024; /// The largest single event, and the longest line, the stream may carry. A longer one ends the stream. const MAX_STREAM_BYTES: usize = 64 * 1024; /// Why one round of syncing failed. #[derive(Debug, thiserror::Error)] enum SyncError { /// A token could not be had from `im`. #[error(transparent)] Oidc(#[from] OidcError), /// A local write failed. #[error(transparent)] Store(#[from] in_core::error::Error), /// The request to `im` failed on the way. #[error("the request to im failed: {0}")] Transport(String), /// `im` answered with a non-success status. #[error("im answered {0}")] Status(reqwest::StatusCode), /// The full directory could not be read. #[error("the directory listing is not what the contracts describe")] Listing, /// `im` sent more than the mirror accepts, in one answer or one event. #[error("im sent more than the mirror accepts")] TooLarge, } /// One member as the directory sends it (contracts section 3.1). Unknown fields are ignored. #[derive(Debug, Deserialize)] struct WireMember { sub: String, #[serde(default)] email: String, #[serde(default)] name: String, #[serde(default)] admin: bool, #[serde(default)] disabled: bool, #[serde(default)] locale: String, #[serde(default)] zoneinfo: String, #[serde(default)] picture_version: i64, #[serde(default)] updated_at: String, } /// The full listing (contracts section 3.2). #[derive(Debug, Deserialize)] struct Listing { #[serde(default)] members: Vec, #[serde(default)] cursor: String, } /// The data of a `deleted` event. #[derive(Debug, Deserialize)] struct DeletedEvent { sub: String, } /// One server-sent event: its id (the cursor), its name and its data. #[derive(Debug, Clone, PartialEq, Eq)] struct SseEvent { id: Option, event: String, data: String, } /// Incremental parser of `text/event-stream`. Bytes go in in any split; complete events come out. #[derive(Debug, Default)] struct SseParser { buffer: Vec, id: Option, event: String, data: Vec, } impl SseParser { /// Adds bytes and returns the events they complete. A blank line ends an event; lines that start /// with `:` are comments (keep-alives) and are skipped. An event or a line over /// [`MAX_STREAM_BYTES`] is an error, so a hostile stream cannot grow the buffers without bound. fn push(&mut self, chunk: &[u8]) -> Result, SyncError> { self.buffer.extend_from_slice(chunk); let mut events = Vec::new(); while let Some(end) = self.buffer.iter().position(|byte| *byte == b'\n') { let raw: Vec = self.buffer.drain(..=end).collect(); let line = String::from_utf8_lossy(&raw); let line = line.trim_end_matches(['\n', '\r']); if line.is_empty() { if !self.data.is_empty() { events.push(SseEvent { id: self.id.take(), event: if self.event.is_empty() { "message".to_owned() } else { std::mem::take(&mut self.event) }, data: self.data.join("\n"), }); self.data.clear(); } self.event.clear(); continue; } if line.starts_with(':') { continue; } let (field, value) = match line.split_once(':') { Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)), None => (line, ""), }; match field { "event" => self.event = value.to_owned(), "data" => { self.data.push(value.to_owned()); if self.data.iter().map(String::len).sum::() > MAX_STREAM_BYTES { return Err(SyncError::TooLarge); } } "id" => self.id = Some(value.to_owned()), _ => {} } } if self.buffer.len() > MAX_STREAM_BYTES { return Err(SyncError::TooLarge); } Ok(events) } } /// What a stream connection did when it stopped on its own. enum Ended { /// The server asked for a full fetch. Resync, /// The stream closed (the server's 50-minute close, or a stop). `healthy` is false for a stream /// that closed at once without events, which counts as a failure for the backoff. Closed { healthy: bool }, } /// The outcome of a stream that closed on its own, judged by what it did before it closed. fn closed(opened: Instant, applied: bool) -> Ended { Ended::Closed { healthy: applied || opened.elapsed() >= QUIET_STREAM_HEALTHY, } } /// Runs the mirror until `stop` is set. Does nothing without an OIDC client. pub async fn run(state: AppState, mut stop: watch::Receiver) { let Some(oidc) = state.oidc.clone() else { return; }; let mut needs_full = matches!(state.store.get_setting(CURSOR_KEY).await, Ok(None) | Err(_)); let mut backoff = BACKOFF_FIRST; loop { if *stop.borrow() { return; } let pause = match round(&state, &oidc, &mut needs_full, &mut stop).await { Ok(Ended::Resync) => { needs_full = true; backoff = BACKOFF_FIRST; CLEAN_PAUSE } Ok(Ended::Closed { healthy: true }) => { backoff = BACKOFF_FIRST; CLEAN_PAUSE } Ok(Ended::Closed { healthy: false }) => { let pause = jittered(backoff); backoff = (backoff * 2).min(BACKOFF_MAX); pause } Err(error) => { tracing::warn!(error = %error, "directory: sync failed, retrying"); needs_full = true; let pause = jittered(backoff); backoff = (backoff * 2).min(BACKOFF_MAX); pause } }; tokio::select! { _ = stop.wait_for(|stopped| *stopped) => return, () = tokio::time::sleep(pause) => {} } } } /// One round: a full fetch when one is due, then the stream from the stored cursor. The flag is cleared /// once the full fetch has applied, so a plain reconnect resumes from the cursor without reading the /// whole listing again. async fn round( state: &AppState, oidc: &OidcClient, needs_full: &mut bool, stop: &mut watch::Receiver, ) -> Result { if *needs_full { full_sync(state, oidc).await?; *needs_full = false; } follow(state, oidc, stop).await } /// Fetches the whole directory, applies it, and stores its cursor. People the listing does not name any /// more are marked deleted, and their sessions end. async fn full_sync(state: &AppState, oidc: &OidcClient) -> Result<(), SyncError> { let token = oidc.service_token().await?; let response = oidc .http() .get(format!("{}/api/v1/directory", oidc.issuer())) .bearer_auth(token) .header(ACCEPT, "application/json") .send() .await .map_err(|e| SyncError::Transport(e.without_url().to_string()))?; if !response.status().is_success() { return Err(SyncError::Status(response.status())); } let bytes = read_limited(response, ROSTER_MAX_BYTES) .await .map_err(|e| SyncError::Transport(e.without_url().to_string()))? .ok_or(SyncError::TooLarge)?; let listing: Listing = serde_json::from_slice(&bytes).map_err(|_| SyncError::Listing)?; let mut named = HashSet::new(); for member in listing.members { named.insert(member.sub.clone()); apply_member(state, member).await?; } for local in state.store.list_members().await? { if !named.contains(&local.sub) && !local.disabled { end_person(state, &local.sub).await?; } } if !listing.cursor.is_empty() { state.store.set_setting(CURSOR_KEY, &listing.cursor).await?; } tracing::info!(members = named.len(), "directory: full sync applied"); Ok(()) } /// Opens the event stream from the stored cursor and applies events until the stream ends, a `resync` /// arrives, or `stop` is set. async fn follow( state: &AppState, oidc: &OidcClient, stop: &mut watch::Receiver, ) -> Result { let cursor = state.store.get_setting(CURSOR_KEY).await?; let token = oidc.service_token().await?; let mut request = oidc .stream_http() .get(format!("{}/api/v1/directory/stream", oidc.issuer())) .bearer_auth(token) .header(ACCEPT, "text/event-stream"); if let Some(cursor) = &cursor { request = request.header("Last-Event-ID", cursor.as_str()); } let response = request .send() .await .map_err(|e| SyncError::Transport(e.without_url().to_string()))?; if !response.status().is_success() { return Err(SyncError::Status(response.status())); } tracing::info!("directory: stream connected"); let opened = Instant::now(); let mut applied = false; let mut body = response.bytes_stream(); let mut parser = SseParser::default(); loop { let chunk = tokio::select! { chunk = body.next() => chunk, _ = stop.wait_for(|stopped| *stopped) => return Ok(closed(opened, applied)), }; let Some(chunk) = chunk else { return Ok(closed(opened, applied)); }; let chunk = chunk.map_err(|e| SyncError::Transport(e.without_url().to_string()))?; for event in parser.push(&chunk)? { applied = true; if let Some(ended) = apply_event(state, event).await? { return Ok(ended); } } } } /// Applies one stream event. `Some` means the stream must stop: a `resync`. An event that cannot be read /// is logged and skipped, so one bad event cannot stall the mirror forever. async fn apply_event(state: &AppState, event: SseEvent) -> Result, SyncError> { match event.event.as_str() { "member" => match serde_json::from_str::(&event.data) { Ok(member) => apply_member(state, member).await?, Err(_) => tracing::warn!("directory: a member event could not be read"), }, "deleted" => match serde_json::from_str::(&event.data) { Ok(deleted) => end_person(state, &deleted.sub).await?, Err(_) => tracing::warn!("directory: a deleted event could not be read"), }, "resync" => return Ok(Some(Ended::Resync)), _ => {} } if let Some(id) = &event.id { state.store.set_setting(CURSOR_KEY, id).await?; } Ok(None) } /// Writes one member from the directory. A disabled member's sessions end as well. async fn apply_member(state: &AppState, member: WireMember) -> Result<(), SyncError> { if !valid_sub(&member.sub) { tracing::warn!("directory: a member has an invalid id and is skipped"); return Ok(()); } let name = if member.name.trim().is_empty() { member.email.clone() } else { member.name }; let fields = MemberFields { sub: member.sub.clone(), email: member.email, name, is_admin: member.admin, locale: if member.locale.is_empty() { "en".to_owned() } else { member.locale }, zoneinfo: if member.zoneinfo.is_empty() { "UTC".to_owned() } else { member.zoneinfo }, picture_version: member.picture_version.max(0), im_updated_at: if member.updated_at.is_empty() { now_stamp() } else { member.updated_at }, }; let default_quota = in_core::settings::resolve( &state.store, &state.config.limits, in_core::settings::DEFAULT_QUOTA_KEY, ) .await? .value; let stored = state .store .apply_directory_member(&fields, member.disabled, default_quota) .await?; if stored.disabled { state.store.delete_sessions_by_sub(&stored.sub).await?; } Ok(()) } /// Marks a person deleted and ends their sessions. async fn end_person(state: &AppState, sub: &str) -> Result<(), SyncError> { if !valid_sub(sub) { return Ok(()); } state.store.mark_member_deleted(sub).await?; state.store.delete_sessions_by_sub(sub).await?; Ok(()) } /// Whether `sub` is a plain identifier. Subjects are ULIDs; anything else is not stored. fn valid_sub(sub: &str) -> bool { !sub.is_empty() && sub.len() <= 64 && sub .bytes() .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') } /// A random wait between half of `base` and `base`, so that retries spread out. fn jittered(base: Duration) -> Duration { let half = base / 2; let span = u64::try_from(half.as_millis()).unwrap_or(u64::MAX); let mut bytes = [0u8; 8]; rand::fill(&mut bytes); let offset = u64::from_le_bytes(bytes) % span.saturating_add(1); half + Duration::from_millis(offset) } #[cfg(test)] mod tests { use super::*; #[test] fn events_are_parsed_across_chunks_and_comments_are_skipped() { let mut parser = SseParser::default(); assert!( parser .push(b": keep-alive\nid: 7\nevent: mem") .expect("bytes") .is_empty() ); let events = parser .push(b"ber\ndata: {\"sub\":\"a\"}\n\n") .expect("bytes"); assert_eq!( events, vec![SseEvent { id: Some("7".into()), event: "member".into(), data: "{\"sub\":\"a\"}".into(), }] ); let events = parser .push(b"event: resync\ndata: {}\r\n\r\n") .expect("bytes"); assert_eq!(events[0].event, "resync"); } #[test] fn jitter_stays_in_the_upper_half_of_the_step() { for _ in 0..50 { let wait = jittered(Duration::from_secs(8)); assert!(wait >= Duration::from_secs(4) && wait <= Duration::from_secs(8)); } } }