iz: live session-revocation logout
Browse files at this commitf4152e1951a04a198d6c73c815bbd6d4d2a4a069Parent: 66ac68610 changed files +779 -68
- crates/iz-core/src/live.rs +8 -0
- crates/iz-core/src/store/mod.rs +12 -0
- crates/iz-core/src/store/turso_store.rs +70 -49
- crates/iz-core/tests/store.rs +7 -3
- crates/iz-web/src/directory.rs +431 -2
- crates/iz-web/src/layout.rs +14 -0
- crates/iz-web/src/live.rs +29 -7
- crates/iz-web/src/main.rs +15 -6
- crates/iz-web/src/server.rs +18 -1
- crates/iz-web/tests/http.rs +175 -0
crates/iz-core/src/live.rsmodified+8 -0
| @@ -24,6 +24,12 @@ pub enum Topic { | |||
| 24 | Task(String), | 24 | Task(String), |
| 25 | /// Users, roles, invites, sessions, photos, profile. | 25 | /// Users, roles, invites, sessions, photos, profile. |
| 26 | Members, | 26 | Members, |
| 27 | + /// One account was killed at the provider — disabled, or gone. The id | ||
| 28 | + /// is the local row's, and the frame names it to exactly one reader: | ||
| 29 | + /// the connection whose own id it is. A session revocation does not | ||
| 30 | + /// ride here — which session died is the provider's knowledge, and a | ||
| 31 | + /// tab whose other session survived must not be sent away. | ||
| 32 | + Revoked(String), | ||
| 27 | /// The mail queue: `mail_send` rows. | 33 | /// The mail queue: `mail_send` rows. |
| 28 | Queue, | 34 | Queue, |
| 29 | /// Mail rules and the decisions they made. | 35 | /// Mail rules and the decisions they made. |
| @@ -45,6 +51,7 @@ impl Topic { | |||
| 45 | Topic::Board => "board", | 51 | Topic::Board => "board", |
| 46 | Topic::Task(_) => "task", | 52 | Topic::Task(_) => "task", |
| 47 | Topic::Members => "members", | 53 | Topic::Members => "members", |
| 54 | + Topic::Revoked(_) => "revoked", | ||
| 48 | Topic::Queue => "queue", | 55 | Topic::Queue => "queue", |
| 49 | Topic::Rules => "rules", | 56 | Topic::Rules => "rules", |
| 50 | Topic::Tags => "tags", | 57 | Topic::Tags => "tags", |
| @@ -57,6 +64,7 @@ impl Topic { | |||
| 57 | pub fn id(&self) -> Option<&str> { | 64 | pub fn id(&self) -> Option<&str> { |
| 58 | match self { | 65 | match self { |
| 59 | Topic::Task(id) => Some(id), | 66 | Topic::Task(id) => Some(id), |
| 67 | + Topic::Revoked(id) => Some(id), | ||
| 60 | _ => None, | 68 | _ => None, |
| 61 | } | 69 | } |
| 62 | } | 70 | } |
crates/iz-core/src/store/mod.rsmodified+12 -0
| @@ -756,6 +756,13 @@ pub trait Store: BoardReads + DetailReads + 'static { | |||
| 756 | /// role-gated route. Sending to zero subscribers is normal and silent, | 756 | /// role-gated route. Sending to zero subscribers is normal and silent, |
| 757 | /// and a slow subscriber's overflow is the client's cue to resync. | 757 | /// and a slow subscriber's overflow is the client's cue to resync. |
| 758 | fn subscribe(&self) -> tokio::sync::broadcast::Receiver<crate::live::Change>; | 758 | fn subscribe(&self) -> tokio::sync::broadcast::Receiver<crate::live::Change>; |
| 759 | + | ||
| 760 | + /// Announces topics with no write behind them — the door for facts that | ||
| 761 | + /// arrive from outside this database, such as a revoked session heard on | ||
| 762 | + /// im's directory stream. This only wakes the subscribers, exactly as a | ||
| 763 | + /// committed write would; which connection is told remains the live | ||
| 764 | + /// channel's own role decision. | ||
| 765 | + fn announce(&self, topics: &[crate::live::Topic]); | ||
| 759 | // -- workspace --------------------------------------------------------- | 766 | // -- workspace --------------------------------------------------------- |
| 760 | 767 | ||
| 761 | /// The account that claimed the workspace, if it has been claimed. | 768 | /// The account that claimed the workspace, if it has been claimed. |
| @@ -888,6 +895,11 @@ pub trait Store: BoardReads + DetailReads + 'static { | |||
| 888 | /// an address has an account. | 895 | /// an address has an account. |
| 889 | async fn user_by_email(&self, workspace_id: &str, email: &str) -> Result<Option<User>>; | 896 | async fn user_by_email(&self, workspace_id: &str, email: &str) -> Result<Option<User>>; |
| 890 | 897 | ||
| 898 | + /// Lookup by provider subject — the key im's directory stream names when | ||
| 899 | + /// it announces a revoked or disabled member. `None` is a subject this | ||
| 900 | + /// workspace has never provisioned. | ||
| 901 | + async fn user_by_sub(&self, sub: &str) -> Result<Option<User>>; | ||
| 902 | + | ||
| 891 | async fn users(&self, workspace_id: &str) -> Result<Vec<User>>; | 903 | async fn users(&self, workspace_id: &str) -> Result<Vec<User>>; |
| 892 | 904 | ||
| 893 | async fn count_users(&self, workspace_id: &str) -> Result<u64>; | 905 | async fn count_users(&self, workspace_id: &str) -> Result<u64>; |
crates/iz-core/src/store/turso_store.rsmodified+70 -49
| @@ -74,7 +74,7 @@ impl TursoStore { | |||
| 74 | /// of a server nobody is looking at. It is dropped on purpose: an | 74 | /// of a server nobody is looking at. It is dropped on purpose: an |
| 75 | /// announcement nobody is waiting for is not a problem, and logging it | 75 | /// announcement nobody is waiting for is not a problem, and logging it |
| 76 | /// would fill the log with the sound of an idle app. | 76 | /// would fill the log with the sound of an idle app. |
| 77 | - fn announce(&self, topics: impl IntoIterator<Item = Topic>) { | 77 | + fn publish(&self, topics: impl IntoIterator<Item = Topic>) { |
| 78 | for topic in topics { | 78 | for topic in topics { |
| 79 | let _ = self.live.send(Change { | 79 | let _ = self.live.send(Change { |
| 80 | topic, | 80 | topic, |
| @@ -1403,6 +1403,10 @@ impl Store for TursoStore { | |||
| 1403 | self.live.subscribe() | 1403 | self.live.subscribe() |
| 1404 | } | 1404 | } |
| 1405 | 1405 | ||
| 1406 | + fn announce(&self, topics: &[crate::live::Topic]) { | ||
| 1407 | + self.publish(topics.iter().cloned()) | ||
| 1408 | + } | ||
| 1409 | + | ||
| 1406 | async fn provision_user( | 1410 | async fn provision_user( |
| 1407 | &self, | 1411 | &self, |
| 1408 | sub: &str, | 1412 | sub: &str, |
| @@ -1592,7 +1596,7 @@ impl Store for TursoStore { | |||
| 1592 | // provider-side rename or role flip, an owner claim. Anything louder | 1596 | // provider-side rename or role flip, an owner claim. Anything louder |
| 1593 | // would re-render every members-watching tab on every request. | 1597 | // would re-render every members-watching tab on every request. |
| 1594 | if changed { | 1598 | if changed { |
| 1595 | - self.announce([Topic::Members]); | 1599 | + self.publish([Topic::Members]); |
| 1596 | } | 1600 | } |
| 1597 | self.user(&id).await?.ok_or(StoreError::NotFound) | 1601 | self.user(&id).await?.ok_or(StoreError::NotFound) |
| 1598 | } | 1602 | } |
| @@ -1752,7 +1756,7 @@ impl Store for TursoStore { | |||
| 1752 | tx.commit().await.map_err(backend)?; | 1756 | tx.commit().await.map_err(backend)?; |
| 1753 | drop(conn); | 1757 | drop(conn); |
| 1754 | if sync != MemberSync::Untouched { | 1758 | if sync != MemberSync::Untouched { |
| 1755 | - self.announce([Topic::Members]); | 1759 | + self.publish([Topic::Members]); |
| 1756 | } | 1760 | } |
| 1757 | Ok(sync) | 1761 | Ok(sync) |
| 1758 | } | 1762 | } |
| @@ -1820,7 +1824,7 @@ impl Store for TursoStore { | |||
| 1820 | Err(e) => return Err(backend(e)), | 1824 | Err(e) => return Err(backend(e)), |
| 1821 | } | 1825 | } |
| 1822 | drop(conn); | 1826 | drop(conn); |
| 1823 | - self.announce([Topic::Members]); | 1827 | + self.publish([Topic::Members]); |
| 1824 | self.user(&id).await?.ok_or(StoreError::NotFound) | 1828 | self.user(&id).await?.ok_or(StoreError::NotFound) |
| 1825 | } | 1829 | } |
| 1826 | 1830 | ||
| @@ -1879,7 +1883,7 @@ impl Store for TursoStore { | |||
| 1879 | .await | 1883 | .await |
| 1880 | .map_err(backend)?; | 1884 | .map_err(backend)?; |
| 1881 | drop(conn); | 1885 | drop(conn); |
| 1882 | - self.announce([Topic::Settings]); | 1886 | + self.publish([Topic::Settings]); |
| 1883 | Ok(()) | 1887 | Ok(()) |
| 1884 | } | 1888 | } |
| 1885 | 1889 | ||
| @@ -1898,7 +1902,7 @@ impl Store for TursoStore { | |||
| 1898 | .await | 1902 | .await |
| 1899 | .map_err(backend)?; | 1903 | .map_err(backend)?; |
| 1900 | drop(conn); | 1904 | drop(conn); |
| 1901 | - self.announce([Topic::Settings]); | 1905 | + self.publish([Topic::Settings]); |
| 1902 | Ok(()) | 1906 | Ok(()) |
| 1903 | } | 1907 | } |
| 1904 | 1908 | ||
| @@ -1917,7 +1921,7 @@ impl Store for TursoStore { | |||
| 1917 | .await | 1921 | .await |
| 1918 | .map_err(backend)?; | 1922 | .map_err(backend)?; |
| 1919 | drop(conn); | 1923 | drop(conn); |
| 1920 | - self.announce([Topic::Settings]); | 1924 | + self.publish([Topic::Settings]); |
| 1921 | Ok(()) | 1925 | Ok(()) |
| 1922 | } | 1926 | } |
| 1923 | 1927 | ||
| @@ -1951,7 +1955,7 @@ impl Store for TursoStore { | |||
| 1951 | .await | 1955 | .await |
| 1952 | .map_err(backend)?; | 1956 | .map_err(backend)?; |
| 1953 | drop(conn); | 1957 | drop(conn); |
| 1954 | - self.announce([Topic::Settings]); | 1958 | + self.publish([Topic::Settings]); |
| 1955 | Ok(()) | 1959 | Ok(()) |
| 1956 | } | 1960 | } |
| 1957 | 1961 | ||
| @@ -2003,7 +2007,7 @@ impl Store for TursoStore { | |||
| 2003 | .await | 2007 | .await |
| 2004 | .map_err(backend)?; | 2008 | .map_err(backend)?; |
| 2005 | drop(conn); | 2009 | drop(conn); |
| 2006 | - self.announce([Topic::Settings]); | 2010 | + self.publish([Topic::Settings]); |
| 2007 | Ok(()) | 2011 | Ok(()) |
| 2008 | } | 2012 | } |
| 2009 | 2013 | ||
| @@ -2026,6 +2030,14 @@ impl Store for TursoStore { | |||
| 2026 | } | 2030 | } |
| 2027 | } | 2031 | } |
| 2028 | 2032 | ||
| 2033 | + async fn user_by_sub(&self, sub: &str) -> Result<Option<User>> { | ||
| 2034 | + let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE oidc_sub = ?1"); | ||
| 2035 | + match self.one_row(&sql, params![sub]).await? { | ||
| 2036 | + Some(row) => Ok(Some(user_from(&row)?)), | ||
| 2037 | + None => Ok(None), | ||
| 2038 | + } | ||
| 2039 | + } | ||
| 2040 | + | ||
| 2029 | async fn users(&self, workspace_id: &str) -> Result<Vec<User>> { | 2041 | async fn users(&self, workspace_id: &str) -> Result<Vec<User>> { |
| 2030 | let conn = self.conn.lock().await; | 2042 | let conn = self.conn.lock().await; |
| 2031 | let sql = format!( | 2043 | let sql = format!( |
| @@ -2115,7 +2127,7 @@ impl Store for TursoStore { | |||
| 2115 | Err(StoreError::NotFound) | 2127 | Err(StoreError::NotFound) |
| 2116 | } else { | 2128 | } else { |
| 2117 | drop(conn); | 2129 | drop(conn); |
| 2118 | - self.announce([Topic::Members]); | 2130 | + self.publish([Topic::Members]); |
| 2119 | Ok(()) | 2131 | Ok(()) |
| 2120 | } | 2132 | } |
| 2121 | } | 2133 | } |
| @@ -2164,7 +2176,7 @@ impl Store for TursoStore { | |||
| 2164 | } | 2176 | } |
| 2165 | tx.commit().await.map_err(backend)?; | 2177 | tx.commit().await.map_err(backend)?; |
| 2166 | drop(conn); | 2178 | drop(conn); |
| 2167 | - self.announce(topics); | 2179 | + self.publish(topics); |
| 2168 | Ok(()) | 2180 | Ok(()) |
| 2169 | } | 2181 | } |
| 2170 | 2182 | ||
| @@ -2181,7 +2193,16 @@ impl Store for TursoStore { | |||
| 2181 | Err(StoreError::NotFound) | 2193 | Err(StoreError::NotFound) |
| 2182 | } else { | 2194 | } else { |
| 2183 | drop(conn); | 2195 | drop(conn); |
| 2184 | - self.announce([Topic::Members]); | 2196 | + // The member list moves either way. The kill naming is one |
| 2197 | + // directional: only a disable names the account's own open tabs | ||
| 2198 | + // so they can leave — an enable is a homecoming, and a frame | ||
| 2199 | + // saying "you were revoked" as the door reopens would send | ||
| 2200 | + // somebody away at the wrong moment. | ||
| 2201 | + if disabled { | ||
| 2202 | + self.publish([Topic::Members, Topic::Revoked(user_id.to_string())]); | ||
| 2203 | + } else { | ||
| 2204 | + self.publish([Topic::Members]); | ||
| 2205 | + } | ||
| 2185 | Ok(()) | 2206 | Ok(()) |
| 2186 | } | 2207 | } |
| 2187 | } | 2208 | } |
| @@ -2205,7 +2226,7 @@ impl Store for TursoStore { | |||
| 2205 | .await | 2226 | .await |
| 2206 | .map_err(backend)?; | 2227 | .map_err(backend)?; |
| 2207 | drop(conn); | 2228 | drop(conn); |
| 2208 | - self.announce([Topic::Board]); | 2229 | + self.publish([Topic::Board]); |
| 2209 | Ok(Column { | 2230 | Ok(Column { |
| 2210 | id, | 2231 | id, |
| 2211 | name: name.to_string(), | 2232 | name: name.to_string(), |
| @@ -2393,7 +2414,7 @@ impl Store for TursoStore { | |||
| 2393 | if reminded { | 2414 | if reminded { |
| 2394 | topics.push(Topic::Queue); | 2415 | topics.push(Topic::Queue); |
| 2395 | } | 2416 | } |
| 2396 | - self.announce(topics); | 2417 | + self.publish(topics); |
| 2397 | let (task_key, position) = written; | 2418 | let (task_key, position) = written; |
| 2398 | Ok(TaskCreated { | 2419 | Ok(TaskCreated { |
| 2399 | row: TaskRow { | 2420 | row: TaskRow { |
| @@ -2495,7 +2516,7 @@ impl Store for TursoStore { | |||
| 2495 | match outcome { | 2516 | match outcome { |
| 2496 | Ok(Ok(())) => { | 2517 | Ok(Ok(())) => { |
| 2497 | tx.commit().await.map_err(backend)?; | 2518 | tx.commit().await.map_err(backend)?; |
| 2498 | - self.announce([Topic::Board, Topic::Task(task_id.to_string())]); | 2519 | + self.publish([Topic::Board, Topic::Task(task_id.to_string())]); |
| 2499 | Ok(()) | 2520 | Ok(()) |
| 2500 | } | 2521 | } |
| 2501 | Ok(Err(refused)) => { | 2522 | Ok(Err(refused)) => { |
| @@ -2575,7 +2596,7 @@ impl Store for TursoStore { | |||
| 2575 | if reminded { | 2596 | if reminded { |
| 2576 | topics.push(Topic::Queue); | 2597 | topics.push(Topic::Queue); |
| 2577 | } | 2598 | } |
| 2578 | - self.announce(topics); | 2599 | + self.publish(topics); |
| 2579 | } | 2600 | } |
| 2580 | Ok(()) | 2601 | Ok(()) |
| 2581 | } | 2602 | } |
| @@ -2615,7 +2636,7 @@ impl Store for TursoStore { | |||
| 2615 | if reminded { | 2636 | if reminded { |
| 2616 | topics.push(Topic::Queue); | 2637 | topics.push(Topic::Queue); |
| 2617 | } | 2638 | } |
| 2618 | - self.announce(topics); | 2639 | + self.publish(topics); |
| 2619 | } | 2640 | } |
| 2620 | Ok(()) | 2641 | Ok(()) |
| 2621 | } | 2642 | } |
| @@ -2721,7 +2742,7 @@ impl Store for TursoStore { | |||
| 2721 | Ok(true) => { | 2742 | Ok(true) => { |
| 2722 | tx.commit().await.map_err(backend)?; | 2743 | tx.commit().await.map_err(backend)?; |
| 2723 | // An edge is visible from both endpoints and on the board. | 2744 | // An edge is visible from both endpoints and on the board. |
| 2724 | - self.announce([ | 2745 | + self.publish([ |
| 2725 | Topic::Board, | 2746 | Topic::Board, |
| 2726 | Topic::Task(blocked_task_id.to_string()), | 2747 | Topic::Task(blocked_task_id.to_string()), |
| 2727 | Topic::Task(blocking_task_id.to_string()), | 2748 | Topic::Task(blocking_task_id.to_string()), |
| @@ -2756,7 +2777,7 @@ impl Store for TursoStore { | |||
| 2756 | .map_err(backend)?; | 2777 | .map_err(backend)?; |
| 2757 | drop(conn); | 2778 | drop(conn); |
| 2758 | if n > 0 { | 2779 | if n > 0 { |
| 2759 | - self.announce([ | 2780 | + self.publish([ |
| 2760 | Topic::Board, | 2781 | Topic::Board, |
| 2761 | Topic::Task(blocked_task_id.to_string()), | 2782 | Topic::Task(blocked_task_id.to_string()), |
| 2762 | Topic::Task(blocking_task_id.to_string()), | 2783 | Topic::Task(blocking_task_id.to_string()), |
| @@ -2811,7 +2832,7 @@ impl Store for TursoStore { | |||
| 2811 | } | 2832 | } |
| 2812 | tx.commit().await.map_err(backend)?; | 2833 | tx.commit().await.map_err(backend)?; |
| 2813 | 2834 | ||
| 2814 | - self.announce([Topic::Task(task_id.to_string()), Topic::Activity]); | 2835 | + self.publish([Topic::Task(task_id.to_string()), Topic::Activity]); |
| 2815 | Ok(CommentWritten { | 2836 | Ok(CommentWritten { |
| 2816 | comment_id, | 2837 | comment_id, |
| 2817 | activity_id, | 2838 | activity_id, |
| @@ -2852,7 +2873,7 @@ impl Store for TursoStore { | |||
| 2852 | return Err(backend(e)); | 2873 | return Err(backend(e)); |
| 2853 | } | 2874 | } |
| 2854 | drop(conn); | 2875 | drop(conn); |
| 2855 | - self.announce([Topic::Task(new.task_id.to_string())]); | 2876 | + self.publish([Topic::Task(new.task_id.to_string())]); |
| 2856 | Ok(id) | 2877 | Ok(id) |
| 2857 | } | 2878 | } |
| 2858 | 2879 | ||
| @@ -2932,7 +2953,7 @@ impl Store for TursoStore { | |||
| 2932 | // the boot sweep collects. | 2953 | // the boot sweep collects. |
| 2933 | let _ = std::fs::remove_file(attachment_file(&self.storage, id)); | 2954 | let _ = std::fs::remove_file(attachment_file(&self.storage, id)); |
| 2934 | if let Some(task_id) = owner { | 2955 | if let Some(task_id) = owner { |
| 2935 | - self.announce([Topic::Task(task_id)]); | 2956 | + self.publish([Topic::Task(task_id)]); |
| 2936 | } | 2957 | } |
| 2937 | } | 2958 | } |
| 2938 | Ok(gone > 0) | 2959 | Ok(gone > 0) |
| @@ -2951,7 +2972,7 @@ impl Store for TursoStore { | |||
| 2951 | .await | 2972 | .await |
| 2952 | .map_err(backend)?; | 2973 | .map_err(backend)?; |
| 2953 | drop(conn); | 2974 | drop(conn); |
| 2954 | - self.announce([Topic::Settings]); | 2975 | + self.publish([Topic::Settings]); |
| 2955 | Ok(()) | 2976 | Ok(()) |
| 2956 | } | 2977 | } |
| 2957 | 2978 | ||
| @@ -2986,7 +3007,7 @@ impl Store for TursoStore { | |||
| 2986 | .await | 3007 | .await |
| 2987 | .map_err(backend)?; | 3008 | .map_err(backend)?; |
| 2988 | drop(conn); | 3009 | drop(conn); |
| 2989 | - self.announce([Topic::Task(new.task_id.to_string())]); | 3010 | + self.publish([Topic::Task(new.task_id.to_string())]); |
| 2990 | Ok(new.id) | 3011 | Ok(new.id) |
| 2991 | } | 3012 | } |
| 2992 | 3013 | ||
| @@ -3033,7 +3054,7 @@ impl Store for TursoStore { | |||
| 3033 | // orphaned bytes the boot sweep collects. | 3054 | // orphaned bytes the boot sweep collects. |
| 3034 | let _ = std::fs::remove_file(attachment_file(&self.storage, id)); | 3055 | let _ = std::fs::remove_file(attachment_file(&self.storage, id)); |
| 3035 | if let Some(task_id) = owner { | 3056 | if let Some(task_id) = owner { |
| 3036 | - self.announce([Topic::Task(task_id)]); | 3057 | + self.publish([Topic::Task(task_id)]); |
| 3037 | } | 3058 | } |
| 3038 | } | 3059 | } |
| 3039 | Ok(moved > 0) | 3060 | Ok(moved > 0) |
| @@ -3055,7 +3076,7 @@ impl Store for TursoStore { | |||
| 3055 | } | 3076 | } |
| 3056 | 3077 | ||
| 3057 | async fn announce_storage(&self) -> Result<()> { | 3078 | async fn announce_storage(&self) -> Result<()> { |
| 3058 | - self.announce([Topic::Settings]); | 3079 | + self.publish([Topic::Settings]); |
| 3059 | Ok(()) | 3080 | Ok(()) |
| 3060 | } | 3081 | } |
| 3061 | 3082 | ||
| @@ -3171,7 +3192,7 @@ impl Store for TursoStore { | |||
| 3171 | if reminded { | 3192 | if reminded { |
| 3172 | topics.push(Topic::Queue); | 3193 | topics.push(Topic::Queue); |
| 3173 | } | 3194 | } |
| 3174 | - self.announce(topics); | 3195 | + self.publish(topics); |
| 3175 | Ok(ids) | 3196 | Ok(ids) |
| 3176 | } | 3197 | } |
| 3177 | Ok(None) => { | 3198 | Ok(None) => { |
| @@ -3374,7 +3395,7 @@ impl Store for TursoStore { | |||
| 3374 | if reminded { | 3395 | if reminded { |
| 3375 | topics.push(Topic::Queue); | 3396 | topics.push(Topic::Queue); |
| 3376 | } | 3397 | } |
| 3377 | - self.announce(topics); | 3398 | + self.publish(topics); |
| 3378 | Ok(Moved::Recorded(Transition { | 3399 | Ok(Moved::Recorded(Transition { |
| 3379 | id: transition_id, | 3400 | id: transition_id, |
| 3380 | task_id: task_id.to_string(), | 3401 | task_id: task_id.to_string(), |
| @@ -3578,7 +3599,7 @@ impl Store for TursoStore { | |||
| 3578 | if reminded { | 3599 | if reminded { |
| 3579 | topics.push(Topic::Queue); | 3600 | topics.push(Topic::Queue); |
| 3580 | } | 3601 | } |
| 3581 | - self.announce(topics); | 3602 | + self.publish(topics); |
| 3582 | Ok(deletion) | 3603 | Ok(deletion) |
| 3583 | } | 3604 | } |
| 3584 | Ok(None) => { | 3605 | Ok(None) => { |
| @@ -3694,7 +3715,7 @@ impl Store for TursoStore { | |||
| 3694 | .map_err(backend)?; | 3715 | .map_err(backend)?; |
| 3695 | drop(conn); | 3716 | drop(conn); |
| 3696 | // Task-scoped: the task's own trail and the workspace feed both grew. | 3717 | // Task-scoped: the task's own trail and the workspace feed both grew. |
| 3697 | - self.announce([Topic::Activity, Topic::Task(task_id.to_string())]); | 3718 | + self.publish([Topic::Activity, Topic::Task(task_id.to_string())]); |
| 3698 | Ok(id) | 3719 | Ok(id) |
| 3699 | } | 3720 | } |
| 3700 | 3721 | ||
| @@ -3716,7 +3737,7 @@ impl Store for TursoStore { | |||
| 3716 | .map_err(backend)?; | 3737 | .map_err(backend)?; |
| 3717 | drop(conn); | 3738 | drop(conn); |
| 3718 | // Workspace-wide, belonging to no task — the feed only. | 3739 | // Workspace-wide, belonging to no task — the feed only. |
| 3719 | - self.announce([Topic::Activity]); | 3740 | + self.publish([Topic::Activity]); |
| 3720 | Ok(id) | 3741 | Ok(id) |
| 3721 | } | 3742 | } |
| 3722 | 3743 | ||
| @@ -3754,7 +3775,7 @@ impl Store for TursoStore { | |||
| 3754 | ) | 3775 | ) |
| 3755 | .await | 3776 | .await |
| 3756 | .map_err(backend)?; | 3777 | .map_err(backend)?; |
| 3757 | - self.announce([Topic::Rules]); | 3778 | + self.publish([Topic::Rules]); |
| 3758 | let sql = format!("SELECT {RULE_COLUMNS} FROM mail_rule WHERE id = ?1"); | 3779 | let sql = format!("SELECT {RULE_COLUMNS} FROM mail_rule WHERE id = ?1"); |
| 3759 | match self.one_row(&sql, params![id]).await? { | 3780 | match self.one_row(&sql, params![id]).await? { |
| 3760 | Some(row) => rule_from(&row), | 3781 | Some(row) => rule_from(&row), |
| @@ -3804,7 +3825,7 @@ impl Store for TursoStore { | |||
| 3804 | return Err(StoreError::NotFound); | 3825 | return Err(StoreError::NotFound); |
| 3805 | } | 3826 | } |
| 3806 | drop(conn); | 3827 | drop(conn); |
| 3807 | - self.announce([Topic::Rules]); | 3828 | + self.publish([Topic::Rules]); |
| 3808 | Ok(()) | 3829 | Ok(()) |
| 3809 | } | 3830 | } |
| 3810 | 3831 | ||
| @@ -3898,7 +3919,7 @@ impl Store for TursoStore { | |||
| 3898 | return Err(StoreError::NotFound); | 3919 | return Err(StoreError::NotFound); |
| 3899 | } | 3920 | } |
| 3900 | drop(conn); | 3921 | drop(conn); |
| 3901 | - self.announce([Topic::Rules]); | 3922 | + self.publish([Topic::Rules]); |
| 3902 | Ok(()) | 3923 | Ok(()) |
| 3903 | } | 3924 | } |
| 3904 | 3925 | ||
| @@ -3915,7 +3936,7 @@ impl Store for TursoStore { | |||
| 3915 | } | 3936 | } |
| 3916 | drop(conn); | 3937 | drop(conn); |
| 3917 | // The rule's queued mail cascaded away with it, so the queue moved too. | 3938 | // The rule's queued mail cascaded away with it, so the queue moved too. |
| 3918 | - self.announce([Topic::Rules, Topic::Queue]); | 3939 | + self.publish([Topic::Rules, Topic::Queue]); |
| 3919 | Ok(()) | 3940 | Ok(()) |
| 3920 | } | 3941 | } |
| 3921 | 3942 | ||
| @@ -3979,7 +4000,7 @@ impl Store for TursoStore { | |||
| 3979 | return Ok(None); | 4000 | return Ok(None); |
| 3980 | } | 4001 | } |
| 3981 | // A mail joined the queue, so the queue panel is out of date. | 4002 | // A mail joined the queue, so the queue panel is out of date. |
| 3982 | - self.announce([Topic::Queue]); | 4003 | + self.publish([Topic::Queue]); |
| 3983 | let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); | 4004 | let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); |
| 3984 | match self.one_row(&sql, params![id]).await? { | 4005 | match self.one_row(&sql, params![id]).await? { |
| 3985 | Some(row) => send_from(&row).map(ClaimedSend::taken).map(Some), | 4006 | Some(row) => send_from(&row).map(ClaimedSend::taken).map(Some), |
| @@ -4009,7 +4030,7 @@ impl Store for TursoStore { | |||
| 4009 | .map_err(backend)?; | 4030 | .map_err(backend)?; |
| 4010 | // Two surfaces at once: the invite is a queued mail, and an invited | 4031 | // Two surfaces at once: the invite is a queued mail, and an invited |
| 4011 | // person shows up in the members list before they ever sign in. | 4032 | // person shows up in the members list before they ever sign in. |
| 4012 | - self.announce([Topic::Queue, Topic::Members]); | 4033 | + self.publish([Topic::Queue, Topic::Members]); |
| 4013 | let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); | 4034 | let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); |
| 4014 | match self.one_row(&sql, params![id]).await? { | 4035 | match self.one_row(&sql, params![id]).await? { |
| 4015 | Some(row) => send_from(&row), | 4036 | Some(row) => send_from(&row), |
| @@ -4037,7 +4058,7 @@ impl Store for TursoStore { | |||
| 4037 | ) | 4058 | ) |
| 4038 | .await | 4059 | .await |
| 4039 | .map_err(backend)?; | 4060 | .map_err(backend)?; |
| 4040 | - self.announce([Topic::Queue]); | 4061 | + self.publish([Topic::Queue]); |
| 4041 | let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); | 4062 | let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); |
| 4042 | match self.one_row(&sql, params![id]).await? { | 4063 | match self.one_row(&sql, params![id]).await? { |
| 4043 | Some(row) => send_from(&row), | 4064 | Some(row) => send_from(&row), |
| @@ -4064,7 +4085,7 @@ impl Store for TursoStore { | |||
| 4064 | // whose subscribers may turn round and read this store, and holding | 4085 | // whose subscribers may turn round and read this store, and holding |
| 4065 | // the single connection while they do is how that deadlocks. | 4086 | // the single connection while they do is how that deadlocks. |
| 4066 | drop(conn); | 4087 | drop(conn); |
| 4067 | - self.announce([Topic::Queue]); | 4088 | + self.publish([Topic::Queue]); |
| 4068 | Ok(()) | 4089 | Ok(()) |
| 4069 | } | 4090 | } |
| 4070 | 4091 | ||
| @@ -4103,7 +4124,7 @@ impl Store for TursoStore { | |||
| 4103 | drop(conn); | 4124 | drop(conn); |
| 4104 | // The attempt counter and the next-try time both just moved, and the | 4125 | // The attempt counter and the next-try time both just moved, and the |
| 4105 | // queue panel renders both. | 4126 | // queue panel renders both. |
| 4106 | - self.announce([Topic::Queue]); | 4127 | + self.publish([Topic::Queue]); |
| 4107 | Ok(()) | 4128 | Ok(()) |
| 4108 | } | 4129 | } |
| 4109 | 4130 | ||
| @@ -4131,7 +4152,7 @@ impl Store for TursoStore { | |||
| 4131 | return Err(StoreError::NotFound); | 4152 | return Err(StoreError::NotFound); |
| 4132 | } | 4153 | } |
| 4133 | drop(conn); | 4154 | drop(conn); |
| 4134 | - self.announce([Topic::Queue]); | 4155 | + self.publish([Topic::Queue]); |
| 4135 | Ok(()) | 4156 | Ok(()) |
| 4136 | } | 4157 | } |
| 4137 | 4158 | ||
| @@ -4261,7 +4282,7 @@ impl Store for TursoStore { | |||
| 4261 | .await | 4282 | .await |
| 4262 | .map_err(backend)?; | 4283 | .map_err(backend)?; |
| 4263 | drop(conn); | 4284 | drop(conn); |
| 4264 | - self.announce([Topic::Queue]); | 4285 | + self.publish([Topic::Queue]); |
| 4265 | Ok(()) | 4286 | Ok(()) |
| 4266 | } | 4287 | } |
| 4267 | 4288 | ||
| @@ -4297,7 +4318,7 @@ impl Store for TursoStore { | |||
| 4297 | .map_err(backend)?; | 4318 | .map_err(backend)?; |
| 4298 | drop(conn); | 4319 | drop(conn); |
| 4299 | // A decision is what the rules page's decisions tab renders. | 4320 | // A decision is what the rules page's decisions tab renders. |
| 4300 | - self.announce([Topic::Rules]); | 4321 | + self.publish([Topic::Rules]); |
| 4301 | Ok(()) | 4322 | Ok(()) |
| 4302 | } | 4323 | } |
| 4303 | 4324 | ||
| @@ -4721,7 +4742,7 @@ impl Store for TursoStore { | |||
| 4721 | .map_err(backend)?; | 4742 | .map_err(backend)?; |
| 4722 | } | 4743 | } |
| 4723 | drop(conn); | 4744 | drop(conn); |
| 4724 | - self.announce([Topic::Queue]); | 4745 | + self.publish([Topic::Queue]); |
| 4725 | Ok(()) | 4746 | Ok(()) |
| 4726 | } | 4747 | } |
| 4727 | 4748 | ||
| @@ -4840,7 +4861,7 @@ impl Store for TursoStore { | |||
| 4840 | }; | 4861 | }; |
| 4841 | tx.commit().await.map_err(backend)?; | 4862 | tx.commit().await.map_err(backend)?; |
| 4842 | 4863 | ||
| 4843 | - self.announce([Topic::Board, Topic::Tags]); | 4864 | + self.publish([Topic::Board, Topic::Tags]); |
| 4844 | Ok(Tag { | 4865 | Ok(Tag { |
| 4845 | id, | 4866 | id, |
| 4846 | board_id: board_id.to_string(), | 4867 | board_id: board_id.to_string(), |
| @@ -4869,7 +4890,7 @@ impl Store for TursoStore { | |||
| 4869 | return Err(StoreError::NotFound); | 4890 | return Err(StoreError::NotFound); |
| 4870 | } | 4891 | } |
| 4871 | drop(conn); | 4892 | drop(conn); |
| 4872 | - self.announce([Topic::Board, Topic::Tags]); | 4893 | + self.publish([Topic::Board, Topic::Tags]); |
| 4873 | Ok(()) | 4894 | Ok(()) |
| 4874 | } | 4895 | } |
| 4875 | 4896 | ||
| @@ -4941,7 +4962,7 @@ impl Store for TursoStore { | |||
| 4941 | } | 4962 | } |
| 4942 | } | 4963 | } |
| 4943 | tx.commit().await.map_err(backend)?; | 4964 | tx.commit().await.map_err(backend)?; |
| 4944 | - self.announce([Topic::Board, Topic::Tags]); | 4965 | + self.publish([Topic::Board, Topic::Tags]); |
| 4945 | Ok(()) | 4966 | Ok(()) |
| 4946 | } | 4967 | } |
| 4947 | 4968 | ||
| @@ -5003,7 +5024,7 @@ impl Store for TursoStore { | |||
| 5003 | } | 5024 | } |
| 5004 | } | 5025 | } |
| 5005 | tx.commit().await.map_err(backend)?; | 5026 | tx.commit().await.map_err(backend)?; |
| 5006 | - self.announce([Topic::Board, Topic::Tags]); | 5027 | + self.publish([Topic::Board, Topic::Tags]); |
| 5007 | Ok(()) | 5028 | Ok(()) |
| 5008 | } | 5029 | } |
| 5009 | 5030 | ||
| @@ -5032,7 +5053,7 @@ impl Store for TursoStore { | |||
| 5032 | return Err(StoreError::NotFound); | 5053 | return Err(StoreError::NotFound); |
| 5033 | } | 5054 | } |
| 5034 | drop(conn); | 5055 | drop(conn); |
| 5035 | - self.announce([Topic::Board, Topic::Task(task_id.to_string()), Topic::Tags]); | 5056 | + self.publish([Topic::Board, Topic::Task(task_id.to_string()), Topic::Tags]); |
| 5036 | Ok(()) | 5057 | Ok(()) |
| 5037 | } | 5058 | } |
| 5038 | } | 5059 | } |
crates/iz-core/tests/store.rsmodified+7 -3
| @@ -5593,7 +5593,11 @@ fn every_writing_method_announces_or_is_named_here() { | |||
| 5593 | || chunk.contains("INSERT OR ") | 5593 | || chunk.contains("INSERT OR ") |
| 5594 | || chunk.contains("UPDATE ") | 5594 | || chunk.contains("UPDATE ") |
| 5595 | || chunk.contains("DELETE FROM"); | 5595 | || chunk.contains("DELETE FROM"); |
| 5596 | - if writes && !chunk.contains("announce(") && !SILENT_ON_PURPOSE.contains(&name) { | 5596 | + if writes |
| 5597 | + && !chunk.contains("publish(") | ||
| 5598 | + && !chunk.contains("announce(") | ||
| 5599 | + && !SILENT_ON_PURPOSE.contains(&name) | ||
| 5600 | + { | ||
| 5597 | silent.push(name.to_string()); | 5601 | silent.push(name.to_string()); |
| 5598 | } | 5602 | } |
| 5599 | } | 5603 | } |
| @@ -5602,8 +5606,8 @@ fn every_writing_method_announces_or_is_named_here() { | |||
| 5602 | silent.is_empty(), | 5606 | silent.is_empty(), |
| 5603 | "these methods change rows without announcing it, so the screens \ | 5607 | "these methods change rows without announcing it, so the screens \ |
| 5604 | showing those rows will go stale until someone reloads by hand: {silent:?}. \ | 5608 | showing those rows will go stale until someone reloads by hand: {silent:?}. \ |
| 5605 | - Either call `self.announce(..)` after the write commits, or add the \ | 5609 | + Either call `self.publish(..)` (or the trait's `self.announce(..)`) after \ |
| 5606 | - method to SILENT_ON_PURPOSE with the reason." | 5610 | + the write commits, or add the method to SILENT_ON_PURPOSE with the reason." |
| 5607 | ); | 5611 | ); |
| 5608 | } | 5612 | } |
| 5609 | 5613 | ||
crates/iz-web/src/directory.rsmodified+431 -2
| @@ -1,5 +1,9 @@ | |||
| 1 | -//! How the identity mirror stands against im — the facts the Settings | 1 | +//! How the identity mirror stands against im. Two halves: the facts the |
| 2 | -//! Connection card renders. The mirror task writes; the page reads. | 2 | +//! Settings Connection card renders (the mirror task writes, the page |
| 3 | +//! reads), and the live connection itself — held and parsed here rather | ||
| 4 | +//! than through the pinned `im-client`, whose frame reader drops every | ||
| 5 | +//! event kind it was not built for, and the feed now carries kinds this | ||
| 6 | +//! app must hear. | ||
| 3 | //! | 7 | //! |
| 4 | //! Deliberately dumb: one mutex over four plain fields, because the card | 8 | //! Deliberately dumb: one mutex over four plain fields, because the card |
| 5 | //! renders once per view and the stream updates a few times a minute. The | 9 | //! renders once per view and the stream updates a few times a minute. The |
| @@ -7,10 +11,14 @@ | |||
| 7 | //! comes near this struct, so the render path cannot leak what it was never | 11 | //! comes near this struct, so the render path cannot leak what it was never |
| 8 | //! given. | 12 | //! given. |
| 9 | 13 | ||
| 14 | +use std::collections::VecDeque; | ||
| 10 | use std::sync::Arc; | 15 | use std::sync::Arc; |
| 11 | use std::time::{Duration, Instant}; | 16 | use std::time::{Duration, Instant}; |
| 12 | 17 | ||
| 18 | +use iz_core::Topic; | ||
| 19 | +use iz_core::store::Store; | ||
| 13 | use parking_lot::Mutex; | 20 | use parking_lot::Mutex; |
| 21 | +use serde::Deserialize; | ||
| 14 | use topcoat::context::{Cx, try_app_context}; | 22 | use topcoat::context::{Cx, try_app_context}; |
| 15 | 23 | ||
| 16 | /// The mirror's health, shared between the stream task and the renderer. | 24 | /// The mirror's health, shared between the stream task and the renderer. |
| @@ -97,3 +105,424 @@ pub fn age_text(age: Option<Duration>) -> String { | |||
| 97 | None => String::new(), | 105 | None => String::new(), |
| 98 | } | 106 | } |
| 99 | } | 107 | } |
| 108 | + | ||
| 109 | +/// Where the live half of the mirror connects. The same issuer and Basic | ||
| 110 | +/// pair the roster client holds, kept apart from it because the stream is | ||
| 111 | +/// read here, frame by frame, rather than through the pinned `im-client` — | ||
| 112 | +/// whose parser drops every event kind it was not built for, and this feed | ||
| 113 | +/// now carries kinds this app must hear. | ||
| 114 | +#[derive(Clone)] | ||
| 115 | +pub struct StreamSource { | ||
| 116 | + http: reqwest::Client, | ||
| 117 | + issuer: String, | ||
| 118 | + client_id: String, | ||
| 119 | + client_secret: String, | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +impl StreamSource { | ||
| 123 | + pub fn new( | ||
| 124 | + issuer: impl Into<String>, | ||
| 125 | + client_id: impl Into<String>, | ||
| 126 | + client_secret: impl Into<String>, | ||
| 127 | + ) -> Self { | ||
| 128 | + Self { | ||
| 129 | + http: reqwest::Client::new(), | ||
| 130 | + issuer: issuer.into(), | ||
| 131 | + client_id: client_id.into(), | ||
| 132 | + client_secret: client_secret.into(), | ||
| 133 | + } | ||
| 134 | + } | ||
| 135 | + | ||
| 136 | + /// `GET /directory/live`, the connection held with no timeout: a change | ||
| 137 | + /// feed is *supposed* to sit idle, and its liveness is im's keep-alive | ||
| 138 | + /// comment. | ||
| 139 | + pub async fn open_stream(&self) -> Result<DirectoryStream, String> { | ||
| 140 | + let response = self | ||
| 141 | + .http | ||
| 142 | + .get(format!("{}/directory/live", self.issuer)) | ||
| 143 | + .basic_auth(&self.client_id, Some(&self.client_secret)) | ||
| 144 | + .send() | ||
| 145 | + .await | ||
| 146 | + .map_err(|e| e.to_string())? | ||
| 147 | + .error_for_status() | ||
| 148 | + .map_err(|e| e.to_string())?; | ||
| 149 | + Ok(DirectoryStream { | ||
| 150 | + response, | ||
| 151 | + reader: FrameReader::default(), | ||
| 152 | + }) | ||
| 153 | + } | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/// One member's row exactly as the stream carries it: the roster's shape | ||
| 157 | +/// plus the `disabled` fact the roster itself never shows — im's | ||
| 158 | +/// `/directory` lists nobody disabled, so the flag travels only here. | ||
| 159 | +/// Unknown fields are ignored, so an im newer than this build can grow the | ||
| 160 | +/// row without a breaking change. | ||
| 161 | +#[derive(Debug, Clone, PartialEq, Deserialize)] | ||
| 162 | +pub struct StreamMember { | ||
| 163 | + pub sub: String, | ||
| 164 | + pub email: String, | ||
| 165 | + pub name: String, | ||
| 166 | + #[serde(default)] | ||
| 167 | + pub admin: bool, | ||
| 168 | + #[serde(default)] | ||
| 169 | + pub photo_version: u64, | ||
| 170 | + #[serde(default = "default_timezone")] | ||
| 171 | + pub timezone: String, | ||
| 172 | + #[serde(default)] | ||
| 173 | + pub disabled: bool, | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +/// The timezone im starts every account on, and the one a mirrored row | ||
| 177 | +/// predating the field reads as. | ||
| 178 | +fn default_timezone() -> String { | ||
| 179 | + "UTC+03:00".to_string() | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +/// One event off im's `/directory/live`, parsed here rather than in the | ||
| 183 | +/// pinned client because the consumer owes the wire more than the pin | ||
| 184 | +/// knows: a `revoked` frame says a session died in im, and a `profile` | ||
| 185 | +/// frame may now carry `disabled`. | ||
| 186 | +#[derive(Debug, Clone, PartialEq)] | ||
| 187 | +pub enum StreamFrame { | ||
| 188 | + /// The named member's row as it now stands. | ||
| 189 | + Profile(StreamMember), | ||
| 190 | + /// At least one of the member's sessions was revoked. Which one is | ||
| 191 | + /// im's knowledge alone; the consumer treats the fact workspace-wide. | ||
| 192 | + Revoked { sub: String }, | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +/// An open `/directory/live` connection. `next` mirrors the pinned | ||
| 196 | +/// client's shape: `Some(Err)` on a wire failure — then the stream is | ||
| 197 | +/// over — and `None` when im closed a healthy one. Either way the caller | ||
| 198 | +/// re-lists and redials. | ||
| 199 | +pub struct DirectoryStream { | ||
| 200 | + response: reqwest::Response, | ||
| 201 | + reader: FrameReader, | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +impl DirectoryStream { | ||
| 205 | + pub async fn next(&mut self) -> Option<Result<StreamFrame, String>> { | ||
| 206 | + loop { | ||
| 207 | + if let Some(frame) = self.reader.ready.pop_front() { | ||
| 208 | + return Some(Ok(frame)); | ||
| 209 | + } | ||
| 210 | + match self.response.chunk().await { | ||
| 211 | + Ok(Some(bytes)) => self.reader.feed(&bytes), | ||
| 212 | + Ok(None) => return None, | ||
| 213 | + Err(e) => return Some(Err(e.to_string())), | ||
| 214 | + } | ||
| 215 | + } | ||
| 216 | + } | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +/// The hand-rolled `text/event-stream` reader. Frames accumulate field by | ||
| 220 | +/// field and dispatch on the blank line, per the SSE grammar; the fields | ||
| 221 | +/// this feed carries are `event`, `data`, and comments, but the parser | ||
| 222 | +/// honors the whole shape — including `data` split over several lines, | ||
| 223 | +/// which the spec joins with `\n`. | ||
| 224 | +#[derive(Default)] | ||
| 225 | +struct FrameReader { | ||
| 226 | + /// Bytes read but not yet through a line terminator. | ||
| 227 | + pending: Vec<u8>, | ||
| 228 | + /// The previous read ended on a bare `\r`, so the next read's leading | ||
| 229 | + /// `\n` — if that is what comes — completes that terminator rather | ||
| 230 | + /// than opening a blank line. | ||
| 231 | + cr_ended: bool, | ||
| 232 | + /// The current frame's `event:` field, if it named one. | ||
| 233 | + event: Option<String>, | ||
| 234 | + /// The current frame's `data:`, joined back into one string. | ||
| 235 | + data: String, | ||
| 236 | + /// Frames completed and waiting to be read. | ||
| 237 | + ready: VecDeque<StreamFrame>, | ||
| 238 | +} | ||
| 239 | + | ||
| 240 | +impl FrameReader { | ||
| 241 | + /// Feeds the next bytes from the wire and queues every frame they | ||
| 242 | + /// completed. Bytes trailing their terminator wait for the rest — a | ||
| 243 | + /// field or a UTF-8 character may straddle two reads. | ||
| 244 | + fn feed(&mut self, bytes: &[u8]) { | ||
| 245 | + // The previous read stopped on a bare `\r`. A `\r\n` split across | ||
| 246 | + // two reads is ONE terminator: the pair's `\n` arriving here | ||
| 247 | + // completes the old one instead of opening a blank line and | ||
| 248 | + // dispatching a frame that has not ended. | ||
| 249 | + let bytes = if self.cr_ended { | ||
| 250 | + self.cr_ended = false; | ||
| 251 | + if bytes.first() == Some(&b'\n') { | ||
| 252 | + &bytes[1..] | ||
| 253 | + } else { | ||
| 254 | + bytes | ||
| 255 | + } | ||
| 256 | + } else { | ||
| 257 | + bytes | ||
| 258 | + }; | ||
| 259 | + self.pending.extend_from_slice(bytes); | ||
| 260 | + let Some(at) = self | ||
| 261 | + .pending | ||
| 262 | + .iter() | ||
| 263 | + .rposition(|&b| b == b'\n' || b == b'\r') | ||
| 264 | + .map(|at| at + 1) | ||
| 265 | + else { | ||
| 266 | + return; | ||
| 267 | + }; | ||
| 268 | + let block: Vec<u8> = self.pending.drain(..at).collect(); | ||
| 269 | + self.cr_ended = block.last() == Some(&b'\r'); | ||
| 270 | + for line in split_lines(&block) { | ||
| 271 | + if line.is_empty() { | ||
| 272 | + // The blank line dispatches whatever accumulated. | ||
| 273 | + if let Some(frame) = self.take() { | ||
| 274 | + self.ready.push_back(frame); | ||
| 275 | + } | ||
| 276 | + } else if line[0] == b':' { | ||
| 277 | + // A comment — im's keep-alives and retry hint live here. | ||
| 278 | + } else { | ||
| 279 | + let (name, value) = match line.iter().position(|&b| b == b':') { | ||
| 280 | + Some(at) => (&line[..at], &line[at + 1..]), | ||
| 281 | + None => (&line[..], &b""[..]), | ||
| 282 | + }; | ||
| 283 | + // One optional space after the colon is not part of the | ||
| 284 | + // value. | ||
| 285 | + let value = value.strip_prefix(b" ").unwrap_or(value); | ||
| 286 | + match name { | ||
| 287 | + b"event" => self.event = Some(String::from_utf8_lossy(value).into_owned()), | ||
| 288 | + b"data" => { | ||
| 289 | + if !self.data.is_empty() { | ||
| 290 | + self.data.push('\n'); | ||
| 291 | + } | ||
| 292 | + self.data.push_str(&String::from_utf8_lossy(value)); | ||
| 293 | + } | ||
| 294 | + // `id` and `retry` mean nothing to a change feed. | ||
| 295 | + _ => {} | ||
| 296 | + } | ||
| 297 | + } | ||
| 298 | + } | ||
| 299 | + } | ||
| 300 | + | ||
| 301 | + /// Ends the current frame and decides what it was. A frame whose kind | ||
| 302 | + /// this build does not know is skipped, not fatal: im may grow the | ||
| 303 | + /// feed, and one strange frame must not end a healthy connection. A | ||
| 304 | + /// known kind whose payload will not parse is logged and dropped for | ||
| 305 | + /// the same reason. | ||
| 306 | + fn take(&mut self) -> Option<StreamFrame> { | ||
| 307 | + let data = std::mem::take(&mut self.data); | ||
| 308 | + let event = self.event.take(); | ||
| 309 | + match event.as_deref() { | ||
| 310 | + // A frame with no kind at all is an older im's bare member | ||
| 311 | + // announcement; it parses exactly as it always did. | ||
| 312 | + None | Some("profile") => match serde_json::from_str::<StreamMember>(&data) { | ||
| 313 | + Ok(member) => Some(StreamFrame::Profile(member)), | ||
| 314 | + Err(problem) => { | ||
| 315 | + eprintln!("directory stream: unreadable profile frame ({problem})"); | ||
| 316 | + None | ||
| 317 | + } | ||
| 318 | + }, | ||
| 319 | + Some("revoked") => match serde_json::from_str::<RevokedFrame>(&data) { | ||
| 320 | + Ok(frame) => Some(StreamFrame::Revoked { sub: frame.sub }), | ||
| 321 | + Err(problem) => { | ||
| 322 | + eprintln!("directory stream: unreadable revoked frame ({problem})"); | ||
| 323 | + None | ||
| 324 | + } | ||
| 325 | + }, | ||
| 326 | + // A kind from an im newer than this build. | ||
| 327 | + Some(_) => None, | ||
| 328 | + } | ||
| 329 | + } | ||
| 330 | +} | ||
| 331 | + | ||
| 332 | +/// The `{"sub": ...}` payload a `revoked` frame carries. | ||
| 333 | +#[derive(Deserialize)] | ||
| 334 | +struct RevokedFrame { | ||
| 335 | + sub: String, | ||
| 336 | +} | ||
| 337 | + | ||
| 338 | +/// Splits a block that ends at a line terminator into lines, accepting the | ||
| 339 | +/// three SSE terminators: `\n`, `\r\n`, and a bare `\r`. A blank line is a | ||
| 340 | +/// frame's dispatch, so it is kept — only the terminator run itself | ||
| 341 | +/// disappears. | ||
| 342 | +fn split_lines(block: &[u8]) -> Vec<Vec<u8>> { | ||
| 343 | + let mut lines = Vec::new(); | ||
| 344 | + let mut start = 0usize; | ||
| 345 | + let mut at = 0usize; | ||
| 346 | + while at < block.len() { | ||
| 347 | + if block[at] == b'\n' || block[at] == b'\r' { | ||
| 348 | + lines.push(block[start..at].to_vec()); | ||
| 349 | + if block[at] == b'\r' && block.get(at + 1) == Some(&b'\n') { | ||
| 350 | + at += 1; | ||
| 351 | + } | ||
| 352 | + at += 1; | ||
| 353 | + start = at; | ||
| 354 | + } else { | ||
| 355 | + at += 1; | ||
| 356 | + } | ||
| 357 | + } | ||
| 358 | + if start < block.len() { | ||
| 359 | + lines.push(block[start..].to_vec()); | ||
| 360 | + } | ||
| 361 | + lines | ||
| 362 | +} | ||
| 363 | + | ||
| 364 | +/// Carries one consumed frame into the local mirror — the one door both | ||
| 365 | +/// the stream task and the tests use, so a frame means the same thing no | ||
| 366 | +/// matter who fed it. | ||
| 367 | +/// | ||
| 368 | +/// * A profile syncs the row the way the roster pass does, and im owns the | ||
| 369 | +/// account's life: a profile whose `disabled` disagrees with the local | ||
| 370 | +/// row flips it through the same store path an admin's hand uses — | ||
| 371 | +/// `true` is a user-level kill whose store announcement names the | ||
| 372 | +/// account's own open tabs, `false` is the homecoming that signs the | ||
| 373 | +/// row back in. | ||
| 374 | +/// * A revoked frame is a session fact — which session died is im's | ||
| 375 | +/// knowledge alone, and a tab whose *other* session survived must not be | ||
| 376 | +/// sent away — so it only announces the member surface. Every tab's | ||
| 377 | +/// refetch re-introspects per request, and that is what sorts out who is | ||
| 378 | +/// still signed in. | ||
| 379 | +pub async fn apply_frame(store: &Arc<dyn Store>, frame: StreamFrame) { | ||
| 380 | + match frame { | ||
| 381 | + StreamFrame::Profile(member) => { | ||
| 382 | + if let Err(problem) = store | ||
| 383 | + .sync_member( | ||
| 384 | + &member.sub, | ||
| 385 | + &member.email, | ||
| 386 | + &member.name, | ||
| 387 | + member.admin, | ||
| 388 | + member.photo_version, | ||
| 389 | + &member.timezone, | ||
| 390 | + ) | ||
| 391 | + .await | ||
| 392 | + { | ||
| 393 | + eprintln!("directory stream: {}: {problem}", member.email); | ||
| 394 | + } | ||
| 395 | + match store.user_by_sub(&member.sub).await { | ||
| 396 | + Ok(Some(user)) if user.disabled != member.disabled => { | ||
| 397 | + if let Err(problem) = store.set_user_disabled(&user.id, member.disabled).await | ||
| 398 | + { | ||
| 399 | + eprintln!("directory stream: {}: {problem}", member.email); | ||
| 400 | + } | ||
| 401 | + } | ||
| 402 | + Ok(_) => {} | ||
| 403 | + Err(problem) => { | ||
| 404 | + eprintln!("directory stream: {}: {problem}", member.email); | ||
| 405 | + } | ||
| 406 | + } | ||
| 407 | + } | ||
| 408 | + StreamFrame::Revoked { .. } => { | ||
| 409 | + store.announce(&[Topic::Members]); | ||
| 410 | + } | ||
| 411 | + } | ||
| 412 | +} | ||
| 413 | + | ||
| 414 | +#[cfg(test)] | ||
| 415 | +mod tests { | ||
| 416 | + use super::*; | ||
| 417 | + | ||
| 418 | + fn frames(wire: &str) -> Vec<StreamFrame> { | ||
| 419 | + let mut reader = FrameReader::default(); | ||
| 420 | + reader.feed(wire.as_bytes()); | ||
| 421 | + reader.ready.drain(..).collect() | ||
| 422 | + } | ||
| 423 | + | ||
| 424 | + fn member(sub: &str, email: &str, name: &str, disabled: bool) -> StreamMember { | ||
| 425 | + StreamMember { | ||
| 426 | + sub: sub.into(), | ||
| 427 | + email: email.into(), | ||
| 428 | + name: name.into(), | ||
| 429 | + admin: false, | ||
| 430 | + photo_version: 0, | ||
| 431 | + timezone: "UTC+03:00".into(), | ||
| 432 | + disabled, | ||
| 433 | + } | ||
| 434 | + } | ||
| 435 | + | ||
| 436 | + /// A kind this build has never heard of is skipped where it stands — | ||
| 437 | + /// the frames on either side of it still land, and the reader is alive | ||
| 438 | + /// for the next bytes. | ||
| 439 | + #[test] | ||
| 440 | + fn an_unknown_event_kind_is_skipped_and_the_stream_lives_on() { | ||
| 441 | + let wire = concat!( | ||
| 442 | + ": keep-alive\n", | ||
| 443 | + "event: profile\n", | ||
| 444 | + "data: {\"sub\":\"s1\",\"email\":\"a@iz.sh\",\"name\":\"A\"}\n", | ||
| 445 | + "\n", | ||
| 446 | + "event: logrollover\n", | ||
| 447 | + "data: {\"whatever\":true}\n", | ||
| 448 | + "\n", | ||
| 449 | + "event: revoked\n", | ||
| 450 | + "data: {\"sub\":\"s1\"}\n", | ||
| 451 | + "\n", | ||
| 452 | + "event: profile\n", | ||
| 453 | + "data: {\"sub\":\"s2\",\"email\":\"b@iz.sh\",\"name\":\"B\",\"disabled\":true}\n", | ||
| 454 | + "\n", | ||
| 455 | + ); | ||
| 456 | + assert_eq!( | ||
| 457 | + frames(wire), | ||
| 458 | + vec![ | ||
| 459 | + StreamFrame::Profile(member("s1", "a@iz.sh", "A", false)), | ||
| 460 | + StreamFrame::Revoked { sub: "s1".into() }, | ||
| 461 | + StreamFrame::Profile(member("s2", "b@iz.sh", "B", true)), | ||
| 462 | + ] | ||
| 463 | + ); | ||
| 464 | + } | ||
| 465 | + | ||
| 466 | + /// im predating the `event:` field altogether announces bare member | ||
| 467 | + /// frames; unknown fields on a known frame are ignored, so a newer im | ||
| 468 | + /// may grow the row without a breaking change. | ||
| 469 | + #[test] | ||
| 470 | + fn a_bare_frame_from_an_older_im_still_parses() { | ||
| 471 | + let wire = concat!( | ||
| 472 | + "data: {\"sub\":\"s1\",\"email\":\"a@iz.sh\",\"name\":\"A\",\"voltage\":9}\n", | ||
| 473 | + "\n", | ||
| 474 | + ); | ||
| 475 | + let seen = frames(wire); | ||
| 476 | + assert_eq!( | ||
| 477 | + seen, | ||
| 478 | + vec![StreamFrame::Profile(member("s1", "a@iz.sh", "A", false))] | ||
| 479 | + ); | ||
| 480 | + } | ||
| 481 | + | ||
| 482 | + /// A frame cut in the middle of its JSON is held until its rest | ||
| 483 | + /// arrives; nothing is lost and nothing is dispatched early. | ||
| 484 | + #[test] | ||
| 485 | + fn a_frame_straddling_two_reads_is_not_lost() { | ||
| 486 | + let mut reader = FrameReader::default(); | ||
| 487 | + reader.feed(b"event: revoked\ndata: {\"su"); | ||
| 488 | + assert!(reader.ready.is_empty()); | ||
| 489 | + reader.feed(b"b\":\"s9\"}\n\n"); | ||
| 490 | + assert_eq!( | ||
| 491 | + reader.ready.drain(..).collect::<Vec<_>>(), | ||
| 492 | + vec![StreamFrame::Revoked { sub: "s9".into() }] | ||
| 493 | + ); | ||
| 494 | + } | ||
| 495 | + | ||
| 496 | + /// A `\r\n` pair split across two reads stays one terminator: the | ||
| 497 | + /// trailing `\r` of a read must not let the next read's leading `\n` | ||
| 498 | + /// arrive as a blank line and dispatch a frame that has not ended. | ||
| 499 | + /// The cut here is exactly at the terminator of the one data line; | ||
| 500 | + /// the blank line that follows in the next read is what dispatches. | ||
| 501 | + #[test] | ||
| 502 | + fn a_crlf_pair_split_across_reads_is_one_terminator() { | ||
| 503 | + let mut reader = FrameReader::default(); | ||
| 504 | + reader.feed(b"data: {\"sub\":\"s1\",\"email\":\"a@iz.sh\",\"name\":\"A\"}\r"); | ||
| 505 | + assert!(reader.ready.is_empty(), "a cut terminator dispatched early"); | ||
| 506 | + reader.feed(b"\n\r\n"); | ||
| 507 | + assert_eq!( | ||
| 508 | + reader.ready.drain(..).collect::<Vec<_>>(), | ||
| 509 | + vec![StreamFrame::Profile(member("s1", "a@iz.sh", "A", false))] | ||
| 510 | + ); | ||
| 511 | + } | ||
| 512 | + | ||
| 513 | + /// The same hold with a named kind: the `\r` after `event: revoked` is | ||
| 514 | + /// a field line's end, not the frame's — draining it would let the | ||
| 515 | + /// next read open with a blank line and burn the frame on an empty | ||
| 516 | + /// payload, losing the revocation for good. | ||
| 517 | + #[test] | ||
| 518 | + fn a_trailing_cr_after_the_event_field_does_not_burn_the_frame() { | ||
| 519 | + let mut reader = FrameReader::default(); | ||
| 520 | + reader.feed(b"event: revoked\r"); | ||
| 521 | + assert!(reader.ready.is_empty()); | ||
| 522 | + reader.feed(b"\ndata: {\"sub\":\"s9\"}\r\n\r\n"); | ||
| 523 | + assert_eq!( | ||
| 524 | + reader.ready.drain(..).collect::<Vec<_>>(), | ||
| 525 | + vec![StreamFrame::Revoked { sub: "s9".into() }] | ||
| 526 | + ); | ||
| 527 | + } | ||
| 528 | +} | ||
crates/iz-web/src/layout.rsmodified+14 -0
| @@ -896,6 +896,14 @@ pub async fn soft_nav_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> { | |||
| 896 | /// disagree with it — the tick re-fetches, and the server stays the only thing | 896 | /// disagree with it — the tick re-fetches, and the server stays the only thing |
| 897 | /// that decides what a moment reads as. It runs only on pages carrying a | 897 | /// that decides what a moment reads as. It runs only on pages carrying a |
| 898 | /// `data-tick` element, so a page with no clock-driven text is silent. | 898 | /// `data-tick` element, so a page with no clock-driven text is silent. |
| 899 | +/// The channel also carries one goodbye: a `revoked` frame means this | ||
| 900 | +/// tab's account was killed at the provider, and the answer is a hard | ||
| 901 | +/// redirect to the front door, not a morph. A dropped stream is the other | ||
| 902 | +/// way a tab learns it may be alone: the error path asks `/api/me`, and a | ||
| 903 | +/// `401` there is the same redirect. A merely restarting server answers | ||
| 904 | +/// 204, so a signed-in tab loses nothing — the `EventSource` reconnects | ||
| 905 | +/// on its own. | ||
| 906 | +/// | ||
| 899 | pub async fn live_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> { | 907 | pub async fn live_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> { |
| 900 | const JS: &str = "\ | 908 | const JS: &str = "\ |
| 901 | (function () { \ | 909 | (function () { \ |
| @@ -925,8 +933,14 @@ pub async fn live_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> { | |||
| 925 | src.onmessage = function (e) { \ | 933 | src.onmessage = function (e) { \ |
| 926 | var frame; \ | 934 | var frame; \ |
| 927 | try { frame = JSON.parse(e.data); } catch (err) { return; } \ | 935 | try { frame = JSON.parse(e.data); } catch (err) { return; } \ |
| 936 | + if (frame && frame.topic === 'revoked') { window.location.href = '/'; return; } \ | ||
| 928 | if (frame && wanted(frame.topic)) { schedule(); } \ | 937 | if (frame && wanted(frame.topic)) { schedule(); } \ |
| 929 | }; \ | 938 | }; \ |
| 939 | + src.onerror = function () { \ | ||
| 940 | + fetch('/api/me', { cache: 'no-store' }).then(function (r) { \ | ||
| 941 | + if (r.status === 401) { window.location.href = '/'; } \ | ||
| 942 | + }).catch(function () { }); \ | ||
| 943 | + }; \ | ||
| 930 | } catch (err) { } \ | 944 | } catch (err) { } \ |
| 931 | setInterval(function () { \ | 945 | setInterval(function () { \ |
| 932 | if (document.querySelector('[data-tick]')) { refresh(); } \ | 946 | if (document.querySelector('[data-tick]')) { refresh(); } \ |
crates/iz-web/src/live.rsmodified+29 -7
| @@ -47,18 +47,24 @@ impl Default for LiveWindow { | |||
| 47 | #[derive(Clone)] | 47 | #[derive(Clone)] |
| 48 | pub struct Shutdown(pub tokio::sync::watch::Receiver<bool>); | 48 | pub struct Shutdown(pub tokio::sync::watch::Receiver<bool>); |
| 49 | 49 | ||
| 50 | -/// Whether a reader of this role may be told that this surface moved. | 50 | +/// Whether a reader may be told that this surface moved. |
| 51 | /// | 51 | /// |
| 52 | /// The board, a task and the member list are what every signed-in person | 52 | /// The board, a task and the member list are what every signed-in person |
| 53 | /// already sees. The queue, the rules, the settings and the activity log are | 53 | /// already sees. The queue, the rules, the settings and the activity log are |
| 54 | /// admin screens, and CLAUDE.md's rule — a role that cannot act on a surface | 54 | /// admin screens, and CLAUDE.md's rule — a role that cannot act on a surface |
| 55 | /// does not see it — reaches the channel too: a member is not told the queue | 55 | /// does not see it — reaches the channel too: a member is not told the queue |
| 56 | /// moved, because being told is itself knowing something about the queue. | 56 | /// moved, because being told is itself knowing something about the queue. |
| 57 | -fn may_hear(topic: &Topic, admin: bool) -> bool { | 57 | +/// |
| 58 | +/// The one topic that is neither surface nor role is [`Topic::Revoked`]: the | ||
| 59 | +/// account it names was killed at the provider, and the only reader it may be | ||
| 60 | +/// named to is the reader it names — hearing it says nothing about anybody | ||
| 61 | +/// else. | ||
| 62 | +fn may_hear(topic: &Topic, reader_id: &str, admin: bool) -> bool { | ||
| 58 | match topic { | 63 | match topic { |
| 59 | // Tags ride with the board: every member sees a card's tag, so being | 64 | // Tags ride with the board: every member sees a card's tag, so being |
| 60 | // told the tags moved tells them nothing they cannot already read. | 65 | // told the tags moved tells them nothing they cannot already read. |
| 61 | Topic::Board | Topic::Task(_) | Topic::Members | Topic::Tags => true, | 66 | Topic::Board | Topic::Task(_) | Topic::Members | Topic::Tags => true, |
| 67 | + Topic::Revoked(id) => id == reader_id, | ||
| 62 | Topic::Queue | Topic::Rules | Topic::Settings | Topic::Activity => admin, | 68 | Topic::Queue | Topic::Rules | Topic::Settings | Topic::Activity => admin, |
| 63 | } | 69 | } |
| 64 | } | 70 | } |
| @@ -92,9 +98,15 @@ async fn live(cx: &Cx) -> topcoat::Result<Response> { | |||
| 92 | let deadline = Instant::now() + try_app_context::<LiveWindow>(cx).copied().unwrap_or_default().0; | 98 | let deadline = Instant::now() + try_app_context::<LiveWindow>(cx).copied().unwrap_or_default().0; |
| 93 | 99 | ||
| 94 | let events = futures_util::stream::unfold( | 100 | let events = futures_util::stream::unfold( |
| 95 | - (rx, admin, deadline, stopping), | 101 | + (rx, admin, deadline, stopping, user.id.clone(), false), |
| 96 | - |(mut rx, admin, deadline, mut stopping)| async move { | 102 | + |(mut rx, admin, deadline, mut stopping, reader_id, mut done)| async move { |
| 97 | loop { | 103 | loop { |
| 104 | + // The goodbye frame went out with the last pass: the account | ||
| 105 | + // this reader signed in as was named killed, and there is | ||
| 106 | + // nothing left to say. | ||
| 107 | + if done { | ||
| 108 | + return None; | ||
| 109 | + } | ||
| 98 | // Already going down: say nothing and end, so this connection | 110 | // Already going down: say nothing and end, so this connection |
| 99 | // is not one the shutdown has to sit and wait out. | 111 | // is not one the shutdown has to sit and wait out. |
| 100 | if stopping.as_ref().is_some_and(|watch| *watch.borrow()) { | 112 | if stopping.as_ref().is_some_and(|watch| *watch.borrow()) { |
| @@ -130,21 +142,31 @@ async fn live(cx: &Cx) -> topcoat::Result<Response> { | |||
| 130 | // after. The stream stays open — a slow moment is not a fault. | 142 | // after. The stream stays open — a slow moment is not a fault. |
| 131 | Ok(Some(Err(RecvError::Lagged(_)))) => Event::new().data(RESYNC), | 143 | Ok(Some(Err(RecvError::Lagged(_)))) => Event::new().data(RESYNC), |
| 132 | Ok(Some(Ok(Change { topic, seq }))) => { | 144 | Ok(Some(Ok(Change { topic, seq }))) => { |
| 133 | - if !may_hear(&topic, admin) { | 145 | + if !may_hear(&topic, &reader_id, admin) { |
| 134 | // Not merely unsent: never named. A member's | 146 | // Not merely unsent: never named. A member's |
| 135 | // connection carries no evidence the queue exists. | 147 | // connection carries no evidence the queue exists. |
| 136 | continue; | 148 | continue; |
| 137 | } | 149 | } |
| 150 | + // The reader's own account was named: this frame is | ||
| 151 | + // the goodbye, and the stream ends right behind it — | ||
| 152 | + // the tab leaves for the front door rather than | ||
| 153 | + // morphing a workspace it can no longer read. | ||
| 154 | + if matches!(topic, Topic::Revoked(_)) { | ||
| 155 | + done = true; | ||
| 156 | + } | ||
| 138 | let frame = Frame { topic: topic.kind(), id: topic.id(), seq }; | 157 | let frame = Frame { topic: topic.kind(), id: topic.id(), seq }; |
| 139 | match Event::new().json_data(&frame) { | 158 | match Event::new().json_data(&frame) { |
| 140 | Ok(event) => event, | 159 | Ok(event) => event, |
| 141 | Err(problem) => { | 160 | Err(problem) => { |
| 142 | - return Some((Err(problem), (rx, admin, deadline, stopping))); | 161 | + return Some(( |
| 162 | + Err(problem), | ||
| 163 | + (rx, admin, deadline, stopping, reader_id, done), | ||
| 164 | + )); | ||
| 143 | } | 165 | } |
| 144 | } | 166 | } |
| 145 | } | 167 | } |
| 146 | }; | 168 | }; |
| 147 | - return Some((Ok(frame), (rx, admin, deadline, stopping))); | 169 | + return Some((Ok(frame), (rx, admin, deadline, stopping, reader_id, done))); |
| 148 | } | 170 | } |
| 149 | }, | 171 | }, |
| 150 | ); | 172 | ); |
crates/iz-web/src/main.rsmodified+15 -6
| @@ -189,6 +189,11 @@ async fn main() { | |||
| 189 | tokio::spawn(directory_stream( | 189 | tokio::spawn(directory_stream( |
| 190 | store.clone(), | 190 | store.clone(), |
| 191 | directory.clone(), | 191 | directory.clone(), |
| 192 | + iz_web::directory::StreamSource::new( | ||
| 193 | + config.oidc.issuer.clone(), | ||
| 194 | + config.oidc.client_id.clone(), | ||
| 195 | + config.oidc.client_secret.clone(), | ||
| 196 | + ), | ||
| 192 | health.clone(), | 197 | health.clone(), |
| 193 | )); | 198 | )); |
| 194 | // The storage mirror's watchdog: follows the family to wherever in | 199 | // The storage mirror's watchdog: follows the family to wherever in |
| @@ -487,7 +492,10 @@ async fn apply_member( | |||
| 487 | } | 492 | } |
| 488 | 493 | ||
| 489 | /// The live half of the mirror: im's `/directory/live`, one event per | 494 | /// The live half of the mirror: im's `/directory/live`, one event per |
| 490 | -/// changed member. Forever, in this shape: a full pass, then the stream; | 495 | +/// changed member — plus the `revoked` kind the pinned client's parser |
| 496 | +/// drops, which is why the connection and its frames are | ||
| 497 | +/// [`iz_web::directory`]'s and only the roster pass still rides the | ||
| 498 | +/// pinned client. Forever, in this shape: a full pass, then the stream; | ||
| 491 | /// whenever the stream ends — im restarting, or its fifty-minute window | 499 | /// whenever the stream ends — im restarting, or its fifty-minute window |
| 492 | /// closing — wait out a backoff that doubles from one second to thirty, | 500 | /// closing — wait out a backoff that doubles from one second to thirty, |
| 493 | /// replay a full pass (the resync that heals whatever the dead stream | 501 | /// replay a full pass (the resync that heals whatever the dead stream |
| @@ -499,20 +507,21 @@ async fn apply_member( | |||
| 499 | async fn directory_stream( | 507 | async fn directory_stream( |
| 500 | store: Arc<dyn iz_core::store::Store>, | 508 | store: Arc<dyn iz_core::store::Store>, |
| 501 | directory: im_client::directory::DirectoryClient, | 509 | directory: im_client::directory::DirectoryClient, |
| 510 | + source: iz_web::directory::StreamSource, | ||
| 502 | health: iz_web::directory::DirectoryHealth, | 511 | health: iz_web::directory::DirectoryHealth, |
| 503 | ) { | 512 | ) { |
| 504 | let mut backoff = std::time::Duration::from_secs(1); | 513 | let mut backoff = std::time::Duration::from_secs(1); |
| 505 | loop { | 514 | loop { |
| 506 | mirror_directory(&store, &directory, &health).await; | 515 | mirror_directory(&store, &directory, &health).await; |
| 507 | - match directory.open_stream().await { | 516 | + match source.open_stream().await { |
| 508 | Ok(mut stream) => { | 517 | Ok(mut stream) => { |
| 509 | health.connected(); | 518 | health.connected(); |
| 510 | backoff = std::time::Duration::from_secs(1); | 519 | backoff = std::time::Duration::from_secs(1); |
| 511 | - while let Some(event) = stream.next().await { | 520 | + while let Some(frame) = stream.next().await { |
| 512 | - match event { | 521 | + match frame { |
| 513 | - Ok(im_client::directory::DirectoryEvent::Profile(member)) => { | 522 | + Ok(frame) => { |
| 514 | health.event(); | 523 | health.event(); |
| 515 | - apply_member(&store, &member).await; | 524 | + iz_web::directory::apply_frame(&store, frame).await; |
| 516 | } | 525 | } |
| 517 | Err(problem) => { | 526 | Err(problem) => { |
| 518 | eprintln!("directory stream: {problem}; re-listing"); | 527 | eprintln!("directory stream: {problem}; re-listing"); |
crates/iz-web/src/server.rsmodified+18 -1
| @@ -20,7 +20,10 @@ use topcoat::asset::AssetBundle; | |||
| 20 | use topcoat::context::{Cx, app_context, memoize, try_app_context}; | 20 | use topcoat::context::{Cx, app_context, memoize, try_app_context}; |
| 21 | use topcoat::cookie::{Cookies, cookies}; | 21 | use topcoat::cookie::{Cookies, cookies}; |
| 22 | use topcoat::router::request::headers; | 22 | use topcoat::router::request::headers; |
| 23 | -use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::Response, to_bytes}; | 23 | +use topcoat::router::{ |
| 24 | + route, Body, HeaderValue, Next, StatusCode, header, response::IntoResponse, response::Response, | ||
| 25 | + to_bytes, | ||
| 26 | +}; | ||
| 24 | 27 | ||
| 25 | /// The workspace store, put into context by the router. | 28 | /// The workspace store, put into context by the router. |
| 26 | pub fn store(cx: &Cx) -> Arc<dyn Store> { | 29 | pub fn store(cx: &Cx) -> Arc<dyn Store> { |
| @@ -328,6 +331,20 @@ pub async fn require_writer(cx: &Cx) -> Result<User, Refusal> { | |||
| 328 | } | 331 | } |
| 329 | } | 332 | } |
| 330 | 333 | ||
| 334 | +/// The lightweight am-I-signed-in probe the live script's error path asks: | ||
| 335 | +/// `204` with no body when the caller carries a live session, `401` when | ||
| 336 | +/// anything about the caller — no cookie, a revoked or disabled one, a | ||
| 337 | +/// store that cannot answer — says otherwise. It exists so a dropped live | ||
| 338 | +/// stream can tell "the server restarted" from "I was signed out" without | ||
| 339 | +/// fetching a page of HTML to learn it. | ||
| 340 | +#[route(GET "/api/me")] | ||
| 341 | +async fn me(cx: &Cx) -> topcoat::Result<Response> { | ||
| 342 | + match current_user(cx).await { | ||
| 343 | + Ok(Some(_)) => StatusCode::NO_CONTENT.into_response(cx), | ||
| 344 | + _ => (StatusCode::UNAUTHORIZED, "").into_response(cx), | ||
| 345 | + } | ||
| 346 | +} | ||
| 347 | + | ||
| 331 | impl From<StoreError> for Refusal { | 348 | impl From<StoreError> for Refusal { |
| 332 | fn from(error: StoreError) -> Self { | 349 | fn from(error: StoreError) -> Self { |
| 333 | eprintln!("store error: {error}"); | 350 | eprintln!("store error: {error}"); |
crates/iz-web/tests/http.rsmodified+175 -0
| @@ -28,6 +28,7 @@ use http::{HeaderValue, Request, StatusCode, header}; | |||
| 28 | use iz_core::Role; | 28 | use iz_core::Role; |
| 29 | use iz_core::board::Moved; | 29 | use iz_core::board::Moved; |
| 30 | use iz_core::store::{Audience, MailOutcome, SendKind, SendState, Store, Trigger, TursoStore}; | 30 | use iz_core::store::{Audience, MailOutcome, SendKind, SendState, Store, Trigger, TursoStore}; |
| 31 | +use iz_web::directory::{StreamFrame, StreamMember, apply_frame}; | ||
| 31 | use iz_web::server::Mail; | 32 | use iz_web::server::Mail; |
| 32 | use topcoat::asset::{AssetBundle, RouterBuilderAssetExt}; | 33 | use topcoat::asset::{AssetBundle, RouterBuilderAssetExt}; |
| 33 | use topcoat::cookie::RouterBuilderCookieExt; | 34 | use topcoat::cookie::RouterBuilderCookieExt; |
| @@ -7532,6 +7533,180 @@ async fn a_queued_mails_next_try_is_marked_for_the_tick() { | |||
| 7532 | ); | 7533 | ); |
| 7533 | } | 7534 | } |
| 7534 | 7535 | ||
| 7536 | +/// The lightweight probe the live script's error path asks. A live session | ||
| 7537 | +/// gets a bodyless yes; no cookie, or a session im no longer vouches for, | ||
| 7538 | +/// gets a plain 401 — so a dropped stream can be told apart from a signed- | ||
| 7539 | +/// out tab without fetching a page of HTML to learn it. | ||
| 7540 | +#[tokio::test] | ||
| 7541 | +async fn the_me_probe_answers_yes_only_to_a_live_session() { | ||
| 7542 | + let app = App::open().await; | ||
| 7543 | + let boss = admin(&app).await; | ||
| 7544 | + | ||
| 7545 | + let live = app.get("/api/me", Some(&boss)).await; | ||
| 7546 | + assert_eq!(live.status, StatusCode::NO_CONTENT); | ||
| 7547 | + assert!(live.bytes.is_empty(), "the probe answered a body"); | ||
| 7548 | + | ||
| 7549 | + let stranger = app.get("/api/me", None).await; | ||
| 7550 | + assert_eq!(stranger.status, StatusCode::UNAUTHORIZED); | ||
| 7551 | + | ||
| 7552 | + // The session revoked in im: once the fake stops vouching for the | ||
| 7553 | + // token, the probe refuses with no page to fetch first. | ||
| 7554 | + app.fake.tokens.lock().clear(); | ||
| 7555 | + let revoked = app.get("/api/me", Some(&boss)).await; | ||
| 7556 | + assert_eq!(revoked.status, StatusCode::UNAUTHORIZED); | ||
| 7557 | +} | ||
| 7558 | + | ||
| 7559 | +/// A session revocation heard off the directory stream is told to the whole | ||
| 7560 | +/// workspace — which session died is im's knowledge alone, so no connection | ||
| 7561 | +/// is named and no tab is sent away; every tab's own refetch, which | ||
| 7562 | +/// re-introspects per request, is what sorts out who is still signed in. | ||
| 7563 | +/// A tab whose other session survived therefore keeps its place. | ||
| 7564 | +#[tokio::test] | ||
| 7565 | +async fn a_session_revocation_announces_the_member_surface_to_everyone() { | ||
| 7566 | + let app = App::open().await; | ||
| 7567 | + let boss = admin(&app).await; | ||
| 7568 | + let bo = invited(&app, &boss, "bo@iz.sh", "Bo", Role::Member).await; | ||
| 7569 | + | ||
| 7570 | + let member_feed = app.live_open(Some(&bo)).await; | ||
| 7571 | + let admin_feed = app.live_open(Some(&boss)).await; | ||
| 7572 | + | ||
| 7573 | + apply_frame( | ||
| 7574 | + &app.store, | ||
| 7575 | + StreamFrame::Revoked { | ||
| 7576 | + sub: "im-bo@iz.sh".into(), | ||
| 7577 | + }, | ||
| 7578 | + ) | ||
| 7579 | + .await; | ||
| 7580 | + | ||
| 7581 | + let heard_by_admin = | ||
| 7582 | + live_until(admin_feed, "members", std::time::Duration::from_secs(10)).await; | ||
| 7583 | + assert!( | ||
| 7584 | + heard_by_admin.contains("members"), | ||
| 7585 | + "no members announcement: {heard_by_admin}" | ||
| 7586 | + ); | ||
| 7587 | + let heard_by_member = live_until( | ||
| 7588 | + member_feed, | ||
| 7589 | + "members", | ||
| 7590 | + std::time::Duration::from_millis(500), | ||
| 7591 | + ) | ||
| 7592 | + .await; | ||
| 7593 | + assert!( | ||
| 7594 | + heard_by_member.contains("members"), | ||
| 7595 | + "the member was not told the member surface moved: {heard_by_member}" | ||
| 7596 | + ); | ||
| 7597 | + assert!( | ||
| 7598 | + !heard_by_admin.contains("revoked") && !heard_by_member.contains("revoked"), | ||
| 7599 | + "a session revocation named a connection: {heard_by_admin} / {heard_by_member}" | ||
| 7600 | + ); | ||
| 7601 | +} | ||
| 7602 | + | ||
| 7603 | +/// A profile arriving `disabled` is a user-level kill: the local row is | ||
| 7604 | +/// disabled through the same store path an admin's hand uses, the | ||
| 7605 | +/// account's own tab is named with the `revoked` topic — and only that | ||
| 7606 | +/// tab — and the row's next probe reads as signed out, exactly as any | ||
| 7607 | +/// refetch would find it. | ||
| 7608 | +#[tokio::test] | ||
| 7609 | +async fn a_disabled_member_is_named_once_and_signed_out_everywhere() { | ||
| 7610 | + let app = App::open().await; | ||
| 7611 | + let boss = admin(&app).await; | ||
| 7612 | + let bo = invited(&app, &boss, "bo@iz.sh", "Bo", Role::Member).await; | ||
| 7613 | + | ||
| 7614 | + let member_feed = app.live_open(Some(&bo)).await; | ||
| 7615 | + let admin_feed = app.live_open(Some(&boss)).await; | ||
| 7616 | + | ||
| 7617 | + apply_frame( | ||
| 7618 | + &app.store, | ||
| 7619 | + StreamFrame::Profile(StreamMember { | ||
| 7620 | + sub: "im-bo@iz.sh".into(), | ||
| 7621 | + email: "bo@iz.sh".into(), | ||
| 7622 | + name: "Bo".into(), | ||
| 7623 | + admin: false, | ||
| 7624 | + photo_version: 0, | ||
| 7625 | + timezone: "UTC+03:00".into(), | ||
| 7626 | + disabled: true, | ||
| 7627 | + }), | ||
| 7628 | + ) | ||
| 7629 | + .await; | ||
| 7630 | + | ||
| 7631 | + // The account's own connection is named — the goodbye frame the client | ||
| 7632 | + // answers with a hard redirect. | ||
| 7633 | + let goodbye = live_until(member_feed, "revoked", std::time::Duration::from_secs(10)).await; | ||
| 7634 | + assert!( | ||
| 7635 | + goodbye.contains("revoked"), | ||
| 7636 | + "the disabled member's tab was not named: {goodbye}" | ||
| 7637 | + ); | ||
| 7638 | + | ||
| 7639 | + // The workspace heard the member surface move; nobody else was named. | ||
| 7640 | + let heard_by_admin = | ||
| 7641 | + live_until(admin_feed, "members", std::time::Duration::from_secs(10)).await; | ||
| 7642 | + assert!( | ||
| 7643 | + heard_by_admin.contains("members"), | ||
| 7644 | + "no members announcement: {heard_by_admin}" | ||
| 7645 | + ); | ||
| 7646 | + assert!( | ||
| 7647 | + !heard_by_admin.contains("revoked"), | ||
| 7648 | + "an uninvolved tab was named: {heard_by_admin}" | ||
| 7649 | + ); | ||
| 7650 | + | ||
| 7651 | + // The row itself, and the seam every refetch would hit. | ||
| 7652 | + let user = app | ||
| 7653 | + .store | ||
| 7654 | + .user_by_sub("im-bo@iz.sh") | ||
| 7655 | + .await | ||
| 7656 | + .unwrap() | ||
| 7657 | + .expect("the disabled member had no local row"); | ||
| 7658 | + assert!(user.disabled); | ||
| 7659 | + assert_eq!( | ||
| 7660 | + app.get("/api/me", Some(&bo)).await.status, | ||
| 7661 | + StatusCode::UNAUTHORIZED | ||
| 7662 | + ); | ||
| 7663 | +} | ||
| 7664 | + | ||
| 7665 | +/// im owns the account's life both ways: the same stream that kills the | ||
| 7666 | +/// row brings it back. A disable lands, then a re-enable — the local flag | ||
| 7667 | +/// follows each, and the member's own probe reads signed-in again, with | ||
| 7668 | +/// no revoked naming on the way back in. | ||
| 7669 | +#[tokio::test] | ||
| 7670 | +async fn a_reenabled_member_is_signed_back_in() { | ||
| 7671 | + let app = App::open().await; | ||
| 7672 | + let _boss = admin(&app).await; | ||
| 7673 | + let bo = member(&app, "bo@iz.sh", "Bo").await; | ||
| 7674 | + | ||
| 7675 | + let disabled = StreamMember { | ||
| 7676 | + sub: "im-bo@iz.sh".into(), | ||
| 7677 | + email: "bo@iz.sh".into(), | ||
| 7678 | + name: "Bo".into(), | ||
| 7679 | + admin: false, | ||
| 7680 | + photo_version: 0, | ||
| 7681 | + timezone: "UTC+03:00".into(), | ||
| 7682 | + disabled: true, | ||
| 7683 | + }; | ||
| 7684 | + apply_frame(&app.store, StreamFrame::Profile(disabled.clone())).await; | ||
| 7685 | + assert!( | ||
| 7686 | + app.store | ||
| 7687 | + .user_by_sub("im-bo@iz.sh") | ||
| 7688 | + .await | ||
| 7689 | + .unwrap() | ||
| 7690 | + .expect("no local row") | ||
| 7691 | + .disabled, | ||
| 7692 | + "the stream did not disable the row" | ||
| 7693 | + ); | ||
| 7694 | + | ||
| 7695 | + let enabled = StreamMember { disabled: false, ..disabled }; | ||
| 7696 | + apply_frame(&app.store, StreamFrame::Profile(enabled)).await; | ||
| 7697 | + assert!( | ||
| 7698 | + !app | ||
| 7699 | + .store | ||
| 7700 | + .user_by_sub("im-bo@iz.sh") | ||
| 7701 | + .await | ||
| 7702 | + .unwrap() | ||
| 7703 | + .expect("no local row") | ||
| 7704 | + .disabled, | ||
| 7705 | + "the stream did not re-enable the row" | ||
| 7706 | + ); | ||
| 7707 | + assert_eq!(app.get("/api/me", Some(&bo)).await.status, StatusCode::NO_CONTENT); | ||
| 7708 | +} | ||
| 7709 | + | ||
| 7535 | /// A live update changes only what actually changed. It morphs the fetched | 7710 | /// A live update changes only what actually changed. It morphs the fetched |
| 7536 | /// document onto the live one instead of replacing the body, which is what | 7711 | /// document onto the live one instead of replacing the body, which is what |
| 7537 | /// leaves an open dropdown open, a caret where it was and a half-typed comment | 7712 | /// leaves an open dropdown open, a caret where it was and a half-typed comment |