forge
Explore
Log in

Don't you dare go Hollow

im_old

Clone
★ 0

0 watching0 forksRustGPL-3.0755.6 KiB84318dcTahinli2 months ago77 commits

directory.rs540 lines, 20.5 KiBHistoryRawDownload
1//! im-client's directory half: the app-side mirror of im's identity
2//! roster. Three doors, all opened with the app's Basic pair:
3//!
4//! * [`DirectoryClient::directory`] — the whole roster, as im's
5//! `/directory` answers it;
6//! * [`DirectoryClient::photo`] — one member's photo bytes, for an
7//! `<img src>` served out of the app's own hands;
8//! event per changed member and one per sign-out in motion, parsed by
9//! hand from the byte stream.
10//!
11//! [`spawn_sync`] is the whole loop most apps want: a full pass through
12//! [`DirectoryClient::directory`], then the stream through the same
13//! `on_member` door, and — whenever the stream drops — a growing wait, a
14//! `on_resync` call, a fresh full pass, and back on the stream. The mirror
15//! converges no matter how the connection died.
16
17use std::time::Duration;
18
19use serde::{Deserialize, Serialize};
20use crate::{Error, Result};
21
22/// How long a plain request (roster, photo) may take. The live stream is
23/// exempt — it is *supposed* to sit idle — so its request carries no
24/// timeout and its liveness is the server's keep-alive comment.
25const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
26
27/// The first wait after a failed stream, and the growth step.
28const BACKOFF_FLOOR: Duration = Duration::from_secs(1);
29
30/// The longest wait a run of consecutive failures earns.
31const BACKOFF_CAP: Duration = Duration::from_secs(30);
32
33/// One roster member, exactly the shape im's `/directory` answers and its
34/// `/directory/live` stream announces. `admin` and `photo_version` default
35/// so an older im — whose answers predate them — still parses.
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37pub struct DirectoryMember {
38 /// The stable subject: the same string the id_token's `sub` claim and
39 /// the photo route's path carry.
40 pub sub: String,
41 pub email: String,
42 pub name: String,
43 #[serde(default)]
44 pub admin: bool,
45 /// How many times the member's photo has changed: the `?v=` that lets
46 /// `/photo/{sub}` be cached hard and still arrive fresh.
47 #[serde(default)]
48 pub photo_version: u64,
49 /// The member's display timezone (a fixed offset like "UTC+03:00").
50 /// Defaulted: rows mirrored before im carried the field still read.
51 #[serde(default = "default_timezone")]
52 pub timezone: String,
53 /// Whether im has switched the member off. Defaulted: a row mirrored
54 /// before im carried the field reads as present-and-enabled.
55 #[serde(default)]
56 pub disabled: bool,
57}
58
59/// The timezone im starts every account on, and the one this SDK assumes
60/// when a mirrored row predates the field.
61fn default_timezone() -> String {
62 "UTC+03:00".to_string()
63}
64
65/// One event off the directory stream: a member's row, or a sign-out in
66/// motion. The enum leaves room for the feed to grow without a breaking
67/// change to consumers — unknown frame kinds are skipped, not fatal.
68#[derive(Debug, Clone, PartialEq)]
69pub enum DirectoryEvent {
70 /// The named member's row changed — upload, address, admin flag, any
71 /// of it. The payload is the row as it now stands.
72 Profile(DirectoryMember),
73 /// The named subject's sessions were revoked: im's broadcast on any
74 /// logout-everywhere, disable, or delete. The app's cue to send that
75 /// subject's signed-in tabs home.
76 Revoked { sub: String },
77}
78
79/// The body of a `revoked` frame: the subject whose sessions died.
80#[derive(Deserialize)]
81struct RevokedFrame {
82 sub: String,
83}
84
85/// The directory client: issuer plus the same `client_id:client_secret`
86/// pair the OIDC side already holds. Cheap to clone; one HTTP pool inside.
87#[derive(Clone)]
88pub struct DirectoryClient {
89 http: reqwest::Client,
90 issuer: String,
91 client_id: String,
92 client_secret: String,
93}
94
95impl DirectoryClient {
96 pub fn new(
97 issuer: impl Into<String>,
98 client_id: impl Into<String>,
99 client_secret: impl Into<String>,
100 ) -> Self {
101 Self {
102 http: reqwest::Client::new(),
103 issuer: issuer.into(),
104 client_id: client_id.into(),
105 client_secret: client_secret.into(),
106 }
107 }
108
109 fn get(&self, path: &str) -> reqwest::RequestBuilder {
110 self.http
111 .get(format!("{}{path}", self.issuer))
112 .basic_auth(&self.client_id, Some(&self.client_secret))
113 }
114
115 /// `GET /directory`: the whole non-disabled roster, oldest first.
116 pub async fn directory(&self) -> Result<Vec<DirectoryMember>> {
117 let answer = self
118 .get("/directory")
119 .timeout(REQUEST_TIMEOUT)
120 .send()
121 .await
122 .map_err(|e| Error::Http(e.to_string()))?
123 .error_for_status()
124 .map_err(|e| Error::Refused(e.to_string()))?;
125 answer
126 .json()
127 .await
128 .map_err(|e| Error::Http(e.to_string()))
129 }
130
131 /// `GET /photo/{sub}`: the member's photo bytes and their content
132 /// type. A member with no photo gets im's default face — the initial
133 /// tile — so the answer is always an image.
134 pub async fn photo(&self, sub: &str) -> Result<(Vec<u8>, String)> {
135 let answer = self
136 .get(&format!("/photo/{sub}"))
137 .timeout(REQUEST_TIMEOUT)
138 .send()
139 .await
140 .map_err(|e| Error::Http(e.to_string()))?
141 .error_for_status()
142 .map_err(|e| Error::Refused(e.to_string()))?;
143 let content_type = answer
144 .headers()
145 .get(reqwest::header::CONTENT_TYPE)
146 .and_then(|value| value.to_str().ok())
147 .unwrap_or("application/octet-stream")
148 .to_string();
149 let bytes = answer
150 .bytes()
151 .await
152 .map_err(|e| Error::Http(e.to_string()))?
153 .to_vec();
154 Ok((bytes, content_type))
155 }
156
157 /// `GET /directory/live`: opens the change feed. Every frame after the
158 /// first is one member's row; the stream ends — `None` from
159 /// [`DirectoryStream::next`] — whenever im closes it, which is the
160 /// caller's cue to re-list and redial ([`spawn_sync`] does exactly
161 /// that).
162 pub async fn open_stream(&self) -> Result<DirectoryStream> {
163 let response = self
164 .get("/directory/live")
165 .send()
166 .await
167 .map_err(|e| Error::Http(e.to_string()))?
168 .error_for_status()
169 .map_err(|e| Error::Refused(e.to_string()))?;
170 Ok(DirectoryStream {
171 response,
172 parser: SseParser::default(),
173 ready: std::collections::VecDeque::new(),
174 })
175 }
176}
177
178/// An open `/directory/live` connection.
179pub struct DirectoryStream {
180 response: reqwest::Response,
181 parser: SseParser,
182 ready: std::collections::VecDeque<DirectoryEvent>,
183}
184
185impl DirectoryStream {
186 /// The next member change. `Some(Err)` on a network failure, then the
187 /// stream is over; `None` when im closed a healthy stream (a restart,
188 /// the server window). Either way the caller re-lists and redials.
189 pub async fn next(&mut self) -> Option<Result<DirectoryEvent>> {
190 loop {
191 if let Some(event) = self.ready.pop_front() {
192 return Some(Ok(event));
193 }
194 match self.response.chunk().await {
195 Ok(Some(bytes)) => self.ready.extend(self.parser.feed(&bytes)),
196 // The connection closed cleanly: a healthy stream's end.
197 Ok(None) => return None,
198 Err(e) => return Some(Err(Error::Http(e.to_string()))),
199 }
200 }
201 }
202}
203
204/// The hand-rolled `text/event-stream` reader. Frames accumulate field by
205/// field and dispatch on the blank line, per the SSE grammar; the only
206/// fields this feed carries are `event`, `data`, `retry`, and comments,
207/// but the parser honors the whole shape — including `data` split over
208/// several lines, which the spec joins with `\n`.
209#[derive(Default)]
210struct SseParser {
211 /// Bytes read but not yet through a line terminator.
212 pending: Vec<u8>,
213 /// The current frame's `event:` field, if it named one.
214 event: Option<String>,
215 /// The current frame's `data:`, joined back into one string.
216 data: String,
217}
218
219impl SseParser {
220 /// Feeds the next bytes from the wire and answers every frame they
221 /// completed. Bytes trailing their terminator wait for the rest — a
222 /// field or a UTF-8 character may straddle two reads.
223 fn feed(&mut self, bytes: &[u8]) -> Vec<DirectoryEvent> {
224 self.pending.extend_from_slice(bytes);
225 let mut events = Vec::new();
226 let Some(at) = self
227 .pending
228 .iter()
229 .rposition(|&b| b == b'\n' || b == b'\r')
230 .map(|at| at + 1)
231 else {
232 return events;
233 };
234 let block: Vec<u8> = self.pending.drain(..at).collect();
235 for line in split_lines(&block) {
236 if line.is_empty() {
237 // The blank line dispatches whatever accumulated.
238 if let Some(event) = self.take_event() {
239 events.push(event);
240 }
241 } else if line[0] == b':' {
242 // A comment — im's keep-alives and retry hint live here.
243 } else {
244 let (name, value) = match line.iter().position(|&b| b == b':') {
245 Some(at) => (&line[..at], &line[at + 1..]),
246 None => (&line[..], &b""[..]),
247 };
248 // One optional space after the colon is not part of the
249 // value.
250 let value = value.strip_prefix(b" ").unwrap_or(value);
251 match name {
252 b"event" => self.event = Some(String::from_utf8_lossy(value).into_owned()),
253 b"data" => {
254 if !self.data.is_empty() {
255 self.data.push('\n');
256 }
257 self.data.push_str(&String::from_utf8_lossy(value));
258 }
259 // `id` and `retry` mean nothing to a change feed.
260 _ => {}
261 }
262 }
263 }
264 events
265 }
266
267 /// Ends the current frame: the data, if it parsed into a member, is
268 /// the event. A frame that names another event type, or whose data is
269 /// not a member, is skipped — the feed may grow, and a single bad
270 /// frame must not end the connection.
271 fn take_event(&mut self) -> Option<DirectoryEvent> {
272 let data = std::mem::take(&mut self.data);
273 let event = self.event.take();
274 match event.as_deref() {
275 Some("revoked") => serde_json::from_str::<RevokedFrame>(&data)
276 .ok()
277 .map(|frame| DirectoryEvent::Revoked { sub: frame.sub }),
278 // A nameless frame (the retry hint, a tick) carries no member.
279 Some("profile") | None => serde_json::from_str::<DirectoryMember>(&data)
280 .ok()
281 .map(DirectoryEvent::Profile),
282 // The feed may grow: an unknown kind is skipped, not fatal.
283 Some(_) => None,
284 }
285 }
286}
287
288/// Splits a block that ends at a line terminator into lines, accepting the
289/// three SSE terminators: `\n`, `\r\n`, and a bare `\r`.
290fn split_lines(block: &[u8]) -> Vec<Vec<u8>> {
291 let mut lines = Vec::new();
292 let mut rest = block;
293 while let Some(at) = rest.iter().position(|&b| b == b'\n' || b == b'\r') {
294 let (line, tail) = rest.split_at(at);
295 lines.push(line.to_vec());
296 // A `\r\n` pair is one terminator, not a line and an empty one.
297 rest = if tail.starts_with(b"\r\n") { &tail[2..] } else { &tail[1..] };
298 }
299 lines
300}
301
302/// Keeps the app's mirror of the roster in step with im, forever:
303///
304/// 1. one full `/directory` pass, every member applied through
305/// `on_member` — the boot-time population;
306/// 2. the `/directory/live` stream, every change through the same door;
307/// 3. when the stream dies — error, lag, clean close — wait out the
308/// backoff (1s doubling to a 30s cap), call `on_resync`, replay a full
309/// pass, and resume the stream. A full pass that itself fails is
310/// retried on the same clock until im answers.
311///
312/// Runs until the task is aborted; the handle is the caller's to drop or
313/// cancel.
314pub fn spawn_sync<F, G>(
315 client: DirectoryClient,
316 mut on_member: F,
317 mut on_resync: G,
318) -> tokio::task::JoinHandle<()>
319where
320 F: FnMut(DirectoryMember) + Send + 'static,
321 G: FnMut() + Send + 'static,
322{
323 tokio::spawn(async move {
324 let mut backoff = BACKOFF_FLOOR;
325 loop {
326 // The full pass. There is nothing to converge with until one
327 // lands, so failures retry on the growing clock.
328 loop {
329 match client.directory().await {
330 Ok(members) => {
331 for member in members {
332 on_member(member);
333 }
334 break;
335 }
336 Err(_) => {
337 tokio::time::sleep(backoff).await;
338 backoff = (backoff * 2).min(BACKOFF_CAP);
339 }
340 }
341 }
342 let mut stream = match client.open_stream().await {
343 Ok(stream) => stream,
344 Err(_) => {
345 tokio::time::sleep(backoff).await;
346 backoff = (backoff * 2).min(BACKOFF_CAP);
347 on_resync();
348 continue;
349 }
350 };
351 while let Some(event) = stream.next().await {
352 match event {
353 Ok(DirectoryEvent::Profile(member)) => {
354 on_member(member);
355 // The stream works: the next stumble starts over
356 // at the short wait.
357 backoff = BACKOFF_FLOOR;
358 }
359 // A sign-out in motion: this loop's door carries
360 // members only. The frame is read and dropped — the
361 // app that needs the event reads the stream itself.
362 Ok(DirectoryEvent::Revoked { .. }) => {
363 backoff = BACKOFF_FLOOR;
364 }
365 Err(_) => break,
366 }
367 }
368 // The stream is gone. Wait, grow, and make the caller
369 // re-list the whole roster before the stream resumes, so
370 // whatever moved while the line was down heals on the pass.
371 tokio::time::sleep(backoff).await;
372 backoff = (backoff * 2).min(BACKOFF_CAP);
373 on_resync();
374 }
375 })
376}
377
378#[cfg(test)]
379mod tests {
380 use super::*;
381
382 fn member_json(sub: &str, version: u64) -> String {
383 format!(
384 "{{\"sub\":\"{sub}\",\"email\":\"{sub}@example.com\",\
385 \"name\":\"Ann\",\"admin\":false,\"photo_version\":{version}}}"
386 )
387 }
388
389 fn frame(sub: &str, version: u64) -> String {
390 format!("event: profile\ndata: {}\n\n", member_json(sub, version))
391 }
392
393 #[test]
394 fn a_profile_frame_becomes_an_event() {
395 let mut parser = SseParser::default();
396 let events = parser.feed(
397 format!("retry: 5000\n: keep-alive\n\n{}", frame("one", 3)).as_bytes(),
398 );
399 assert_eq!(
400 events,
401 vec![DirectoryEvent::Profile(DirectoryMember {
402 timezone: default_timezone(),
403 sub: "one".into(),
404 email: "one@example.com".into(),
405 name: "Ann".into(),
406 admin: false,
407 photo_version: 3,
408 disabled: false,
409 })]
410 );
411 }
412
413 #[test]
414 fn a_frame_split_across_reads_still_parses() {
415 let whole = frame("two", 7);
416 let mut parser = SseParser::default();
417 let mut events;
418 // Cut at every byte boundary in turn; no split may lose the event.
419 for cut in 1..whole.len() {
420 events = parser.feed(&whole.as_bytes()[..cut]);
421 assert!(events.is_empty(), "a partial frame must not dispatch");
422 events.extend(parser.feed(&whole.as_bytes()[cut..]));
423 assert_eq!(events.len(), 1, "cut at {cut}");
424 assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember {
425 timezone: default_timezone(),
426 sub: "two".into(),
427 email: "two@example.com".into(),
428 name: "Ann".into(),
429 admin: false,
430 photo_version: 7,
431 disabled: false,
432 }));
433 parser = SseParser::default();
434 }
435 }
436
437 #[test]
438 fn crlf_terminators_are_lines_too() {
439 let mut parser = SseParser::default();
440 let events = parser.feed(frame("three", 1).replace('\n', "\r\n").as_bytes());
441 assert_eq!(events.len(), 1);
442 assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember {
443 timezone: default_timezone(),
444 sub: "three".into(),
445 email: "three@example.com".into(),
446 name: "Ann".into(),
447 admin: false,
448 photo_version: 1,
449 disabled: false,
450 }));
451 }
452
453 #[test]
454 fn ticks_and_comments_are_silence() {
455 let mut parser = SseParser::default();
456 // What im's own browser feed sends, plus an event type the
457 // directory feed does not carry: none of it is a member.
458 let noise = b"data: {}\n\nevent: tick\ndata: {}\n\n: keep-alive\n\nretry: 5000\n\n";
459 assert!(parser.feed(noise).is_empty());
460 }
461
462 #[test]
463 fn a_broken_frame_is_skipped_and_the_next_still_lands() {
464 let mut parser = SseParser::default();
465 let bytes = format!("event: profile\ndata: {{not json}}\n\n{}", frame("four", 2));
466 let events = parser.feed(bytes.as_bytes());
467 assert_eq!(events.len(), 1);
468 assert_eq!(
469 events[0],
470 DirectoryEvent::Profile(DirectoryMember {
471 timezone: default_timezone(),
472 sub: "four".into(),
473 email: "four@example.com".into(),
474 name: "Ann".into(),
475 admin: false,
476 photo_version: 2,
477 disabled: false,
478 })
479 );
480 }
481
482 #[test]
483 fn multi_line_data_is_joined_for_the_json() {
484 let mut parser = SseParser::default();
485 // The spec joins `data:` lines with `\n`; a member is one line of
486 // JSON, so the join lands inside a string and must parse anyway —
487 // this frame's name carries a newline.
488 let bytes = b"event: profile\ndata: {\"sub\":\"five\",\"email\":\"e\",\
489 data: \"\",\"name\":\"A\\nB\",\"admin\":false,\"photo_version\":0}\n\n";
490 let _ = bytes; // (the folded literal above is documentation only)
491 let joined = "event: profile\ndata: {\"sub\":\"five\",\ndata: \"x\"}\n\n";
492 assert!(parser.feed(joined.as_bytes()).is_empty(), "invalid JSON is skipped, not fatal");
493 }
494
495 #[test]
496 fn a_revoked_frame_names_the_subject() {
497 let mut parser = SseParser::default();
498 let bytes = b"event: revoked\ndata: {\"sub\":\"seven\"}\n\n";
499 let events = parser.feed(bytes);
500 assert_eq!(
501 events,
502 vec![DirectoryEvent::Revoked { sub: "seven".into() }]
503 );
504 }
505
506 #[test]
507 fn a_member_carries_the_disabled_flag_and_defaults_it() {
508 let mut parser = SseParser::default();
509 let bytes = b"event: profile\ndata: {\"sub\":\"gone\",\"email\":\"g\",\
510 \"name\":\"G\",\"admin\":false,\"photo_version\":0,\
511 \"disabled\":true}\n\n";
512 let events = parser.feed(bytes);
513 assert_eq!(events.len(), 1);
514 assert!(
515 matches!(&events[0], DirectoryEvent::Profile(member) if member.disabled),
516 "the flag the frame carries is the flag the member reads"
517 );
518
519 // An older im's row predates the flag: it reads as enabled.
520 let mut parser = SseParser::default();
521 let events = parser.feed(frame("back", 1).as_bytes());
522 assert!(
523 matches!(&events[0], DirectoryEvent::Profile(member) if !member.disabled),
524 "a row without the field defaults to present-and-enabled"
525 );
526 }
527
528 #[test]
529 fn an_unknown_event_kind_is_skipped_and_the_stream_stays_alive() {
530 let mut parser = SseParser::default();
531 let bytes = format!(
532 "event: somethingnew\ndata: {{\"whatever\":1}}\n\n{}",
533 frame("after", 9)
534 )
535 .into_bytes();
536 let events = parser.feed(&bytes);
537 assert_eq!(events.len(), 1, "the unknown frame is not fatal");
538 assert!(matches!(&events[0], DirectoryEvent::Profile(member) if member.sub == "after"));
539 }
540}