forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

directory.rs476 lines, 16.5 KiBHistoryRawDownload
1//! The members mirror: a local copy of the people directory of `im` (contracts section 3), kept current by
2//! a stream, so pages show a name or an avatar without calling `im`.
3//!
4//! The worker does a full fetch when it has no cursor yet, then follows the event stream from the cursor
5//! it stored in the `settings` table. A `resync` event means the cursor is too old: the next round does a
6//! full fetch. A `deleted` event, a `disabled` member, and a person missing from a full fetch all end the
7//! person's local sessions, which is the second of the two paths in contracts section 2.5.
8//!
9//! When the stream fails, the worker waits with exponential backoff from 1 s to 60 s, each wait a random
10//! point between half of the step and the whole step, so a restarted `im` is not hit all at once. A stream that ends
11//! on its own (the 50-minute close of contracts section 3.2) is reconnected after one second, provided it
12//! carried events or stayed open for a minute. A stream that closes at once without events is retried with
13//! the backoff, so a proxy that keeps closing connections cannot make the worker reconnect every second.
14
15use std::collections::HashSet;
16use std::time::{Duration, Instant};
17
18use futures_util::StreamExt;
19use http::header::ACCEPT;
20use in_core::store::members::MemberFields;
21use in_core::time::now_stamp;
22use serde::Deserialize;
23use tokio::sync::watch;
24
25use crate::oidc::{OidcClient, OidcError, read_limited};
26use crate::state::AppState;
27
28/// The `settings` key of the directory cursor.
29pub const CURSOR_KEY: &str = "directory_cursor";
30
31/// The first wait after a failure.
32const BACKOFF_FIRST: Duration = Duration::from_secs(1);
33
34/// The longest wait between attempts after failures.
35const BACKOFF_MAX: Duration = Duration::from_secs(60);
36
37/// The pause after a stream that ended cleanly, before it is reconnected.
38const CLEAN_PAUSE: Duration = Duration::from_secs(1);
39
40/// How long a stream must stay open, with no event at all, to count as healthy. A quiet directory keeps
41/// a stream open for a long time without events, so that is not a failure.
42const QUIET_STREAM_HEALTHY: Duration = Duration::from_secs(60);
43
44/// The largest full listing the mirror reads. Matches the cap that `iz` uses for the same listing.
45const ROSTER_MAX_BYTES: usize = 8 * 1024 * 1024;
46
47/// The largest single event, and the longest line, the stream may carry. A longer one ends the stream.
48const MAX_STREAM_BYTES: usize = 64 * 1024;
49
50/// Why one round of syncing failed.
51#[derive(Debug, thiserror::Error)]
52enum SyncError {
53 /// A token could not be had from `im`.
54 #[error(transparent)]
55 Oidc(#[from] OidcError),
56 /// A local write failed.
57 #[error(transparent)]
58 Store(#[from] in_core::error::Error),
59 /// The request to `im` failed on the way.
60 #[error("the request to im failed: {0}")]
61 Transport(String),
62 /// `im` answered with a non-success status.
63 #[error("im answered {0}")]
64 Status(reqwest::StatusCode),
65 /// The full directory could not be read.
66 #[error("the directory listing is not what the contracts describe")]
67 Listing,
68 /// `im` sent more than the mirror accepts, in one answer or one event.
69 #[error("im sent more than the mirror accepts")]
70 TooLarge,
71}
72
73/// One member as the directory sends it (contracts section 3.1). Unknown fields are ignored.
74#[derive(Debug, Deserialize)]
75struct WireMember {
76 sub: String,
77 #[serde(default)]
78 email: String,
79 #[serde(default)]
80 name: String,
81 #[serde(default)]
82 admin: bool,
83 #[serde(default)]
84 disabled: bool,
85 #[serde(default)]
86 locale: String,
87 #[serde(default)]
88 zoneinfo: String,
89 #[serde(default)]
90 picture_version: i64,
91 #[serde(default)]
92 updated_at: String,
93}
94
95/// The full listing (contracts section 3.2).
96#[derive(Debug, Deserialize)]
97struct Listing {
98 #[serde(default)]
99 members: Vec<WireMember>,
100 #[serde(default)]
101 cursor: String,
102}
103
104/// The data of a `deleted` event.
105#[derive(Debug, Deserialize)]
106struct DeletedEvent {
107 sub: String,
108}
109
110/// One server-sent event: its id (the cursor), its name and its data.
111#[derive(Debug, Clone, PartialEq, Eq)]
112struct SseEvent {
113 id: Option<String>,
114 event: String,
115 data: String,
116}
117
118/// Incremental parser of `text/event-stream`. Bytes go in in any split; complete events come out.
119#[derive(Debug, Default)]
120struct SseParser {
121 buffer: Vec<u8>,
122 id: Option<String>,
123 event: String,
124 data: Vec<String>,
125}
126
127impl SseParser {
128 /// Adds bytes and returns the events they complete. A blank line ends an event; lines that start
129 /// with `:` are comments (keep-alives) and are skipped. An event or a line over
130 /// [`MAX_STREAM_BYTES`] is an error, so a hostile stream cannot grow the buffers without bound.
131 fn push(&mut self, chunk: &[u8]) -> Result<Vec<SseEvent>, SyncError> {
132 self.buffer.extend_from_slice(chunk);
133 let mut events = Vec::new();
134 while let Some(end) = self.buffer.iter().position(|byte| *byte == b'\n') {
135 let raw: Vec<u8> = self.buffer.drain(..=end).collect();
136 let line = String::from_utf8_lossy(&raw);
137 let line = line.trim_end_matches(['\n', '\r']);
138 if line.is_empty() {
139 if !self.data.is_empty() {
140 events.push(SseEvent {
141 id: self.id.take(),
142 event: if self.event.is_empty() {
143 "message".to_owned()
144 } else {
145 std::mem::take(&mut self.event)
146 },
147 data: self.data.join("\n"),
148 });
149 self.data.clear();
150 }
151 self.event.clear();
152 continue;
153 }
154 if line.starts_with(':') {
155 continue;
156 }
157 let (field, value) = match line.split_once(':') {
158 Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)),
159 None => (line, ""),
160 };
161 match field {
162 "event" => self.event = value.to_owned(),
163 "data" => {
164 self.data.push(value.to_owned());
165 if self.data.iter().map(String::len).sum::<usize>() > MAX_STREAM_BYTES {
166 return Err(SyncError::TooLarge);
167 }
168 }
169 "id" => self.id = Some(value.to_owned()),
170 _ => {}
171 }
172 }
173 if self.buffer.len() > MAX_STREAM_BYTES {
174 return Err(SyncError::TooLarge);
175 }
176 Ok(events)
177 }
178}
179
180/// What a stream connection did when it stopped on its own.
181enum Ended {
182 /// The server asked for a full fetch.
183 Resync,
184 /// The stream closed (the server's 50-minute close, or a stop). `healthy` is false for a stream
185 /// that closed at once without events, which counts as a failure for the backoff.
186 Closed { healthy: bool },
187}
188
189/// The outcome of a stream that closed on its own, judged by what it did before it closed.
190fn closed(opened: Instant, applied: bool) -> Ended {
191 Ended::Closed {
192 healthy: applied || opened.elapsed() >= QUIET_STREAM_HEALTHY,
193 }
194}
195
196/// Runs the mirror until `stop` is set. Does nothing without an OIDC client.
197pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) {
198 let Some(oidc) = state.oidc.clone() else {
199 return;
200 };
201 let mut needs_full = matches!(state.store.get_setting(CURSOR_KEY).await, Ok(None) | Err(_));
202 let mut backoff = BACKOFF_FIRST;
203 loop {
204 if *stop.borrow() {
205 return;
206 }
207 let pause = match round(&state, &oidc, &mut needs_full, &mut stop).await {
208 Ok(Ended::Resync) => {
209 needs_full = true;
210 backoff = BACKOFF_FIRST;
211 CLEAN_PAUSE
212 }
213 Ok(Ended::Closed { healthy: true }) => {
214 backoff = BACKOFF_FIRST;
215 CLEAN_PAUSE
216 }
217 Ok(Ended::Closed { healthy: false }) => {
218 let pause = jittered(backoff);
219 backoff = (backoff * 2).min(BACKOFF_MAX);
220 pause
221 }
222 Err(error) => {
223 tracing::warn!(error = %error, "directory: sync failed, retrying");
224 needs_full = true;
225 let pause = jittered(backoff);
226 backoff = (backoff * 2).min(BACKOFF_MAX);
227 pause
228 }
229 };
230 tokio::select! {
231 _ = stop.wait_for(|stopped| *stopped) => return,
232 () = tokio::time::sleep(pause) => {}
233 }
234 }
235}
236
237/// One round: a full fetch when one is due, then the stream from the stored cursor. The flag is cleared
238/// once the full fetch has applied, so a plain reconnect resumes from the cursor without reading the
239/// whole listing again.
240async fn round(
241 state: &AppState,
242 oidc: &OidcClient,
243 needs_full: &mut bool,
244 stop: &mut watch::Receiver<bool>,
245) -> Result<Ended, SyncError> {
246 if *needs_full {
247 full_sync(state, oidc).await?;
248 *needs_full = false;
249 }
250 follow(state, oidc, stop).await
251}
252
253/// Fetches the whole directory, applies it, and stores its cursor. People the listing does not name any
254/// more are marked deleted, and their sessions end.
255async fn full_sync(state: &AppState, oidc: &OidcClient) -> Result<(), SyncError> {
256 let token = oidc.service_token().await?;
257 let response = oidc
258 .http()
259 .get(format!("{}/api/v1/directory", oidc.issuer()))
260 .bearer_auth(token)
261 .header(ACCEPT, "application/json")
262 .send()
263 .await
264 .map_err(|e| SyncError::Transport(e.without_url().to_string()))?;
265 if !response.status().is_success() {
266 return Err(SyncError::Status(response.status()));
267 }
268 let bytes = read_limited(response, ROSTER_MAX_BYTES)
269 .await
270 .map_err(|e| SyncError::Transport(e.without_url().to_string()))?
271 .ok_or(SyncError::TooLarge)?;
272 let listing: Listing = serde_json::from_slice(&bytes).map_err(|_| SyncError::Listing)?;
273
274 let mut named = HashSet::new();
275 for member in listing.members {
276 named.insert(member.sub.clone());
277 apply_member(state, member).await?;
278 }
279 for local in state.store.list_members().await? {
280 if !named.contains(&local.sub) && !local.disabled {
281 end_person(state, &local.sub).await?;
282 }
283 }
284 if !listing.cursor.is_empty() {
285 state.store.set_setting(CURSOR_KEY, &listing.cursor).await?;
286 }
287 tracing::info!(members = named.len(), "directory: full sync applied");
288 Ok(())
289}
290
291/// Opens the event stream from the stored cursor and applies events until the stream ends, a `resync`
292/// arrives, or `stop` is set.
293async fn follow(
294 state: &AppState,
295 oidc: &OidcClient,
296 stop: &mut watch::Receiver<bool>,
297) -> Result<Ended, SyncError> {
298 let cursor = state.store.get_setting(CURSOR_KEY).await?;
299 let token = oidc.service_token().await?;
300 let mut request = oidc
301 .stream_http()
302 .get(format!("{}/api/v1/directory/stream", oidc.issuer()))
303 .bearer_auth(token)
304 .header(ACCEPT, "text/event-stream");
305 if let Some(cursor) = &cursor {
306 request = request.header("Last-Event-ID", cursor.as_str());
307 }
308 let response = request
309 .send()
310 .await
311 .map_err(|e| SyncError::Transport(e.without_url().to_string()))?;
312 if !response.status().is_success() {
313 return Err(SyncError::Status(response.status()));
314 }
315 tracing::info!("directory: stream connected");
316
317 let opened = Instant::now();
318 let mut applied = false;
319 let mut body = response.bytes_stream();
320 let mut parser = SseParser::default();
321 loop {
322 let chunk = tokio::select! {
323 chunk = body.next() => chunk,
324 _ = stop.wait_for(|stopped| *stopped) => return Ok(closed(opened, applied)),
325 };
326 let Some(chunk) = chunk else {
327 return Ok(closed(opened, applied));
328 };
329 let chunk = chunk.map_err(|e| SyncError::Transport(e.without_url().to_string()))?;
330 for event in parser.push(&chunk)? {
331 applied = true;
332 if let Some(ended) = apply_event(state, event).await? {
333 return Ok(ended);
334 }
335 }
336 }
337}
338
339/// Applies one stream event. `Some` means the stream must stop: a `resync`. An event that cannot be read
340/// is logged and skipped, so one bad event cannot stall the mirror forever.
341async fn apply_event(state: &AppState, event: SseEvent) -> Result<Option<Ended>, SyncError> {
342 match event.event.as_str() {
343 "member" => match serde_json::from_str::<WireMember>(&event.data) {
344 Ok(member) => apply_member(state, member).await?,
345 Err(_) => tracing::warn!("directory: a member event could not be read"),
346 },
347 "deleted" => match serde_json::from_str::<DeletedEvent>(&event.data) {
348 Ok(deleted) => end_person(state, &deleted.sub).await?,
349 Err(_) => tracing::warn!("directory: a deleted event could not be read"),
350 },
351 "resync" => return Ok(Some(Ended::Resync)),
352 _ => {}
353 }
354 if let Some(id) = &event.id {
355 state.store.set_setting(CURSOR_KEY, id).await?;
356 }
357 Ok(None)
358}
359
360/// Writes one member from the directory. A disabled member's sessions end as well.
361async fn apply_member(state: &AppState, member: WireMember) -> Result<(), SyncError> {
362 if !valid_sub(&member.sub) {
363 tracing::warn!("directory: a member has an invalid id and is skipped");
364 return Ok(());
365 }
366 let name = if member.name.trim().is_empty() {
367 member.email.clone()
368 } else {
369 member.name
370 };
371 let fields = MemberFields {
372 sub: member.sub.clone(),
373 email: member.email,
374 name,
375 is_admin: member.admin,
376 locale: if member.locale.is_empty() {
377 "en".to_owned()
378 } else {
379 member.locale
380 },
381 zoneinfo: if member.zoneinfo.is_empty() {
382 "UTC".to_owned()
383 } else {
384 member.zoneinfo
385 },
386 picture_version: member.picture_version.max(0),
387 im_updated_at: if member.updated_at.is_empty() {
388 now_stamp()
389 } else {
390 member.updated_at
391 },
392 };
393 let default_quota = in_core::settings::resolve(
394 &state.store,
395 &state.config.limits,
396 in_core::settings::DEFAULT_QUOTA_KEY,
397 )
398 .await?
399 .value;
400 let stored = state
401 .store
402 .apply_directory_member(&fields, member.disabled, default_quota)
403 .await?;
404 if stored.disabled {
405 state.store.delete_sessions_by_sub(&stored.sub).await?;
406 }
407 Ok(())
408}
409
410/// Marks a person deleted and ends their sessions.
411async fn end_person(state: &AppState, sub: &str) -> Result<(), SyncError> {
412 if !valid_sub(sub) {
413 return Ok(());
414 }
415 state.store.mark_member_deleted(sub).await?;
416 state.store.delete_sessions_by_sub(sub).await?;
417 Ok(())
418}
419
420/// Whether `sub` is a plain identifier. Subjects are ULIDs; anything else is not stored.
421fn valid_sub(sub: &str) -> bool {
422 !sub.is_empty()
423 && sub.len() <= 64
424 && sub
425 .bytes()
426 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
427}
428
429/// A random wait between half of `base` and `base`, so that retries spread out.
430fn jittered(base: Duration) -> Duration {
431 let half = base / 2;
432 let span = u64::try_from(half.as_millis()).unwrap_or(u64::MAX);
433 let mut bytes = [0u8; 8];
434 rand::fill(&mut bytes);
435 let offset = u64::from_le_bytes(bytes) % span.saturating_add(1);
436 half + Duration::from_millis(offset)
437}
438
439#[cfg(test)]
440mod tests {
441 use super::*;
442
443 #[test]
444 fn events_are_parsed_across_chunks_and_comments_are_skipped() {
445 let mut parser = SseParser::default();
446 assert!(
447 parser
448 .push(b": keep-alive\nid: 7\nevent: mem")
449 .expect("bytes")
450 .is_empty()
451 );
452 let events = parser
453 .push(b"ber\ndata: {\"sub\":\"a\"}\n\n")
454 .expect("bytes");
455 assert_eq!(
456 events,
457 vec![SseEvent {
458 id: Some("7".into()),
459 event: "member".into(),
460 data: "{\"sub\":\"a\"}".into(),
461 }]
462 );
463 let events = parser
464 .push(b"event: resync\ndata: {}\r\n\r\n")
465 .expect("bytes");
466 assert_eq!(events[0].event, "resync");
467 }
468
469 #[test]
470 fn jitter_stays_in_the_upper_half_of_the_step() {
471 for _ in 0..50 {
472 let wait = jittered(Duration::from_secs(8));
473 assert!(wait >= Duration::from_secs(4) && wait <= Duration::from_secs(8));
474 }
475 }
476}