Profile changes live everywhere: photo_version, version-aware /photo, /directory photo_version + /directory/live stream, typed live bus, im-client directory module
Browse files at this commit339b1989edd27b1a00b1d5c432fe8ccd77aa94faParent: dec57cf16 changed files +885 -147
- crates/im-client/src/directory.rs +453 -0
- crates/im-client/src/lib.rs +7 -0
- crates/im-core/src/accounts.rs +16 -12
- crates/im-core/src/model.rs +4 -0
- crates/im-core/src/oidc.rs +1 -0
- crates/im-core/src/photos.rs +2 -2
- crates/im-core/src/store.rs +14 -0
- crates/im-migrate/src/main.rs +1 -0
- crates/im-web/src/admin.rs +8 -5
- crates/im-web/src/auth.rs +6 -0
- crates/im-web/src/directory.rs +119 -14
- crates/im-web/src/layout.rs +4 -7
- crates/im-web/src/live.rs +15 -2
- crates/im-web/src/main.rs +0 -1
- crates/im-web/src/photo.rs +206 -99
- crates/im-web/src/server.rs +29 -5
crates/im-client/src/directory.rsadded+453 -0
| @@ -0,0 +1,453 @@ | |||
| 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 | +//! * [`DirectoryClient::open_stream`] — the `/directory/live` feed, one | ||
| 9 | +//! event per changed member, parsed by 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 | + | ||
| 17 | +use std::time::Duration; | ||
| 18 | + | ||
| 19 | +use serde::{Deserialize, Serialize}; | ||
| 20 | +use 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. | ||
| 25 | +const REQUEST_TIMEOUT: Duration = Duration::from_secs(15); | ||
| 26 | + | ||
| 27 | +/// The first wait after a failed stream, and the growth step. | ||
| 28 | +const BACKOFF_FLOOR: Duration = Duration::from_secs(1); | ||
| 29 | + | ||
| 30 | +/// The longest wait a run of consecutive failures earns. | ||
| 31 | +const 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)] | ||
| 37 | +pub 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 | +} | ||
| 50 | + | ||
| 51 | +/// One event off the directory stream. The only thing `/directory/live` | ||
| 52 | +/// announces today is a changed member; the enum leaves room for the feed | ||
| 53 | +/// to grow without a breaking change to consumers. | ||
| 54 | +#[derive(Debug, Clone, PartialEq)] | ||
| 55 | +pub enum DirectoryEvent { | ||
| 56 | + /// The named member's row changed — upload, address, admin flag, any | ||
| 57 | + /// of it. The payload is the row as it now stands. | ||
| 58 | + Profile(DirectoryMember), | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// The directory client: issuer plus the same `client_id:client_secret` | ||
| 62 | +/// pair the OIDC side already holds. Cheap to clone; one HTTP pool inside. | ||
| 63 | +#[derive(Clone)] | ||
| 64 | +pub struct DirectoryClient { | ||
| 65 | + http: reqwest::Client, | ||
| 66 | + issuer: String, | ||
| 67 | + client_id: String, | ||
| 68 | + client_secret: String, | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +impl DirectoryClient { | ||
| 72 | + pub fn new( | ||
| 73 | + issuer: impl Into<String>, | ||
| 74 | + client_id: impl Into<String>, | ||
| 75 | + client_secret: impl Into<String>, | ||
| 76 | + ) -> Self { | ||
| 77 | + Self { | ||
| 78 | + http: reqwest::Client::new(), | ||
| 79 | + issuer: issuer.into(), | ||
| 80 | + client_id: client_id.into(), | ||
| 81 | + client_secret: client_secret.into(), | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + fn get(&self, path: &str) -> reqwest::RequestBuilder { | ||
| 86 | + self.http | ||
| 87 | + .get(format!("{}{path}", self.issuer)) | ||
| 88 | + .basic_auth(&self.client_id, Some(&self.client_secret)) | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + /// `GET /directory`: the whole non-disabled roster, oldest first. | ||
| 92 | + pub async fn directory(&self) -> Result<Vec<DirectoryMember>> { | ||
| 93 | + let answer = self | ||
| 94 | + .get("/directory") | ||
| 95 | + .timeout(REQUEST_TIMEOUT) | ||
| 96 | + .send() | ||
| 97 | + .await | ||
| 98 | + .map_err(|e| Error::Http(e.to_string()))? | ||
| 99 | + .error_for_status() | ||
| 100 | + .map_err(|e| Error::Refused(e.to_string()))?; | ||
| 101 | + answer | ||
| 102 | + .json() | ||
| 103 | + .await | ||
| 104 | + .map_err(|e| Error::Http(e.to_string())) | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + /// `GET /photo/{sub}`: the member's photo bytes and their content | ||
| 108 | + /// type. A member with no photo gets im's default face — the initial | ||
| 109 | + /// tile — so the answer is always an image. | ||
| 110 | + pub async fn photo(&self, sub: &str) -> Result<(Vec<u8>, String)> { | ||
| 111 | + let answer = self | ||
| 112 | + .get(&format!("/photo/{sub}")) | ||
| 113 | + .timeout(REQUEST_TIMEOUT) | ||
| 114 | + .send() | ||
| 115 | + .await | ||
| 116 | + .map_err(|e| Error::Http(e.to_string()))? | ||
| 117 | + .error_for_status() | ||
| 118 | + .map_err(|e| Error::Refused(e.to_string()))?; | ||
| 119 | + let content_type = answer | ||
| 120 | + .headers() | ||
| 121 | + .get(reqwest::header::CONTENT_TYPE) | ||
| 122 | + .and_then(|value| value.to_str().ok()) | ||
| 123 | + .unwrap_or("application/octet-stream") | ||
| 124 | + .to_string(); | ||
| 125 | + let bytes = answer | ||
| 126 | + .bytes() | ||
| 127 | + .await | ||
| 128 | + .map_err(|e| Error::Http(e.to_string()))? | ||
| 129 | + .to_vec(); | ||
| 130 | + Ok((bytes, content_type)) | ||
| 131 | + } | ||
| 132 | + | ||
| 133 | + /// `GET /directory/live`: opens the change feed. Every frame after the | ||
| 134 | + /// first is one member's row; the stream ends — `None` from | ||
| 135 | + /// [`DirectoryStream::next`] — whenever im closes it, which is the | ||
| 136 | + /// caller's cue to re-list and redial ([`spawn_sync`] does exactly | ||
| 137 | + /// that). | ||
| 138 | + pub async fn open_stream(&self) -> Result<DirectoryStream> { | ||
| 139 | + let response = self | ||
| 140 | + .get("/directory/live") | ||
| 141 | + .send() | ||
| 142 | + .await | ||
| 143 | + .map_err(|e| Error::Http(e.to_string()))? | ||
| 144 | + .error_for_status() | ||
| 145 | + .map_err(|e| Error::Refused(e.to_string()))?; | ||
| 146 | + Ok(DirectoryStream { | ||
| 147 | + response, | ||
| 148 | + parser: SseParser::default(), | ||
| 149 | + ready: std::collections::VecDeque::new(), | ||
| 150 | + }) | ||
| 151 | + } | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +/// An open `/directory/live` connection. | ||
| 155 | +pub struct DirectoryStream { | ||
| 156 | + response: reqwest::Response, | ||
| 157 | + parser: SseParser, | ||
| 158 | + ready: std::collections::VecDeque<DirectoryEvent>, | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +impl DirectoryStream { | ||
| 162 | + /// The next member change. `Some(Err)` on a network failure, then the | ||
| 163 | + /// stream is over; `None` when im closed a healthy stream (a restart, | ||
| 164 | + /// the server window). Either way the caller re-lists and redials. | ||
| 165 | + pub async fn next(&mut self) -> Option<Result<DirectoryEvent>> { | ||
| 166 | + loop { | ||
| 167 | + if let Some(event) = self.ready.pop_front() { | ||
| 168 | + return Some(Ok(event)); | ||
| 169 | + } | ||
| 170 | + match self.response.chunk().await { | ||
| 171 | + Ok(Some(bytes)) => self.ready.extend(self.parser.feed(&bytes)), | ||
| 172 | + // The connection closed cleanly: a healthy stream's end. | ||
| 173 | + Ok(None) => return None, | ||
| 174 | + Err(e) => return Some(Err(Error::Http(e.to_string()))), | ||
| 175 | + } | ||
| 176 | + } | ||
| 177 | + } | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +/// The hand-rolled `text/event-stream` reader. Frames accumulate field by | ||
| 181 | +/// field and dispatch on the blank line, per the SSE grammar; the only | ||
| 182 | +/// fields this feed carries are `event`, `data`, `retry`, and comments, | ||
| 183 | +/// but the parser honors the whole shape — including `data` split over | ||
| 184 | +/// several lines, which the spec joins with `\n`. | ||
| 185 | +#[derive(Default)] | ||
| 186 | +struct SseParser { | ||
| 187 | + /// Bytes read but not yet through a line terminator. | ||
| 188 | + pending: Vec<u8>, | ||
| 189 | + /// The current frame's `event:` field, if it named one. | ||
| 190 | + event: Option<String>, | ||
| 191 | + /// The current frame's `data:`, joined back into one string. | ||
| 192 | + data: String, | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +impl SseParser { | ||
| 196 | + /// Feeds the next bytes from the wire and answers every frame they | ||
| 197 | + /// completed. Bytes trailing their terminator wait for the rest — a | ||
| 198 | + /// field or a UTF-8 character may straddle two reads. | ||
| 199 | + fn feed(&mut self, bytes: &[u8]) -> Vec<DirectoryEvent> { | ||
| 200 | + self.pending.extend_from_slice(bytes); | ||
| 201 | + let mut events = Vec::new(); | ||
| 202 | + let Some(at) = self | ||
| 203 | + .pending | ||
| 204 | + .iter() | ||
| 205 | + .rposition(|&b| b == b'\n' || b == b'\r') | ||
| 206 | + .map(|at| at + 1) | ||
| 207 | + else { | ||
| 208 | + return events; | ||
| 209 | + }; | ||
| 210 | + let block: Vec<u8> = self.pending.drain(..at).collect(); | ||
| 211 | + for line in split_lines(&block) { | ||
| 212 | + if line.is_empty() { | ||
| 213 | + // The blank line dispatches whatever accumulated. | ||
| 214 | + if let Some(event) = self.take_event() { | ||
| 215 | + events.push(event); | ||
| 216 | + } | ||
| 217 | + } else if line[0] == b':' { | ||
| 218 | + // A comment — im's keep-alives and retry hint live here. | ||
| 219 | + } else { | ||
| 220 | + let (name, value) = match line.iter().position(|&b| b == b':') { | ||
| 221 | + Some(at) => (&line[..at], &line[at + 1..]), | ||
| 222 | + None => (&line[..], &b""[..]), | ||
| 223 | + }; | ||
| 224 | + // One optional space after the colon is not part of the | ||
| 225 | + // value. | ||
| 226 | + let value = value.strip_prefix(b" ").unwrap_or(value); | ||
| 227 | + match name { | ||
| 228 | + b"event" => self.event = Some(String::from_utf8_lossy(value).into_owned()), | ||
| 229 | + b"data" => { | ||
| 230 | + if !self.data.is_empty() { | ||
| 231 | + self.data.push('\n'); | ||
| 232 | + } | ||
| 233 | + self.data.push_str(&String::from_utf8_lossy(value)); | ||
| 234 | + } | ||
| 235 | + // `id` and `retry` mean nothing to a change feed. | ||
| 236 | + _ => {} | ||
| 237 | + } | ||
| 238 | + } | ||
| 239 | + } | ||
| 240 | + events | ||
| 241 | + } | ||
| 242 | + | ||
| 243 | + /// Ends the current frame: the data, if it parsed into a member, is | ||
| 244 | + /// the event. A frame that names another event type, or whose data is | ||
| 245 | + /// not a member, is skipped — the feed may grow, and a single bad | ||
| 246 | + /// frame must not end the connection. | ||
| 247 | + fn take_event(&mut self) -> Option<DirectoryEvent> { | ||
| 248 | + let data = std::mem::take(&mut self.data); | ||
| 249 | + let event = self.event.take(); | ||
| 250 | + if let Some(kind) = event { | ||
| 251 | + if kind != "profile" { | ||
| 252 | + return None; | ||
| 253 | + } | ||
| 254 | + } | ||
| 255 | + serde_json::from_str::<DirectoryMember>(&data) | ||
| 256 | + .ok() | ||
| 257 | + .map(DirectoryEvent::Profile) | ||
| 258 | + } | ||
| 259 | +} | ||
| 260 | + | ||
| 261 | +/// Splits a block that ends at a line terminator into lines, accepting the | ||
| 262 | +/// three SSE terminators: `\n`, `\r\n`, and a bare `\r`. | ||
| 263 | +fn split_lines(block: &[u8]) -> Vec<Vec<u8>> { | ||
| 264 | + let mut lines = Vec::new(); | ||
| 265 | + let mut rest = block; | ||
| 266 | + while let Some(at) = rest.iter().position(|&b| b == b'\n' || b == b'\r') { | ||
| 267 | + let (line, tail) = rest.split_at(at); | ||
| 268 | + lines.push(line.to_vec()); | ||
| 269 | + // A `\r\n` pair is one terminator, not a line and an empty one. | ||
| 270 | + rest = if tail.starts_with(b"\r\n") { &tail[2..] } else { &tail[1..] }; | ||
| 271 | + } | ||
| 272 | + lines | ||
| 273 | +} | ||
| 274 | + | ||
| 275 | +/// Keeps the app's mirror of the roster in step with im, forever: | ||
| 276 | +/// | ||
| 277 | +/// 1. one full `/directory` pass, every member applied through | ||
| 278 | +/// `on_member` — the boot-time population; | ||
| 279 | +/// 2. the `/directory/live` stream, every change through the same door; | ||
| 280 | +/// 3. when the stream dies — error, lag, clean close — wait out the | ||
| 281 | +/// backoff (1s doubling to a 30s cap), call `on_resync`, replay a full | ||
| 282 | +/// pass, and resume the stream. A full pass that itself fails is | ||
| 283 | +/// retried on the same clock until im answers. | ||
| 284 | +/// | ||
| 285 | +/// Runs until the task is aborted; the handle is the caller's to drop or | ||
| 286 | +/// cancel. | ||
| 287 | +pub fn spawn_sync<F, G>( | ||
| 288 | + client: DirectoryClient, | ||
| 289 | + mut on_member: F, | ||
| 290 | + mut on_resync: G, | ||
| 291 | +) -> tokio::task::JoinHandle<()> | ||
| 292 | +where | ||
| 293 | + F: FnMut(DirectoryMember) + Send + 'static, | ||
| 294 | + G: FnMut() + Send + 'static, | ||
| 295 | +{ | ||
| 296 | + tokio::spawn(async move { | ||
| 297 | + let mut backoff = BACKOFF_FLOOR; | ||
| 298 | + loop { | ||
| 299 | + // The full pass. There is nothing to converge with until one | ||
| 300 | + // lands, so failures retry on the growing clock. | ||
| 301 | + loop { | ||
| 302 | + match client.directory().await { | ||
| 303 | + Ok(members) => { | ||
| 304 | + for member in members { | ||
| 305 | + on_member(member); | ||
| 306 | + } | ||
| 307 | + break; | ||
| 308 | + } | ||
| 309 | + Err(_) => { | ||
| 310 | + tokio::time::sleep(backoff).await; | ||
| 311 | + backoff = (backoff * 2).min(BACKOFF_CAP); | ||
| 312 | + } | ||
| 313 | + } | ||
| 314 | + } | ||
| 315 | + let mut stream = match client.open_stream().await { | ||
| 316 | + Ok(stream) => stream, | ||
| 317 | + Err(_) => { | ||
| 318 | + tokio::time::sleep(backoff).await; | ||
| 319 | + backoff = (backoff * 2).min(BACKOFF_CAP); | ||
| 320 | + on_resync(); | ||
| 321 | + continue; | ||
| 322 | + } | ||
| 323 | + }; | ||
| 324 | + while let Some(event) = stream.next().await { | ||
| 325 | + match event { | ||
| 326 | + Ok(DirectoryEvent::Profile(member)) => { | ||
| 327 | + on_member(member); | ||
| 328 | + // The stream works: the next stumble starts over | ||
| 329 | + // at the short wait. | ||
| 330 | + backoff = BACKOFF_FLOOR; | ||
| 331 | + } | ||
| 332 | + Err(_) => break, | ||
| 333 | + } | ||
| 334 | + } | ||
| 335 | + // The stream is gone. Wait, grow, and make the caller | ||
| 336 | + // re-list the whole roster before the stream resumes, so | ||
| 337 | + // whatever moved while the line was down heals on the pass. | ||
| 338 | + tokio::time::sleep(backoff).await; | ||
| 339 | + backoff = (backoff * 2).min(BACKOFF_CAP); | ||
| 340 | + on_resync(); | ||
| 341 | + } | ||
| 342 | + }) | ||
| 343 | +} | ||
| 344 | + | ||
| 345 | +#[cfg(test)] | ||
| 346 | +mod tests { | ||
| 347 | + use super::*; | ||
| 348 | + | ||
| 349 | + fn member_json(sub: &str, version: u64) -> String { | ||
| 350 | + format!( | ||
| 351 | + "{{\"sub\":\"{sub}\",\"email\":\"{sub}@example.com\",\ | ||
| 352 | + \"name\":\"Ann\",\"admin\":false,\"photo_version\":{version}}}" | ||
| 353 | + ) | ||
| 354 | + } | ||
| 355 | + | ||
| 356 | + fn frame(sub: &str, version: u64) -> String { | ||
| 357 | + format!("event: profile\ndata: {}\n\n", member_json(sub, version)) | ||
| 358 | + } | ||
| 359 | + | ||
| 360 | + #[test] | ||
| 361 | + fn a_profile_frame_becomes_an_event() { | ||
| 362 | + let mut parser = SseParser::default(); | ||
| 363 | + let events = parser.feed( | ||
| 364 | + format!("retry: 5000\n: keep-alive\n\n{}", frame("one", 3)).as_bytes(), | ||
| 365 | + ); | ||
| 366 | + assert_eq!( | ||
| 367 | + events, | ||
| 368 | + vec![DirectoryEvent::Profile(DirectoryMember { | ||
| 369 | + sub: "one".into(), | ||
| 370 | + email: "one@example.com".into(), | ||
| 371 | + name: "Ann".into(), | ||
| 372 | + admin: false, | ||
| 373 | + photo_version: 3, | ||
| 374 | + })] | ||
| 375 | + ); | ||
| 376 | + } | ||
| 377 | + | ||
| 378 | + #[test] | ||
| 379 | + fn a_frame_split_across_reads_still_parses() { | ||
| 380 | + let whole = frame("two", 7); | ||
| 381 | + let mut parser = SseParser::default(); | ||
| 382 | + let mut events = Vec::new(); | ||
| 383 | + // Cut at every byte boundary in turn; no split may lose the event. | ||
| 384 | + for cut in 1..whole.len() { | ||
| 385 | + events = parser.feed(&whole.as_bytes()[..cut]); | ||
| 386 | + assert!(events.is_empty(), "a partial frame must not dispatch"); | ||
| 387 | + events.extend(parser.feed(&whole.as_bytes()[cut..])); | ||
| 388 | + assert_eq!(events.len(), 1, "cut at {cut}"); | ||
| 389 | + assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember { | ||
| 390 | + sub: "two".into(), | ||
| 391 | + email: "two@example.com".into(), | ||
| 392 | + name: "Ann".into(), | ||
| 393 | + admin: false, | ||
| 394 | + photo_version: 7, | ||
| 395 | + })); | ||
| 396 | + parser = SseParser::default(); | ||
| 397 | + } | ||
| 398 | + } | ||
| 399 | + | ||
| 400 | + #[test] | ||
| 401 | + fn crlf_terminators_are_lines_too() { | ||
| 402 | + let mut parser = SseParser::default(); | ||
| 403 | + let events = parser.feed(frame("three", 1).replace('\n', "\r\n").as_bytes()); | ||
| 404 | + assert_eq!(events.len(), 1); | ||
| 405 | + assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember { | ||
| 406 | + sub: "three".into(), | ||
| 407 | + email: "three@example.com".into(), | ||
| 408 | + name: "Ann".into(), | ||
| 409 | + admin: false, | ||
| 410 | + photo_version: 1, | ||
| 411 | + })); | ||
| 412 | + } | ||
| 413 | + | ||
| 414 | + #[test] | ||
| 415 | + fn ticks_and_comments_are_silence() { | ||
| 416 | + let mut parser = SseParser::default(); | ||
| 417 | + // What im's own browser feed sends, plus an event type the | ||
| 418 | + // directory feed does not carry: none of it is a member. | ||
| 419 | + let noise = b"data: {}\n\nevent: tick\ndata: {}\n\n: keep-alive\n\nretry: 5000\n\n"; | ||
| 420 | + assert!(parser.feed(noise).is_empty()); | ||
| 421 | + } | ||
| 422 | + | ||
| 423 | + #[test] | ||
| 424 | + fn a_broken_frame_is_skipped_and_the_next_still_lands() { | ||
| 425 | + let mut parser = SseParser::default(); | ||
| 426 | + let bytes = format!("event: profile\ndata: {{not json}}\n\n{}", frame("four", 2)); | ||
| 427 | + let events = parser.feed(bytes.as_bytes()); | ||
| 428 | + assert_eq!(events.len(), 1); | ||
| 429 | + assert_eq!( | ||
| 430 | + events[0], | ||
| 431 | + DirectoryEvent::Profile(DirectoryMember { | ||
| 432 | + sub: "four".into(), | ||
| 433 | + email: "four@example.com".into(), | ||
| 434 | + name: "Ann".into(), | ||
| 435 | + admin: false, | ||
| 436 | + photo_version: 2, | ||
| 437 | + }) | ||
| 438 | + ); | ||
| 439 | + } | ||
| 440 | + | ||
| 441 | + #[test] | ||
| 442 | + fn multi_line_data_is_joined_for_the_json() { | ||
| 443 | + let mut parser = SseParser::default(); | ||
| 444 | + // The spec joins `data:` lines with `\n`; a member is one line of | ||
| 445 | + // JSON, so the join lands inside a string and must parse anyway — | ||
| 446 | + // this frame's name carries a newline. | ||
| 447 | + let bytes = b"event: profile\ndata: {\"sub\":\"five\",\"email\":\"e\",\ | ||
| 448 | + data: \"\",\"name\":\"A\\nB\",\"admin\":false,\"photo_version\":0}\n\n"; | ||
| 449 | + let _ = bytes; // (the folded literal above is documentation only) | ||
| 450 | + let joined = "event: profile\ndata: {\"sub\":\"five\",\ndata: \"x\"}\n\n"; | ||
| 451 | + assert!(parser.feed(joined.as_bytes()).is_empty(), "invalid JSON is skipped, not fatal"); | ||
| 452 | + } | ||
| 453 | +} | ||
crates/im-client/src/lib.rsmodified+7 -0
| @@ -23,6 +23,8 @@ use topcoat::cookie::{Cookie, Cookies, cookie, cookies}; | |||
| 23 | use topcoat::router::response::{IntoResponse, Response}; | 23 | use topcoat::router::response::{IntoResponse, Response}; |
| 24 | use topcoat::router::{HeaderValue, RouterBuilder, StatusCode, header, route}; | 24 | use topcoat::router::{HeaderValue, RouterBuilder, StatusCode, header, route}; |
| 25 | 25 | ||
| 26 | +pub mod directory; | ||
| 27 | + | ||
| 26 | // --------------------------------------------------------------------------- | 28 | // --------------------------------------------------------------------------- |
| 27 | // Configuration and state | 29 | // Configuration and state |
| 28 | // --------------------------------------------------------------------------- | 30 | // --------------------------------------------------------------------------- |
| @@ -137,6 +139,7 @@ async fn introspect(state: &ImClient, token: &str) -> Option<(User, i64)> { | |||
| 137 | email: answer["email"].as_str()?.to_string(), | 139 | email: answer["email"].as_str()?.to_string(), |
| 138 | name: answer["name"].as_str()?.to_string(), | 140 | name: answer["name"].as_str()?.to_string(), |
| 139 | admin: answer["admin"].as_bool().unwrap_or(false), | 141 | admin: answer["admin"].as_bool().unwrap_or(false), |
| 142 | + photo_version: answer["photo_version"].as_u64().unwrap_or(0), | ||
| 140 | }, | 143 | }, |
| 141 | answer["exp"].as_i64()?, | 144 | answer["exp"].as_i64()?, |
| 142 | )) | 145 | )) |
| @@ -150,6 +153,10 @@ pub struct User { | |||
| 150 | pub name: String, | 153 | pub name: String, |
| 151 | #[serde(default)] | 154 | #[serde(default)] |
| 152 | pub admin: bool, | 155 | pub admin: bool, |
| 156 | + /// How many times the person's photo has changed: the `/photo/{sub}?v=` | ||
| 157 | + /// cache buster. Absent on an older im — reads 0 there. | ||
| 158 | + #[serde(default)] | ||
| 159 | + pub photo_version: u64, | ||
| 153 | } | 160 | } |
| 154 | 161 | ||
| 155 | // --------------------------------------------------------------------------- | 162 | // --------------------------------------------------------------------------- |
crates/im-core/src/accounts.rsmodified+16 -12
| @@ -385,6 +385,7 @@ pub async fn create_user_from_invite( | |||
| 385 | name: name.to_string(), | 385 | name: name.to_string(), |
| 386 | totp_confirmed: false, | 386 | totp_confirmed: false, |
| 387 | has_photo: false, | 387 | has_photo: false, |
| 388 | + photo_version: 0, | ||
| 388 | admin: invite.admin, | 389 | admin: invite.admin, |
| 389 | disabled: false, | 390 | disabled: false, |
| 390 | created_at: store::now(), | 391 | created_at: store::now(), |
| @@ -655,7 +656,7 @@ pub async fn verify_login( | |||
| 655 | let mut rows = conn | 656 | let mut rows = conn |
| 656 | .query( | 657 | .query( |
| 657 | "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at, \ | 658 | "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at, \ |
| 658 | - photo_mime IS NOT NULL, theme, language, ui FROM users WHERE email = ?1 COLLATE NOCASE", | 659 | + photo_mime IS NOT NULL, photo_version, theme, language, ui FROM users WHERE email = ?1 COLLATE NOCASE", |
| 659 | turso::params![email], | 660 | turso::params![email], |
| 660 | ) | 661 | ) |
| 661 | .await | 662 | .await |
| @@ -670,12 +671,13 @@ pub async fn verify_login( | |||
| 670 | name: store::text(&row, 2)?, | 671 | name: store::text(&row, 2)?, |
| 671 | totp_confirmed: store::int(&row, 4)? != 0, | 672 | totp_confirmed: store::int(&row, 4)? != 0, |
| 672 | has_photo: store::int(&row, 8)? != 0, | 673 | has_photo: store::int(&row, 8)? != 0, |
| 674 | + photo_version: store::int(&row, 9)? as u64, | ||
| 673 | admin: store::int(&row, 5)? != 0, | 675 | admin: store::int(&row, 5)? != 0, |
| 674 | disabled: store::int(&row, 6)? != 0, | 676 | disabled: store::int(&row, 6)? != 0, |
| 675 | created_at: store::parse_stamp(&store::text(&row, 7)?)?, | 677 | created_at: store::parse_stamp(&store::text(&row, 7)?)?, |
| 676 | - theme: store::text(&row, 9)?, | 678 | + theme: store::text(&row, 10)?, |
| 677 | - language: store::text(&row, 10)?, | 679 | + language: store::text(&row, 11)?, |
| 678 | - ui: store::text(&row, 11)?, | 680 | + ui: store::text(&row, 12)?, |
| 679 | }; | 681 | }; |
| 680 | let phc = store::text(&row, 3)?; | 682 | let phc = store::text(&row, 3)?; |
| 681 | if !verify_password(password, &phc) || user.disabled { | 683 | if !verify_password(password, &phc) || user.disabled { |
| @@ -748,7 +750,7 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> { | |||
| 748 | let mut rows = conn | 750 | let mut rows = conn |
| 749 | .query( | 751 | .query( |
| 750 | "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \ | 752 | "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \ |
| 751 | - photo_mime IS NOT NULL, theme, language, ui FROM users WHERE id = ?1", | 753 | + photo_mime IS NOT NULL, photo_version, theme, language, ui FROM users WHERE id = ?1", |
| 752 | turso::params![id.to_string()], | 754 | turso::params![id.to_string()], |
| 753 | ) | 755 | ) |
| 754 | .await | 756 | .await |
| @@ -762,12 +764,13 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> { | |||
| 762 | name: store::text(&row, 2)?, | 764 | name: store::text(&row, 2)?, |
| 763 | totp_confirmed: store::int(&row, 3)? != 0, | 765 | totp_confirmed: store::int(&row, 3)? != 0, |
| 764 | has_photo: store::int(&row, 7)? != 0, | 766 | has_photo: store::int(&row, 7)? != 0, |
| 767 | + photo_version: store::int(&row, 8)? as u64, | ||
| 765 | admin: store::int(&row, 4)? != 0, | 768 | admin: store::int(&row, 4)? != 0, |
| 766 | disabled: store::int(&row, 5)? != 0, | 769 | disabled: store::int(&row, 5)? != 0, |
| 767 | created_at: store::parse_stamp(&store::text(&row, 6)?)?, | 770 | created_at: store::parse_stamp(&store::text(&row, 6)?)?, |
| 768 | - theme: store::text(&row, 8)?, | 771 | + theme: store::text(&row, 9)?, |
| 769 | - language: store::text(&row, 9)?, | 772 | + language: store::text(&row, 10)?, |
| 770 | - ui: store::text(&row, 10)?, | 773 | + ui: store::text(&row, 11)?, |
| 771 | })) | 774 | })) |
| 772 | } | 775 | } |
| 773 | 776 | ||
| @@ -798,7 +801,7 @@ pub async fn list_users(store: &Store) -> Result<Vec<User>> { | |||
| 798 | let mut rows = conn | 801 | let mut rows = conn |
| 799 | .query( | 802 | .query( |
| 800 | "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \ | 803 | "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \ |
| 801 | - photo_mime IS NOT NULL, theme, language, ui FROM users ORDER BY created_at", | 804 | + photo_mime IS NOT NULL, photo_version, theme, language, ui FROM users ORDER BY created_at", |
| 802 | (), | 805 | (), |
| 803 | ) | 806 | ) |
| 804 | .await | 807 | .await |
| @@ -811,12 +814,13 @@ pub async fn list_users(store: &Store) -> Result<Vec<User>> { | |||
| 811 | name: store::text(&row, 2)?, | 814 | name: store::text(&row, 2)?, |
| 812 | totp_confirmed: store::int(&row, 3)? != 0, | 815 | totp_confirmed: store::int(&row, 3)? != 0, |
| 813 | has_photo: store::int(&row, 7)? != 0, | 816 | has_photo: store::int(&row, 7)? != 0, |
| 817 | + photo_version: store::int(&row, 8)? as u64, | ||
| 814 | admin: store::int(&row, 4)? != 0, | 818 | admin: store::int(&row, 4)? != 0, |
| 815 | disabled: store::int(&row, 5)? != 0, | 819 | disabled: store::int(&row, 5)? != 0, |
| 816 | created_at: store::parse_stamp(&store::text(&row, 6)?)?, | 820 | created_at: store::parse_stamp(&store::text(&row, 6)?)?, |
| 817 | - theme: store::text(&row, 8)?, | 821 | + theme: store::text(&row, 9)?, |
| 818 | - language: store::text(&row, 9)?, | 822 | + language: store::text(&row, 10)?, |
| 819 | - ui: store::text(&row, 10)?, | 823 | + ui: store::text(&row, 11)?, |
| 820 | }); | 824 | }); |
| 821 | } | 825 | } |
| 822 | Ok(users) | 826 | Ok(users) |
crates/im-core/src/model.rsmodified+4 -0
| @@ -54,6 +54,10 @@ pub struct User { | |||
| 54 | /// Whether this person has a profile photo: the row keeps the mime | 54 | /// Whether this person has a profile photo: the row keeps the mime |
| 55 | /// type, the bytes live as a file under the storage tree (`photos.rs`). | 55 | /// type, the bytes live as a file under the storage tree (`photos.rs`). |
| 56 | pub has_photo: bool, | 56 | pub has_photo: bool, |
| 57 | + /// How many times the photo has changed: the `/photo/{id}?v=` cache | ||
| 58 | + /// buster. Lives in the row, so every process — and every sibling app | ||
| 59 | + /// reading `/directory` — sees the same one, restart-proof. | ||
| 60 | + pub photo_version: u64, | ||
| 57 | /// im's own admin flag — crosses only via /introspect to registered apps, | 61 | /// im's own admin flag — crosses only via /introspect to registered apps, |
| 58 | /// never in id_token/userinfo; apps may derive their own admin | 62 | /// never in id_token/userinfo; apps may derive their own admin |
| 59 | /// authorization from it. | 63 | /// authorization from it. |
crates/im-core/src/oidc.rsmodified+1 -0
| @@ -512,6 +512,7 @@ pub async fn introspect_app_session( | |||
| 512 | "email": user.email, | 512 | "email": user.email, |
| 513 | "name": user.name, | 513 | "name": user.name, |
| 514 | "admin": user.admin, | 514 | "admin": user.admin, |
| 515 | + "photo_version": user.photo_version, | ||
| 515 | "exp": expires.unix_timestamp(), | 516 | "exp": expires.unix_timestamp(), |
| 516 | }))) | 517 | }))) |
| 517 | } | 518 | } |
crates/im-core/src/photos.rsmodified+2 -2
| @@ -47,7 +47,7 @@ pub async fn set_photo(store: &Store, user: &UserId, bytes: &[u8], mime: &str) - | |||
| 47 | let written = { | 47 | let written = { |
| 48 | let conn = store.conn.lock().await; | 48 | let conn = store.conn.lock().await; |
| 49 | conn.execute( | 49 | conn.execute( |
| 50 | - "UPDATE users SET photo_mime = ?1 WHERE id = ?2", | 50 | + "UPDATE users SET photo_mime = ?1, photo_version = photo_version + 1 WHERE id = ?2", |
| 51 | turso::params![mime, id.clone()], | 51 | turso::params![mime, id.clone()], |
| 52 | ) | 52 | ) |
| 53 | .await | 53 | .await |
| @@ -69,7 +69,7 @@ pub async fn clear_photo(store: &Store, user: &UserId) -> Result<()> { | |||
| 69 | { | 69 | { |
| 70 | let conn = store.conn.lock().await; | 70 | let conn = store.conn.lock().await; |
| 71 | conn.execute( | 71 | conn.execute( |
| 72 | - "UPDATE users SET photo_mime = NULL WHERE id = ?1", | 72 | + "UPDATE users SET photo_mime = NULL, photo_version = photo_version + 1 WHERE id = ?1", |
| 73 | turso::params![id.clone()], | 73 | turso::params![id.clone()], |
| 74 | ) | 74 | ) |
| 75 | .await | 75 | .await |
crates/im-core/src/store.rsmodified+14 -0
| @@ -47,6 +47,7 @@ CREATE TABLE IF NOT EXISTS users ( | |||
| 47 | disabled INTEGER NOT NULL DEFAULT 0, | 47 | disabled INTEGER NOT NULL DEFAULT 0, |
| 48 | created_at TEXT NOT NULL, | 48 | created_at TEXT NOT NULL, |
| 49 | photo_mime TEXT, | 49 | photo_mime TEXT, |
| 50 | + photo_version INTEGER NOT NULL DEFAULT 0, | ||
| 50 | theme TEXT NOT NULL DEFAULT 'light', | 51 | theme TEXT NOT NULL DEFAULT 'light', |
| 51 | language TEXT NOT NULL DEFAULT 'en', | 52 | language TEXT NOT NULL DEFAULT 'en', |
| 52 | ui TEXT NOT NULL DEFAULT 'instrument' | 53 | ui TEXT NOT NULL DEFAULT 'instrument' |
| @@ -220,6 +221,19 @@ impl Store { | |||
| 220 | .await | 221 | .await |
| 221 | .map_err(backend)?; | 222 | .map_err(backend)?; |
| 222 | } | 223 | } |
| 224 | + // How many times the profile photo has changed: the URL cache | ||
| 225 | + // buster (`/photo/{id}?v=`), kept in the row so every process | ||
| 226 | + // and every sibling app reads the same one. Databases born | ||
| 227 | + // before photos carried versions grow it here; every existing | ||
| 228 | + // row reads 0, and the first upload after the move bumps it. | ||
| 229 | + if !has_column(&conn, "users", "photo_version").await? { | ||
| 230 | + conn.execute( | ||
| 231 | + "ALTER TABLE users ADD COLUMN photo_version INTEGER NOT NULL DEFAULT 0", | ||
| 232 | + (), | ||
| 233 | + ) | ||
| 234 | + .await | ||
| 235 | + .map_err(backend)?; | ||
| 236 | + } | ||
| 223 | // Per-user display preferences (theme/language/ui): databases | 237 | // Per-user display preferences (theme/language/ui): databases |
| 224 | // born before these columns grow them here — TEXT NOT NULL with | 238 | // born before these columns grow them here — TEXT NOT NULL with |
| 225 | // a DEFAULT so every existing row reads the default. | 239 | // a DEFAULT so every existing row reads the default. |
crates/im-migrate/src/main.rsmodified+1 -0
| @@ -36,6 +36,7 @@ CREATE TABLE IF NOT EXISTS users ( | |||
| 36 | disabled INTEGER NOT NULL DEFAULT 0, | 36 | disabled INTEGER NOT NULL DEFAULT 0, |
| 37 | created_at TEXT NOT NULL, | 37 | created_at TEXT NOT NULL, |
| 38 | photo_mime TEXT, | 38 | photo_mime TEXT, |
| 39 | + photo_version INTEGER NOT NULL DEFAULT 0, | ||
| 39 | theme TEXT NOT NULL DEFAULT 'light', | 40 | theme TEXT NOT NULL DEFAULT 'light', |
| 40 | language TEXT NOT NULL DEFAULT 'en', | 41 | language TEXT NOT NULL DEFAULT 'en', |
| 41 | ui TEXT NOT NULL DEFAULT 'instrument' | 42 | ui TEXT NOT NULL DEFAULT 'instrument' |
crates/im-web/src/admin.rsmodified+8 -5
| @@ -1236,8 +1236,9 @@ async fn user_email(cx: &Cx, Form(input): Form<UserEmailForm>) -> Result<Respons | |||
| 1236 | Err(redirect) => return Ok(redirect), | 1236 | Err(redirect) => return Ok(redirect), |
| 1237 | }; | 1237 | }; |
| 1238 | let store = &app(cx).store; | 1238 | let store = &app(cx).store; |
| 1239 | - match accounts::set_email(store, &UserId::from(input.user), &input.email).await { | 1239 | + let user_id = UserId::from(input.user); |
| 1240 | - Ok(()) => {} | 1240 | + match accounts::set_email(store, &user_id, &input.email).await { |
| 1241 | + Ok(()) => server::notify_profile(cx, &user_id).await, | ||
| 1241 | Err(accounts::AccountError::EmailTaken) => return back(cx, "users", "&error=email_taken"), | 1242 | Err(accounts::AccountError::EmailTaken) => return back(cx, "users", "&error=email_taken"), |
| 1242 | Err(accounts::AccountError::InvalidEmail) => return back(cx, "users", "&error=bad_email"), | 1243 | Err(accounts::AccountError::InvalidEmail) => return back(cx, "users", "&error=bad_email"), |
| 1243 | Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), | 1244 | Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), |
| @@ -1352,11 +1353,13 @@ async fn set_disabled(cx: &Cx, input: UserAction, disabled: bool) -> Result<Resp | |||
| 1352 | }; | 1353 | }; |
| 1353 | let store = &app(cx).store; | 1354 | let store = &app(cx).store; |
| 1354 | let user_id = UserId::from(input.user); | 1355 | let user_id = UserId::from(input.user); |
| 1355 | - accounts::set_disabled(store, &user_id, disabled).await?; | ||
| 1356 | if disabled { | 1356 | if disabled { |
| 1357 | // A disabled account keeps no sessions either. | 1357 | // A disabled account keeps no sessions either. |
| 1358 | im_core::sessions::revoke_user_sessions(store, &user_id).await?; | 1358 | im_core::sessions::revoke_user_sessions(store, &user_id).await?; |
| 1359 | } | 1359 | } |
| 1360 | + // Announced whether the flag moved either way: the disable drops the | ||
| 1361 | + // member from the next roster read, the enable restores it. | ||
| 1362 | + server::notify_profile(cx, &user_id).await; | ||
| 1360 | let email = accounts::user_by_id(store, &user_id) | 1363 | let email = accounts::user_by_id(store, &user_id) |
| 1361 | .await? | 1364 | .await? |
| 1362 | .map(|u| u.email); | 1365 | .map(|u| u.email); |
| @@ -1541,7 +1544,7 @@ fn store_of(cx: &Cx) -> std::sync::Arc<im_core::store::Store> { | |||
| 1541 | /// itself wait on a mail server. | 1544 | /// itself wait on a mail server. |
| 1542 | async fn probe( | 1545 | async fn probe( |
| 1543 | store: std::sync::Arc<im_core::store::Store>, | 1546 | store: std::sync::Arc<im_core::store::Store>, |
| 1544 | - live: tokio::sync::broadcast::Sender<()>, | 1547 | + live: tokio::sync::broadcast::Sender<server::LiveEvent>, |
| 1545 | ) { | 1548 | ) { |
| 1546 | let check = match mailer::check(&store).await { | 1549 | let check = match mailer::check(&store).await { |
| 1547 | Ok(took_ms) => settings::SenderCheck { | 1550 | Ok(took_ms) => settings::SenderCheck { |
| @@ -1559,5 +1562,5 @@ async fn probe( | |||
| 1559 | eprintln!("im: failed to record the sender check: {problem}"); | 1562 | eprintln!("im: failed to record the sender check: {problem}"); |
| 1560 | } | 1563 | } |
| 1561 | // The chip changed; watching tabs re-read it on the next tick. | 1564 | // The chip changed; watching tabs re-read it on the next tick. |
| 1562 | - let _ = live.send(()); | 1565 | + let _ = live.send(server::LiveEvent::Tick); |
| 1563 | } | 1566 | } |
crates/im-web/src/auth.rsmodified+6 -0
| @@ -258,6 +258,9 @@ async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Redirect { | |||
| 258 | }; | 258 | }; |
| 259 | let token = im_core::sessions::create_session(store, &user.id, &session_meta(cx)).await?; | 259 | let token = im_core::sessions::create_session(store, &user.id, &session_meta(cx)).await?; |
| 260 | server::log_event(cx, "invite_accepted", Some(&user.email), None).await; | 260 | server::log_event(cx, "invite_accepted", Some(&user.email), None).await; |
| 261 | + // A member exists from this moment on: the roster — and every app | ||
| 262 | + // mirroring it — learns the new row now, not on their next full list. | ||
| 263 | + server::notify_profile(cx, &user.id).await; | ||
| 261 | server::set_session_cookie(cx, token.expose()); | 264 | server::set_session_cookie(cx, token.expose()); |
| 262 | see("/".to_string()) | 265 | see("/".to_string()) |
| 263 | } | 266 | } |
| @@ -479,6 +482,9 @@ async fn email_confirm(cx: &Cx, Form(input): Form<EmailConfirmForm>) -> Redirect | |||
| 479 | match accounts::confirm_email_change(store, &input.token).await { | 482 | match accounts::confirm_email_change(store, &input.token).await { |
| 480 | Ok(accounts::EmailChangeConfirmed::Applied(user)) => { | 483 | Ok(accounts::EmailChangeConfirmed::Applied(user)) => { |
| 481 | server::log_event(cx, "email_changed", Some(&user.email), None).await; | 484 | server::log_event(cx, "email_changed", Some(&user.email), None).await; |
| 485 | + // Both mailboxes agreed and the address is rewritten: the | ||
| 486 | + // roster's row moved with it. | ||
| 487 | + server::notify_profile(cx, &user.id).await; | ||
| 482 | if server::current_user(cx).await.is_some() { | 488 | if server::current_user(cx).await.is_some() { |
| 483 | see("/?section=profile&ok=email_changed".to_string()) | 489 | see("/?section=profile&ok=email_changed".to_string()) |
| 484 | } else { | 490 | } else { |
crates/im-web/src/directory.rsmodified+119 -14
| @@ -4,23 +4,45 @@ | |||
| 4 | //! never see it — the only credential is a client's Basic pair, the same | 4 | //! never see it — the only credential is a client's Basic pair, the same |
| 5 | //! one the photo route takes. | 5 | //! one the photo route takes. |
| 6 | 6 | ||
| 7 | +use std::time::{Duration, Instant}; | ||
| 8 | + | ||
| 9 | +use futures_util::StreamExt; | ||
| 10 | +use tokio::sync::broadcast::error::RecvError; | ||
| 7 | use topcoat::context::Cx; | 11 | use topcoat::context::Cx; |
| 8 | use topcoat::router::content::Json; | 12 | use topcoat::router::content::Json; |
| 13 | +use topcoat::router::content::sse::{Event, KeepAlive, Sse}; | ||
| 9 | use topcoat::router::response::IntoResponse as _; | 14 | use topcoat::router::response::IntoResponse as _; |
| 10 | use topcoat::router::{StatusCode, route}; | 15 | use topcoat::router::{StatusCode, route}; |
| 11 | 16 | ||
| 12 | use crate::server; | 17 | use crate::server; |
| 13 | 18 | ||
| 14 | /// One directory entry: exactly what an app needs to provision a member — | 19 | /// One directory entry: exactly what an app needs to provision a member — |
| 15 | -/// the stable subject, the address, the display name, and whether im calls | 20 | +/// the stable subject, the address, the display name, whether im calls |
| 16 | /// them an admin (apps derive their own admin authorization from it, as | 21 | /// them an admin (apps derive their own admin authorization from it, as |
| 17 | -/// with `/introspect`). | 22 | +/// with `/introspect`), and how many times the photo has changed — the |
| 18 | -#[derive(serde::Serialize)] | 23 | +/// `?v=` that lets `/photo/{sub}` stay cacheable and still go fresh. One |
| 19 | -struct DirectoryMember { | 24 | +/// shape, three readers: `/directory` JSON, the `/directory/live` stream, |
| 20 | - sub: String, | 25 | +/// and the in-process live bus all serialize it the same way. |
| 21 | - email: String, | 26 | +#[derive(Clone, Debug, serde::Serialize)] |
| 22 | - name: String, | 27 | +pub struct DirectoryMember { |
| 23 | - admin: bool, | 28 | + pub sub: String, |
| 29 | + pub email: String, | ||
| 30 | + pub name: String, | ||
| 31 | + pub admin: bool, | ||
| 32 | + pub photo_version: u64, | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +impl DirectoryMember { | ||
| 36 | + /// The member this user row answers as right now. | ||
| 37 | + pub fn of(user: &im_core::model::User) -> Self { | ||
| 38 | + Self { | ||
| 39 | + sub: user.id.to_string(), | ||
| 40 | + email: user.email.clone(), | ||
| 41 | + name: user.name.clone(), | ||
| 42 | + admin: user.admin, | ||
| 43 | + photo_version: user.photo_version, | ||
| 44 | + } | ||
| 45 | + } | ||
| 24 | } | 46 | } |
| 25 | 47 | ||
| 26 | /// `GET /directory`: the non-disabled roster as JSON. A wrong or missing | 48 | /// `GET /directory`: the non-disabled roster as JSON. A wrong or missing |
| @@ -39,15 +61,98 @@ async fn directory(cx: &Cx) -> topcoat::Result<topcoat::router::response::Respon | |||
| 39 | let members: Vec<DirectoryMember> = users | 61 | let members: Vec<DirectoryMember> = users |
| 40 | .into_iter() | 62 | .into_iter() |
| 41 | .filter(|user| !user.disabled) | 63 | .filter(|user| !user.disabled) |
| 42 | - .map(|user| DirectoryMember { | 64 | + .map(|user| DirectoryMember::of(&user)) |
| 43 | - sub: user.id.to_string(), | ||
| 44 | - email: user.email, | ||
| 45 | - name: user.name, | ||
| 46 | - admin: user.admin, | ||
| 47 | - }) | ||
| 48 | .collect(); | 65 | .collect(); |
| 49 | Json(serde_json::to_value(members).unwrap()).into_response(cx) | 66 | Json(serde_json::to_value(members).unwrap()).into_response(cx) |
| 50 | } | 67 | } |
| 68 | +/// `GET /directory/live`: the roster's change feed, as server-sent events. | ||
| 69 | +/// The same Basic pair `/directory` takes is the only credential. The | ||
| 70 | +/// stream opens with the reconnection hint, then carries one `profile` | ||
| 71 | +/// event per changed member, serialized exactly as `/directory` would | ||
| 72 | +/// answer that member; keep-alive comments hold quiet stretches and | ||
| 73 | +/// proxies open. Every change announces itself after its commit, so a | ||
| 74 | +/// frame's row never runs ahead of `/directory` itself. A lagged reader | ||
| 75 | +/// gets no frame — which rows dropped is unknowable — and heals the gap | ||
| 76 | +/// the way any disconnect does: wait out the retry hint, re-list the | ||
| 77 | +/// whole roster, resume. | ||
| 78 | +#[route(GET "/directory/live")] | ||
| 79 | +async fn directory_live(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> { | ||
| 80 | + if server::app_client(cx).await.is_none() { | ||
| 81 | + return ( | ||
| 82 | + StatusCode::UNAUTHORIZED, | ||
| 83 | + Json(serde_json::json!({ "error": "invalid_client" })), | ||
| 84 | + ) | ||
| 85 | + .into_response(cx); | ||
| 86 | + } | ||
| 87 | + let rx = server::app(cx).live.subscribe(); | ||
| 88 | + let stopping = | ||
| 89 | + topcoat::context::try_app_context::<crate::live::Shutdown>(cx).map(|s| s.0.clone()); | ||
| 90 | + let deadline = Instant::now() + crate::live::WINDOW; | ||
| 91 | + | ||
| 92 | + let events = futures_util::stream::unfold( | ||
| 93 | + (rx, deadline, stopping, true), | ||
| 94 | + |(mut rx, deadline, mut stopping, mut first)| async move { | ||
| 95 | + // The one frame every client sees first: how long to wait | ||
| 96 | + // before dialing back in after the stream drops. | ||
| 97 | + if first { | ||
| 98 | + first = false; | ||
| 99 | + return Some(( | ||
| 100 | + Ok::<_, std::convert::Infallible>( | ||
| 101 | + Event::new() | ||
| 102 | + .comment("directory live") | ||
| 103 | + .retry(Duration::from_millis(5000)), | ||
| 104 | + ), | ||
| 105 | + (rx, deadline, stopping, first), | ||
| 106 | + )); | ||
| 107 | + } | ||
| 108 | + loop { | ||
| 109 | + // Already going down: end, so this connection is not one | ||
| 110 | + // the shutdown has to sit and wait out. | ||
| 111 | + if stopping.as_ref().is_some_and(|watch| *watch.borrow()) { | ||
| 112 | + return None; | ||
| 113 | + } | ||
| 114 | + let left = deadline.saturating_duration_since(Instant::now()); | ||
| 115 | + if left.is_zero() { | ||
| 116 | + return None; | ||
| 117 | + } | ||
| 118 | + let heard = tokio::time::timeout(left, async { | ||
| 119 | + match stopping.as_mut() { | ||
| 120 | + Some(watch) => tokio::select! { | ||
| 121 | + _ = watch.changed() => None, | ||
| 122 | + got = rx.recv() => Some(got), | ||
| 123 | + }, | ||
| 124 | + None => Some(rx.recv().await), | ||
| 125 | + } | ||
| 126 | + }) | ||
| 127 | + .await; | ||
| 128 | + let member = match heard { | ||
| 129 | + // The window closed, the server is stopping, or the | ||
| 130 | + // broadcaster is gone — the process with it. Ending is | ||
| 131 | + // the point: the client reconnects on its own. | ||
| 132 | + Err(_) | Ok(None) => return None, | ||
| 133 | + Ok(Some(Err(RecvError::Closed))) => return None, | ||
| 134 | + // A tick moves im's own pages, not the roster; a lagged | ||
| 135 | + // reader cannot know which rows it lost. Both are silence | ||
| 136 | + // here — a full re-list after any reconnect heals both. | ||
| 137 | + Ok(Some(Err(RecvError::Lagged(_)))) | Ok(Some(Ok(server::LiveEvent::Tick))) => { | ||
| 138 | + continue; | ||
| 139 | + } | ||
| 140 | + Ok(Some(Ok(server::LiveEvent::Profile(member)))) => member, | ||
| 141 | + }; | ||
| 142 | + return Some(( | ||
| 143 | + Ok(Event::new() | ||
| 144 | + .event("profile") | ||
| 145 | + .data(serde_json::to_string(&member).expect("member JSON"))), | ||
| 146 | + (rx, deadline, stopping, first), | ||
| 147 | + )); | ||
| 148 | + } | ||
| 149 | + }, | ||
| 150 | + ); | ||
| 151 | + | ||
| 152 | + Sse::new(events.boxed()) | ||
| 153 | + .keep_alive(KeepAlive::new()) | ||
| 154 | + .into_response(cx) | ||
| 155 | +} | ||
| 51 | 156 | ||
| 52 | /// `GET /family`: the app switcher's list — every service with its wordmark, | 157 | /// `GET /family`: the app switcher's list — every service with its wordmark, |
| 53 | /// name, and base URL, in the stored order, as a bare JSON array. Registered | 158 | /// name, and base URL, in the stored order, as a bare JSON array. Registered |
crates/im-web/src/layout.rsmodified+4 -7
| @@ -58,15 +58,12 @@ pub async fn family_wordmark(cx: &Cx) -> Result { | |||
| 58 | } | 58 | } |
| 59 | 59 | ||
| 60 | /// The profile card's face: the photo when the account has one, the name's | 60 | /// The profile card's face: the photo when the account has one, the name's |
| 61 | -/// first letter on a quiet tile when it does not. The URL's stamp comes from | 61 | +/// first letter on a quiet tile when it does not. The URL's `?v=` is the |
| 62 | -/// `photo::PhotoStamps`, so a changed photo is a changed URL. | 62 | +/// row's `photo_version` — the same number `/directory` answers with — so |
| 63 | +/// a changed photo is a changed URL, in this process and in every sibling. | ||
| 63 | pub async fn avatar(cx: &Cx, user: &im_core::model::User) -> Result { | 64 | pub async fn avatar(cx: &Cx, user: &im_core::model::User) -> Result { |
| 64 | if user.has_photo { | 65 | if user.has_photo { |
| 65 | - let src = format!( | 66 | + let src = format!("/photo/{}?v={}", user.id, user.photo_version); |
| 66 | - "/photo/{}?v={}", | ||
| 67 | - user.id, | ||
| 68 | - crate::photo::photo_stamp(cx, &user.id.to_string()) | ||
| 69 | - ); | ||
| 70 | view! { | 67 | view! { |
| 71 | cx => | 68 | cx => |
| 72 | <img class="profile-avatar" src=(src) alt=(user.name.clone())> | 69 | <img class="profile-avatar" src=(src) alt=(user.name.clone())> |
crates/im-web/src/live.rsmodified+15 -2
| @@ -22,7 +22,7 @@ use crate::server; | |||
| 22 | /// opens another. The session is resolved once, at connect, and never again | 22 | /// opens another. The session is resolved once, at connect, and never again |
| 23 | /// for the life of the stream — the reconnect is what re-authenticates, so a | 23 | /// for the life of the stream — the reconnect is what re-authenticates, so a |
| 24 | /// session revoked mid-stream goes quiet within one window rather than never. | 24 | /// session revoked mid-stream goes quiet within one window rather than never. |
| 25 | -const WINDOW: Duration = Duration::from_secs(50 * 60); | 25 | +pub(crate) const WINDOW: Duration = Duration::from_secs(50 * 60); |
| 26 | 26 | ||
| 27 | /// Tells a live stream that the process is going down. | 27 | /// Tells a live stream that the process is going down. |
| 28 | /// | 28 | /// |
| @@ -84,7 +84,20 @@ async fn live(cx: &Cx) -> topcoat::Result<Response> { | |||
| 84 | // Which ones is unknowable, so the tick says "re-read | 84 | // Which ones is unknowable, so the tick says "re-read |
| 85 | // everything" — the client refetches the whole page, so | 85 | // everything" — the client refetches the whole page, so |
| 86 | // a lagged tick and a plain tick are the same frame. | 86 | // a lagged tick and a plain tick are the same frame. |
| 87 | - Ok(Some(Err(RecvError::Lagged(_)))) | Ok(Some(Ok(()))) => {} | 87 | + Ok(Some(Err(RecvError::Lagged(_)))) | Ok(Some(Ok(server::LiveEvent::Tick))) => {} |
| 88 | + // One member's row changed. The frame names which one — | ||
| 89 | + // im's own client still just re-fetches the page it is | ||
| 90 | + // on, so the payload is forward-compatibility for a | ||
| 91 | + // future page that can react to its own subject alone. | ||
| 92 | + Ok(Some(Ok(server::LiveEvent::Profile(member)))) => { | ||
| 93 | + return Some(( | ||
| 94 | + Ok::<_, std::convert::Infallible>(Event::new().data( | ||
| 95 | + serde_json::json!({ "kind": "profile", "sub": member.sub }) | ||
| 96 | + .to_string(), | ||
| 97 | + )), | ||
| 98 | + (rx, deadline, stopping), | ||
| 99 | + )); | ||
| 100 | + } | ||
| 88 | } | 101 | } |
| 89 | return Some(( | 102 | return Some(( |
| 90 | Ok::<_, std::convert::Infallible>(Event::new().data("{}")), | 103 | Ok::<_, std::convert::Infallible>(Event::new().data("{}")), |
crates/im-web/src/main.rsmodified+0 -1
| @@ -291,7 +291,6 @@ async fn serve(config: Config) { | |||
| 291 | .cookies() | 291 | .cookies() |
| 292 | .assets(bundle) | 292 | .assets(bundle) |
| 293 | .app_context(app) | 293 | .app_context(app) |
| 294 | - .app_context(photo::PhotoStamps::default()) | ||
| 295 | .app_context(live::Shutdown(stopping)) | 294 | .app_context(live::Shutdown(stopping)) |
| 296 | .build(); | 295 | .build(); |
| 297 | 296 | ||
crates/im-web/src/photo.rsmodified+206 -99
| @@ -3,15 +3,11 @@ | |||
| 3 | //! answer is im's, though: a plain 303 whose query names the code, which the | 3 | //! answer is im's, though: a plain 303 whose query names the code, which the |
| 4 | //! landing reads back on render. | 4 | //! landing reads back on render. |
| 5 | 5 | ||
| 6 | -use std::collections::HashMap; | ||
| 7 | -use std::sync::{Arc, LazyLock}; | ||
| 8 | - | ||
| 9 | use im_core::photos; | 6 | use im_core::photos; |
| 10 | -use parking_lot::Mutex; | 7 | +use topcoat::context::Cx; |
| 11 | -use time::OffsetDateTime; | ||
| 12 | -use topcoat::context::{Cx, try_app_context}; | ||
| 13 | use topcoat::router::content::multipart::Multipart; | 8 | use topcoat::router::content::multipart::Multipart; |
| 14 | use topcoat::router::request::headers as request_headers; | 9 | use topcoat::router::request::headers as request_headers; |
| 10 | +use topcoat::router::request::uri; | ||
| 15 | use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route}; | 11 | use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route}; |
| 16 | 12 | ||
| 17 | use crate::auth::{Redirect, see}; | 13 | use crate::auth::{Redirect, see}; |
| @@ -76,11 +72,10 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Redirect { | |||
| 76 | }; | 72 | }; |
| 77 | return match photos::set_photo(&store, &user.id, &collected, mime).await { | 73 | return match photos::set_photo(&store, &user.id, &collected, mime).await { |
| 78 | Ok(()) => { | 74 | Ok(()) => { |
| 79 | - // The bytes changed, so the URL the avatar renders has to | 75 | + // The row is committed with its bumped version: announce the |
| 80 | - // change with them — bump before the answer goes out. | 76 | + // changed face to every open tab and every app on the |
| 81 | - if let Some(stamps) = try_app_context::<PhotoStamps>(cx) { | 77 | + // directory stream before the answer goes out. |
| 82 | - stamps.bump(&user.id.to_string()); | 78 | + server::notify_profile(cx, &user.id).await; |
| 83 | - } | ||
| 84 | server::log_event(cx, "photo_saved", Some(&user.email), None).await; | 79 | server::log_event(cx, "photo_saved", Some(&user.email), None).await; |
| 85 | see("/?ok=photo_saved".to_string()) | 80 | see("/?ok=photo_saved".to_string()) |
| 86 | } | 81 | } |
| @@ -98,6 +93,8 @@ async fn delete(cx: &Cx) -> Redirect { | |||
| 98 | let store = server::app(cx).store.clone(); | 93 | let store = server::app(cx).store.clone(); |
| 99 | match photos::clear_photo(&store, &user.id).await { | 94 | match photos::clear_photo(&store, &user.id).await { |
| 100 | Ok(()) => { | 95 | Ok(()) => { |
| 96 | + // Committed: the face is gone, the version moved on either way. | ||
| 97 | + server::notify_profile(cx, &user.id).await; | ||
| 101 | server::log_event(cx, "photo_removed", Some(&user.email), None).await; | 98 | server::log_event(cx, "photo_removed", Some(&user.email), None).await; |
| 102 | see("/?ok=photo_removed".to_string()) | 99 | see("/?ok=photo_removed".to_string()) |
| 103 | } | 100 | } |
| @@ -105,77 +102,21 @@ async fn delete(cx: &Cx) -> Redirect { | |||
| 105 | } | 102 | } |
| 106 | } | 103 | } |
| 107 | 104 | ||
| 108 | -/// Photo URL version stamps, in process memory. The `user` row carries no | ||
| 109 | -/// photo-updated moment and a schema column for cache-busting is out of | ||
| 110 | -/// proportion, so the stamp lives here: `upload` bumps it when the bytes | ||
| 111 | -/// change, and the avatar render reads it back. A photo whose bytes this | ||
| 112 | -/// process never saw change stamps at the process start, which is still a | ||
| 113 | -/// URL no browser has fetched, so it is re-downloaded exactly once per | ||
| 114 | -/// restart and cached from then on. | ||
| 115 | -#[derive(Clone, Default)] | ||
| 116 | -pub struct PhotoStamps(Arc<Mutex<HashMap<String, i64>>>); | ||
| 117 | - | ||
| 118 | -/// Unix microseconds at first use: the stamp for every photo whose bytes | ||
| 119 | -/// this process never saw change. Stable for the process's lifetime, and | ||
| 120 | -/// later than any stamp an earlier process emitted, so no pre-restart URL | ||
| 121 | -/// survives a restart. | ||
| 122 | -static PROCESS_START: LazyLock<i64> = | ||
| 123 | - LazyLock::new(|| (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000) as i64); | ||
| 124 | - | ||
| 125 | -impl PhotoStamps { | ||
| 126 | - fn stamp(&self, user_id: &str) -> i64 { | ||
| 127 | - self.0 | ||
| 128 | - .lock() | ||
| 129 | - .get(user_id) | ||
| 130 | - .copied() | ||
| 131 | - .unwrap_or(*PROCESS_START) | ||
| 132 | - } | ||
| 133 | - | ||
| 134 | - fn bump(&self, user_id: &str) { | ||
| 135 | - let now = (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000) as i64; | ||
| 136 | - let mut stamps = self.0.lock(); | ||
| 137 | - // A write always moves the URL: never emit a stamp this user has | ||
| 138 | - // already rendered with, even when two writes land inside the same | ||
| 139 | - // microsecond. | ||
| 140 | - let stamp = stamps.get(user_id).copied().unwrap_or(*PROCESS_START); | ||
| 141 | - stamps.insert(user_id.to_string(), now.max(stamp + 1)); | ||
| 142 | - } | ||
| 143 | -} | ||
| 144 | - | ||
| 145 | -/// The stamp an avatar's photo URL carries. A router built without | ||
| 146 | -/// `PhotoStamps` falls back to the process start, which is still a URL no | ||
| 147 | -/// browser has fetched before. | ||
| 148 | -pub fn photo_stamp(cx: &Cx, user_id: &str) -> i64 { | ||
| 149 | - match try_app_context::<PhotoStamps>(cx) { | ||
| 150 | - Some(stamps) => stamps.stamp(user_id), | ||
| 151 | - None => *PROCESS_START, | ||
| 152 | - } | ||
| 153 | -} | ||
| 154 | - | ||
| 155 | -/// A cheap, non-cryptographic hash — good enough for an `ETag` on bytes only | ||
| 156 | -/// this server ever writes. | ||
| 157 | -fn fnv1a(bytes: &[u8]) -> u64 { | ||
| 158 | - let mut hash: u64 = 0xcbf29ce484222325; | ||
| 159 | - for &b in bytes { | ||
| 160 | - hash ^= b as u64; | ||
| 161 | - hash = hash.wrapping_mul(0x100000001b3); | ||
| 162 | - } | ||
| 163 | - hash | ||
| 164 | -} | ||
| 165 | - | ||
| 166 | fn not_found() -> (StatusCode, HeaderMap, Vec<u8>) { | 105 | fn not_found() -> (StatusCode, HeaderMap, Vec<u8>) { |
| 167 | (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) | 106 | (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) |
| 168 | } | 107 | } |
| 169 | 108 | ||
| 170 | -/// The response for served bytes: the ETag and cache policy, the 304 when | 109 | +/// The response for served bytes: the version ETag — strong, one per photo |
| 171 | -/// the caller's copy is already this one. | 110 | +/// generation — the caller's cache policy, and the 304 when the caller's |
| 111 | +/// copy is already this one. | ||
| 172 | fn bytes_response( | 112 | fn bytes_response( |
| 173 | cx: &Cx, | 113 | cx: &Cx, |
| 174 | bytes: Vec<u8>, | 114 | bytes: Vec<u8>, |
| 175 | content_type: &str, | 115 | content_type: &str, |
| 176 | cache: &'static str, | 116 | cache: &'static str, |
| 117 | + version: u64, | ||
| 177 | ) -> (StatusCode, HeaderMap, Vec<u8>) { | 118 | ) -> (StatusCode, HeaderMap, Vec<u8>) { |
| 178 | - let etag = format!("\"{:x}\"", fnv1a(&bytes)); | 119 | + let etag = format!("\"p{version}\""); |
| 179 | let mut headers = HeaderMap::new(); | 120 | let mut headers = HeaderMap::new(); |
| 180 | headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap()); | 121 | headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap()); |
| 181 | headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); | 122 | headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); |
| @@ -215,6 +156,16 @@ fn default_avatar(initial: &str) -> Vec<u8> { | |||
| 215 | .into_bytes() | 156 | .into_bytes() |
| 216 | } | 157 | } |
| 217 | 158 | ||
| 159 | +/// The `v` pair of this request's query string, if it carried one. Matched | ||
| 160 | +/// verbatim against the row's `photo_version`; a version needs no escaping, | ||
| 161 | +/// so a plain split is the whole parse. | ||
| 162 | +fn requested_version(cx: &Cx) -> Option<&str> { | ||
| 163 | + uri(cx) | ||
| 164 | + .query()? | ||
| 165 | + .split('&') | ||
| 166 | + .find_map(|pair| pair.strip_prefix("v=")) | ||
| 167 | +} | ||
| 168 | + | ||
| 218 | /// Serves one person's photo. Signed-in only — either through the session | 169 | /// Serves one person's photo. Signed-in only — either through the session |
| 219 | /// cookie or as a registered OIDC app presenting HTTP Basic over | 170 | /// cookie or as a registered OIDC app presenting HTTP Basic over |
| 220 | /// `client_id:client_secret`. | 171 | /// `client_id:client_secret`. |
| @@ -224,10 +175,15 @@ fn default_avatar(initial: &str) -> Vec<u8> { | |||
| 224 | /// `<img>` shows a person, never a broken-image glyph. An unknown id gets | 175 | /// `<img>` shows a person, never a broken-image glyph. An unknown id gets |
| 225 | /// the same tile with a `?`, so an authenticated fetch still cannot tell a | 176 | /// the same tile with a `?`, so an authenticated fetch still cannot tell a |
| 226 | /// missing person from a missing photo; only the missing credential reads | 177 | /// missing person from a missing photo; only the missing credential reads |
| 227 | -/// as the not-found. The tile answers `no-cache` (revalidating on its | 178 | +/// as the not-found. |
| 228 | -/// ETag) where the photo answers `immutable`: apps fetch this URL without | 179 | +/// |
| 229 | -/// the stamp im's own pages add, so a photo uploaded later must replace | 180 | +/// Caching hangs off the row's `photo_version`, the same number the |
| 230 | -/// the tile, and a year of `immutable` would pin the letter forever. | 181 | +/// directory answers with: a URL whose `?v=` names the current version |
| 182 | +/// may cache for a year — a changed photo is a changed URL — while every | ||
| 183 | +/// other spelling of the route, the bare `/photo/{sub}` an app fetches or | ||
| 184 | +/// the photoless tile, answers `no-cache` and revalidates on the ETag. | ||
| 185 | +/// The version comes from the store, not from process memory, so a | ||
| 186 | +/// restart forgets nothing and every reader sees the same one. | ||
| 231 | #[route(GET "/photo/{user_id}")] | 187 | #[route(GET "/photo/{user_id}")] |
| 232 | async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> { | 188 | async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> { |
| 233 | if server::current_user(cx).await.is_none() && !server::valid_app(cx).await { | 189 | if server::current_user(cx).await.is_none() && !server::valid_app(cx).await { |
| @@ -235,33 +191,32 @@ async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> { | |||
| 235 | } | 191 | } |
| 236 | let target = im_core::model::UserId::from(path_param::<UserId>(cx).to_string()); | 192 | let target = im_core::model::UserId::from(path_param::<UserId>(cx).to_string()); |
| 237 | let store = server::app(cx).store.clone(); | 193 | let store = server::app(cx).store.clone(); |
| 194 | + let user = im_core::accounts::user_by_id(&store, &target) | ||
| 195 | + .await | ||
| 196 | + .ok() | ||
| 197 | + .flatten(); | ||
| 198 | + let version = user.as_ref().map_or(0, |user| user.photo_version); | ||
| 238 | if let Ok(Some((bytes, mime))) = photos::photo(&store, &target).await { | 199 | if let Ok(Some((bytes, mime))) = photos::photo(&store, &target).await { |
| 239 | - // The stamp in the URL is the other half of this caching: `upload` | ||
| 240 | - // bumps it whenever the bytes change, so a year of `immutable` | ||
| 241 | - // never shows an old photo — a changed photo is a changed URL. | ||
| 242 | // `private` because the route is session-gated. | 200 | // `private` because the route is session-gated. |
| 243 | - return Ok(bytes_response( | 201 | + let cache = if requested_version(cx) == Some(version.to_string().as_str()) { |
| 244 | - cx, | 202 | + "private, max-age=31536000, immutable" |
| 245 | - bytes, | 203 | + } else { |
| 246 | - &mime, | 204 | + "private, no-cache" |
| 247 | - "private, max-age=31536000, immutable", | 205 | + }; |
| 248 | - )); | 206 | + return Ok(bytes_response(cx, bytes, &mime, cache, version)); |
| 249 | } | 207 | } |
| 250 | - let initial = match im_core::accounts::user_by_id(&store, &target).await { | 208 | + let initial = user |
| 251 | - Ok(Some(user)) => user | 209 | + .as_ref() |
| 252 | - .name | 210 | + .and_then(|user| user.name.chars().next()) |
| 253 | - .chars() | 211 | + .unwrap_or('?') |
| 254 | - .next() | 212 | + .to_uppercase() |
| 255 | - .unwrap_or('?') | 213 | + .to_string(); |
| 256 | - .to_uppercase() | ||
| 257 | - .to_string(), | ||
| 258 | - _ => "?".to_string(), | ||
| 259 | - }; | ||
| 260 | Ok(bytes_response( | 214 | Ok(bytes_response( |
| 261 | cx, | 215 | cx, |
| 262 | default_avatar(&initial), | 216 | default_avatar(&initial), |
| 263 | "image/svg+xml", | 217 | "image/svg+xml", |
| 264 | "private, no-cache", | 218 | "private, no-cache", |
| 219 | + version, | ||
| 265 | )) | 220 | )) |
| 266 | } | 221 | } |
| 267 | 222 | ||
| @@ -270,7 +225,6 @@ mod tests { | |||
| 270 | use std::path::Path; | 225 | use std::path::Path; |
| 271 | use std::sync::Arc; | 226 | use std::sync::Arc; |
| 272 | 227 | ||
| 273 | - use super::PhotoStamps; | ||
| 274 | use im_core::accounts::{create_invite, create_user_from_invite}; | 228 | use im_core::accounts::{create_invite, create_user_from_invite}; |
| 275 | use im_core::model::UserId; | 229 | use im_core::model::UserId; |
| 276 | use im_core::oidc::create_client; | 230 | use im_core::oidc::create_client; |
| @@ -288,6 +242,7 @@ mod tests { | |||
| 288 | 242 | ||
| 289 | struct Setup { | 243 | struct Setup { |
| 290 | router: Router, | 244 | router: Router, |
| 245 | + store: Arc<Store>, | ||
| 291 | user_id: UserId, | 246 | user_id: UserId, |
| 292 | plain_id: UserId, | 247 | plain_id: UserId, |
| 293 | client_id: String, | 248 | client_id: String, |
| @@ -320,8 +275,9 @@ mod tests { | |||
| 320 | .await | 275 | .await |
| 321 | .unwrap(); | 276 | .unwrap(); |
| 322 | let (live, _) = tokio::sync::broadcast::channel(64); | 277 | let (live, _) = tokio::sync::broadcast::channel(64); |
| 278 | + let store = Arc::new(store); | ||
| 323 | let app = server::App { | 279 | let app = server::App { |
| 324 | - store: Arc::new(store), | 280 | + store: store.clone(), |
| 325 | config: Config { | 281 | config: Config { |
| 326 | database: ":memory:".into(), | 282 | database: ":memory:".into(), |
| 327 | listen: "127.0.0.1:7650".parse().unwrap(), | 283 | listen: "127.0.0.1:7650".parse().unwrap(), |
| @@ -334,10 +290,10 @@ mod tests { | |||
| 334 | .discover() | 290 | .discover() |
| 335 | .cookies() | 291 | .cookies() |
| 336 | .app_context(app) | 292 | .app_context(app) |
| 337 | - .app_context(PhotoStamps::default()) | ||
| 338 | .build(); | 293 | .build(); |
| 339 | Setup { | 294 | Setup { |
| 340 | router, | 295 | router, |
| 296 | + store, | ||
| 341 | user_id: user.id, | 297 | user_id: user.id, |
| 342 | plain_id: plain.id, | 298 | plain_id: plain.id, |
| 343 | client_id: client_id.to_string(), | 299 | client_id: client_id.to_string(), |
| @@ -354,19 +310,36 @@ mod tests { | |||
| 354 | ) | 310 | ) |
| 355 | } | 311 | } |
| 356 | 312 | ||
| 313 | + /// GETs `/photo/{id}` — the plain helper most tests use. | ||
| 357 | async fn get( | 314 | async fn get( |
| 358 | router: &Router, | 315 | router: &Router, |
| 359 | user_id: &str, | 316 | user_id: &str, |
| 360 | auth: Option<String>, | 317 | auth: Option<String>, |
| 361 | cookie: Option<&str>, | 318 | cookie: Option<&str>, |
| 362 | ) -> (StatusCode, HeaderMap, Vec<u8>) { | 319 | ) -> (StatusCode, HeaderMap, Vec<u8>) { |
| 363 | - let mut builder = http::Request::builder().uri(format!("/photo/{user_id}")); | 320 | + get_uri(router, &format!("/photo/{user_id}"), auth, cookie, None).await |
| 321 | + } | ||
| 322 | + | ||
| 323 | + /// GETs a photo URI — with or without the `?v=` pair — optionally | ||
| 324 | + /// carrying an app's Basic pair, a session cookie, and an | ||
| 325 | + /// `If-None-Match` for the revalidation dance. | ||
| 326 | + async fn get_uri( | ||
| 327 | + router: &Router, | ||
| 328 | + uri: &str, | ||
| 329 | + auth: Option<String>, | ||
| 330 | + cookie: Option<&str>, | ||
| 331 | + if_none_match: Option<&str>, | ||
| 332 | + ) -> (StatusCode, HeaderMap, Vec<u8>) { | ||
| 333 | + let mut builder = http::Request::builder().uri(uri); | ||
| 364 | if let Some(auth) = auth { | 334 | if let Some(auth) = auth { |
| 365 | builder = builder.header(header::AUTHORIZATION, auth); | 335 | builder = builder.header(header::AUTHORIZATION, auth); |
| 366 | } | 336 | } |
| 367 | if let Some(cookie) = cookie { | 337 | if let Some(cookie) = cookie { |
| 368 | builder = builder.header(header::COOKIE, cookie); | 338 | builder = builder.header(header::COOKIE, cookie); |
| 369 | } | 339 | } |
| 340 | + if let Some(etag) = if_none_match { | ||
| 341 | + builder = builder.header(header::IF_NONE_MATCH, etag); | ||
| 342 | + } | ||
| 370 | let response = router.handle(builder.body(Body::empty()).unwrap()).await; | 343 | let response = router.handle(builder.body(Body::empty()).unwrap()).await; |
| 371 | let (parts, body) = response.into_parts(); | 344 | let (parts, body) = response.into_parts(); |
| 372 | let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec(); | 345 | let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec(); |
| @@ -505,4 +478,138 @@ mod tests { | |||
| 505 | assert_eq!(status, StatusCode::OK); | 478 | assert_eq!(status, StatusCode::OK); |
| 506 | assert_eq!(bytes, PHOTO); | 479 | assert_eq!(bytes, PHOTO); |
| 507 | } | 480 | } |
| 481 | + | ||
| 482 | + #[tokio::test] | ||
| 483 | + async fn versioned_url_caches_immutably_on_the_version_etag() { | ||
| 484 | + let setup = setup().await; | ||
| 485 | + // Setup uploads once, so Ann's row sits at version 1. | ||
| 486 | + let uri = format!("/photo/{}?v=1", setup.user_id); | ||
| 487 | + let (status, headers, _) = | ||
| 488 | + get_uri(&setup.router, &uri, Some(basic(&setup.client_id, &setup.secret)), None, None) | ||
| 489 | + .await; | ||
| 490 | + assert_eq!(status, StatusCode::OK); | ||
| 491 | + assert_eq!(headers.get(header::ETAG).unwrap(), "\"p1\""); | ||
| 492 | + assert_eq!( | ||
| 493 | + headers.get(header::CACHE_CONTROL).unwrap(), | ||
| 494 | + "private, max-age=31536000, immutable" | ||
| 495 | + ); | ||
| 496 | + } | ||
| 497 | + | ||
| 498 | + #[tokio::test] | ||
| 499 | + async fn unversioned_url_must_revalidate() { | ||
| 500 | + let setup = setup().await; | ||
| 501 | + let (status, headers, _) = get( | ||
| 502 | + &setup.router, | ||
| 503 | + setup.user_id.as_str(), | ||
| 504 | + Some(basic(&setup.client_id, &setup.secret)), | ||
| 505 | + None, | ||
| 506 | + ) | ||
| 507 | + .await; | ||
| 508 | + assert_eq!(status, StatusCode::OK); | ||
| 509 | + assert_eq!(headers.get(header::ETAG).unwrap(), "\"p1\""); | ||
| 510 | + // The bare URL an app fetches cannot promise freshness: a year of | ||
| 511 | + // `immutable` would pin yesterday's face until the next restart | ||
| 512 | + // minted a new stamp. | ||
| 513 | + assert_eq!( | ||
| 514 | + headers.get(header::CACHE_CONTROL).unwrap(), | ||
| 515 | + "private, no-cache" | ||
| 516 | + ); | ||
| 517 | + } | ||
| 518 | + | ||
| 519 | + #[tokio::test] | ||
| 520 | + async fn a_stale_version_asks_for_a_revalidation_too() { | ||
| 521 | + let setup = setup().await; | ||
| 522 | + let uri = format!("/photo/{}?v=0", setup.user_id); | ||
| 523 | + let (_, headers, _) = | ||
| 524 | + get_uri(&setup.router, &uri, Some(basic(&setup.client_id, &setup.secret)), None, None) | ||
| 525 | + .await; | ||
| 526 | + assert_eq!( | ||
| 527 | + headers.get(header::CACHE_CONTROL).unwrap(), | ||
| 528 | + "private, no-cache" | ||
| 529 | + ); | ||
| 530 | + } | ||
| 531 | + | ||
| 532 | + #[tokio::test] | ||
| 533 | + async fn matching_if_none_match_answers_not_modified() { | ||
| 534 | + let setup = setup().await; | ||
| 535 | + let uri = format!("/photo/{}?v=1", setup.user_id); | ||
| 536 | + let (status, headers, bytes) = get_uri( | ||
| 537 | + &setup.router, | ||
| 538 | + &uri, | ||
| 539 | + Some(basic(&setup.client_id, &setup.secret)), | ||
| 540 | + None, | ||
| 541 | + Some("\"p1\""), | ||
| 542 | + ) | ||
| 543 | + .await; | ||
| 544 | + assert_eq!(status, StatusCode::NOT_MODIFIED); | ||
| 545 | + assert_eq!(headers.get(header::ETAG).unwrap(), "\"p1\""); | ||
| 546 | + assert!(bytes.is_empty()); | ||
| 547 | + // A stale copy revalidates to the full answer, never a 304. | ||
| 548 | + let (status, _, _) = get_uri( | ||
| 549 | + &setup.router, | ||
| 550 | + &uri, | ||
| 551 | + Some(basic(&setup.client_id, &setup.secret)), | ||
| 552 | + None, | ||
| 553 | + Some("\"p0\""), | ||
| 554 | + ) | ||
| 555 | + .await; | ||
| 556 | + assert_eq!(status, StatusCode::OK); | ||
| 557 | + } | ||
| 558 | + | ||
| 559 | + #[tokio::test] | ||
| 560 | + async fn a_new_upload_moves_the_version_and_the_etag() { | ||
| 561 | + let setup = setup().await; | ||
| 562 | + set_photo( | ||
| 563 | + &setup.store, | ||
| 564 | + &setup.user_id, | ||
| 565 | + b"\x89PNG\r\n\x1a\nother-bytes", | ||
| 566 | + "image/png", | ||
| 567 | + ) | ||
| 568 | + .await | ||
| 569 | + .unwrap(); | ||
| 570 | + // The old cached copy is stale on both spellings of the URL. | ||
| 571 | + let uri = format!("/photo/{}?v=1", setup.user_id); | ||
| 572 | + let (_, headers, _) = | ||
| 573 | + get_uri(&setup.router, &uri, Some(basic(&setup.client_id, &setup.secret)), None, None) | ||
| 574 | + .await; | ||
| 575 | + assert_eq!( | ||
| 576 | + headers.get(header::CACHE_CONTROL).unwrap(), | ||
| 577 | + "private, no-cache" | ||
| 578 | + ); | ||
| 579 | + let uri = format!("/photo/{}?v=2", setup.user_id); | ||
| 580 | + let (status, headers, bytes) = | ||
| 581 | + get_uri(&setup.router, &uri, Some(basic(&setup.client_id, &setup.secret)), None, None) | ||
| 582 | + .await; | ||
| 583 | + assert_eq!(status, StatusCode::OK); | ||
| 584 | + assert_eq!(headers.get(header::ETAG).unwrap(), "\"p2\""); | ||
| 585 | + assert_eq!( | ||
| 586 | + headers.get(header::CACHE_CONTROL).unwrap(), | ||
| 587 | + "private, max-age=31536000, immutable" | ||
| 588 | + ); | ||
| 589 | + assert_eq!(bytes, b"\x89PNG\r\n\x1a\nother-bytes"); | ||
| 590 | + } | ||
| 591 | + | ||
| 592 | + #[tokio::test] | ||
| 593 | + async fn the_photoless_tile_validates_on_the_version_etag() { | ||
| 594 | + let setup = setup().await; | ||
| 595 | + let (status, headers, _) = get( | ||
| 596 | + &setup.router, | ||
| 597 | + setup.plain_id.as_str(), | ||
| 598 | + Some(basic(&setup.client_id, &setup.secret)), | ||
| 599 | + None, | ||
| 600 | + ) | ||
| 601 | + .await; | ||
| 602 | + assert_eq!(status, StatusCode::OK); | ||
| 603 | + assert_eq!(headers.get(header::ETAG).unwrap(), "\"p0\""); | ||
| 604 | + let (status, _, bytes) = get_uri( | ||
| 605 | + &setup.router, | ||
| 606 | + &format!("/photo/{}", setup.plain_id), | ||
| 607 | + Some(basic(&setup.client_id, &setup.secret)), | ||
| 608 | + None, | ||
| 609 | + Some("\"p0\""), | ||
| 610 | + ) | ||
| 611 | + .await; | ||
| 612 | + assert_eq!(status, StatusCode::NOT_MODIFIED); | ||
| 613 | + assert!(bytes.is_empty()); | ||
| 614 | + } | ||
| 508 | } | 615 | } |
crates/im-web/src/server.rsmodified+29 -5
| @@ -27,16 +27,40 @@ pub const PENDING_MINUTES: i64 = 10; | |||
| 27 | pub struct App { | 27 | pub struct App { |
| 28 | pub store: Arc<Store>, | 28 | pub store: Arc<Store>, |
| 29 | pub config: Config, | 29 | pub config: Config, |
| 30 | - /// The live channel's ticker: any mutation announces itself here, and | 30 | + /// The live channel: any mutation announces itself here, and every open |
| 31 | - /// every open admin tab re-reads what it is showing. Carries no data — | 31 | + /// tab re-reads what it is showing. A `Tick` says "re-fetch", nothing |
| 32 | - /// a tick says "re-fetch", nothing more. | 32 | + /// more — never a row, never a name. A `Profile` carries the full |
| 33 | - pub live: tokio::sync::broadcast::Sender<()>, | 33 | + /// directory row of the one member whose row changed, for the app-facing |
| 34 | + /// `/directory/live` stream. | ||
| 35 | + pub live: tokio::sync::broadcast::Sender<LiveEvent>, | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// What travels the live channel. `Tick` is the panel's "something moved — | ||
| 39 | +/// re-read"; `Profile` is the directory's own news: this member's row, as it | ||
| 40 | +/// now stands, serialized exactly as `/directory` would have answered it. | ||
| 41 | +#[derive(Clone, Debug)] | ||
| 42 | +pub enum LiveEvent { | ||
| 43 | + Tick, | ||
| 44 | + Profile(crate::directory::DirectoryMember), | ||
| 34 | } | 45 | } |
| 35 | 46 | ||
| 36 | /// Announce that the panel's data moved. Sends are lossy on purpose: nobody | 47 | /// Announce that the panel's data moved. Sends are lossy on purpose: nobody |
| 37 | /// listening is not an error, and a lagging tab gets a resync tick. | 48 | /// listening is not an error, and a lagging tab gets a resync tick. |
| 38 | pub fn note(cx: &Cx) { | 49 | pub fn note(cx: &Cx) { |
| 39 | - let _ = app(cx).live.send(()); | 50 | + let _ = app(cx).live.send(LiveEvent::Tick); |
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// Announce that one member's row changed. Re-reads the row — the callers | ||
| 54 | +/// hold the pre-write copy — and broadcasts it as the member `/directory` | ||
| 55 | +/// would answer. A row that no longer resolves (deleted) has no member to | ||
| 56 | +/// announce; the next full pass is where a removal surfaces. | ||
| 57 | +pub async fn notify_profile(cx: &Cx, user_id: &im_core::model::UserId) { | ||
| 58 | + let Ok(Some(user)) = im_core::accounts::user_by_id(&app(cx).store, user_id).await else { | ||
| 59 | + return; | ||
| 60 | + }; | ||
| 61 | + let _ = app(cx).live.send(LiveEvent::Profile( | ||
| 62 | + crate::directory::DirectoryMember::of(&user), | ||
| 63 | + )); | ||
| 40 | } | 64 | } |
| 41 | 65 | ||
| 42 | /// Log the event, then tick the live channel — the two travel together so | 66 | /// Log the event, then tick the live channel — the two travel together so |