A session on Settings → Sessions opens its details in a popup (user agent, sign-in and last IP, times) instead of a page, and a session from before IPs were recorded says "Not recorded"
Browse files at this commitdcdcd272ebe9cfa730d4c78e4125a1d61317c01bParent: c0cdb72- feat
- a session on Settings → Sessions opens its details in a popup (user agent, sign-in and last IP, times) instead of a page, and a session from before IPs were recorded says "Not recorded"
- the shell's live updates (online, unread, activity, repo side) come over one stream, /-/shell/events, so a page no longer opens six event streams and hangs the next navigation on HTTP/1.1
- clippy is clean on Rust 1.99
17 changed files +380 -90
- crates/forge-runner/src/executor.rs +1 -2
- crates/forge-web/assets/nav.js +56 -44
- crates/forge-web/src/i18n/mod.rs +8 -0
- crates/forge-web/src/live.rs +26 -5
- crates/forge-web/src/pages/activity.rs +14 -4
- crates/forge-web/src/pages/ci_runs.rs +9 -7
- crates/forge-web/src/pages/dashboard.rs +18 -1
- crates/forge-web/src/pages/mod.rs +1 -0
- crates/forge-web/src/pages/notifications.rs +19 -10
- crates/forge-web/src/pages/register.rs +1 -2
- crates/forge-web/src/pages/repo_side.rs +1 -0
- crates/forge-web/src/pages/settings_live.rs +13 -2
- crates/forge-web/src/pages/settings_sessions.rs +71 -10
- crates/forge-web/src/pages/shell_events.rs +88 -0
- crates/forge-web/src/repo_stats.rs +2 -2
- crates/forge-web/src/views/mod.rs +1 -1
- style/_account_admin.scss +51 -0
crates/forge-runner/src/executor.rsmodified+1 -2
| @@ -1096,8 +1096,7 @@ mod tests { | |||
| 1096 | #[test] | 1096 | #[test] |
| 1097 | fn parallelism_defaults_follow_the_cpu_limit_and_job_env_wins() { | 1097 | fn parallelism_defaults_follow_the_cpu_limit_and_job_env_wins() { |
| 1098 | let mut job = fixture_job("true"); | 1098 | let mut job = fixture_job("true"); |
| 1099 | - let mut limits = Limits::default(); | 1099 | + let limits = Limits { cpus: "0.5".to_owned(), ..Limits::default() }; |
| 1100 | - limits.cpus = "0.5".to_owned(); | ||
| 1101 | let env = job_env_with_defaults(&job, &limits).expect("env"); | 1100 | let env = job_env_with_defaults(&job, &limits).expect("env"); |
| 1102 | assert!(env.contains(&("CARGO_BUILD_JOBS".to_owned(), "1".to_owned()))); | 1101 | assert!(env.contains(&("CARGO_BUILD_JOBS".to_owned(), "1".to_owned()))); |
| 1103 | job.env.insert("CARGO_BUILD_JOBS".to_owned(), "7".to_owned()); | 1102 | job.env.insert("CARGO_BUILD_JOBS".to_owned(), "7".to_owned()); |
crates/forge-web/assets/nav.jsmodified+56 -44
| @@ -192,8 +192,6 @@ | |||
| 192 | syncLog(); | 192 | syncLog(); |
| 193 | followTail(); | 193 | followTail(); |
| 194 | restoreJobs(jobs); | 194 | restoreJobs(jobs); |
| 195 | - syncUnread(); | ||
| 196 | - syncActivity(); | ||
| 197 | syncLive(); | 195 | syncLive(); |
| 198 | syncPush(); | 196 | syncPush(); |
| 199 | syncTick(); | 197 | syncTick(); |
| @@ -549,8 +547,10 @@ | |||
| 549 | }; | 547 | }; |
| 550 | } | 548 | } |
| 551 | 549 | ||
| 552 | - // Every page holds one stream to /-/alive (no data, no login). Its error means the server, or the | 550 | + // Every page holds one stream to /-/shell/events (`/-/alive` for a page from before a deploy, and for |
| 553 | - // proxy in front of it, is down; its open means it is back. | 551 | + // an anonymous visitor the same alive events). Its error means the server, or the proxy in front of |
| 552 | + // it, is down; its open means it is back. Signed-in viewers also get `unread` (the inbox count), | ||
| 553 | + // `activity` (the live strip and ring) and `side` (the sidebar's repo list) on the same connection. | ||
| 554 | // A `theme` event carries the signed-in user's appearance as `name=value` pairs joined by `;` | 554 | // A `theme` event carries the signed-in user's appearance as `name=value` pairs joined by `;` |
| 555 | // (the `<html>` attributes). An empty value removes the attribute. Only data-* names are applied. | 555 | // (the `<html>` attributes). An empty value removes the attribute. Only data-* names are applied. |
| 556 | function applyAppearance(data) { | 556 | function applyAppearance(data) { |
| @@ -588,13 +588,19 @@ | |||
| 588 | if (link.down) { armBanner(); } | 588 | if (link.down) { armBanner(); } |
| 589 | } | 589 | } |
| 590 | if (window.EventSource) { | 590 | if (window.EventSource) { |
| 591 | - alive = keepOpen('/-/alive', aliveOpen, aliveDown, { | 591 | + alive = keepOpen('/-/shell/events', aliveOpen, aliveDown, { |
| 592 | theme: applyAppearance, | 592 | theme: applyAppearance, |
| 593 | language: function () { refreshLive(true); }, | 593 | language: function () { refreshLive(true); }, |
| 594 | // The header's identity (username, avatar, admin rights) or the session changed: the page re-renders. | 594 | // The header's identity (username, avatar, admin rights) or the session changed: the page re-renders. |
| 595 | account: function () { refreshLive(true); }, | 595 | account: function () { refreshLive(true); }, |
| 596 | // A live server setting changed (the banner, registration, limits...): the page re-renders. | 596 | // A live server setting changed (the banner, registration, limits...): the page re-renders. |
| 597 | - settings: function () { refreshLive(true); } | 597 | + settings: function () { refreshLive(true); }, |
| 598 | + // The inbox count changed (see `unreadChanged` above). | ||
| 599 | + unread: unreadChanged, | ||
| 600 | + // The viewer's activity changed: the strip, ring and chips are fetched again. | ||
| 601 | + activity: function () { refreshActivity(); }, | ||
| 602 | + // The sidebar's repo list changed (the sidebar is re-rendered with the page). | ||
| 603 | + side: sideChanged | ||
| 598 | }); | 604 | }); |
| 599 | document.addEventListener('visibilitychange', function () { wake(false); }); | 605 | document.addEventListener('visibilitychange', function () { wake(false); }); |
| 600 | document.addEventListener('resume', function () { wake(true); }); | 606 | document.addEventListener('resume', function () { wake(true); }); |
| @@ -1233,12 +1239,10 @@ | |||
| 1233 | // A filtered view asked for in place: the URL is replaced (no history entry per change), fields | 1239 | // A filtered view asked for in place: the URL is replaced (no history entry per change), fields |
| 1234 | // and caret come through the swap, and the scroll stays put. | 1240 | // and caret come through the swap, and the scroll stays put. |
| 1235 | // Live unread count. The profile corner (data-unread-stream) is re-rendered by every swap, so it is | 1241 | // Live unread count. The profile corner (data-unread-stream) is re-rendered by every swap, so it is |
| 1236 | - // looked up on each update. One EventSource serves the page and stays open across swaps. It is | 1242 | + // looked up on each update. The count arrives as an `unread` event of the shell stream (see |
| 1237 | - // opened only while a corner is shown (signed-in pages) and closed when it is gone. The server | 1243 | + // `/-/shell/events`, opened with the alive handlers above), which the server pushes on each change; |
| 1238 | - // pushes each change; nothing polls. Each `unread` event also tells the activity stream below to | 1244 | + // nothing polls. Each `unread` event also refreshes the activity (below). The count shows twice: as |
| 1239 | - // refresh. The count shows twice: as a dot on the menu toggle (has-dot), and next to Notifications | 1245 | + // a dot on the menu toggle (has-dot), and next to Notifications in the sidebar and the phone menu. |
| 1240 | - // in the sidebar and the phone menu. | ||
| 1241 | - var unreadStream = null; | ||
| 1242 | 1246 | ||
| 1243 | // Shows the count in one link the way the server renders it: a span with the number, or no span at zero. | 1247 | // Shows the count in one link the way the server renders it: a span with the number, or no span at zero. |
| 1244 | function setCount(el, cls, n) { | 1248 | function setCount(el, cls, n) { |
| @@ -1264,28 +1268,17 @@ | |||
| 1264 | for (var i = 0; i < links.length; i++) { setCount(links[i], 'count', n); } | 1268 | for (var i = 0; i < links.length; i++) { setCount(links[i], 'count', n); } |
| 1265 | } | 1269 | } |
| 1266 | 1270 | ||
| 1267 | - function syncUnread() { | 1271 | + // An `unread` event: the count, then the activity is fetched again. |
| 1268 | - if (!document.querySelector('[data-unread-stream]')) { | 1272 | + function unreadChanged(data) { |
| 1269 | - if (unreadStream) { unreadStream.close(); unreadStream = null; } | 1273 | + setUnread(parseInt(data, 10) || 0); |
| 1270 | - return; | ||
| 1271 | - } | ||
| 1272 | - if (unreadStream || !window.EventSource) { return; } | ||
| 1273 | - unreadStream = new EventSource('/notifications/stream'); | ||
| 1274 | - unreadStream.addEventListener('unread', function (e) { | ||
| 1275 | - setUnread(parseInt(e.data, 10) || 0); | ||
| 1276 | refreshActivity(); | 1274 | refreshActivity(); |
| 1277 | - }); | ||
| 1278 | } | 1275 | } |
| 1279 | 1276 | ||
| 1280 | - syncUnread(); | ||
| 1281 | - | ||
| 1282 | // The live activity: the profile corner (heat ring, chips, waiting list) and the live strip after | 1277 | // The live activity: the profile corner (heat ring, chips, waiting list) and the live strip after |
| 1283 | - // the path bar. The server's activity JSON (GET /-/activity) is the source. A `changed` event of | 1278 | + // the path bar. The server's activity JSON (GET /-/activity) is the source. An `activity` event of |
| 1284 | - // its stream, and every `unread` event above, fetches it again and redraws whatever is on the page. | 1279 | + // the shell stream, and every `unread` event, fetches it again and redraws whatever is on the page. |
| 1285 | - // Nothing changes before the JSON says so. The stream stays open across swaps while a strip is | 1280 | + // Nothing changes before the JSON says so. A finished run leaves the strip when the server's window |
| 1286 | - // shown, as the unread one does. A finished run leaves the strip when the server's window ends, so | 1281 | + // ends, so while any is listed the JSON is fetched again every 30 s. |
| 1287 | - // while any is listed the JSON is fetched again every 30 s. | ||
| 1288 | - var activityStream = null; | ||
| 1289 | var activitySeq = 0; // a fetch's number: only the newest answer is drawn | 1282 | var activitySeq = 0; // a fetch's number: only the newest answer is drawn |
| 1290 | var activityTimer = null; // the next refetch while finished runs are listed | 1283 | var activityTimer = null; // the next refetch while finished runs are listed |
| 1291 | var SVG_NS = 'http://www.w3.org/2000/svg'; | 1284 | var SVG_NS = 'http://www.w3.org/2000/svg'; |
| @@ -1516,20 +1509,6 @@ | |||
| 1516 | }).catch(function () { }); | 1509 | }).catch(function () { }); |
| 1517 | } | 1510 | } |
| 1518 | 1511 | ||
| 1519 | - // One EventSource serves the page's strip and stays open across swaps. It is opened only while a | ||
| 1520 | - // strip is shown and closed when it is gone. | ||
| 1521 | - function syncActivity() { | ||
| 1522 | - if (!document.querySelector('.live-strip[data-activity]')) { | ||
| 1523 | - if (activityStream) { activityStream.close(); activityStream = null; } | ||
| 1524 | - return; | ||
| 1525 | - } | ||
| 1526 | - if (activityStream || !window.EventSource) { return; } | ||
| 1527 | - activityStream = new EventSource('/-/activity/stream'); | ||
| 1528 | - activityStream.addEventListener('changed', function () { refreshActivity(); }); | ||
| 1529 | - } | ||
| 1530 | - | ||
| 1531 | - syncActivity(); | ||
| 1532 | - | ||
| 1533 | // The CI log (a job page's [data-live-log]). The server sends the raw text; this turns it into | 1512 | // The CI log (a job page's [data-live-log]). The server sends the raw text; this turns it into |
| 1534 | // numbered lines (#L12 anchors) with ANSI colours as spans, `::group::name` / `::endgroup::` | 1513 | // numbered lines (#L12 anchors) with ANSI colours as spans, `::group::name` / `::endgroup::` |
| 1535 | // sections as <details>, and a search box with highlight and next/previous. Streamed bytes go | 1514 | // sections as <details>, and a search box with highlight and next/previous. Streamed bytes go |
| @@ -2069,6 +2048,15 @@ | |||
| 2069 | return es; | 2048 | return es; |
| 2070 | } | 2049 | } |
| 2071 | 2050 | ||
| 2051 | + // A `side` event of the shell stream: the sidebar's repo list changed. The page is re-rendered with | ||
| 2052 | + // it, as a `changed` event of a data-live stream would, but at most once a second (a code view or a | ||
| 2053 | + // live-now page re-renders at once). | ||
| 2054 | + function sideChanged() { | ||
| 2055 | + if (document.querySelector('[data-live-code], [data-live-now]')) { refreshLive(true); return; } | ||
| 2056 | + if (liveTimer) { return; } | ||
| 2057 | + liveTimer = setTimeout(function () { liveTimer = null; refreshLive(true); }, 1000); | ||
| 2058 | + } | ||
| 2059 | + | ||
| 2072 | // Closes the streams the page no longer names and opens the ones it newly names. | 2060 | // Closes the streams the page no longer names and opens the ones it newly names. |
| 2073 | function syncLive() { | 2061 | function syncLive() { |
| 2074 | var want = liveWanted(); | 2062 | var want = liveWanted(); |
| @@ -3345,6 +3333,30 @@ | |||
| 3345 | href: function (dlg, path) { return fileHref(dlg, path); } | 3333 | href: function (dlg, path) { return fileHref(dlg, path); } |
| 3346 | }; | 3334 | }; |
| 3347 | 3335 | ||
| 3336 | + // A link with data-dialog opens the <dialog> whose id it names, in place of following the link. | ||
| 3337 | + // Modifier and non-primary clicks still follow the link (a new tab, say). It listens in the capture | ||
| 3338 | + // phase on window, so it runs before the soft navigation (capture on document) follows the link. | ||
| 3339 | + window.addEventListener('click', function (e) { | ||
| 3340 | + if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return; } | ||
| 3341 | + var t = e.target; | ||
| 3342 | + if (!t || !t.closest) { return; } | ||
| 3343 | + var link = t.closest('[data-dialog]'); | ||
| 3344 | + if (!link) { return; } | ||
| 3345 | + var dlg = document.getElementById(link.getAttribute('data-dialog')); | ||
| 3346 | + if (!dlg || dlg.tagName !== 'DIALOG' || typeof dlg.showModal !== 'function') { return; } | ||
| 3347 | + e.preventDefault(); | ||
| 3348 | + if (!dlg.open) { dlg.showModal(); } | ||
| 3349 | + // The same function each time, so the listener is added once however often the dialog opens. | ||
| 3350 | + dlg.addEventListener('click', closeOnBackdrop); | ||
| 3351 | + }, true); | ||
| 3352 | + | ||
| 3353 | + // A click on a dialog's backdrop (the dialog element itself, outside its box) closes it. | ||
| 3354 | + function closeOnBackdrop(e) { | ||
| 3355 | + var r = this.getBoundingClientRect(); | ||
| 3356 | + var inside = e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom; | ||
| 3357 | + if (e.target === this && !inside) { this.close(); } | ||
| 3358 | + } | ||
| 3359 | + | ||
| 3348 | document.addEventListener('click', function (e) { | 3360 | document.addEventListener('click', function (e) { |
| 3349 | var t = e.target; | 3361 | var t = e.target; |
| 3350 | if (!t || !t.closest) { return; } | 3362 | if (!t || !t.closest) { return; } |
crates/forge-web/src/i18n/mod.rsmodified+8 -0
| @@ -267,6 +267,8 @@ pub enum Key { | |||
| 267 | LastSeenAt, | 267 | LastSeenAt, |
| 268 | ExpiresAt, | 268 | ExpiresAt, |
| 269 | BackToSessions, | 269 | BackToSessions, |
| 270 | + NotRecorded, | ||
| 271 | + Close, | ||
| 270 | 272 | ||
| 271 | // Metadata lines (see the helpers below for the words in between). | 273 | // Metadata lines (see the helpers below for the words in between). |
| 272 | Added, | 274 | Added, |
| @@ -485,6 +487,8 @@ pub const ALL: &[Key] = &[ | |||
| 485 | Key::LastSeenAt, | 487 | Key::LastSeenAt, |
| 486 | Key::ExpiresAt, | 488 | Key::ExpiresAt, |
| 487 | Key::BackToSessions, | 489 | Key::BackToSessions, |
| 490 | + Key::NotRecorded, | ||
| 491 | + Key::Close, | ||
| 488 | Key::Added, | 492 | Key::Added, |
| 489 | Key::LastUsed, | 493 | Key::LastUsed, |
| 490 | Key::Created, | 494 | Key::Created, |
| @@ -889,6 +893,10 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | |||
| 889 | (ExpiresAt, Tr) => "Bitiş", | 893 | (ExpiresAt, Tr) => "Bitiş", |
| 890 | (BackToSessions, En) => "Back to sessions", | 894 | (BackToSessions, En) => "Back to sessions", |
| 891 | (BackToSessions, Tr) => "Oturumlara dön", | 895 | (BackToSessions, Tr) => "Oturumlara dön", |
| 896 | + (NotRecorded, En) => "Not recorded", | ||
| 897 | + (NotRecorded, Tr) => "Kaydedilmedi", | ||
| 898 | + (Close, En) => "Close", | ||
| 899 | + (Close, Tr) => "Kapat", | ||
| 892 | (RevokeAllOthers, En) => "Revoke all other sessions", | 900 | (RevokeAllOthers, En) => "Revoke all other sessions", |
| 893 | (RevokeAllOthers, Tr) => "Diğer tüm oturumları iptal et", | 901 | (RevokeAllOthers, Tr) => "Diğer tüm oturumları iptal et", |
| 894 | 902 | ||
crates/forge-web/src/live.rsmodified+26 -5
| @@ -28,7 +28,7 @@ use std::future::Future; | |||
| 28 | use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; | 28 | use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; |
| 29 | 29 | ||
| 30 | use futures_util::future::select_all; | 30 | use futures_util::future::select_all; |
| 31 | -use futures_util::stream; | 31 | +use futures_util::{Stream, stream}; |
| 32 | use tokio::sync::watch; | 32 | use tokio::sync::watch; |
| 33 | use topcoat::Result; | 33 | use topcoat::Result; |
| 34 | use topcoat::context::Cx; | 34 | use topcoat::context::Cx; |
| @@ -216,6 +216,11 @@ fn changed_event() -> Result<Event> { | |||
| 216 | Ok(Event::new().event("changed").data("1")) | 216 | Ok(Event::new().event("changed").data("1")) |
| 217 | } | 217 | } |
| 218 | 218 | ||
| 219 | +/// A `name` event with no data the client reads, sent on each change of a page's state. | ||
| 220 | +fn named_event(name: &'static str) -> Result<Event> { | ||
| 221 | + Ok(Event::new().event(name).data("1")) | ||
| 222 | +} | ||
| 223 | + | ||
| 219 | /// Waits until one of `wakes` is bumped. False when a topic is gone, which ends the stream. | 224 | /// Waits until one of `wakes` is bumped. False when a topic is gone, which ends the stream. |
| 220 | async fn wait_any(wakes: &mut [watch::Receiver<u64>]) -> bool { | 225 | async fn wait_any(wakes: &mut [watch::Receiver<u64>]) -> bool { |
| 221 | let waits = wakes.iter_mut().map(|rx| Box::pin(rx.changed())); | 226 | let waits = wakes.iter_mut().map(|rx| Box::pin(rx.changed())); |
| @@ -262,6 +267,23 @@ pub async fn stream_changes_with<F, Fut>( | |||
| 262 | extra: Vec<watch::Receiver<u64>>, | 267 | extra: Vec<watch::Receiver<u64>>, |
| 263 | read: F, | 268 | read: F, |
| 264 | ) -> Result<Response> | 269 | ) -> Result<Response> |
| 270 | +where | ||
| 271 | + F: Fn() -> Fut + Send + 'static, | ||
| 272 | + Fut: Future<Output = Result<String>> + Send, | ||
| 273 | +{ | ||
| 274 | + let events = named_changes(hub, topics.to_vec(), extra, "changed", read).await?; | ||
| 275 | + events_response(cx, events) | ||
| 276 | +} | ||
| 277 | + | ||
| 278 | +/// The events of [`stream_changes_with`] as a stream, each named `name`, for a caller that merges | ||
| 279 | +/// several streams into one response (see `pages::shell_events`). | ||
| 280 | +pub async fn named_changes<F, Fut>( | ||
| 281 | + hub: &LiveHub, | ||
| 282 | + topics: Vec<Topic>, | ||
| 283 | + extra: Vec<watch::Receiver<u64>>, | ||
| 284 | + name: &'static str, | ||
| 285 | + read: F, | ||
| 286 | +) -> Result<impl Stream<Item = Result<Event>> + Send + 'static> | ||
| 265 | where | 287 | where |
| 266 | F: Fn() -> Fut + Send + 'static, | 288 | F: Fn() -> Fut + Send + 'static, |
| 267 | Fut: Future<Output = Result<String>> + Send, | 289 | Fut: Future<Output = Result<String>> + Send, |
| @@ -271,7 +293,7 @@ where | |||
| 271 | topics.iter().map(|topic| hub.subscribe(topic)).collect(); | 293 | topics.iter().map(|topic| hub.subscribe(topic)).collect(); |
| 272 | wakes.extend(extra); | 294 | wakes.extend(extra); |
| 273 | let last = read().await?; | 295 | let last = read().await?; |
| 274 | - let events = stream::unfold(Follow { wakes, read, last }, |mut follow| async move { | 296 | + Ok(stream::unfold(Follow { wakes, read, last }, move |mut follow| async move { |
| 275 | loop { | 297 | loop { |
| 276 | if !wait_any(&mut follow.wakes).await { | 298 | if !wait_any(&mut follow.wakes).await { |
| 277 | return None; | 299 | return None; |
| @@ -287,10 +309,9 @@ where | |||
| 287 | continue; | 309 | continue; |
| 288 | } | 310 | } |
| 289 | follow.last = now; | 311 | follow.last = now; |
| 290 | - return Some((changed_event(), follow)); | 312 | + return Some((named_event(name), follow)); |
| 291 | } | 313 | } |
| 292 | - }); | 314 | + })) |
| 293 | - events_response(cx, events) | ||
| 294 | } | 315 | } |
| 295 | 316 | ||
| 296 | #[cfg(test)] | 317 | #[cfg(test)] |
crates/forge-web/src/pages/activity.rsmodified+14 -4
| @@ -15,6 +15,8 @@ use topcoat::router::{Body, HeaderValue, StatusCode, route}; | |||
| 15 | 15 | ||
| 16 | use crate::auth::current_user; | 16 | use crate::auth::current_user; |
| 17 | use crate::pages::ci_runs::{changed_stream, events_response, run_href}; | 17 | use crate::pages::ci_runs::{changed_stream, events_response, run_href}; |
| 18 | +use futures_util::Stream; | ||
| 19 | +use topcoat::router::content::sse::Event; | ||
| 18 | use crate::state::AppState; | 20 | use crate::state::AppState; |
| 19 | use crate::views::repo_href; | 21 | use crate::views::repo_href; |
| 20 | 22 | ||
| @@ -126,9 +128,18 @@ async fn activity_stream(cx: &Cx) -> Result<Response> { | |||
| 126 | return Ok(res); | 128 | return Ok(res); |
| 127 | }; | 129 | }; |
| 128 | let state = app_context::<AppState>(cx).clone(); | 130 | let state = app_context::<AppState>(cx).clone(); |
| 129 | - // Subscribed before the first read, so a run change in between is sent. | 131 | + events_response(cx, activity_changes(state, user, "changed")) |
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// The viewer's activity events, each named `name`: one now, then one after each run change that | ||
| 135 | +/// alters the JSON. Subscribed when built, before the first read, so a change in between is sent. | ||
| 136 | +pub(crate) fn activity_changes( | ||
| 137 | + state: AppState, | ||
| 138 | + user: User, | ||
| 139 | + name: &'static str, | ||
| 140 | +) -> impl Stream<Item = Result<Event>> + Send + 'static { | ||
| 130 | let wake = state.ci_live.subscribe_any_run(); | 141 | let wake = state.ci_live.subscribe_any_run(); |
| 131 | - let events = changed_stream(wake, true, move || { | 142 | + changed_stream(wake, true, name, move || { |
| 132 | let state = state.clone(); | 143 | let state = state.clone(); |
| 133 | let user = user.clone(); | 144 | let user = user.clone(); |
| 134 | async move { | 145 | async move { |
| @@ -136,8 +147,7 @@ async fn activity_stream(cx: &Cx) -> Result<Response> { | |||
| 136 | let body = activity_json(&state, &user).await?.to_string(); | 147 | let body = activity_json(&state, &user).await?.to_string(); |
| 137 | Ok(Some((body, false))) | 148 | Ok(Some((body, false))) |
| 138 | } | 149 | } |
| 139 | - }); | 150 | + }) |
| 140 | - events_response(cx, events) | ||
| 141 | } | 151 | } |
| 142 | 152 | ||
| 143 | #[cfg(test)] | 153 | #[cfg(test)] |
crates/forge-web/src/pages/ci_runs.rsmodified+9 -7
| @@ -1978,13 +1978,15 @@ pub(crate) fn changed_event(status: String) -> Result<Event> { | |||
| 1978 | Ok(Event::new().event("changed").data(status)) | 1978 | Ok(Event::new().event("changed").data(status)) |
| 1979 | } | 1979 | } |
| 1980 | 1980 | ||
| 1981 | -/// The `changed` events of a CI page. The first event carries the status now. Each later one | 1981 | +/// The events of a CI page, each named `name` (`changed` on a page's own stream). The first event |
| 1982 | -/// follows a wake of `wake`: with `only_on_status`, only when the status differs from the last one | 1982 | +/// carries the status now. Each later one follows a wake of `wake`: with `only_on_status`, only when |
| 1983 | -/// sent. The stream ends after the terminal status is sent, when the row is gone, or when the signal | 1983 | +/// the status differs from the last one sent. The stream ends after the terminal status is sent, |
| 1984 | -/// closes. Subscribe `wake` before the first read, so a change in between is not lost. | 1984 | +/// when the row is gone, or when the signal closes. Subscribe `wake` before the first read, so a |
| 1985 | +/// change in between is not lost. | ||
| 1985 | pub(crate) fn changed_stream<F, Fut>( | 1986 | pub(crate) fn changed_stream<F, Fut>( |
| 1986 | wake: watch::Receiver<u64>, | 1987 | wake: watch::Receiver<u64>, |
| 1987 | only_on_status: bool, | 1988 | only_on_status: bool, |
| 1989 | + name: &'static str, | ||
| 1988 | read: F, | 1990 | read: F, |
| 1989 | ) -> impl Stream<Item = Result<Event>> + Send + 'static | 1991 | ) -> impl Stream<Item = Result<Event>> + Send + 'static |
| 1990 | where | 1992 | where |
| @@ -2011,7 +2013,7 @@ where | |||
| 2011 | done: false, | 2013 | done: false, |
| 2012 | primed: false, | 2014 | primed: false, |
| 2013 | }, | 2015 | }, |
| 2014 | - |mut follow| async move { | 2016 | + move |mut follow| async move { |
| 2015 | loop { | 2017 | loop { |
| 2016 | if follow.done { | 2018 | if follow.done { |
| 2017 | return None; | 2019 | return None; |
| @@ -2033,7 +2035,7 @@ where | |||
| 2033 | let send = changed || !follow.only_on_status; | 2035 | let send = changed || !follow.only_on_status; |
| 2034 | follow.last = Some(status.clone()); | 2036 | follow.last = Some(status.clone()); |
| 2035 | if send { | 2037 | if send { |
| 2036 | - return Some((changed_event(status), follow)); | 2038 | + return Some((Ok(Event::new().event(name).data(status)), follow)); |
| 2037 | } | 2039 | } |
| 2038 | } | 2040 | } |
| 2039 | }, | 2041 | }, |
| @@ -2156,7 +2158,7 @@ async fn run_events(cx: &Cx) -> Result<Response> { | |||
| 2156 | let run_id = run.id.clone(); | 2158 | let run_id = run.id.clone(); |
| 2157 | let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone()); | 2159 | let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone()); |
| 2158 | let repo_id = ctx.repo.id.clone(); | 2160 | let repo_id = ctx.repo.id.clone(); |
| 2159 | - let events = changed_stream(wake, false, move || { | 2161 | + let events = changed_stream(wake, false, "changed", move || { |
| 2160 | let store = store.clone(); | 2162 | let store = store.clone(); |
| 2161 | let run_id = run_id.clone(); | 2163 | let run_id = run_id.clone(); |
| 2162 | let viewer = viewer.clone(); | 2164 | let viewer = viewer.clone(); |
crates/forge-web/src/pages/dashboard.rsmodified+18 -1
| @@ -12,6 +12,7 @@ use forge_core::{Notification, Repo, Visibility}; | |||
| 12 | use jiff::{Timestamp, civil}; | 12 | use jiff::{Timestamp, civil}; |
| 13 | use topcoat::Result; | 13 | use topcoat::Result; |
| 14 | use topcoat::context::{Cx, app_context}; | 14 | use topcoat::context::{Cx, app_context}; |
| 15 | +use topcoat::router::content::sse::Event; | ||
| 15 | use topcoat::router::response::Response; | 16 | use topcoat::router::response::Response; |
| 16 | use topcoat::router::{Body, StatusCode, page, query_params, route}; | 17 | use topcoat::router::{Body, StatusCode, page, query_params, route}; |
| 17 | use topcoat::view::{View, component, view}; | 18 | use topcoat::view::{View, component, view}; |
| @@ -20,7 +21,7 @@ use crate::auth::{current_user, percent_encode}; | |||
| 20 | use crate::i18n::misc::{self as m, K as MK}; | 21 | use crate::i18n::misc::{self as m, K as MK}; |
| 21 | use crate::i18n::orgs::{self as g, K}; | 22 | use crate::i18n::orgs::{self as g, K}; |
| 22 | use crate::i18n::{self, Lang}; | 23 | use crate::i18n::{self, Lang}; |
| 23 | -use crate::live::{Topic, stream_changes}; | 24 | +use crate::live::{Topic, named_changes, stream_changes}; |
| 24 | use crate::pages::issue_parts::stamp_unix; | 25 | use crate::pages::issue_parts::stamp_unix; |
| 25 | use crate::pages::repo_settings::{notice_banner_for, take_notice}; | 26 | use crate::pages::repo_settings::{notice_banner_for, take_notice}; |
| 26 | use crate::state::AppState; | 27 | use crate::state::AppState; |
| @@ -133,6 +134,22 @@ async fn side_events(cx: &Cx) -> Result<Response> { | |||
| 133 | .await | 134 | .await |
| 134 | } | 135 | } |
| 135 | 136 | ||
| 137 | +/// The sidebar's change events for `user`, each named `name` (`changed` on `/-/side/events`). | ||
| 138 | +pub(crate) async fn side_changes( | ||
| 139 | + state: &AppState, | ||
| 140 | + user: &forge_core::User, | ||
| 141 | + name: &'static str, | ||
| 142 | +) -> topcoat::Result<impl futures_util::Stream<Item = topcoat::Result<Event>> + Send + 'static> { | ||
| 143 | + let topics = vec![Topic::User(user.id.clone())]; | ||
| 144 | + let (state_for_read, user) = (state.clone(), user.clone()); | ||
| 145 | + named_changes(&state.live, topics, Vec::new(), name, move || { | ||
| 146 | + let state = state_for_read.clone(); | ||
| 147 | + let user = user.clone(); | ||
| 148 | + async move { side_fingerprint(&state, &user).await } | ||
| 149 | + }) | ||
| 150 | + .await | ||
| 151 | +} | ||
| 152 | + | ||
| 136 | /// The sidebar's repo list as it shows: the names in order, and the total. | 153 | /// The sidebar's repo list as it shows: the names in order, and the total. |
| 137 | async fn side_fingerprint(state: &AppState, user: &forge_core::User) -> Result<String> { | 154 | async fn side_fingerprint(state: &AppState, user: &forge_core::User) -> Result<String> { |
| 138 | let (listed, total) = state | 155 | let (listed, total) = state |
crates/forge-web/src/pages/mod.rsmodified+1 -0
| @@ -135,6 +135,7 @@ pub mod settings_security; | |||
| 135 | pub mod settings_sessions; | 135 | pub mod settings_sessions; |
| 136 | pub mod settings_tokens; | 136 | pub mod settings_tokens; |
| 137 | pub mod setup; | 137 | pub mod setup; |
| 138 | +pub mod shell_events; | ||
| 138 | pub mod snippet_raw; | 139 | pub mod snippet_raw; |
| 139 | pub mod snippets; | 140 | pub mod snippets; |
| 140 | pub mod snippets_live; | 141 | pub mod snippets_live; |
crates/forge-web/src/pages/notifications.rsmodified+19 -10
| @@ -12,7 +12,7 @@ use forge_core::store::admin_alerts::AdminNotice; | |||
| 12 | use forge_core::store::advisories::AdvisoryNotice; | 12 | use forge_core::store::advisories::AdvisoryNotice; |
| 13 | use forge_core::store::transfers::PendingTransfer; | 13 | use forge_core::store::transfers::PendingTransfer; |
| 14 | use forge_core::{Notification, Reason, Role, SubState, User, WatchLevel}; | 14 | use forge_core::{Notification, Reason, Role, SubState, User, WatchLevel}; |
| 15 | -use futures_util::{StreamExt, future, stream}; | 15 | +use futures_util::{Stream, StreamExt, future, stream}; |
| 16 | use serde::Deserialize; | 16 | use serde::Deserialize; |
| 17 | use topcoat::Result; | 17 | use topcoat::Result; |
| 18 | use topcoat::context::{Cx, app_context}; | 18 | use topcoat::context::{Cx, app_context}; |
| @@ -725,6 +725,22 @@ fn unread_event(count: u64) -> topcoat::Result<Event> { | |||
| 725 | Ok(Event::new().event("unread").data(count.to_string())) | 725 | Ok(Event::new().event("unread").data(count.to_string())) |
| 726 | } | 726 | } |
| 727 | 727 | ||
| 728 | +/// The viewer's unread count as `unread` events: one now, then one after each change to the inbox. | ||
| 729 | +/// Subscribed before the count is read, so a change in between is pushed again, never missed. | ||
| 730 | +pub(crate) async fn unread_changes( | ||
| 731 | + state: &AppState, | ||
| 732 | + user_id: &str, | ||
| 733 | +) -> Result<impl Stream<Item = Result<Event>> + Send + 'static> { | ||
| 734 | + let subscription = state.notify_hub.subscribe(user_id); | ||
| 735 | + let count = state.store.unread_count(user_id).await?; | ||
| 736 | + let first = stream::once(future::ready(unread_event(count))); | ||
| 737 | + let changes = stream::unfold(subscription, |mut sub| async move { | ||
| 738 | + let count = sub.next_count().await?; | ||
| 739 | + Some((unread_event(count), sub)) | ||
| 740 | + }); | ||
| 741 | + Ok(first.chain(changes)) | ||
| 742 | +} | ||
| 743 | + | ||
| 728 | /// The bell's live count. Sends an `unread` event with the viewer's unread count now, then one | 744 | /// The bell's live count. Sends an `unread` event with the viewer's unread count now, then one |
| 729 | /// after each change to the inbox, until the viewer disconnects or the server shuts down. An | 745 | /// after each change to the inbox, until the viewer disconnects or the server shuts down. An |
| 730 | /// anonymous viewer gets a bare 401: an event stream has no login page to redirect to. | 746 | /// anonymous viewer gets a bare 401: an event stream has no login page to redirect to. |
| @@ -736,15 +752,8 @@ async fn notification_stream(cx: &Cx) -> Result<Response> { | |||
| 736 | return Ok(res); | 752 | return Ok(res); |
| 737 | }; | 753 | }; |
| 738 | let state = app_context::<AppState>(cx); | 754 | let state = app_context::<AppState>(cx); |
| 739 | - let subscription = state.notify_hub.subscribe(&user.id); | 755 | + let events = unread_changes(state, &user.id).await?; |
| 740 | - // Read after subscribing: a change that lands in between is pushed again, never missed. | 756 | + events_response(cx, events) |
| 741 | - let count = state.store.unread_count(&user.id).await?; | ||
| 742 | - let first = stream::once(future::ready(unread_event(count))); | ||
| 743 | - let changes = stream::unfold(subscription, |mut sub| async move { | ||
| 744 | - let count = sub.next_count().await?; | ||
| 745 | - Some((unread_event(count), sub)) | ||
| 746 | - }); | ||
| 747 | - events_response(cx, first.chain(changes)) | ||
| 748 | } | 757 | } |
| 749 | 758 | ||
| 750 | /// Subscribes or unsubscribes the viewer from an issue. | 759 | /// Subscribes or unsubscribes the viewer from an issue. |
crates/forge-web/src/pages/register.rsmodified+1 -2
| @@ -423,11 +423,10 @@ async fn verify_resend(cx: &Cx, Form(form): Form<ResendForm>) -> Result<SeeOther | |||
| 423 | let state = app_context::<AppState>(cx); | 423 | let state = app_context::<AppState>(cx); |
| 424 | if let Some(address) = viewer.0.email.clone() | 424 | if let Some(address) = viewer.0.email.clone() |
| 425 | && !state.store.email_is_verified(&viewer.0.id).await? | 425 | && !state.store.email_is_verified(&viewer.0.id).await? |
| 426 | + && !account::send_verify(state, &viewer.0, &address).await? | ||
| 426 | { | 427 | { |
| 427 | - if !account::send_verify(state, &viewer.0, &address).await? { | ||
| 428 | return Ok(see_other("/settings/security?saved=verify_wait")); | 428 | return Ok(see_other("/settings/security?saved=verify_wait")); |
| 429 | } | 429 | } |
| 430 | - } | ||
| 431 | Ok(see_other("/settings/security?saved=verify_sent")) | 430 | Ok(see_other("/settings/security?saved=verify_sent")) |
| 432 | } | 431 | } |
| 433 | 432 | ||
crates/forge-web/src/pages/repo_side.rsmodified+1 -0
| @@ -63,6 +63,7 @@ fn dir_size(path: &Path) -> u64 { | |||
| 63 | } | 63 | } |
| 64 | 64 | ||
| 65 | /// The tree facts of `repo` at `commit`, read once per commit. `root` is the root entry names. | 65 | /// The tree facts of `repo` at `commit`, read once per commit. `root` is the root entry names. |
| 66 | +#[allow(clippy::ptr_arg)] // the path is moved into a blocking task, which needs an owned PathBuf | ||
| 66 | pub async fn tree_facts( | 67 | pub async fn tree_facts( |
| 67 | state: &AppState, | 68 | state: &AppState, |
| 68 | repo: &Repo, | 69 | repo: &Repo, |
crates/forge-web/src/pages/settings_live.rsmodified+13 -2
| @@ -24,7 +24,7 @@ | |||
| 24 | use std::collections::VecDeque; | 24 | use std::collections::VecDeque; |
| 25 | 25 | ||
| 26 | use forge_core::server_settings::{self, FIELDS, Kind}; | 26 | use forge_core::server_settings::{self, FIELDS, Kind}; |
| 27 | -use futures_util::stream; | 27 | +use futures_util::stream::{self, BoxStream, StreamExt}; |
| 28 | use tokio::sync::watch; | 28 | use tokio::sync::watch; |
| 29 | use topcoat::Result; | 29 | use topcoat::Result; |
| 30 | use topcoat::context::{Cx, app_context, try_app_context}; | 30 | use topcoat::context::{Cx, app_context, try_app_context}; |
| @@ -172,6 +172,17 @@ pub async fn alive_response(cx: &Cx) -> Result<Response> { | |||
| 172 | let viewer = current_user(cx) | 172 | let viewer = current_user(cx) |
| 173 | .await? | 173 | .await? |
| 174 | .map(|(user, session)| (user.id, session.id)); | 174 | .map(|(user, session)| (user.id, session.id)); |
| 175 | + let events = alive_stream(state, viewer).await?; | ||
| 176 | + events_response(cx, events) | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +/// The events of the alive stream for `viewer` (the user and session ids, when signed in). See | ||
| 180 | +/// [`alive_response`]. The caller holds the stream slot; `pages::shell_events` merges it with the | ||
| 181 | +/// shell's other streams. | ||
| 182 | +pub async fn alive_stream( | ||
| 183 | + state: AppState, | ||
| 184 | + viewer: Option<(String, String)>, | ||
| 185 | +) -> Result<BoxStream<'static, Result<Event>>> { | ||
| 175 | // Subscribed before each baseline is read, so a change in between is not lost. | 186 | // Subscribed before each baseline is read, so a change in between is not lost. |
| 176 | let server_wake = state.live.subscribe(&Topic::ServerSettings); | 187 | let server_wake = state.live.subscribe(&Topic::ServerSettings); |
| 177 | let settings_last = settings_fingerprint(&state); | 188 | let settings_last = settings_fingerprint(&state); |
| @@ -195,7 +206,7 @@ pub async fn alive_response(cx: &Cx) -> Result<Response> { | |||
| 195 | settings_last, | 206 | settings_last, |
| 196 | queue: VecDeque::new(), | 207 | queue: VecDeque::new(), |
| 197 | }; | 208 | }; |
| 198 | - events_response(cx, stream::unfold(alive, next_alive_event)) | 209 | + Ok(stream::unfold(alive, next_alive_event).boxed()) |
| 199 | } | 210 | } |
| 200 | 211 | ||
| 201 | /// Waits for the next event of the alive stream. A wake that changes nothing the viewer sees sends | 212 | /// Waits for the next event of the alive stream. A wake that changes nothing the viewer sees sends |
crates/forge-web/src/pages/settings_sessions.rsmodified+71 -10
| @@ -65,7 +65,7 @@ async fn sessions_view( | |||
| 65 | for session in sessions.into_iter() { | 65 | for session in sessions.into_iter() { |
| 66 | <li class="item"> | 66 | <li class="item"> |
| 67 | <div class="item-main"> | 67 | <div class="item-main"> |
| 68 | - <a href=(format!("/settings/sessions/{}", session.id))><strong>(session_label(lang, &session))</strong></a> | 68 | + <a href=(format!("/settings/sessions/{}", session.id)) data-dialog=(format!("session-{}", session.id))><strong>(session_label(lang, &session))</strong></a> |
| 69 | <span class="muted small">(i18n::dated_label(lang, Key::SignedIn)) " " rel_time(lang: lang, stamp: session.created_at.as_str()) " · " (i18n::dated_label(lang, Key::LastSeen)) " " rel_time(lang: lang, stamp: session.last_seen.as_str()) " · " (i18n::dated_label(lang, Key::ExpiresLabel)) " " rel_time(lang: lang, stamp: session.expires_at.as_str()) (address_text(&session))</span> | 69 | <span class="muted small">(i18n::dated_label(lang, Key::SignedIn)) " " rel_time(lang: lang, stamp: session.created_at.as_str()) " · " (i18n::dated_label(lang, Key::LastSeen)) " " rel_time(lang: lang, stamp: session.last_seen.as_str()) " · " (i18n::dated_label(lang, Key::ExpiresLabel)) " " rel_time(lang: lang, stamp: session.expires_at.as_str()) (address_text(&session))</span> |
| 70 | if session.id == current_id { | 70 | if session.id == current_id { |
| 71 | <span class="badge public">(t(lang, Key::ThisSession))</span> | 71 | <span class="badge public">(t(lang, Key::ThisSession))</span> |
| @@ -78,6 +78,15 @@ async fn sessions_view( | |||
| 78 | <button type="submit" class="danger">(t(lang, Key::Revoke))</button> | 78 | <button type="submit" class="danger">(t(lang, Key::Revoke))</button> |
| 79 | </form> | 79 | </form> |
| 80 | } | 80 | } |
| 81 | + <dialog class="session-dialog" id=(format!("session-{}", session.id)) aria-labelledby=(format!("session-{}-title", session.id))> | ||
| 82 | + <div class="session-dialog-head"> | ||
| 83 | + <h2 id=(format!("session-{}-title", session.id))>(session_label(lang, &session))</h2> | ||
| 84 | + <form method="dialog"> | ||
| 85 | + <button type="submit">(t(lang, Key::Close))</button> | ||
| 86 | + </form> | ||
| 87 | + </div> | ||
| 88 | + session_details(lang: lang, csrf: csrf, session: session.clone(), current: session.id == current_id) | ||
| 89 | + </dialog> | ||
| 81 | </li> | 90 | </li> |
| 82 | } | 91 | } |
| 83 | </ul> | 92 | </ul> |
| @@ -93,8 +102,10 @@ async fn sessions_view( | |||
| 93 | }) | 102 | }) |
| 94 | } | 103 | } |
| 95 | 104 | ||
| 105 | +/// The facts about one session, shared by its dialog on the list and its detail page: the badge | ||
| 106 | +/// when it is the current session, the key/value grid, and the revoke button for any other one. | ||
| 96 | #[component] | 107 | #[component] |
| 97 | -async fn session_detail_view( | 108 | +async fn session_details( |
| 98 | lang: Lang, | 109 | lang: Lang, |
| 99 | csrf: &str, | 110 | csrf: &str, |
| 100 | session: Session, | 111 | session: Session, |
| @@ -104,17 +115,20 @@ async fn session_detail_view( | |||
| 104 | .user_agent | 115 | .user_agent |
| 105 | .clone() | 116 | .clone() |
| 106 | .unwrap_or_else(|| t(lang, Key::UnknownBrowser).to_owned()); | 117 | .unwrap_or_else(|| t(lang, Key::UnknownBrowser).to_owned()); |
| 107 | - let sign_in_ip = session.ip.clone().unwrap_or_else(|| "-".to_owned()); | 118 | + // Sessions from before IP recording have no sign-in address. |
| 108 | - let last_ip = session.last_ip.clone().unwrap_or_else(|| "-".to_owned()); | 119 | + let sign_in_ip = session |
| 120 | + .ip | ||
| 121 | + .clone() | ||
| 122 | + .unwrap_or_else(|| t(lang, Key::NotRecorded).to_owned()); | ||
| 123 | + let last_ip = session | ||
| 124 | + .last_ip | ||
| 125 | + .clone() | ||
| 126 | + .unwrap_or_else(|| t(lang, Key::NotRecorded).to_owned()); | ||
| 109 | let id = session.id.clone(); | 127 | let id = session.id.clone(); |
| 110 | Ok(view! { | 128 | Ok(view! { |
| 111 | - <section class="page-head"> | ||
| 112 | - <h1>(session_label(lang, &session))</h1> | ||
| 113 | - </section> | ||
| 114 | if current { | 129 | if current { |
| 115 | <p><span class="badge public">(t(lang, Key::ThisSession))</span></p> | 130 | <p><span class="badge public">(t(lang, Key::ThisSession))</span></p> |
| 116 | } | 131 | } |
| 117 | - <section class="card"> | ||
| 118 | <dl class="kv-grid"> | 132 | <dl class="kv-grid"> |
| 119 | <div><dt>(t(lang, Key::UserAgent))</dt><dd>(user_agent.as_str())</dd></div> | 133 | <div><dt>(t(lang, Key::UserAgent))</dt><dd>(user_agent.as_str())</dd></div> |
| 120 | <div><dt>(t(lang, Key::SignInIp))</dt><dd>(sign_in_ip.as_str())</dd></div> | 134 | <div><dt>(t(lang, Key::SignInIp))</dt><dd>(sign_in_ip.as_str())</dd></div> |
| @@ -123,8 +137,6 @@ async fn session_detail_view( | |||
| 123 | <div><dt>(t(lang, Key::LastSeenAt))</dt><dd>rel_time(lang: lang, stamp: session.last_seen.as_str())</dd></div> | 137 | <div><dt>(t(lang, Key::LastSeenAt))</dt><dd>rel_time(lang: lang, stamp: session.last_seen.as_str())</dd></div> |
| 124 | <div><dt>(t(lang, Key::ExpiresAt))</dt><dd>rel_time(lang: lang, stamp: session.expires_at.as_str())</dd></div> | 138 | <div><dt>(t(lang, Key::ExpiresAt))</dt><dd>rel_time(lang: lang, stamp: session.expires_at.as_str())</dd></div> |
| 125 | </dl> | 139 | </dl> |
| 126 | - </section> | ||
| 127 | - <section class="card"> | ||
| 128 | if !current { | 140 | if !current { |
| 129 | <form method="post" action="/settings/sessions/revoke"> | 141 | <form method="post" action="/settings/sessions/revoke"> |
| 130 | <input type="hidden" name="csrf" value=(csrf)> | 142 | <input type="hidden" name="csrf" value=(csrf)> |
| @@ -132,6 +144,22 @@ async fn session_detail_view( | |||
| 132 | <button type="submit" class="danger">(t(lang, Key::Revoke))</button> | 144 | <button type="submit" class="danger">(t(lang, Key::Revoke))</button> |
| 133 | </form> | 145 | </form> |
| 134 | } | 146 | } |
| 147 | + }) | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +#[component] | ||
| 151 | +async fn session_detail_view( | ||
| 152 | + lang: Lang, | ||
| 153 | + csrf: &str, | ||
| 154 | + session: Session, | ||
| 155 | + current: bool, | ||
| 156 | +) -> Result<impl View> { | ||
| 157 | + Ok(view! { | ||
| 158 | + <section class="page-head"> | ||
| 159 | + <h1>(session_label(lang, &session))</h1> | ||
| 160 | + </section> | ||
| 161 | + <section class="card"> | ||
| 162 | + session_details(lang: lang, csrf: csrf, session: session, current: current) | ||
| 135 | <p><a href="/settings/sessions">(t(lang, Key::BackToSessions))</a></p> | 163 | <p><a href="/settings/sessions">(t(lang, Key::BackToSessions))</a></p> |
| 136 | </section> | 164 | </section> |
| 137 | }) | 165 | }) |
| @@ -254,6 +282,39 @@ mod tests { | |||
| 254 | 282 | ||
| 255 | const CSRF: &str = "sessions-test-csrf"; | 283 | const CSRF: &str = "sessions-test-csrf"; |
| 256 | 284 | ||
| 285 | + #[tokio::test] | ||
| 286 | + async fn sessions_list_renders_a_dialog_per_session() { | ||
| 287 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 288 | + let state = crate::test_support::test_state(dir.path()).await; | ||
| 289 | + let store = state.store.clone(); | ||
| 290 | + let router = crate::test_support::app_router(state.clone()); | ||
| 291 | + let tahinli = store | ||
| 292 | + .create_user("tahinli", None, "x", false) | ||
| 293 | + .await | ||
| 294 | + .expect("tahinli"); | ||
| 295 | + crate::test_support::create_session(&store, &tahinli.id, "tahinli-token", CSRF).await; | ||
| 296 | + let current = store | ||
| 297 | + .list_sessions(&tahinli.id) | ||
| 298 | + .await | ||
| 299 | + .expect("sessions") | ||
| 300 | + .pop() | ||
| 301 | + .expect("one session"); | ||
| 302 | + | ||
| 303 | + let req = Request::builder() | ||
| 304 | + .method("GET") | ||
| 305 | + .uri("/settings/sessions") | ||
| 306 | + .header("cookie", format!("__Host-{SESSION_COOKIE}=tahinli-token")) | ||
| 307 | + .body(Body::empty()) | ||
| 308 | + .expect("request"); | ||
| 309 | + let res = router.handle(req).await; | ||
| 310 | + assert_eq!(res.status().as_u16(), 200); | ||
| 311 | + let body = to_bytes(res.into_body(), usize::MAX).await.expect("body"); | ||
| 312 | + let html = String::from_utf8_lossy(&body); | ||
| 313 | + let id = format!("session-{}", current.id); | ||
| 314 | + assert!(html.contains(&format!("<dialog class=\"session-dialog\" id=\"{id}\""))); | ||
| 315 | + assert!(html.contains(&format!("data-dialog=\"{id}\""))); | ||
| 316 | + } | ||
| 317 | + | ||
| 257 | #[tokio::test] | 318 | #[tokio::test] |
| 258 | async fn revoking_the_current_session_is_audited() { | 319 | async fn revoking_the_current_session_is_audited() { |
| 259 | let dir = tempfile::tempdir().expect("tempdir"); | 320 | let dir = tempfile::tempdir().expect("tempdir"); |
crates/forge-web/src/pages/shell_events.rsadded+88 -0
| @@ -0,0 +1,88 @@ | |||
| 1 | +//! `GET /-/shell/events`: the one live stream a page holds. It merges the four streams every | ||
| 2 | +//! signed-in page used to open (`/-/alive`, `/notifications/stream`, `/-/activity/stream` and | ||
| 3 | +//! `/-/side/events`) into one response. Chromium allows six connections per host over HTTP/1.1, and | ||
| 4 | +//! a page that held more than that could not load anything else. | ||
| 5 | +//! | ||
| 6 | +//! The events are named: `settings`, `theme`, `language` and `account` (the alive part, see | ||
| 7 | +//! `settings_live::alive_stream`), `unread` (the inbox count), `activity` (the viewer's live strip | ||
| 8 | +//! and ring) and `side` (the sidebar's repo list). An anonymous visitor gets the alive part only. | ||
| 9 | +//! Each part keeps its own fingerprint, so an event is sent only when that part changed. The old | ||
| 10 | +//! routes stay registered for tabs opened before a deploy. | ||
| 11 | + | ||
| 12 | +use futures_util::StreamExt; | ||
| 13 | +use futures_util::stream::{self, BoxStream}; | ||
| 14 | +use topcoat::Result; | ||
| 15 | +use topcoat::context::{Cx, try_app_context}; | ||
| 16 | +use topcoat::router::content::sse::Event; | ||
| 17 | +use topcoat::router::response::Response; | ||
| 18 | +use topcoat::router::route; | ||
| 19 | + | ||
| 20 | +use crate::auth::current_user; | ||
| 21 | +use crate::pages::activity::activity_changes; | ||
| 22 | +use crate::pages::ci_runs::events_response; | ||
| 23 | +use crate::pages::dashboard::side_changes; | ||
| 24 | +use crate::pages::notifications::unread_changes; | ||
| 25 | +use crate::pages::settings_live::alive_stream; | ||
| 26 | +use crate::state::AppState; | ||
| 27 | + | ||
| 28 | +/// `GET /-/shell/events`: the shell's live events for the viewer, opened once per page. An anonymous | ||
| 29 | +/// visitor gets the alive part only. The viewer comes from the session, never from the URL. | ||
| 30 | +#[route(GET "/-/shell/events")] | ||
| 31 | +async fn shell_events(cx: &Cx) -> Result<Response> { | ||
| 32 | + // A router with no app state (the asset tests) has nothing to follow: the stream only stays open. | ||
| 33 | + let Some(state) = try_app_context::<AppState>(cx).cloned() else { | ||
| 34 | + return events_response(cx, stream::pending::<Result<Event>>()); | ||
| 35 | + }; | ||
| 36 | + let viewer = current_user(cx).await?; | ||
| 37 | + let ids = viewer | ||
| 38 | + .as_ref() | ||
| 39 | + .map(|(user, session)| (user.id.clone(), session.id.clone())); | ||
| 40 | + let mut parts: Vec<BoxStream<'static, Result<Event>>> = | ||
| 41 | + vec![alive_stream(state.clone(), ids).await?]; | ||
| 42 | + if let Some((user, _)) = viewer { | ||
| 43 | + parts.push(unread_changes(&state, &user.id).await?.boxed()); | ||
| 44 | + parts.push(activity_changes(state.clone(), user.clone(), "activity").boxed()); | ||
| 45 | + parts.push(side_changes(&state, &user, "side").await?.boxed()); | ||
| 46 | + } | ||
| 47 | + events_response(cx, stream::select_all(parts)) | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +#[cfg(test)] | ||
| 51 | +mod tests { | ||
| 52 | + use topcoat::router::request::Request; | ||
| 53 | + use topcoat::router::{Body, StatusCode}; | ||
| 54 | + | ||
| 55 | + use crate::auth::SESSION_COOKIE; | ||
| 56 | + | ||
| 57 | + /// The shell stream answers `text/event-stream` to an anonymous visitor and to a signed-in one. | ||
| 58 | + #[tokio::test] | ||
| 59 | + async fn shell_events_is_an_event_stream_for_anonymous_and_signed_in_viewers() { | ||
| 60 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 61 | + let state = crate::test_support::test_state(dir.path()).await; | ||
| 62 | + let store = state.store.clone(); | ||
| 63 | + let router = crate::test_support::app_router(state); | ||
| 64 | + let user = store | ||
| 65 | + .create_user("tahinli", None, "x", false) | ||
| 66 | + .await | ||
| 67 | + .expect("user"); | ||
| 68 | + crate::test_support::create_session(&store, &user.id, "tok", "csrf").await; | ||
| 69 | + | ||
| 70 | + for cookie in [None, Some(format!("__Host-{SESSION_COOKIE}=tok"))] { | ||
| 71 | + let mut builder = Request::builder().method("GET").uri("/-/shell/events"); | ||
| 72 | + if let Some(cookie) = &cookie { | ||
| 73 | + builder = builder.header("cookie", cookie.as_str()); | ||
| 74 | + } | ||
| 75 | + let res = router | ||
| 76 | + .handle(builder.body(Body::empty()).expect("request")) | ||
| 77 | + .await; | ||
| 78 | + assert_eq!(res.status(), StatusCode::OK, "cookie: {cookie:?}"); | ||
| 79 | + assert!( | ||
| 80 | + res.headers()["content-type"] | ||
| 81 | + .to_str() | ||
| 82 | + .expect("header") | ||
| 83 | + .starts_with("text/event-stream"), | ||
| 84 | + "cookie: {cookie:?}" | ||
| 85 | + ); | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | +} | ||
crates/forge-web/src/repo_stats.rsmodified+2 -2
| @@ -165,7 +165,7 @@ pub fn languages(files: &[(String, u64)], top: usize) -> Vec<LangShare> { | |||
| 165 | }) | 165 | }) |
| 166 | .collect(); | 166 | .collect(); |
| 167 | // Biggest first; equal sizes keep their name order, which the BTreeMap gave. | 167 | // Biggest first; equal sizes keep their name order, which the BTreeMap gave. |
| 168 | - rows.sort_by(|a, b| b.bytes.cmp(&a.bytes)); | 168 | + rows.sort_by_key(|a| std::cmp::Reverse(a.bytes)); |
| 169 | 169 | ||
| 170 | if rows.len() > top { | 170 | if rows.len() > top { |
| 171 | let rest = rows.split_off(top); | 171 | let rest = rows.split_off(top); |
| @@ -306,7 +306,7 @@ const LICENSE_NAMES: &[&str] = &[ | |||
| 306 | 306 | ||
| 307 | /// The root entry that holds the license, if any: LICENSE, LICENSE.md, LICENSE.txt, LICENCE, | 307 | /// The root entry that holds the license, if any: LICENSE, LICENSE.md, LICENSE.txt, LICENCE, |
| 308 | /// COPYING, LICENSE-MIT ... (case-insensitive). The first match in a fixed preference order. | 308 | /// COPYING, LICENSE-MIT ... (case-insensitive). The first match in a fixed preference order. |
| 309 | -pub fn license_file<'a>(root_names: &'a [String]) -> Option<&'a str> { | 309 | +pub fn license_file(root_names: &[String]) -> Option<&str> { |
| 310 | LICENSE_NAMES.iter().find_map(|want| { | 310 | LICENSE_NAMES.iter().find_map(|want| { |
| 311 | root_names | 311 | root_names |
| 312 | .iter() | 312 | .iter() |
crates/forge-web/src/views/mod.rsmodified+1 -1
| @@ -868,7 +868,7 @@ async fn side_nav( | |||
| 868 | (o::t(lang, OK::Settings)) | 868 | (o::t(lang, OK::Settings)) |
| 869 | </a> | 869 | </a> |
| 870 | </nav> | 870 | </nav> |
| 871 | - <div class="side-group" data-live="/-/side/events"> | 871 | + <div class="side-group" data-shell-live="side"> |
| 872 | <h2 class="side-h">(o::t(lang, OK::RecentRepositories))</h2> | 872 | <h2 class="side-h">(o::t(lang, OK::RecentRepositories))</h2> |
| 873 | if empty { | 873 | if empty { |
| 874 | <p class="side-empty">(o::t(lang, OK::NoReposYet))</p> | 874 | <p class="side-empty">(o::t(lang, OK::NoReposYet))</p> |
style/_account_admin.scssmodified+51 -0
| @@ -51,6 +51,57 @@ | |||
| 51 | } | 51 | } |
| 52 | } | 52 | } |
| 53 | 53 | ||
| 54 | +// A session's details over /settings/sessions, opened from its title. The body is the kv-grid in two | ||
| 55 | +// columns; the close button sits at the top right, and the revoke button under the grid. | ||
| 56 | +dialog.session-dialog { | ||
| 57 | + width: min(640px, calc(100% - 32px)); | ||
| 58 | + max-height: min(80vh, 640px); | ||
| 59 | + margin: 10vh auto 0; | ||
| 60 | + padding: 20px 24px; | ||
| 61 | + overflow: auto; | ||
| 62 | + color: var(--text); | ||
| 63 | + background: var(--surface); | ||
| 64 | + border: 1px solid var(--border); | ||
| 65 | + border-radius: var(--radius-md); | ||
| 66 | + box-shadow: var(--shadow); | ||
| 67 | + | ||
| 68 | + &::backdrop { | ||
| 69 | + background: rgba(0, 0, 0, 0.45); | ||
| 70 | + } | ||
| 71 | + | ||
| 72 | + .session-dialog-head { | ||
| 73 | + display: flex; | ||
| 74 | + align-items: center; | ||
| 75 | + justify-content: space-between; | ||
| 76 | + gap: 12px; | ||
| 77 | + margin-bottom: 16px; | ||
| 78 | + | ||
| 79 | + h2 { | ||
| 80 | + margin: 0; | ||
| 81 | + min-width: 0; | ||
| 82 | + font-size: 1.125rem; | ||
| 83 | + overflow-wrap: anywhere; | ||
| 84 | + } | ||
| 85 | + | ||
| 86 | + form { | ||
| 87 | + margin: 0; | ||
| 88 | + flex: none; | ||
| 89 | + } | ||
| 90 | + } | ||
| 91 | + | ||
| 92 | + .kv-grid { | ||
| 93 | + grid-template-columns: repeat(2, minmax(0, 1fr)); | ||
| 94 | + | ||
| 95 | + @media (max-width: 520px) { | ||
| 96 | + grid-template-columns: minmax(0, 1fr); | ||
| 97 | + } | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + > form { | ||
| 101 | + margin-top: 16px; | ||
| 102 | + } | ||
| 103 | +} | ||
| 104 | + | ||
| 54 | // Admin user detail. The header: a back link, the avatar, the name with a status dot and a role | 105 | // Admin user detail. The header: a back link, the avatar, the name with a status dot and a role |
| 55 | // badge, one muted meta line, then one row of small facts. Under it the actions are hairline rows | 106 | // badge, one muted meta line, then one row of small facts. Under it the actions are hairline rows |
| 56 | // (title and one line of help on the left, the button on the right); the destructive ones sit in | 107 | // (title and one line of help on the left, the button on the right); the destructive ones sit in |