diff --git a/crates/im-client/src/directory.rs b/crates/im-client/src/directory.rs new file mode 100644 index 0000000..650f257 --- /dev/null +++ b/crates/im-client/src/directory.rs @@ -0,0 +1,453 @@ +//! im-client's directory half: the app-side mirror of im's identity +//! roster. Three doors, all opened with the app's Basic pair: +//! +//! * [`DirectoryClient::directory`] — the whole roster, as im's +//! `/directory` answers it; +//! * [`DirectoryClient::photo`] — one member's photo bytes, for an +//! `` served out of the app's own hands; +//! * [`DirectoryClient::open_stream`] — the `/directory/live` feed, one +//! event per changed member, parsed by hand from the byte stream. +//! +//! [`spawn_sync`] is the whole loop most apps want: a full pass through +//! [`DirectoryClient::directory`], then the stream through the same +//! `on_member` door, and — whenever the stream drops — a growing wait, a +//! `on_resync` call, a fresh full pass, and back on the stream. The mirror +//! converges no matter how the connection died. + +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use crate::{Error, Result}; + +/// How long a plain request (roster, photo) may take. The live stream is +/// exempt — it is *supposed* to sit idle — so its request carries no +/// timeout and its liveness is the server's keep-alive comment. +const REQUEST_TIMEOUT: Duration = Duration::from_secs(15); + +/// The first wait after a failed stream, and the growth step. +const BACKOFF_FLOOR: Duration = Duration::from_secs(1); + +/// The longest wait a run of consecutive failures earns. +const BACKOFF_CAP: Duration = Duration::from_secs(30); + +/// One roster member, exactly the shape im's `/directory` answers and its +/// `/directory/live` stream announces. `admin` and `photo_version` default +/// so an older im — whose answers predate them — still parses. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct DirectoryMember { + /// The stable subject: the same string the id_token's `sub` claim and + /// the photo route's path carry. + pub sub: String, + pub email: String, + pub name: String, + #[serde(default)] + pub admin: bool, + /// How many times the member's photo has changed: the `?v=` that lets + /// `/photo/{sub}` be cached hard and still arrive fresh. + #[serde(default)] + pub photo_version: u64, +} + +/// One event off the directory stream. The only thing `/directory/live` +/// announces today is a changed member; the enum leaves room for the feed +/// to grow without a breaking change to consumers. +#[derive(Debug, Clone, PartialEq)] +pub enum DirectoryEvent { + /// The named member's row changed — upload, address, admin flag, any + /// of it. The payload is the row as it now stands. + Profile(DirectoryMember), +} + +/// The directory client: issuer plus the same `client_id:client_secret` +/// pair the OIDC side already holds. Cheap to clone; one HTTP pool inside. +#[derive(Clone)] +pub struct DirectoryClient { + http: reqwest::Client, + issuer: String, + client_id: String, + client_secret: String, +} + +impl DirectoryClient { + pub fn new( + issuer: impl Into, + client_id: impl Into, + client_secret: impl Into, + ) -> Self { + Self { + http: reqwest::Client::new(), + issuer: issuer.into(), + client_id: client_id.into(), + client_secret: client_secret.into(), + } + } + + fn get(&self, path: &str) -> reqwest::RequestBuilder { + self.http + .get(format!("{}{path}", self.issuer)) + .basic_auth(&self.client_id, Some(&self.client_secret)) + } + + /// `GET /directory`: the whole non-disabled roster, oldest first. + pub async fn directory(&self) -> Result> { + let answer = self + .get("/directory") + .timeout(REQUEST_TIMEOUT) + .send() + .await + .map_err(|e| Error::Http(e.to_string()))? + .error_for_status() + .map_err(|e| Error::Refused(e.to_string()))?; + answer + .json() + .await + .map_err(|e| Error::Http(e.to_string())) + } + + /// `GET /photo/{sub}`: the member's photo bytes and their content + /// type. A member with no photo gets im's default face — the initial + /// tile — so the answer is always an image. + pub async fn photo(&self, sub: &str) -> Result<(Vec, String)> { + let answer = self + .get(&format!("/photo/{sub}")) + .timeout(REQUEST_TIMEOUT) + .send() + .await + .map_err(|e| Error::Http(e.to_string()))? + .error_for_status() + .map_err(|e| Error::Refused(e.to_string()))?; + let content_type = answer + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or("application/octet-stream") + .to_string(); + let bytes = answer + .bytes() + .await + .map_err(|e| Error::Http(e.to_string()))? + .to_vec(); + Ok((bytes, content_type)) + } + + /// `GET /directory/live`: opens the change feed. Every frame after the + /// first is one member's row; the stream ends — `None` from + /// [`DirectoryStream::next`] — whenever im closes it, which is the + /// caller's cue to re-list and redial ([`spawn_sync`] does exactly + /// that). + pub async fn open_stream(&self) -> Result { + let response = self + .get("/directory/live") + .send() + .await + .map_err(|e| Error::Http(e.to_string()))? + .error_for_status() + .map_err(|e| Error::Refused(e.to_string()))?; + Ok(DirectoryStream { + response, + parser: SseParser::default(), + ready: std::collections::VecDeque::new(), + }) + } +} + +/// An open `/directory/live` connection. +pub struct DirectoryStream { + response: reqwest::Response, + parser: SseParser, + ready: std::collections::VecDeque, +} + +impl DirectoryStream { + /// The next member change. `Some(Err)` on a network failure, then the + /// stream is over; `None` when im closed a healthy stream (a restart, + /// the server window). Either way the caller re-lists and redials. + pub async fn next(&mut self) -> Option> { + loop { + if let Some(event) = self.ready.pop_front() { + return Some(Ok(event)); + } + match self.response.chunk().await { + Ok(Some(bytes)) => self.ready.extend(self.parser.feed(&bytes)), + // The connection closed cleanly: a healthy stream's end. + Ok(None) => return None, + Err(e) => return Some(Err(Error::Http(e.to_string()))), + } + } + } +} + +/// The hand-rolled `text/event-stream` reader. Frames accumulate field by +/// field and dispatch on the blank line, per the SSE grammar; the only +/// fields this feed carries are `event`, `data`, `retry`, and comments, +/// but the parser honors the whole shape — including `data` split over +/// several lines, which the spec joins with `\n`. +#[derive(Default)] +struct SseParser { + /// Bytes read but not yet through a line terminator. + pending: Vec, + /// The current frame's `event:` field, if it named one. + event: Option, + /// The current frame's `data:`, joined back into one string. + data: String, +} + +impl SseParser { + /// Feeds the next bytes from the wire and answers every frame they + /// completed. Bytes trailing their terminator wait for the rest — a + /// field or a UTF-8 character may straddle two reads. + fn feed(&mut self, bytes: &[u8]) -> Vec { + self.pending.extend_from_slice(bytes); + let mut events = Vec::new(); + let Some(at) = self + .pending + .iter() + .rposition(|&b| b == b'\n' || b == b'\r') + .map(|at| at + 1) + else { + return events; + }; + let block: Vec = self.pending.drain(..at).collect(); + for line in split_lines(&block) { + if line.is_empty() { + // The blank line dispatches whatever accumulated. + if let Some(event) = self.take_event() { + events.push(event); + } + } else if line[0] == b':' { + // A comment — im's keep-alives and retry hint live here. + } else { + let (name, value) = match line.iter().position(|&b| b == b':') { + Some(at) => (&line[..at], &line[at + 1..]), + None => (&line[..], &b""[..]), + }; + // One optional space after the colon is not part of the + // value. + let value = value.strip_prefix(b" ").unwrap_or(value); + match name { + b"event" => self.event = Some(String::from_utf8_lossy(value).into_owned()), + b"data" => { + if !self.data.is_empty() { + self.data.push('\n'); + } + self.data.push_str(&String::from_utf8_lossy(value)); + } + // `id` and `retry` mean nothing to a change feed. + _ => {} + } + } + } + events + } + + /// Ends the current frame: the data, if it parsed into a member, is + /// the event. A frame that names another event type, or whose data is + /// not a member, is skipped — the feed may grow, and a single bad + /// frame must not end the connection. + fn take_event(&mut self) -> Option { + let data = std::mem::take(&mut self.data); + let event = self.event.take(); + if let Some(kind) = event { + if kind != "profile" { + return None; + } + } + serde_json::from_str::(&data) + .ok() + .map(DirectoryEvent::Profile) + } +} + +/// Splits a block that ends at a line terminator into lines, accepting the +/// three SSE terminators: `\n`, `\r\n`, and a bare `\r`. +fn split_lines(block: &[u8]) -> Vec> { + let mut lines = Vec::new(); + let mut rest = block; + while let Some(at) = rest.iter().position(|&b| b == b'\n' || b == b'\r') { + let (line, tail) = rest.split_at(at); + lines.push(line.to_vec()); + // A `\r\n` pair is one terminator, not a line and an empty one. + rest = if tail.starts_with(b"\r\n") { &tail[2..] } else { &tail[1..] }; + } + lines +} + +/// Keeps the app's mirror of the roster in step with im, forever: +/// +/// 1. one full `/directory` pass, every member applied through +/// `on_member` — the boot-time population; +/// 2. the `/directory/live` stream, every change through the same door; +/// 3. when the stream dies — error, lag, clean close — wait out the +/// backoff (1s doubling to a 30s cap), call `on_resync`, replay a full +/// pass, and resume the stream. A full pass that itself fails is +/// retried on the same clock until im answers. +/// +/// Runs until the task is aborted; the handle is the caller's to drop or +/// cancel. +pub fn spawn_sync( + client: DirectoryClient, + mut on_member: F, + mut on_resync: G, +) -> tokio::task::JoinHandle<()> +where + F: FnMut(DirectoryMember) + Send + 'static, + G: FnMut() + Send + 'static, +{ + tokio::spawn(async move { + let mut backoff = BACKOFF_FLOOR; + loop { + // The full pass. There is nothing to converge with until one + // lands, so failures retry on the growing clock. + loop { + match client.directory().await { + Ok(members) => { + for member in members { + on_member(member); + } + break; + } + Err(_) => { + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(BACKOFF_CAP); + } + } + } + let mut stream = match client.open_stream().await { + Ok(stream) => stream, + Err(_) => { + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(BACKOFF_CAP); + on_resync(); + continue; + } + }; + while let Some(event) = stream.next().await { + match event { + Ok(DirectoryEvent::Profile(member)) => { + on_member(member); + // The stream works: the next stumble starts over + // at the short wait. + backoff = BACKOFF_FLOOR; + } + Err(_) => break, + } + } + // The stream is gone. Wait, grow, and make the caller + // re-list the whole roster before the stream resumes, so + // whatever moved while the line was down heals on the pass. + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(BACKOFF_CAP); + on_resync(); + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn member_json(sub: &str, version: u64) -> String { + format!( + "{{\"sub\":\"{sub}\",\"email\":\"{sub}@example.com\",\ + \"name\":\"Ann\",\"admin\":false,\"photo_version\":{version}}}" + ) + } + + fn frame(sub: &str, version: u64) -> String { + format!("event: profile\ndata: {}\n\n", member_json(sub, version)) + } + + #[test] + fn a_profile_frame_becomes_an_event() { + let mut parser = SseParser::default(); + let events = parser.feed( + format!("retry: 5000\n: keep-alive\n\n{}", frame("one", 3)).as_bytes(), + ); + assert_eq!( + events, + vec![DirectoryEvent::Profile(DirectoryMember { + sub: "one".into(), + email: "one@example.com".into(), + name: "Ann".into(), + admin: false, + photo_version: 3, + })] + ); + } + + #[test] + fn a_frame_split_across_reads_still_parses() { + let whole = frame("two", 7); + let mut parser = SseParser::default(); + let mut events = Vec::new(); + // Cut at every byte boundary in turn; no split may lose the event. + for cut in 1..whole.len() { + events = parser.feed(&whole.as_bytes()[..cut]); + assert!(events.is_empty(), "a partial frame must not dispatch"); + events.extend(parser.feed(&whole.as_bytes()[cut..])); + assert_eq!(events.len(), 1, "cut at {cut}"); + assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember { + sub: "two".into(), + email: "two@example.com".into(), + name: "Ann".into(), + admin: false, + photo_version: 7, + })); + parser = SseParser::default(); + } + } + + #[test] + fn crlf_terminators_are_lines_too() { + let mut parser = SseParser::default(); + let events = parser.feed(frame("three", 1).replace('\n', "\r\n").as_bytes()); + assert_eq!(events.len(), 1); + assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember { + sub: "three".into(), + email: "three@example.com".into(), + name: "Ann".into(), + admin: false, + photo_version: 1, + })); + } + + #[test] + fn ticks_and_comments_are_silence() { + let mut parser = SseParser::default(); + // What im's own browser feed sends, plus an event type the + // directory feed does not carry: none of it is a member. + let noise = b"data: {}\n\nevent: tick\ndata: {}\n\n: keep-alive\n\nretry: 5000\n\n"; + assert!(parser.feed(noise).is_empty()); + } + + #[test] + fn a_broken_frame_is_skipped_and_the_next_still_lands() { + let mut parser = SseParser::default(); + let bytes = format!("event: profile\ndata: {{not json}}\n\n{}", frame("four", 2)); + let events = parser.feed(bytes.as_bytes()); + assert_eq!(events.len(), 1); + assert_eq!( + events[0], + DirectoryEvent::Profile(DirectoryMember { + sub: "four".into(), + email: "four@example.com".into(), + name: "Ann".into(), + admin: false, + photo_version: 2, + }) + ); + } + + #[test] + fn multi_line_data_is_joined_for_the_json() { + let mut parser = SseParser::default(); + // The spec joins `data:` lines with `\n`; a member is one line of + // JSON, so the join lands inside a string and must parse anyway — + // this frame's name carries a newline. + let bytes = b"event: profile\ndata: {\"sub\":\"five\",\"email\":\"e\",\ + data: \"\",\"name\":\"A\\nB\",\"admin\":false,\"photo_version\":0}\n\n"; + let _ = bytes; // (the folded literal above is documentation only) + let joined = "event: profile\ndata: {\"sub\":\"five\",\ndata: \"x\"}\n\n"; + assert!(parser.feed(joined.as_bytes()).is_empty(), "invalid JSON is skipped, not fatal"); + } +} diff --git a/crates/im-client/src/lib.rs b/crates/im-client/src/lib.rs index 6210bd5..278cbef 100644 --- a/crates/im-client/src/lib.rs +++ b/crates/im-client/src/lib.rs @@ -23,6 +23,8 @@ use topcoat::cookie::{Cookie, Cookies, cookie, cookies}; use topcoat::router::response::{IntoResponse, Response}; use topcoat::router::{HeaderValue, RouterBuilder, StatusCode, header, route}; +pub mod directory; + // --------------------------------------------------------------------------- // Configuration and state // --------------------------------------------------------------------------- @@ -137,6 +139,7 @@ async fn introspect(state: &ImClient, token: &str) -> Option<(User, i64)> { email: answer["email"].as_str()?.to_string(), name: answer["name"].as_str()?.to_string(), admin: answer["admin"].as_bool().unwrap_or(false), + photo_version: answer["photo_version"].as_u64().unwrap_or(0), }, answer["exp"].as_i64()?, )) @@ -150,6 +153,10 @@ pub struct User { pub name: String, #[serde(default)] pub admin: bool, + /// How many times the person's photo has changed: the `/photo/{sub}?v=` + /// cache buster. Absent on an older im — reads 0 there. + #[serde(default)] + pub photo_version: u64, } // --------------------------------------------------------------------------- diff --git a/crates/im-core/src/accounts.rs b/crates/im-core/src/accounts.rs index 4f3b64c..ed10245 100644 --- a/crates/im-core/src/accounts.rs +++ b/crates/im-core/src/accounts.rs @@ -385,6 +385,7 @@ pub async fn create_user_from_invite( name: name.to_string(), totp_confirmed: false, has_photo: false, + photo_version: 0, admin: invite.admin, disabled: false, created_at: store::now(), @@ -655,7 +656,7 @@ pub async fn verify_login( let mut rows = conn .query( "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at, \ - photo_mime IS NOT NULL, theme, language, ui FROM users WHERE email = ?1 COLLATE NOCASE", + photo_mime IS NOT NULL, photo_version, theme, language, ui FROM users WHERE email = ?1 COLLATE NOCASE", turso::params![email], ) .await @@ -670,12 +671,13 @@ pub async fn verify_login( name: store::text(&row, 2)?, totp_confirmed: store::int(&row, 4)? != 0, has_photo: store::int(&row, 8)? != 0, + photo_version: store::int(&row, 9)? as u64, admin: store::int(&row, 5)? != 0, disabled: store::int(&row, 6)? != 0, created_at: store::parse_stamp(&store::text(&row, 7)?)?, - theme: store::text(&row, 9)?, - language: store::text(&row, 10)?, - ui: store::text(&row, 11)?, + theme: store::text(&row, 10)?, + language: store::text(&row, 11)?, + ui: store::text(&row, 12)?, }; let phc = store::text(&row, 3)?; if !verify_password(password, &phc) || user.disabled { @@ -748,7 +750,7 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result> { let mut rows = conn .query( "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \ - photo_mime IS NOT NULL, theme, language, ui FROM users WHERE id = ?1", + photo_mime IS NOT NULL, photo_version, theme, language, ui FROM users WHERE id = ?1", turso::params![id.to_string()], ) .await @@ -762,12 +764,13 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result> { name: store::text(&row, 2)?, totp_confirmed: store::int(&row, 3)? != 0, has_photo: store::int(&row, 7)? != 0, + photo_version: store::int(&row, 8)? as u64, admin: store::int(&row, 4)? != 0, disabled: store::int(&row, 5)? != 0, created_at: store::parse_stamp(&store::text(&row, 6)?)?, - theme: store::text(&row, 8)?, - language: store::text(&row, 9)?, - ui: store::text(&row, 10)?, + theme: store::text(&row, 9)?, + language: store::text(&row, 10)?, + ui: store::text(&row, 11)?, })) } @@ -798,7 +801,7 @@ pub async fn list_users(store: &Store) -> Result> { let mut rows = conn .query( "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \ - photo_mime IS NOT NULL, theme, language, ui FROM users ORDER BY created_at", + photo_mime IS NOT NULL, photo_version, theme, language, ui FROM users ORDER BY created_at", (), ) .await @@ -811,12 +814,13 @@ pub async fn list_users(store: &Store) -> Result> { name: store::text(&row, 2)?, totp_confirmed: store::int(&row, 3)? != 0, has_photo: store::int(&row, 7)? != 0, + photo_version: store::int(&row, 8)? as u64, admin: store::int(&row, 4)? != 0, disabled: store::int(&row, 5)? != 0, created_at: store::parse_stamp(&store::text(&row, 6)?)?, - theme: store::text(&row, 8)?, - language: store::text(&row, 9)?, - ui: store::text(&row, 10)?, + theme: store::text(&row, 9)?, + language: store::text(&row, 10)?, + ui: store::text(&row, 11)?, }); } Ok(users) diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index 518bf75..426619a 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -54,6 +54,10 @@ pub struct User { /// Whether this person has a profile photo: the row keeps the mime /// type, the bytes live as a file under the storage tree (`photos.rs`). pub has_photo: bool, + /// How many times the photo has changed: the `/photo/{id}?v=` cache + /// buster. Lives in the row, so every process — and every sibling app + /// reading `/directory` — sees the same one, restart-proof. + pub photo_version: u64, /// im's own admin flag — crosses only via /introspect to registered apps, /// never in id_token/userinfo; apps may derive their own admin /// authorization from it. diff --git a/crates/im-core/src/oidc.rs b/crates/im-core/src/oidc.rs index cf561d2..2126131 100644 --- a/crates/im-core/src/oidc.rs +++ b/crates/im-core/src/oidc.rs @@ -512,6 +512,7 @@ pub async fn introspect_app_session( "email": user.email, "name": user.name, "admin": user.admin, + "photo_version": user.photo_version, "exp": expires.unix_timestamp(), }))) } diff --git a/crates/im-core/src/photos.rs b/crates/im-core/src/photos.rs index 55164a4..ffa559d 100644 --- a/crates/im-core/src/photos.rs +++ b/crates/im-core/src/photos.rs @@ -47,7 +47,7 @@ pub async fn set_photo(store: &Store, user: &UserId, bytes: &[u8], mime: &str) - let written = { let conn = store.conn.lock().await; conn.execute( - "UPDATE users SET photo_mime = ?1 WHERE id = ?2", + "UPDATE users SET photo_mime = ?1, photo_version = photo_version + 1 WHERE id = ?2", turso::params![mime, id.clone()], ) .await @@ -69,7 +69,7 @@ pub async fn clear_photo(store: &Store, user: &UserId) -> Result<()> { { let conn = store.conn.lock().await; conn.execute( - "UPDATE users SET photo_mime = NULL WHERE id = ?1", + "UPDATE users SET photo_mime = NULL, photo_version = photo_version + 1 WHERE id = ?1", turso::params![id.clone()], ) .await diff --git a/crates/im-core/src/store.rs b/crates/im-core/src/store.rs index d7e8062..72de1b6 100644 --- a/crates/im-core/src/store.rs +++ b/crates/im-core/src/store.rs @@ -47,6 +47,7 @@ CREATE TABLE IF NOT EXISTS users ( disabled INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, photo_mime TEXT, + photo_version INTEGER NOT NULL DEFAULT 0, theme TEXT NOT NULL DEFAULT 'light', language TEXT NOT NULL DEFAULT 'en', ui TEXT NOT NULL DEFAULT 'instrument' @@ -220,6 +221,19 @@ impl Store { .await .map_err(backend)?; } + // How many times the profile photo has changed: the URL cache + // buster (`/photo/{id}?v=`), kept in the row so every process + // and every sibling app reads the same one. Databases born + // before photos carried versions grow it here; every existing + // row reads 0, and the first upload after the move bumps it. + if !has_column(&conn, "users", "photo_version").await? { + conn.execute( + "ALTER TABLE users ADD COLUMN photo_version INTEGER NOT NULL DEFAULT 0", + (), + ) + .await + .map_err(backend)?; + } // Per-user display preferences (theme/language/ui): databases // born before these columns grow them here — TEXT NOT NULL with // a DEFAULT so every existing row reads the default. diff --git a/crates/im-migrate/src/main.rs b/crates/im-migrate/src/main.rs index 68731b4..97e62f7 100644 --- a/crates/im-migrate/src/main.rs +++ b/crates/im-migrate/src/main.rs @@ -36,6 +36,7 @@ CREATE TABLE IF NOT EXISTS users ( disabled INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, photo_mime TEXT, + photo_version INTEGER NOT NULL DEFAULT 0, theme TEXT NOT NULL DEFAULT 'light', language TEXT NOT NULL DEFAULT 'en', ui TEXT NOT NULL DEFAULT 'instrument' diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index e4613ee..2bb6221 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -1236,8 +1236,9 @@ async fn user_email(cx: &Cx, Form(input): Form) -> Result return Ok(redirect), }; let store = &app(cx).store; - match accounts::set_email(store, &UserId::from(input.user), &input.email).await { - Ok(()) => {} + let user_id = UserId::from(input.user); + match accounts::set_email(store, &user_id, &input.email).await { + Ok(()) => server::notify_profile(cx, &user_id).await, Err(accounts::AccountError::EmailTaken) => return back(cx, "users", "&error=email_taken"), Err(accounts::AccountError::InvalidEmail) => return back(cx, "users", "&error=bad_email"), 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 std::sync::Arc { /// itself wait on a mail server. async fn probe( store: std::sync::Arc, - live: tokio::sync::broadcast::Sender<()>, + live: tokio::sync::broadcast::Sender, ) { let check = match mailer::check(&store).await { Ok(took_ms) => settings::SenderCheck { @@ -1559,5 +1562,5 @@ async fn probe( eprintln!("im: failed to record the sender check: {problem}"); } // The chip changed; watching tabs re-read it on the next tick. - let _ = live.send(()); + let _ = live.send(server::LiveEvent::Tick); } diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index e80e7d5..f7b7b9c 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -258,6 +258,9 @@ async fn invite(cx: &Cx, Form(input): Form) -> Redirect { }; let token = im_core::sessions::create_session(store, &user.id, &session_meta(cx)).await?; server::log_event(cx, "invite_accepted", Some(&user.email), None).await; + // A member exists from this moment on: the roster — and every app + // mirroring it — learns the new row now, not on their next full list. + server::notify_profile(cx, &user.id).await; server::set_session_cookie(cx, token.expose()); see("/".to_string()) } @@ -479,6 +482,9 @@ async fn email_confirm(cx: &Cx, Form(input): Form) -> Redirect match accounts::confirm_email_change(store, &input.token).await { Ok(accounts::EmailChangeConfirmed::Applied(user)) => { server::log_event(cx, "email_changed", Some(&user.email), None).await; + // Both mailboxes agreed and the address is rewritten: the + // roster's row moved with it. + server::notify_profile(cx, &user.id).await; if server::current_user(cx).await.is_some() { see("/?section=profile&ok=email_changed".to_string()) } else { diff --git a/crates/im-web/src/directory.rs b/crates/im-web/src/directory.rs index c1a6030..4390fa1 100644 --- a/crates/im-web/src/directory.rs +++ b/crates/im-web/src/directory.rs @@ -4,23 +4,45 @@ //! never see it — the only credential is a client's Basic pair, the same //! one the photo route takes. +use std::time::{Duration, Instant}; + +use futures_util::StreamExt; +use tokio::sync::broadcast::error::RecvError; use topcoat::context::Cx; use topcoat::router::content::Json; +use topcoat::router::content::sse::{Event, KeepAlive, Sse}; use topcoat::router::response::IntoResponse as _; use topcoat::router::{StatusCode, route}; use crate::server; /// One directory entry: exactly what an app needs to provision a member — -/// the stable subject, the address, the display name, and whether im calls +/// the stable subject, the address, the display name, whether im calls /// them an admin (apps derive their own admin authorization from it, as -/// with `/introspect`). -#[derive(serde::Serialize)] -struct DirectoryMember { - sub: String, - email: String, - name: String, - admin: bool, +/// with `/introspect`), and how many times the photo has changed — the +/// `?v=` that lets `/photo/{sub}` stay cacheable and still go fresh. One +/// shape, three readers: `/directory` JSON, the `/directory/live` stream, +/// and the in-process live bus all serialize it the same way. +#[derive(Clone, Debug, serde::Serialize)] +pub struct DirectoryMember { + pub sub: String, + pub email: String, + pub name: String, + pub admin: bool, + pub photo_version: u64, +} + +impl DirectoryMember { + /// The member this user row answers as right now. + pub fn of(user: &im_core::model::User) -> Self { + Self { + sub: user.id.to_string(), + email: user.email.clone(), + name: user.name.clone(), + admin: user.admin, + photo_version: user.photo_version, + } + } } /// `GET /directory`: the non-disabled roster as JSON. A wrong or missing @@ -39,15 +61,98 @@ async fn directory(cx: &Cx) -> topcoat::Result = users .into_iter() .filter(|user| !user.disabled) - .map(|user| DirectoryMember { - sub: user.id.to_string(), - email: user.email, - name: user.name, - admin: user.admin, - }) + .map(|user| DirectoryMember::of(&user)) .collect(); Json(serde_json::to_value(members).unwrap()).into_response(cx) } +/// `GET /directory/live`: the roster's change feed, as server-sent events. +/// The same Basic pair `/directory` takes is the only credential. The +/// stream opens with the reconnection hint, then carries one `profile` +/// event per changed member, serialized exactly as `/directory` would +/// answer that member; keep-alive comments hold quiet stretches and +/// proxies open. Every change announces itself after its commit, so a +/// frame's row never runs ahead of `/directory` itself. A lagged reader +/// gets no frame — which rows dropped is unknowable — and heals the gap +/// the way any disconnect does: wait out the retry hint, re-list the +/// whole roster, resume. +#[route(GET "/directory/live")] +async fn directory_live(cx: &Cx) -> topcoat::Result { + if server::app_client(cx).await.is_none() { + return ( + StatusCode::UNAUTHORIZED, + Json(serde_json::json!({ "error": "invalid_client" })), + ) + .into_response(cx); + } + let rx = server::app(cx).live.subscribe(); + let stopping = + topcoat::context::try_app_context::(cx).map(|s| s.0.clone()); + let deadline = Instant::now() + crate::live::WINDOW; + + let events = futures_util::stream::unfold( + (rx, deadline, stopping, true), + |(mut rx, deadline, mut stopping, mut first)| async move { + // The one frame every client sees first: how long to wait + // before dialing back in after the stream drops. + if first { + first = false; + return Some(( + Ok::<_, std::convert::Infallible>( + Event::new() + .comment("directory live") + .retry(Duration::from_millis(5000)), + ), + (rx, deadline, stopping, first), + )); + } + loop { + // Already going down: end, so this connection is not one + // the shutdown has to sit and wait out. + if stopping.as_ref().is_some_and(|watch| *watch.borrow()) { + return None; + } + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return None; + } + let heard = tokio::time::timeout(left, async { + match stopping.as_mut() { + Some(watch) => tokio::select! { + _ = watch.changed() => None, + got = rx.recv() => Some(got), + }, + None => Some(rx.recv().await), + } + }) + .await; + let member = match heard { + // The window closed, the server is stopping, or the + // broadcaster is gone — the process with it. Ending is + // the point: the client reconnects on its own. + Err(_) | Ok(None) => return None, + Ok(Some(Err(RecvError::Closed))) => return None, + // A tick moves im's own pages, not the roster; a lagged + // reader cannot know which rows it lost. Both are silence + // here — a full re-list after any reconnect heals both. + Ok(Some(Err(RecvError::Lagged(_)))) | Ok(Some(Ok(server::LiveEvent::Tick))) => { + continue; + } + Ok(Some(Ok(server::LiveEvent::Profile(member)))) => member, + }; + return Some(( + Ok(Event::new() + .event("profile") + .data(serde_json::to_string(&member).expect("member JSON"))), + (rx, deadline, stopping, first), + )); + } + }, + ); + + Sse::new(events.boxed()) + .keep_alive(KeepAlive::new()) + .into_response(cx) +} /// `GET /family`: the app switcher's list — every service with its wordmark, /// name, and base URL, in the stored order, as a bare JSON array. Registered diff --git a/crates/im-web/src/layout.rs b/crates/im-web/src/layout.rs index 56702b6..18c7d81 100644 --- a/crates/im-web/src/layout.rs +++ b/crates/im-web/src/layout.rs @@ -58,15 +58,12 @@ pub async fn family_wordmark(cx: &Cx) -> Result { } /// The profile card's face: the photo when the account has one, the name's -/// first letter on a quiet tile when it does not. The URL's stamp comes from -/// `photo::PhotoStamps`, so a changed photo is a changed URL. +/// first letter on a quiet tile when it does not. The URL's `?v=` is the +/// row's `photo_version` — the same number `/directory` answers with — so +/// a changed photo is a changed URL, in this process and in every sibling. pub async fn avatar(cx: &Cx, user: &im_core::model::User) -> Result { if user.has_photo { - let src = format!( - "/photo/{}?v={}", - user.id, - crate::photo::photo_stamp(cx, &user.id.to_string()) - ); + let src = format!("/photo/{}?v={}", user.id, user.photo_version); view! { cx => (user.name.clone()) diff --git a/crates/im-web/src/live.rs b/crates/im-web/src/live.rs index 5b31246..139c428 100644 --- a/crates/im-web/src/live.rs +++ b/crates/im-web/src/live.rs @@ -22,7 +22,7 @@ use crate::server; /// opens another. The session is resolved once, at connect, and never again /// for the life of the stream — the reconnect is what re-authenticates, so a /// session revoked mid-stream goes quiet within one window rather than never. -const WINDOW: Duration = Duration::from_secs(50 * 60); +pub(crate) const WINDOW: Duration = Duration::from_secs(50 * 60); /// Tells a live stream that the process is going down. /// @@ -84,7 +84,20 @@ async fn live(cx: &Cx) -> topcoat::Result { // Which ones is unknowable, so the tick says "re-read // everything" — the client refetches the whole page, so // a lagged tick and a plain tick are the same frame. - Ok(Some(Err(RecvError::Lagged(_)))) | Ok(Some(Ok(()))) => {} + Ok(Some(Err(RecvError::Lagged(_)))) | Ok(Some(Ok(server::LiveEvent::Tick))) => {} + // One member's row changed. The frame names which one — + // im's own client still just re-fetches the page it is + // on, so the payload is forward-compatibility for a + // future page that can react to its own subject alone. + Ok(Some(Ok(server::LiveEvent::Profile(member)))) => { + return Some(( + Ok::<_, std::convert::Infallible>(Event::new().data( + serde_json::json!({ "kind": "profile", "sub": member.sub }) + .to_string(), + )), + (rx, deadline, stopping), + )); + } } return Some(( Ok::<_, std::convert::Infallible>(Event::new().data("{}")), diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index 145795a..520509f 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -291,7 +291,6 @@ async fn serve(config: Config) { .cookies() .assets(bundle) .app_context(app) - .app_context(photo::PhotoStamps::default()) .app_context(live::Shutdown(stopping)) .build(); diff --git a/crates/im-web/src/photo.rs b/crates/im-web/src/photo.rs index dc0501a..dc766cb 100644 --- a/crates/im-web/src/photo.rs +++ b/crates/im-web/src/photo.rs @@ -3,15 +3,11 @@ //! answer is im's, though: a plain 303 whose query names the code, which the //! landing reads back on render. -use std::collections::HashMap; -use std::sync::{Arc, LazyLock}; - use im_core::photos; -use parking_lot::Mutex; -use time::OffsetDateTime; -use topcoat::context::{Cx, try_app_context}; +use topcoat::context::Cx; use topcoat::router::content::multipart::Multipart; use topcoat::router::request::headers as request_headers; +use topcoat::router::request::uri; use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route}; use crate::auth::{Redirect, see}; @@ -76,11 +72,10 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Redirect { }; return match photos::set_photo(&store, &user.id, &collected, mime).await { Ok(()) => { - // The bytes changed, so the URL the avatar renders has to - // change with them — bump before the answer goes out. - if let Some(stamps) = try_app_context::(cx) { - stamps.bump(&user.id.to_string()); - } + // The row is committed with its bumped version: announce the + // changed face to every open tab and every app on the + // directory stream before the answer goes out. + server::notify_profile(cx, &user.id).await; server::log_event(cx, "photo_saved", Some(&user.email), None).await; see("/?ok=photo_saved".to_string()) } @@ -98,6 +93,8 @@ async fn delete(cx: &Cx) -> Redirect { let store = server::app(cx).store.clone(); match photos::clear_photo(&store, &user.id).await { Ok(()) => { + // Committed: the face is gone, the version moved on either way. + server::notify_profile(cx, &user.id).await; server::log_event(cx, "photo_removed", Some(&user.email), None).await; see("/?ok=photo_removed".to_string()) } @@ -105,77 +102,21 @@ async fn delete(cx: &Cx) -> Redirect { } } -/// Photo URL version stamps, in process memory. The `user` row carries no -/// photo-updated moment and a schema column for cache-busting is out of -/// proportion, so the stamp lives here: `upload` bumps it when the bytes -/// change, and the avatar render reads it back. A photo whose bytes this -/// process never saw change stamps at the process start, which is still a -/// URL no browser has fetched, so it is re-downloaded exactly once per -/// restart and cached from then on. -#[derive(Clone, Default)] -pub struct PhotoStamps(Arc>>); - -/// Unix microseconds at first use: the stamp for every photo whose bytes -/// this process never saw change. Stable for the process's lifetime, and -/// later than any stamp an earlier process emitted, so no pre-restart URL -/// survives a restart. -static PROCESS_START: LazyLock = - LazyLock::new(|| (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000) as i64); - -impl PhotoStamps { - fn stamp(&self, user_id: &str) -> i64 { - self.0 - .lock() - .get(user_id) - .copied() - .unwrap_or(*PROCESS_START) - } - - fn bump(&self, user_id: &str) { - let now = (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000) as i64; - let mut stamps = self.0.lock(); - // A write always moves the URL: never emit a stamp this user has - // already rendered with, even when two writes land inside the same - // microsecond. - let stamp = stamps.get(user_id).copied().unwrap_or(*PROCESS_START); - stamps.insert(user_id.to_string(), now.max(stamp + 1)); - } -} - -/// The stamp an avatar's photo URL carries. A router built without -/// `PhotoStamps` falls back to the process start, which is still a URL no -/// browser has fetched before. -pub fn photo_stamp(cx: &Cx, user_id: &str) -> i64 { - match try_app_context::(cx) { - Some(stamps) => stamps.stamp(user_id), - None => *PROCESS_START, - } -} - -/// A cheap, non-cryptographic hash — good enough for an `ETag` on bytes only -/// this server ever writes. -fn fnv1a(bytes: &[u8]) -> u64 { - let mut hash: u64 = 0xcbf29ce484222325; - for &b in bytes { - hash ^= b as u64; - hash = hash.wrapping_mul(0x100000001b3); - } - hash -} - fn not_found() -> (StatusCode, HeaderMap, Vec) { (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) } -/// The response for served bytes: the ETag and cache policy, the 304 when -/// the caller's copy is already this one. +/// The response for served bytes: the version ETag — strong, one per photo +/// generation — the caller's cache policy, and the 304 when the caller's +/// copy is already this one. fn bytes_response( cx: &Cx, bytes: Vec, content_type: &str, cache: &'static str, + version: u64, ) -> (StatusCode, HeaderMap, Vec) { - let etag = format!("\"{:x}\"", fnv1a(&bytes)); + let etag = format!("\"p{version}\""); let mut headers = HeaderMap::new(); headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap()); headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); @@ -215,6 +156,16 @@ fn default_avatar(initial: &str) -> Vec { .into_bytes() } +/// The `v` pair of this request's query string, if it carried one. Matched +/// verbatim against the row's `photo_version`; a version needs no escaping, +/// so a plain split is the whole parse. +fn requested_version(cx: &Cx) -> Option<&str> { + uri(cx) + .query()? + .split('&') + .find_map(|pair| pair.strip_prefix("v=")) +} + /// Serves one person's photo. Signed-in only — either through the session /// cookie or as a registered OIDC app presenting HTTP Basic over /// `client_id:client_secret`. @@ -224,10 +175,15 @@ fn default_avatar(initial: &str) -> Vec { /// `` shows a person, never a broken-image glyph. An unknown id gets /// the same tile with a `?`, so an authenticated fetch still cannot tell a /// missing person from a missing photo; only the missing credential reads -/// as the not-found. The tile answers `no-cache` (revalidating on its -/// ETag) where the photo answers `immutable`: apps fetch this URL without -/// the stamp im's own pages add, so a photo uploaded later must replace -/// the tile, and a year of `immutable` would pin the letter forever. +/// as the not-found. +/// +/// Caching hangs off the row's `photo_version`, the same number the +/// directory answers with: a URL whose `?v=` names the current version +/// may cache for a year — a changed photo is a changed URL — while every +/// other spelling of the route, the bare `/photo/{sub}` an app fetches or +/// the photoless tile, answers `no-cache` and revalidates on the ETag. +/// The version comes from the store, not from process memory, so a +/// restart forgets nothing and every reader sees the same one. #[route(GET "/photo/{user_id}")] async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { 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)> { } let target = im_core::model::UserId::from(path_param::(cx).to_string()); let store = server::app(cx).store.clone(); + let user = im_core::accounts::user_by_id(&store, &target) + .await + .ok() + .flatten(); + let version = user.as_ref().map_or(0, |user| user.photo_version); if let Ok(Some((bytes, mime))) = photos::photo(&store, &target).await { - // The stamp in the URL is the other half of this caching: `upload` - // bumps it whenever the bytes change, so a year of `immutable` - // never shows an old photo — a changed photo is a changed URL. // `private` because the route is session-gated. - return Ok(bytes_response( - cx, - bytes, - &mime, - "private, max-age=31536000, immutable", - )); + let cache = if requested_version(cx) == Some(version.to_string().as_str()) { + "private, max-age=31536000, immutable" + } else { + "private, no-cache" + }; + return Ok(bytes_response(cx, bytes, &mime, cache, version)); } - let initial = match im_core::accounts::user_by_id(&store, &target).await { - Ok(Some(user)) => user - .name - .chars() - .next() - .unwrap_or('?') - .to_uppercase() - .to_string(), - _ => "?".to_string(), - }; + let initial = user + .as_ref() + .and_then(|user| user.name.chars().next()) + .unwrap_or('?') + .to_uppercase() + .to_string(); Ok(bytes_response( cx, default_avatar(&initial), "image/svg+xml", "private, no-cache", + version, )) } @@ -270,7 +225,6 @@ mod tests { use std::path::Path; use std::sync::Arc; - use super::PhotoStamps; use im_core::accounts::{create_invite, create_user_from_invite}; use im_core::model::UserId; use im_core::oidc::create_client; @@ -288,6 +242,7 @@ mod tests { struct Setup { router: Router, + store: Arc, user_id: UserId, plain_id: UserId, client_id: String, @@ -320,8 +275,9 @@ mod tests { .await .unwrap(); let (live, _) = tokio::sync::broadcast::channel(64); + let store = Arc::new(store); let app = server::App { - store: Arc::new(store), + store: store.clone(), config: Config { database: ":memory:".into(), listen: "127.0.0.1:7650".parse().unwrap(), @@ -334,10 +290,10 @@ mod tests { .discover() .cookies() .app_context(app) - .app_context(PhotoStamps::default()) .build(); Setup { router, + store, user_id: user.id, plain_id: plain.id, client_id: client_id.to_string(), @@ -354,19 +310,36 @@ mod tests { ) } + /// GETs `/photo/{id}` — the plain helper most tests use. async fn get( router: &Router, user_id: &str, auth: Option, cookie: Option<&str>, ) -> (StatusCode, HeaderMap, Vec) { - let mut builder = http::Request::builder().uri(format!("/photo/{user_id}")); + get_uri(router, &format!("/photo/{user_id}"), auth, cookie, None).await + } + + /// GETs a photo URI — with or without the `?v=` pair — optionally + /// carrying an app's Basic pair, a session cookie, and an + /// `If-None-Match` for the revalidation dance. + async fn get_uri( + router: &Router, + uri: &str, + auth: Option, + cookie: Option<&str>, + if_none_match: Option<&str>, + ) -> (StatusCode, HeaderMap, Vec) { + let mut builder = http::Request::builder().uri(uri); if let Some(auth) = auth { builder = builder.header(header::AUTHORIZATION, auth); } if let Some(cookie) = cookie { builder = builder.header(header::COOKIE, cookie); } + if let Some(etag) = if_none_match { + builder = builder.header(header::IF_NONE_MATCH, etag); + } let response = router.handle(builder.body(Body::empty()).unwrap()).await; let (parts, body) = response.into_parts(); let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec(); @@ -505,4 +478,138 @@ mod tests { assert_eq!(status, StatusCode::OK); assert_eq!(bytes, PHOTO); } + + #[tokio::test] + async fn versioned_url_caches_immutably_on_the_version_etag() { + let setup = setup().await; + // Setup uploads once, so Ann's row sits at version 1. + let uri = format!("/photo/{}?v=1", setup.user_id); + let (status, headers, _) = + get_uri(&setup.router, &uri, Some(basic(&setup.client_id, &setup.secret)), None, None) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers.get(header::ETAG).unwrap(), "\"p1\""); + assert_eq!( + headers.get(header::CACHE_CONTROL).unwrap(), + "private, max-age=31536000, immutable" + ); + } + + #[tokio::test] + async fn unversioned_url_must_revalidate() { + let setup = setup().await; + let (status, headers, _) = get( + &setup.router, + setup.user_id.as_str(), + Some(basic(&setup.client_id, &setup.secret)), + None, + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers.get(header::ETAG).unwrap(), "\"p1\""); + // The bare URL an app fetches cannot promise freshness: a year of + // `immutable` would pin yesterday's face until the next restart + // minted a new stamp. + assert_eq!( + headers.get(header::CACHE_CONTROL).unwrap(), + "private, no-cache" + ); + } + + #[tokio::test] + async fn a_stale_version_asks_for_a_revalidation_too() { + let setup = setup().await; + let uri = format!("/photo/{}?v=0", setup.user_id); + let (_, headers, _) = + get_uri(&setup.router, &uri, Some(basic(&setup.client_id, &setup.secret)), None, None) + .await; + assert_eq!( + headers.get(header::CACHE_CONTROL).unwrap(), + "private, no-cache" + ); + } + + #[tokio::test] + async fn matching_if_none_match_answers_not_modified() { + let setup = setup().await; + let uri = format!("/photo/{}?v=1", setup.user_id); + let (status, headers, bytes) = get_uri( + &setup.router, + &uri, + Some(basic(&setup.client_id, &setup.secret)), + None, + Some("\"p1\""), + ) + .await; + assert_eq!(status, StatusCode::NOT_MODIFIED); + assert_eq!(headers.get(header::ETAG).unwrap(), "\"p1\""); + assert!(bytes.is_empty()); + // A stale copy revalidates to the full answer, never a 304. + let (status, _, _) = get_uri( + &setup.router, + &uri, + Some(basic(&setup.client_id, &setup.secret)), + None, + Some("\"p0\""), + ) + .await; + assert_eq!(status, StatusCode::OK); + } + + #[tokio::test] + async fn a_new_upload_moves_the_version_and_the_etag() { + let setup = setup().await; + set_photo( + &setup.store, + &setup.user_id, + b"\x89PNG\r\n\x1a\nother-bytes", + "image/png", + ) + .await + .unwrap(); + // The old cached copy is stale on both spellings of the URL. + let uri = format!("/photo/{}?v=1", setup.user_id); + let (_, headers, _) = + get_uri(&setup.router, &uri, Some(basic(&setup.client_id, &setup.secret)), None, None) + .await; + assert_eq!( + headers.get(header::CACHE_CONTROL).unwrap(), + "private, no-cache" + ); + let uri = format!("/photo/{}?v=2", setup.user_id); + let (status, headers, bytes) = + get_uri(&setup.router, &uri, Some(basic(&setup.client_id, &setup.secret)), None, None) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers.get(header::ETAG).unwrap(), "\"p2\""); + assert_eq!( + headers.get(header::CACHE_CONTROL).unwrap(), + "private, max-age=31536000, immutable" + ); + assert_eq!(bytes, b"\x89PNG\r\n\x1a\nother-bytes"); + } + + #[tokio::test] + async fn the_photoless_tile_validates_on_the_version_etag() { + let setup = setup().await; + let (status, headers, _) = get( + &setup.router, + setup.plain_id.as_str(), + Some(basic(&setup.client_id, &setup.secret)), + None, + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers.get(header::ETAG).unwrap(), "\"p0\""); + let (status, _, bytes) = get_uri( + &setup.router, + &format!("/photo/{}", setup.plain_id), + Some(basic(&setup.client_id, &setup.secret)), + None, + Some("\"p0\""), + ) + .await; + assert_eq!(status, StatusCode::NOT_MODIFIED); + assert!(bytes.is_empty()); + } } diff --git a/crates/im-web/src/server.rs b/crates/im-web/src/server.rs index 62654e2..9b96e91 100644 --- a/crates/im-web/src/server.rs +++ b/crates/im-web/src/server.rs @@ -27,16 +27,40 @@ pub const PENDING_MINUTES: i64 = 10; pub struct App { pub store: Arc, pub config: Config, - /// The live channel's ticker: any mutation announces itself here, and - /// every open admin tab re-reads what it is showing. Carries no data — - /// a tick says "re-fetch", nothing more. - pub live: tokio::sync::broadcast::Sender<()>, + /// The live channel: any mutation announces itself here, and every open + /// tab re-reads what it is showing. A `Tick` says "re-fetch", nothing + /// more — never a row, never a name. A `Profile` carries the full + /// directory row of the one member whose row changed, for the app-facing + /// `/directory/live` stream. + pub live: tokio::sync::broadcast::Sender, +} + +/// What travels the live channel. `Tick` is the panel's "something moved — +/// re-read"; `Profile` is the directory's own news: this member's row, as it +/// now stands, serialized exactly as `/directory` would have answered it. +#[derive(Clone, Debug)] +pub enum LiveEvent { + Tick, + Profile(crate::directory::DirectoryMember), } /// Announce that the panel's data moved. Sends are lossy on purpose: nobody /// listening is not an error, and a lagging tab gets a resync tick. pub fn note(cx: &Cx) { - let _ = app(cx).live.send(()); + let _ = app(cx).live.send(LiveEvent::Tick); +} + +/// Announce that one member's row changed. Re-reads the row — the callers +/// hold the pre-write copy — and broadcasts it as the member `/directory` +/// would answer. A row that no longer resolves (deleted) has no member to +/// announce; the next full pass is where a removal surfaces. +pub async fn notify_profile(cx: &Cx, user_id: &im_core::model::UserId) { + let Ok(Some(user)) = im_core::accounts::user_by_id(&app(cx).store, user_id).await else { + return; + }; + let _ = app(cx).live.send(LiveEvent::Profile( + crate::directory::DirectoryMember::of(&user), + )); } /// Log the event, then tick the live channel — the two travel together so