forge
Explore
Log in

Don't you dare go Hollow

Settings pages update live, and the theme follows into every open tab

Browse files at this commit

d7d6a17efcfe64929e095166244b4689846a4811Ahmet Kaan GümüşParent: 72169d5
  • feat
    • settings pages update live, and the theme follows into every open tab
Show full message
⚡ feat: settings pages update live, and the theme follows into every open tab
crates/forge-web/src/api/mod.rsmodified+1 -0
@@ -114,6 +114,7 @@ pub async fn authenticate(
114114 if let Err(e) = state.store.touch_token(&token_id).await {
115115 return Err(internal(e));
116116 }
117+ crate::pages::settings_live::bump_account(state, &user.id);
117118 Ok(Some(user))
118119 }
119120
crates/forge-web/src/api/packages.rsmodified+1 -0
@@ -59,6 +59,7 @@ async fn caller(cx: &Cx, scope_required: bool) -> Result<Option<User>, Refusal>
5959 if let Err(e) = state.store.touch_token(&token_id).await {
6060 return Err(Box::new(failure(PackageError::Internal(e.to_string()))));
6161 }
62+ crate::pages::settings_live::bump_account(state, &user.id);
6263 Ok(Some(user))
6364 }
6465
crates/forge-web/src/auth.rsmodified+4 -0
@@ -83,6 +83,10 @@ pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {
8383 user_agent(cx).as_deref(),
8484 )
8585 .await?;
86+ // A new sign-in shows up in the user's session list in their other open tabs.
87+ app_context::<AppState>(cx)
88+ .live
89+ .bump(&crate::live::Topic::Account(user.id.clone()));
8690 let max_age = time::Duration::seconds(i64::try_from(SESSION_TTL.as_secs()).unwrap_or(i64::MAX));
8791 session_jar(cx).add(
8892 Cookie::build((SESSION_COOKIE, token))
crates/forge-web/src/boot.rsmodified+1 -0
@@ -165,6 +165,7 @@ pub async fn serve(
165165 let public: Router = Router::builder()
166166 .discover()
167167 .app_context(state.clone())
168+ .layer(crate::pages::settings_live::AccountWriteLayer)
168169 .cookies()
169170 .layer(crate::pages::settings_profile::avatar_body_limit())
170171 .layer(crate::pages::repo_ctx::RepoMovedLayer)
crates/forge-web/src/git_auth.rsmodified+1 -0
@@ -72,6 +72,7 @@ pub async fn user_from_basic(
7272 .touch_token(&access.id)
7373 .await
7474 .map_err(internal)?;
75+ crate::pages::settings_live::bump_account(state, &user.id);
7576 Ok(Some(user))
7677 }
7778
crates/forge-web/src/live.rsmodified+4 -0
@@ -103,6 +103,10 @@ pub enum Topic {
103103 /// replaced or removed, or an asset was downloaded (its count). Keyed by repo id. The release
104104 /// list and the release pages follow it. Bumped by [`crate::release_ops`].
105105 RepoReleases(String),
106+ /// A user's own settings: a profile, key, token, passkey, session, notification or appearance
107+ /// setting changed, or a sign-in or a key or token use happened. Keyed by user id. Streamed only
108+ /// to that user, never to the public profile viewers who follow [`Topic::User`].
109+ Account(String),
106110 }
107111
108112 /// The hub of the admin pages. It is process-wide, not part of [`crate::state::AppState`]: the
crates/forge-web/src/pages/admin_mail.rsmodified+4 -0
@@ -948,6 +948,10 @@ mod tests {
948948 settings.contains(r#"data-live="/admin/mail/events""#),
949949 "the settings tab is live too"
950950 );
951+ assert!(
952+ settings.contains(r#"data-live="/settings/theme/events""#),
953+ "the theme follows into the admin pages"
954+ );
951955 assert!(
952956 !settings.contains("Reset your password"),
953957 "the queue is on its own tab"
crates/forge-web/src/pages/admin_server.rsmodified+1 -0
@@ -886,6 +886,7 @@ mod tests {
886886 let page = admin_get(&fx, "/admin/server?restarting=an-older-boot").await;
887887 assert!(!page.contains("Restarting..."));
888888 assert!(page.contains(r#"data-live="/admin/server/events""#));
889+ assert!(page.contains(r#"data-live="/settings/theme/events""#));
889890 assert!(page.contains("The server restarted"));
890891 }
891892
crates/forge-web/src/pages/ci_tests.rsmodified+14 -3
@@ -340,7 +340,10 @@ async fn pages_are_live_while_not_finished_and_never_meta_refresh() {
340340 finish_job(&fx).await;
341341 let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await;
342342 assert!(
343- !done.text().contains("data-live="),
343+ !done
344+ .text()
345+ .replace(r#"data-live="/settings/theme/events""#, "")
346+ .contains("data-live="),
344347 "job not live when finished"
345348 );
346349 assert!(
@@ -504,7 +507,13 @@ async fn run_list_is_live_on_page_one_only() {
504507 Some(&cookie_for("tahinli-token")),
505508 )
506509 .await;
507- assert!(!second.text().contains("data-live="), "page 2 is not live");
510+ assert!(
511+ !second
512+ .text()
513+ .replace(r#"data-live="/settings/theme/events""#, "")
514+ .contains("data-live="),
515+ "page 2 is not live"
516+ );
508517 let run = get(
509518 &fx.app,
510519 &format!("{RUN_BASE}/runs/30?page=2"),
@@ -512,7 +521,9 @@ async fn run_list_is_live_on_page_one_only() {
512521 )
513522 .await;
514523 assert!(
515- !run.text().contains("data-live="),
524+ !run.text()
525+ .replace(r#"data-live="/settings/theme/events""#, "")
526+ .contains("data-live="),
516527 "a run on page 2 is not live"
517528 );
518529 }
crates/forge-web/src/pages/mod.rsmodified+1 -0
@@ -121,6 +121,7 @@ pub mod settings_gpg;
121121 #[cfg(test)]
122122 mod settings_gpg_tests;
123123 pub mod settings_keys;
124+pub mod settings_live;
124125 pub mod settings_notifications;
125126 pub mod settings_profile;
126127 pub mod settings_security;
crates/forge-web/src/pages/settings_live.rsadded+236 -0
@@ -0,0 +1,236 @@
1+//! Live settings. The signed-in user's own settings pages (`/settings/...`) follow
2+//! [`Topic::Account`] of their own user through `GET /settings/events`. The settings section of the
3+//! sidebar names that stream (see `views::section_for`), so every page under `/settings` follows it
4+//! without an attribute of its own. Public profile viewers follow [`Topic::User`] and never wake.
5+//!
6+//! Writes reach the topic two ways:
7+//! - A POST under `/settings/` (a profile, key, token, passkey, session, notification, appearance
8+//! or security change): [`AccountWriteLayer`] bumps the viewer's topic after the handler ran, so
9+//! no route calls a bump itself. A refused write bumps too: the page re-reads and agrees.
10+//! - Anything outside those paths that changes what the pages show: a sign-in (`auth::login`), and
11+//! a key or token used by git, the API, SSH or a package client. Those call [`bump_account`].
12+//!
13+//! The stream sends `changed` on each wake and carries no data: the page re-reads itself. A session
14+//! revoked elsewhere is caught the same way. The re-read finds no session, so the page leaves for
15+//! the login page.
16+
17+use topcoat::Result;
18+use topcoat::context::{Cx, app_context};
19+use topcoat::router::request::{method, uri};
20+use topcoat::router::response::Response;
21+use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode, route};
22+
23+use crate::auth::current_user;
24+use crate::live::{LiveHub, Topic, stream_changes, stream_wakes};
25+use crate::state::AppState;
26+
27+/// Wakes the settings pages of `user_id`. Called after a write that changes what they show.
28+pub fn bump_account(state: &AppState, user_id: &str) {
29+ state.live.bump(&Topic::Account(user_id.to_owned()));
30+}
31+
32+/// The change stream of the viewer's settings. The viewer comes from the session only, so a user
33+/// can follow only their own settings. Without a session: 401.
34+#[route(GET "/settings/events")]
35+async fn settings_events(cx: &Cx) -> Result<Response> {
36+ let Some((user, _)) = current_user(cx).await? else {
37+ let mut res = Response::new(Body::empty());
38+ *res.status_mut() = StatusCode::UNAUTHORIZED;
39+ return Ok(res);
40+ };
41+ let hub: &LiveHub = &app_context::<AppState>(cx).live;
42+ stream_wakes(cx, hub, &[Topic::Account(user.id)])
43+}
44+
45+/// The appearance stream of a signed-in user's tabs. The shell of every signed-in page follows it,
46+/// so a theme, accent, base, language or sidebar change made in one tab reaches the others. It
47+/// sends `changed` only when the appearance differs from what the page shows.
48+#[route(GET "/settings/theme/events")]
49+async fn theme_events(cx: &Cx) -> Result<Response> {
50+ let Some((user, _)) = current_user(cx).await? else {
51+ let mut res = Response::new(Body::empty());
52+ *res.status_mut() = StatusCode::UNAUTHORIZED;
53+ return Ok(res);
54+ };
55+ let state = app_context::<AppState>(cx).clone();
56+ let topics = [Topic::Account(user.id.clone())];
57+ let user_id = user.id;
58+ stream_changes(cx, &state.live.clone(), &topics, move || {
59+ let state = state.clone();
60+ let user_id = user_id.clone();
61+ async move { appearance_fingerprint(&state, &user_id).await }
62+ })
63+ .await
64+}
65+
66+/// The appearance fields of a user, as one line. Compared, never sent.
67+async fn appearance_fingerprint(state: &AppState, user_id: &str) -> Result<String> {
68+ let Some(user) = state.store.user_by_id(user_id).await? else {
69+ return Ok(String::new());
70+ };
71+ Ok(format!(
72+ "{}|{}|{}|{}|{}|{}|{}",
73+ user.theme,
74+ user.language,
75+ user.accent,
76+ user.accent_dark,
77+ user.base_light,
78+ user.base_dark,
79+ user.sidebar_side
80+ ))
81+}
82+
83+/// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router
84+/// in `boot.rs` and the test router. It sits on a path, so it runs inside the cookie layer (a
85+/// pathless layer would run outside it, where the session cannot be read).
86+pub struct AccountWriteLayer;
87+
88+impl Layer for AccountWriteLayer {
89+ fn path(&self) -> Option<&Path> {
90+ Some(Path::new("/settings"))
91+ }
92+
93+ fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
94+ Box::pin(bump_after_settings_write(cx, body, next))
95+ }
96+}
97+
98+/// Bumps the viewer's topic once the handler has run. The viewer is read before the handler, so a
99+/// write that ends the viewer's own session (a revoke of the current one) still wakes the tabs.
100+async fn bump_after_settings_write(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> {
101+ if *method(cx) != Method::POST || !uri(cx).path().starts_with("/settings/") {
102+ return next.run(cx, body).await;
103+ }
104+ let viewer = current_user(cx)
105+ .await
106+ .ok()
107+ .flatten()
108+ .map(|(user, _)| user.id);
109+ let result = next.run(cx, body).await;
110+ if let Some(user_id) = viewer {
111+ bump_account(app_context::<AppState>(cx), &user_id);
112+ }
113+ result
114+}
115+
116+#[cfg(test)]
117+mod tests {
118+ use futures_util::StreamExt;
119+ use topcoat::router::request::Request;
120+ use topcoat::router::{Body, to_bytes};
121+
122+ use crate::auth::SESSION_COOKIE;
123+ use crate::live::Topic;
124+ use crate::test_support::{app_router, create_session, test_state};
125+
126+ const CSRF: &str = "settings-live-csrf";
127+
128+ #[tokio::test]
129+ async fn the_stream_needs_a_session() {
130+ let dir = tempfile::tempdir().expect("tempdir");
131+ let router = app_router(test_state(dir.path()).await);
132+ let request = Request::builder()
133+ .method("GET")
134+ .uri("/settings/events")
135+ .body(Body::empty())
136+ .expect("request");
137+ assert_eq!(router.handle(request).await.status().as_u16(), 401);
138+ }
139+
140+ #[tokio::test]
141+ async fn the_theme_stream_needs_a_session_and_the_settings_name_their_streams() {
142+ let dir = tempfile::tempdir().expect("tempdir");
143+ let state = test_state(dir.path()).await;
144+ let store = state.store.clone();
145+ let owner = store
146+ .create_user("tahinli", None, "h", false)
147+ .await
148+ .expect("user");
149+ create_session(&store, &owner.id, "owner-token", CSRF).await;
150+ let router = app_router(state);
151+
152+ let anon = Request::builder()
153+ .method("GET")
154+ .uri("/settings/theme/events")
155+ .body(Body::empty())
156+ .expect("request");
157+ assert_eq!(router.handle(anon).await.status().as_u16(), 401);
158+
159+ let page = Request::builder()
160+ .method("GET")
161+ .uri("/settings/profile")
162+ .header("cookie", format!("__Host-{SESSION_COOKIE}=owner-token"))
163+ .body(Body::empty())
164+ .expect("request");
165+ let res = router.handle(page).await;
166+ let html =
167+ String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.expect("body"))
168+ .into_owned();
169+ assert!(html.contains("<body") && html.contains("data-live=\"/settings/theme/events\""));
170+ assert!(html.contains("data-live=\"/settings/events\""));
171+ }
172+
173+ #[tokio::test]
174+ async fn a_write_under_settings_wakes_only_the_writers_own_topic() {
175+ let dir = tempfile::tempdir().expect("tempdir");
176+ let state = test_state(dir.path()).await;
177+ let store = state.store.clone();
178+ let live = state.live.clone();
179+ let owner = store
180+ .create_user("tahinli", None, "h", false)
181+ .await
182+ .expect("user");
183+ let other = store
184+ .create_user("mallory", None, "h", false)
185+ .await
186+ .expect("user");
187+ create_session(&store, &owner.id, "owner-token", CSRF).await;
188+ create_session(&store, &other.id, "other-token", CSRF).await;
189+ let owner_wake = live.subscribe(&Topic::Account(owner.id.clone()));
190+ let other_wake = live.subscribe(&Topic::Account(other.id.clone()));
191+ let router = app_router(state);
192+
193+ let request = Request::builder()
194+ .method("POST")
195+ .uri("/settings/keys/delete")
196+ .header("cookie", format!("__Host-{SESSION_COOKIE}=owner-token"))
197+ .header("content-type", "application/x-www-form-urlencoded")
198+ .body(Body::from(format!("csrf={CSRF}&id=none")))
199+ .expect("request");
200+ let res = router.handle(request).await;
201+ to_bytes(res.into_body(), usize::MAX).await.expect("body");
202+
203+ assert!(owner_wake.has_changed().expect("open"));
204+ assert!(!other_wake.has_changed().expect("open"));
205+ }
206+
207+ #[tokio::test]
208+ async fn the_stream_sends_a_changed_event_per_write() {
209+ let dir = tempfile::tempdir().expect("tempdir");
210+ let state = test_state(dir.path()).await;
211+ let store = state.store.clone();
212+ let live = state.live.clone();
213+ let owner = store
214+ .create_user("tahinli", None, "h", false)
215+ .await
216+ .expect("user");
217+ create_session(&store, &owner.id, "owner-token", CSRF).await;
218+ let router = app_router(state);
219+
220+ let request = Request::builder()
221+ .method("GET")
222+ .uri("/settings/events")
223+ .header("cookie", format!("__Host-{SESSION_COOKIE}=owner-token"))
224+ .body(Body::empty())
225+ .expect("request");
226+ let res = router.handle(request).await;
227+ assert_eq!(res.status().as_u16(), 200);
228+ let mut frames = res.into_body().into_data_stream();
229+ let retry = frames.next().await.expect("a frame").expect("data");
230+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
231+
232+ live.bump(&Topic::Account(owner.id.clone()));
233+ let changed = frames.next().await.expect("a frame").expect("data");
234+ assert_eq!(&changed[..], b"event: changed\ndata: 1\n\n");
235+ }
236+}
crates/forge-web/src/ssh_backend.rsmodified+1 -0
@@ -75,6 +75,7 @@ impl GitBackend for SshBackend {
7575 if let Err(e) = self.state.store.touch_ssh_key(&key.id).await {
7676 tracing::warn!(error = %e, "could not record ssh key use");
7777 }
78+ crate::pages::settings_live::bump_account(&self.state, &key.user_id);
7879 // A key that belongs to an organization is refused here, not only in `authorize`.
7980 match self.state.store.user_by_id(&key.user_id).await {
8081 Ok(Some(owner)) if !owner.is_org() => Some(key.user_id),
crates/forge-web/src/test_support.rsmodified+1 -0
@@ -97,6 +97,7 @@ pub fn app_router(state: AppState) -> Router {
9797 Router::builder()
9898 .discover()
9999 .app_context(state)
100+ .layer(crate::pages::settings_live::AccountWriteLayer)
100101 .cookies()
101102 .layer(avatar_body_limit())
102103 .layer(RepoMovedLayer)
crates/forge-web/src/views/mod.rsmodified+18 -4
@@ -165,6 +165,8 @@ pub async fn shell(
165165 let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned());
166166 let lang = i18n::lang(__cx, viewer.map(|(user, _)| user));
167167 let banner = crate::pages::banner::current(__cx);
168+ // A signed-in tab follows its appearance, so a change in another tab applies here too.
169+ let theme_live = signed_in.then_some("/settings/theme/events");
168170 let banner_back = back.clone().unwrap_or_else(|| "/".to_owned());
169171 let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss);
170172 // The admin area and the user settings swap the global links for their own list. Signed-in only.
@@ -267,7 +269,7 @@ pub async fn shell(
267269 }
268270 <script src=(NAV_SCRIPT_HREF) defer="defer"></script>
269271 </head>
270- <body data-link-restarting=(lk::t(lang, LinkKey::Restarting)) data-link-back=(lk::t(lang, LinkKey::BackSubmit))>
272+ <body data-link-restarting=(lk::t(lang, LinkKey::Restarting)) data-link-back=(lk::t(lang, LinkKey::BackSubmit)) data-live=(theme_live)>
271273 <header class="topbar">
272274 if signed_in {
273275 <details class="nav-toggle">
@@ -276,7 +278,7 @@ pub async fn shell(
276278 </summary>
277279 <div class="nav-panel">
278280 if let Some(section) = section_menu {
279- section_nav(title: section.title.as_str(), back: section.back, items: section.items, current: section.current)
281+ section_nav(title: section.title.as_str(), back: section.back, items: section.items, current: section.current, live: section.live)
280282 } else {
281283 side_nav(lang: lang, current: current, unread: unread_menu, repos: side_repos_menu)
282284 }
@@ -363,7 +365,7 @@ pub async fn shell(
363365 if signed_in {
364366 <aside class="shell-sidebar">
365367 if let Some(section) = section {
366- section_nav(title: section.title.as_str(), back: section.back, items: section.items, current: section.current)
368+ section_nav(title: section.title.as_str(), back: section.back, items: section.items, current: section.current, live: section.live)
367369 } else {
368370 side_nav(lang: lang, current: current, unread: unread_aside, repos: side_repos)
369371 }
@@ -472,6 +474,8 @@ pub struct Section {
472474 pub back: &'static str,
473475 pub items: Vec<NavItem>,
474476 pub current: &'static str,
477+ /// The stream the section's pages follow, or empty when they follow none.
478+ pub live: &'static str,
475479 }
476480
477481 fn admin_items(lang: Lang) -> Vec<NavItem> {
@@ -623,6 +627,7 @@ pub fn section_for(lang: Lang, path: &str) -> Option<Section> {
623627 back: t(lang, Key::BackToSite),
624628 items,
625629 current,
630+ live: "",
626631 });
627632 }
628633 _ => return None,
@@ -631,11 +636,18 @@ pub fn section_for(lang: Lang, path: &str) -> Option<Section> {
631636 .iter()
632637 .find(|item| item.key == second)
633638 .map_or("", |item| item.key);
639+ // Every page of the user's settings follows their own change stream (see `pages::settings_live`).
640+ let live = if first == "settings" {
641+ "/settings/events"
642+ } else {
643+ ""
644+ };
634645 Some(Section {
635646 title,
636647 back: t(lang, Key::BackToSite),
637648 items,
638649 current,
650+ live,
639651 })
640652 }
641653
@@ -647,7 +659,9 @@ async fn section_nav(
647659 back: &str,
648660 items: Vec<NavItem>,
649661 current: &str,
662+ live: &str,
650663 ) -> Result<impl View> {
664+ let live = (!live.is_empty()).then_some(live);
651665 let links: Vec<(NavItem, bool)> = items
652666 .into_iter()
653667 .map(|item| {
@@ -664,7 +678,7 @@ async fn section_nav(
664678 </nav>
665679 <div class="side-group">
666680 <h2 class="side-h">(title)</h2>
667- <nav class="side-links" aria-label=(title)>
681+ <nav class="side-links" aria-label=(title) data-live=(live)>
668682 for (item, on) in links.into_iter() {
669683 <a class=(side_class(on)) href=(item.href) aria-current=(on.then_some("page"))>
670684 nav_icon(name: item.icon)
docs/architecture.mdmodified+3 -0
@@ -272,9 +272,12 @@ Pages update without a reload. A write that changes what a page shows calls `Liv
272272 | Admin replication `/admin/replication` | `/admin/replication/events` | each copy's status and the database snapshot |
273273 | Admin health `/admin/health` | `/admin/health/events` | the alerts, the counts and the mail queue. The disk and tree probes are read when the page renders, not on each change |
274274 | Admin server `/admin/server` | `/admin/server/events` | saved or reset settings. A page waiting for a restart gets one event when a new process answers |
275+| Settings `/settings/...` (profile, keys, GPG, tokens, sessions, security, passkeys, notifications, appearance, export) | `/settings/events` (the section sidebar), `/settings/theme/events` (every signed-in page) | the viewer's own account topic: a setting, key, token, passkey or session changed, or a sign-in or key use happened. The theme stream sends only when the appearance (theme, accents, base, language, sidebar side) differs. A revoked current session leaves for the login page on the next re-read |
275276
276277 The org streams follow the same access as their pages: a non-member gets 404, and a member who is not an owner gets 403 on the settings stream. A team page names only the linked repos the viewer may read. Each org write (a POST under `/org/{org}/members`, `teams` or `settings`) wakes the org's streams. The org notices (for example "Member added.") are carried in the redirect's `?notice=` query, not a cookie, so a live refresh of the page shows the same notice again.
277278
279+The user topics are keyed by user id, and their streams take the viewer from the session, so no URL names another user's inbox. The account topic (`Topic::Account`) is keyed the same way and is never sent to a public profile viewer. Repo streams follow the same visibility as the repo page (a private repo answers 404 to a viewer who cannot read it). Explore lists public repos only.
280+
278281 The user topics are keyed by user id, and their streams take the viewer from the session, so no URL names another user's inbox. Repo streams follow the same visibility as the repo page (a private repo answers 404 to a viewer who cannot read it). Explore lists public repos only. The admin streams answer 404 to anyone who is not an instance admin, like the admin pages they serve. Every audited write also wakes the account pages of the users it names, so a login or a passkey change updates the account's facts. The admin pages' hub is process-wide (`live::admin()`), because the audit writer has no app state.
279282
280283 The release list and release pages follow `RepoReleases` (`/{owner}/{repo}/releases/events` and `/{owner}/{repo}/releases/tag/{tag}/events`). A page can hold several streams at once: the repo header (`/{owner}/{repo}/events`) sits above the page's own list, issue, pull or run. `nav.js` opens one EventSource for each distinct `data-live` URL in the page, so each of them updates the page.