Everything live-updates: server settings and the banner, repo header counts and switches, labels, milestones, review requests, pull timeline, runner online state, health, CI artifacts and purges, and admin CLI writes
Browse files at this commit374e72194e656b81a7ece3889a901937daef7a0fParent: 24b6025- feat
- everything live-updates: server settings and the banner, repo header counts and switches, labels, milestones, review requests, pull timeline, runner online state, health, CI artifacts and purges, and admin CLI writes
- small-range settings and required approvals use the stepper
53 changed files +1314 -220
- crates/forge-core/src/store/ci.rs +47 -14
- crates/forge-core/src/store/health.rs +12 -1
- crates/forge-web/assets/nav.js +45 -12
- crates/forge-web/src/admin_cli.rs +39 -1
- crates/forge-web/src/admin_client.rs +27 -0
- crates/forge-web/src/alerts.rs +15 -0
- crates/forge-web/src/boot.rs +1 -0
- crates/forge-web/src/ci/api.rs +15 -0
- crates/forge-web/src/ci/live.rs +51 -0
- crates/forge-web/src/ci/reaper.rs +21 -1
- crates/forge-web/src/importer/mod.rs +22 -0
- crates/forge-web/src/internal.rs +97 -0
- crates/forge-web/src/live.rs +24 -4
- crates/forge-web/src/mail/worker.rs +6 -1
- crates/forge-web/src/merge_queue.rs +12 -10
- crates/forge-web/src/mirrors/mod.rs +3 -0
- crates/forge-web/src/oci/manifests.rs +4 -0
- crates/forge-web/src/package_ops.rs +12 -0
- crates/forge-web/src/pages/admin_health.rs +74 -17
- crates/forge-web/src/pages/admin_runners.rs +2 -8
- crates/forge-web/src/pages/admin_server.rs +9 -0
- crates/forge-web/src/pages/assets.rs +3 -1
- crates/forge-web/src/pages/banner.rs +3 -0
- crates/forge-web/src/pages/ci_job.rs +75 -39
- crates/forge-web/src/pages/ci_runs.rs +0 -7
- crates/forge-web/src/pages/ci_tests.rs +7 -6
- crates/forge-web/src/pages/code_live.rs +137 -24
- crates/forge-web/src/pages/code_search.rs +3 -0
- crates/forge-web/src/pages/compare.rs +4 -0
- crates/forge-web/src/pages/discussion_settings.rs +3 -0
- crates/forge-web/src/pages/edit_history.rs +7 -3
- crates/forge-web/src/pages/import.rs +32 -1
- crates/forge-web/src/pages/issue_parts.rs +2 -0
- crates/forge-web/src/pages/issues_list.rs +4 -0
- crates/forge-web/src/pages/labels_page.rs +10 -3
- crates/forge-web/src/pages/milestones_page.rs +5 -2
- crates/forge-web/src/pages/notifications.rs +8 -0
- crates/forge-web/src/pages/org_live.rs +4 -2
- crates/forge-web/src/pages/org_new.rs +3 -0
- crates/forge-web/src/pages/org_settings.rs +5 -1
- crates/forge-web/src/pages/profile.rs +18 -0
- crates/forge-web/src/pages/profile_pins.rs +52 -4
- crates/forge-web/src/pages/pull_live.rs +48 -1
- crates/forge-web/src/pages/pull_reviews.rs +2 -0
- crates/forge-web/src/pages/repo.rs +2 -2
- crates/forge-web/src/pages/repo_settings.rs +10 -4
- crates/forge-web/src/pages/repo_settings_live.rs +8 -1
- crates/forge-web/src/pages/review_requests.rs +45 -3
- crates/forge-web/src/pages/settings_live.rs +248 -41
- crates/forge-web/src/pages/settings_profile.rs +15 -5
- crates/forge-web/src/pages/wiki.rs +3 -0
- crates/forge-web/src/post_update.rs +9 -0
- crates/forge-web/src/views/mod.rs +1 -1
crates/forge-core/src/store/ci.rsmodified+47 -14
| @@ -738,6 +738,19 @@ impl Store { | |||
| 738 | Ok(true) | 738 | Ok(true) |
| 739 | } | 739 | } |
| 740 | 740 | ||
| 741 | + /// Whether the runner is disabled. `false` when the runner is gone. A primary-key read. | ||
| 742 | + pub async fn runner_disabled(&self, id: &str) -> Result<bool> { | ||
| 743 | + let conn = self.read_conn().await; | ||
| 744 | + let found = fetch_opt( | ||
| 745 | + &conn, | ||
| 746 | + "SELECT disabled FROM ci_runners WHERE id = ?1", | ||
| 747 | + (id.to_string(),), | ||
| 748 | + |row| col_bool(row, 0), | ||
| 749 | + ) | ||
| 750 | + .await?; | ||
| 751 | + Ok(found.unwrap_or(false)) | ||
| 752 | + } | ||
| 753 | + | ||
| 741 | /// The runner's concurrency override, read fresh. `None` when unset or the runner is gone. | 754 | /// The runner's concurrency override, read fresh. `None` when unset or the runner is gone. |
| 742 | pub async fn runner_concurrency_override(&self, id: &str) -> Result<Option<u32>> { | 755 | pub async fn runner_concurrency_override(&self, id: &str) -> Result<Option<u32>> { |
| 743 | let conn = self.read_conn().await; | 756 | let conn = self.read_conn().await; |
| @@ -1641,26 +1654,38 @@ impl Store { | |||
| 1641 | /// but the newest `keep_runs` runs that have artifacts are deleted (0 keeps all). Then, if | 1654 | /// but the newest `keep_runs` runs that have artifacts are deleted (0 keeps all). Then, if |
| 1642 | /// `max_total_bytes` is non-zero and the artifacts left still exceed it, the artifacts of the | 1655 | /// `max_total_bytes` is non-zero and the artifacts left still exceed it, the artifacts of the |
| 1643 | /// oldest runs are deleted a whole run at a time until the total fits. Artifact ids are | 1656 | /// oldest runs are deleted a whole run at a time until the total fits. Artifact ids are |
| 1644 | - /// returned (deduplicated) so the caller deletes the files. | 1657 | + /// returned (deduplicated) so the caller deletes the files. Run ids are returned too (the runs |
| 1658 | + /// whose logs or artifacts went), so the pages showing them can be woken. | ||
| 1645 | pub async fn purge_old( | 1659 | pub async fn purge_old( |
| 1646 | &self, | 1660 | &self, |
| 1647 | logs_before: &str, | 1661 | logs_before: &str, |
| 1648 | artifacts_before: &str, | 1662 | artifacts_before: &str, |
| 1649 | keep_runs: u32, | 1663 | keep_runs: u32, |
| 1650 | max_total_bytes: u64, | 1664 | max_total_bytes: u64, |
| 1651 | - ) -> Result<(Vec<String>, Vec<String>)> { | 1665 | + ) -> Result<(Vec<String>, Vec<String>, Vec<String>)> { |
| 1652 | let conn = self.inner.conn.lock().await; | 1666 | let conn = self.inner.conn.lock().await; |
| 1653 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 1667 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 1654 | - let outcome: Result<(Vec<String>, Vec<String>)> = async { | 1668 | + let outcome: Result<(Vec<String>, Vec<String>, Vec<String>)> = async { |
| 1655 | - let job_ids = fetch_all( | 1669 | + // Which run owns each artifact, read before the rows go. |
| 1670 | + let owners: BTreeMap<String, String> = fetch_all( | ||
| 1656 | &tx, | 1671 | &tx, |
| 1657 | - "SELECT j.id FROM ci_jobs j JOIN ci_runs r ON r.id = j.run_id \ | 1672 | + "SELECT a.id, j.run_id FROM ci_artifacts a JOIN ci_jobs j ON j.id = a.job_id", |
| 1673 | + (), | ||
| 1674 | + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), | ||
| 1675 | + ) | ||
| 1676 | + .await? | ||
| 1677 | + .into_iter() | ||
| 1678 | + .collect(); | ||
| 1679 | + let log_jobs = fetch_all( | ||
| 1680 | + &tx, | ||
| 1681 | + "SELECT j.id, j.run_id FROM ci_jobs j JOIN ci_runs r ON r.id = j.run_id \ | ||
| 1658 | WHERE r.finished_at IS NOT NULL AND r.finished_at < ?1 AND j.log_bytes > 0 \ | 1682 | WHERE r.finished_at IS NOT NULL AND r.finished_at < ?1 AND j.log_bytes > 0 \ |
| 1659 | ORDER BY j.id", | 1683 | ORDER BY j.id", |
| 1660 | (logs_before.to_string(),), | 1684 | (logs_before.to_string(),), |
| 1661 | - |row| col_text(row, 0), | 1685 | + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), |
| 1662 | ) | 1686 | ) |
| 1663 | .await?; | 1687 | .await?; |
| 1688 | + let job_ids: Vec<String> = log_jobs.iter().map(|(id, _)| id.clone()).collect(); | ||
| 1664 | for id in &job_ids { | 1689 | for id in &job_ids { |
| 1665 | tx.execute( | 1690 | tx.execute( |
| 1666 | "UPDATE ci_jobs SET log_bytes = 0 WHERE id = ?1", | 1691 | "UPDATE ci_jobs SET log_bytes = 0 WHERE id = ?1", |
| @@ -1738,7 +1763,14 @@ impl Store { | |||
| 1738 | 1763 | ||
| 1739 | artifact_ids.sort(); | 1764 | artifact_ids.sort(); |
| 1740 | artifact_ids.dedup(); | 1765 | artifact_ids.dedup(); |
| 1741 | - Ok((job_ids, artifact_ids)) | 1766 | + let mut run_ids: Vec<String> = log_jobs |
| 1767 | + .into_iter() | ||
| 1768 | + .map(|(_, run)| run) | ||
| 1769 | + .chain(artifact_ids.iter().filter_map(|id| owners.get(id).cloned())) | ||
| 1770 | + .collect(); | ||
| 1771 | + run_ids.sort(); | ||
| 1772 | + run_ids.dedup(); | ||
| 1773 | + Ok((job_ids, artifact_ids, run_ids)) | ||
| 1742 | } | 1774 | } |
| 1743 | .await; | 1775 | .await; |
| 1744 | finish(tx, outcome).await | 1776 | finish(tx, outcome).await |
| @@ -3278,11 +3310,12 @@ mod tests { | |||
| 3278 | 3310 | ||
| 3279 | assert_eq!( | 3311 | assert_eq!( |
| 3280 | fx.store.purge_old(DAWN, DAWN, 0, 0).await.unwrap(), | 3312 | fx.store.purge_old(DAWN, DAWN, 0, 0).await.unwrap(), |
| 3281 | - (vec![], vec![]) | 3313 | + (vec![], vec![], vec![]) |
| 3282 | ); | 3314 | ); |
| 3283 | - let (logs, artifacts) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap(); | 3315 | + let (logs, artifacts, runs) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap(); |
| 3284 | assert_eq!(logs, vec![a.id.clone()]); | 3316 | assert_eq!(logs, vec![a.id.clone()]); |
| 3285 | assert_eq!(artifacts.len(), 1); | 3317 | assert_eq!(artifacts.len(), 1); |
| 3318 | + assert_eq!(runs, vec![run.id.clone()]); | ||
| 3286 | assert_eq!(job_named(&fx.store, &run.id, "a").await.log_bytes, 0); | 3319 | assert_eq!(job_named(&fx.store, &run.id, "a").await.log_bytes, 0); |
| 3287 | assert!( | 3320 | assert!( |
| 3288 | fx.store | 3321 | fx.store |
| @@ -3291,8 +3324,8 @@ mod tests { | |||
| 3291 | .unwrap() | 3324 | .unwrap() |
| 3292 | .is_none() | 3325 | .is_none() |
| 3293 | ); | 3326 | ); |
| 3294 | - let (logs2, artifacts2) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap(); | 3327 | + let (logs2, artifacts2, runs2) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap(); |
| 3295 | - assert!(logs2.is_empty() && artifacts2.is_empty()); | 3328 | + assert!(logs2.is_empty() && artifacts2.is_empty() && runs2.is_empty()); |
| 3296 | } | 3329 | } |
| 3297 | 3330 | ||
| 3298 | #[tokio::test] | 3331 | #[tokio::test] |
| @@ -3319,12 +3352,12 @@ mod tests { | |||
| 3319 | tokio::time::sleep(Duration::from_millis(2)).await; | 3352 | tokio::time::sleep(Duration::from_millis(2)).await; |
| 3320 | } | 3353 | } |
| 3321 | // Keep the newest two runs: the oldest run's artifact goes. | 3354 | // Keep the newest two runs: the oldest run's artifact goes. |
| 3322 | - let (_, deleted) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap(); | 3355 | + let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap(); |
| 3323 | assert_eq!(deleted, vec![artifacts[0].clone()]); | 3356 | assert_eq!(deleted, vec![artifacts[0].clone()]); |
| 3324 | // 20 + 30 bytes left against a 35 byte limit: the older run (20 bytes) goes. | 3357 | // 20 + 30 bytes left against a 35 byte limit: the older run (20 bytes) goes. |
| 3325 | - let (_, deleted) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); | 3358 | + let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); |
| 3326 | assert_eq!(deleted, vec![artifacts[1].clone()]); | 3359 | assert_eq!(deleted, vec![artifacts[1].clone()]); |
| 3327 | - let (_, again) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); | 3360 | + let (_, again, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); |
| 3328 | assert!(again.is_empty()); | 3361 | assert!(again.is_empty()); |
| 3329 | } | 3362 | } |
| 3330 | 3363 | ||
crates/forge-core/src/store/health.rsmodified+12 -1
| @@ -2,11 +2,22 @@ | |||
| 2 | 2 | ||
| 3 | use super::{Store, col_int, fetch_opt}; | 3 | use super::{Store, col_int, fetch_opt}; |
| 4 | use crate::error::{Error, Result}; | 4 | use crate::error::{Error, Result}; |
| 5 | -use crate::time::stamp_ago; | 5 | +use crate::time::{stamp_ago, stamp_to_unix}; |
| 6 | 6 | ||
| 7 | /// Window in which a runner's last report counts as online. | 7 | /// Window in which a runner's last report counts as online. |
| 8 | pub const RUNNER_ONLINE_SECS: u64 = 90; | 8 | pub const RUNNER_ONLINE_SECS: u64 = 90; |
| 9 | 9 | ||
| 10 | +/// Whether a runner counts as online at `now_unix`: enabled, and its last report within | ||
| 11 | +/// [`RUNNER_ONLINE_SECS`]. The runners page dot and the live signal of the runners page both use | ||
| 12 | +/// this one rule. | ||
| 13 | +pub fn runner_is_online(disabled: bool, last_seen_at: Option<&str>, now_unix: i64) -> bool { | ||
| 14 | + let limit = i64::try_from(RUNNER_ONLINE_SECS).unwrap_or(i64::MAX); | ||
| 15 | + !disabled | ||
| 16 | + && last_seen_at | ||
| 17 | + .and_then(stamp_to_unix) | ||
| 18 | + .is_some_and(|seen| now_unix.saturating_sub(seen) <= limit) | ||
| 19 | +} | ||
| 20 | + | ||
| 10 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | 21 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 11 | pub struct HealthCounts { | 22 | pub struct HealthCounts { |
| 12 | pub repos: i64, | 23 | pub repos: i64, |
crates/forge-web/assets/nav.jsmodified+45 -12
| @@ -174,6 +174,7 @@ | |||
| 174 | syncPush(); | 174 | syncPush(); |
| 175 | syncTick(); | 175 | syncTick(); |
| 176 | syncRel(); | 176 | syncRel(); |
| 177 | + syncBannerExpiry(); | ||
| 177 | } | 178 | } |
| 178 | 179 | ||
| 179 | // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place. | 180 | // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place. |
| @@ -550,7 +551,11 @@ | |||
| 550 | if (window.EventSource) { | 551 | if (window.EventSource) { |
| 551 | alive = keepOpen('/-/alive', aliveOpen, aliveDown, { | 552 | alive = keepOpen('/-/alive', aliveOpen, aliveDown, { |
| 552 | theme: applyAppearance, | 553 | theme: applyAppearance, |
| 553 | - language: function () { refreshLive(true); } | 554 | + language: function () { refreshLive(true); }, |
| 555 | + // The header's identity (username, avatar, admin rights) or the session changed: the page re-renders. | ||
| 556 | + account: function () { refreshLive(true); }, | ||
| 557 | + // A live server setting changed (the banner, registration, limits...): the page re-renders. | ||
| 558 | + settings: function () { refreshLive(true); } | ||
| 554 | }); | 559 | }); |
| 555 | document.addEventListener('visibilitychange', function () { wake(false); }); | 560 | document.addEventListener('visibilitychange', function () { wake(false); }); |
| 556 | document.addEventListener('resume', function () { wake(true); }); | 561 | document.addEventListener('resume', function () { wake(true); }); |
| @@ -768,7 +773,9 @@ | |||
| 768 | document.addEventListener('click', function (e) { | 773 | document.addEventListener('click', function (e) { |
| 769 | var btn = e.target && e.target.closest ? e.target.closest('[data-step]') : null; | 774 | var btn = e.target && e.target.closest ? e.target.closest('[data-step]') : null; |
| 770 | if (!btn || !btn.form) { return; } | 775 | if (!btn || !btn.form) { return; } |
| 771 | - var field = btn.form.querySelector('input[type="number"]'); | 776 | + // The pill's own field first: a form can hold several number fields (the server settings). |
| 777 | + var pill = btn.closest('.runner-pill'); | ||
| 778 | + var field = (pill && pill.querySelector('input[type="number"]')) || btn.form.querySelector('input[type="number"]'); | ||
| 772 | if (!field) { return; } | 779 | if (!field) { return; } |
| 773 | var next = (parseFloat(field.value) || 0) + (parseFloat(btn.getAttribute('data-step')) || 0); | 780 | var next = (parseFloat(field.value) || 0) + (parseFloat(btn.getAttribute('data-step')) || 0); |
| 774 | var min = parseFloat(field.min); | 781 | var min = parseFloat(field.min); |
| @@ -1099,19 +1106,18 @@ | |||
| 1099 | // Live unread count. The bell is re-rendered by every swap, so it is looked up on each update. One | 1106 | // Live unread count. The bell is re-rendered by every swap, so it is looked up on each update. One |
| 1100 | // EventSource serves the page and stays open across swaps. It is opened only while a bell is shown | 1107 | // EventSource serves the page and stays open across swaps. It is opened only while a bell is shown |
| 1101 | // (signed-in pages) and closed when the bell is gone. The server pushes each change; nothing polls. | 1108 | // (signed-in pages) and closed when the bell is gone. The server pushes each change; nothing polls. |
| 1109 | + // The count shows twice: on the bell, and next to Notifications in the sidebar and the phone menu. | ||
| 1102 | var unreadStream = null; | 1110 | var unreadStream = null; |
| 1103 | 1111 | ||
| 1104 | function bell() { return document.querySelector('a.bell'); } | 1112 | function bell() { return document.querySelector('a.bell'); } |
| 1105 | 1113 | ||
| 1106 | - // Shows the count the way the server renders it: a `.bell-count` span with the number, or no span at zero. | 1114 | + // Shows the count in one link the way the server renders it: a span with the number, or no span at zero. |
| 1107 | - function setUnread(n) { | 1115 | + function setCount(el, cls, n) { |
| 1108 | - var el = bell(); | 1116 | + var badge = el.querySelector('.' + cls); |
| 1109 | - if (!el) { return; } | ||
| 1110 | - var badge = el.querySelector('.bell-count'); | ||
| 1111 | if (n > 0) { | 1117 | if (n > 0) { |
| 1112 | if (!badge) { | 1118 | if (!badge) { |
| 1113 | badge = document.createElement('span'); | 1119 | badge = document.createElement('span'); |
| 1114 | - badge.className = 'bell-count'; | 1120 | + badge.className = cls; |
| 1115 | el.appendChild(badge); | 1121 | el.appendChild(badge); |
| 1116 | } | 1122 | } |
| 1117 | badge.textContent = String(n); | 1123 | badge.textContent = String(n); |
| @@ -1120,6 +1126,14 @@ | |||
| 1120 | } | 1126 | } |
| 1121 | } | 1127 | } |
| 1122 | 1128 | ||
| 1129 | + function setUnread(n) { | ||
| 1130 | + var el = bell(); | ||
| 1131 | + if (el) { setCount(el, 'bell-count', n); } | ||
| 1132 | + // The sidebar's Notifications link (the sidebar and the phone menu hold one each), `.count` as the server renders it. | ||
| 1133 | + var links = document.querySelectorAll('nav.side-links a[href="/notifications"]'); | ||
| 1134 | + for (var i = 0; i < links.length; i++) { setCount(links[i], 'count', n); } | ||
| 1135 | + } | ||
| 1136 | + | ||
| 1123 | function syncUnread() { | 1137 | function syncUnread() { |
| 1124 | if (!bell()) { | 1138 | if (!bell()) { |
| 1125 | if (unreadStream) { unreadStream.close(); unreadStream = null; } | 1139 | if (unreadStream) { unreadStream.close(); unreadStream = null; } |
| @@ -1625,14 +1639,14 @@ | |||
| 1625 | // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose | 1639 | // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose |
| 1626 | // `log` events append the new bytes as they come. The stream opens at the tail's data-offset, and | 1640 | // `log` events append the new bytes as they come. The stream opens at the tail's data-offset, and |
| 1627 | // each swap brings a fresh offset, so the stream is opened again after every swap. The server ends | 1641 | // each swap brings a fresh offset, so the stream is opened again after every swap. The server ends |
| 1628 | - // the stream once the status is terminal, and the swap that shows that page (no data-live) closes it. | 1642 | + // the stream once a run is terminal; a job's stream stays open and wakes on its own changes, and the swap that shows that page (no data-live) closes it. |
| 1629 | // Every element with data-live names an event stream the page follows: the repo header, the | 1643 | // Every element with data-live names an event stream the page follows: the repo header, the |
| 1630 | // page's own list, issue or run. One EventSource is open per distinct URL, so a page with several | 1644 | // page's own list, issue or run. One EventSource is open per distinct URL, so a page with several |
| 1631 | // streams updates for each of them. A `changed` event re-fetches the page and swaps it in with no | 1645 | // streams updates for each of them. A `changed` event re-fetches the page and swaps it in with no |
| 1632 | // history entry and the scroll kept. A job page also has a log tail (data-live-log) whose `log` | 1646 | // history entry and the scroll kept. A job page also has a log tail (data-live-log) whose `log` |
| 1633 | // events append the new bytes as they come. The tail's stream opens at its data-offset, and each | 1647 | // events append the new bytes as they come. The tail's stream opens at its data-offset, and each |
| 1634 | // swap brings a fresh offset, so that stream is opened again after every swap. The server ends | 1648 | // swap brings a fresh offset, so that stream is opened again after every swap. The server ends |
| 1635 | - // the stream once the status is terminal, and the swap that shows that page (no data-live) closes it. | 1649 | + // the stream once a run is terminal; a job's stream stays open and wakes on its own changes, and the swap that shows that page (no data-live) closes it. |
| 1636 | var liveStreams = {}; // URL (with the tail's offset) -> EventSource | 1650 | var liveStreams = {}; // URL (with the tail's offset) -> EventSource |
| 1637 | var liveTimer = null; // a run list's pending refresh: bursts of events (log lines) share one | 1651 | var liveTimer = null; // a run list's pending refresh: bursts of events (log lines) share one |
| 1638 | 1652 | ||
| @@ -1656,7 +1670,8 @@ | |||
| 1656 | function openLive(url) { | 1670 | function openLive(url) { |
| 1657 | var es = new EventSource(url); | 1671 | var es = new EventSource(url); |
| 1658 | es.addEventListener('changed', function (e) { | 1672 | es.addEventListener('changed', function (e) { |
| 1659 | - // A job page's stream opens with the status the page already shows: nothing to re-render then. | 1673 | + // A job event carries the job's fingerprint (status|artifact ids|log), which the page renders as |
| 1674 | + // data-live-state. The same fingerprint means nothing changed: nothing to re-render then. | ||
| 1660 | var job = document.querySelector('[data-live-log]'); | 1675 | var job = document.querySelector('[data-live-log]'); |
| 1661 | var wrap = job ? job.closest('[data-live]') : null; | 1676 | var wrap = job ? job.closest('[data-live]') : null; |
| 1662 | if (wrap && wrap.getAttribute('data-live-state') === e.data) { return; } | 1677 | if (wrap && wrap.getAttribute('data-live-state') === e.data) { return; } |
| @@ -1704,7 +1719,8 @@ | |||
| 1704 | 1719 | ||
| 1705 | // A change re-renders the current page. It waits while a navigation is on the wire, since that | 1720 | // A change re-renders the current page. It waits while a navigation is on the wire, since that |
| 1706 | // response could be superseded: the change is kept and sent after that request completes. | 1721 | // response could be superseded: the change is kept and sent after that request completes. |
| 1707 | - // `force` re-renders a page that holds no stream of its own (a language change, sent by /-/alive). | 1722 | + // `force` re-renders a page that holds no stream of its own (a language change, or a live server |
| 1723 | + // setting such as the banner, sent by /-/alive). | ||
| 1708 | function refreshLive(force) { | 1724 | function refreshLive(force) { |
| 1709 | if (!force && !Object.keys(liveStreams).length) { return; } | 1725 | if (!force && !Object.keys(liveStreams).length) { return; } |
| 1710 | // A one-time secret (a token, recovery codes) is on screen only in the response that made it: a | 1726 | // A one-time secret (a token, recovery codes) is on screen only in the response that made it: a |
| @@ -1813,6 +1829,22 @@ | |||
| 1813 | } | 1829 | } |
| 1814 | } | 1830 | } |
| 1815 | 1831 | ||
| 1832 | + // The site banner with an expiry carries `data-expires` (unix seconds). When it passes, the banner | ||
| 1833 | + // is removed here, so an open page does not keep one that is gone. One timer is armed for the | ||
| 1834 | + // banner on the page; a swap re-arms it. setTimeout takes a 32-bit delay, so a longer wait is armed | ||
| 1835 | + // again when this one fires. | ||
| 1836 | + var bannerTimer = null; | ||
| 1837 | + | ||
| 1838 | + function syncBannerExpiry() { | ||
| 1839 | + if (bannerTimer) { clearTimeout(bannerTimer); } | ||
| 1840 | + bannerTimer = null; | ||
| 1841 | + var banner = document.querySelector('.site-banner[data-expires]'); | ||
| 1842 | + if (!banner) { return; } | ||
| 1843 | + var wait = (parseInt(banner.getAttribute('data-expires'), 10) || 0) * 1000 - Date.now(); | ||
| 1844 | + if (wait <= 0) { banner.remove(); return; } | ||
| 1845 | + bannerTimer = setTimeout(syncBannerExpiry, Math.min(wait, 2147483647)); | ||
| 1846 | + } | ||
| 1847 | + | ||
| 1816 | function syncRel() { | 1848 | function syncRel() { |
| 1817 | var now = document.documentElement.getAttribute('data-rel-now'); | 1849 | var now = document.documentElement.getAttribute('data-rel-now'); |
| 1818 | relSkew = now === null ? 0 : (parseInt(now, 10) || 0) * 1000 - Date.now(); | 1850 | relSkew = now === null ? 0 : (parseInt(now, 10) || 0) * 1000 - Date.now(); |
| @@ -1888,6 +1920,7 @@ | |||
| 1888 | syncPush(); | 1920 | syncPush(); |
| 1889 | syncTick(); | 1921 | syncTick(); |
| 1890 | syncRel(); | 1922 | syncRel(); |
| 1923 | + syncBannerExpiry(); | ||
| 1891 | 1924 | ||
| 1892 | window.__forgeQuery = function (href) { | 1925 | window.__forgeQuery = function (href) { |
| 1893 | var url = pageUrl(href); | 1926 | var url = pageUrl(href); |
crates/forge-web/src/admin_cli.rsmodified+39 -1
| @@ -25,7 +25,7 @@ use forge_core::store::user_delete::{DeletionReport, GHOST_USERNAME}; | |||
| 25 | use forge_core::{AuditAction, Config, Error, Store, names, token}; | 25 | use forge_core::{AuditAction, Config, Error, Store, names, token}; |
| 26 | use forge_git::GitEnv; | 26 | use forge_git::GitEnv; |
| 27 | 27 | ||
| 28 | -use crate::admin_client::running_server; | 28 | +use crate::admin_client::{notify_live, running_server}; |
| 29 | use crate::audit::{self, Actor, Target}; | 29 | use crate::audit::{self, Actor, Target}; |
| 30 | use crate::auth::hash_password_async; | 30 | use crate::auth::hash_password_async; |
| 31 | use crate::backup::{ | 31 | use crate::backup::{ |
| @@ -98,6 +98,11 @@ pub async fn create_user( | |||
| 98 | serde_json::json!({ "admin": user.is_admin }), | 98 | serde_json::json!({ "admin": user.is_admin }), |
| 99 | ) | 99 | ) |
| 100 | .await; | 100 | .await; |
| 101 | + notify_live( | ||
| 102 | + &config, | ||
| 103 | + serde_json::json!({ "admin": ["users", "audit"], "user_ids": [user.id] }), | ||
| 104 | + ) | ||
| 105 | + .await; | ||
| 101 | println!( | 106 | println!( |
| 102 | "created user {} (id {}{})", | 107 | "created user {} (id {}{})", |
| 103 | user.username, | 108 | user.username, |
| @@ -112,7 +117,16 @@ pub async fn create_user( | |||
| 112 | pub async fn delete_user(config_path: &Path, username: &str, yes: bool) -> forge_core::Result<()> { | 117 | pub async fn delete_user(config_path: &Path, username: &str, yes: bool) -> forge_core::Result<()> { |
| 113 | let config = Config::load(config_path)?; | 118 | let config = Config::load(config_path)?; |
| 114 | let store = Store::open(&config.database).await?; | 119 | let store = Store::open(&config.database).await?; |
| 120 | + // The id is gone once the account is deleted, so it is read first. | ||
| 121 | + let user_id = store.user_by_username(username).await?.map(|u| u.id); | ||
| 115 | let report = delete_user_in(&store, username, yes).await?; | 122 | let report = delete_user_in(&store, username, yes).await?; |
| 123 | + if let Some(id) = user_id { | ||
| 124 | + notify_live( | ||
| 125 | + &config, | ||
| 126 | + serde_json::json!({ "admin": ["users", "audit"], "user_ids": [id] }), | ||
| 127 | + ) | ||
| 128 | + .await; | ||
| 129 | + } | ||
| 116 | print_deletion_report(&format!("deleted {username}"), &report); | 130 | print_deletion_report(&format!("deleted {username}"), &report); |
| 117 | Ok(()) | 131 | Ok(()) |
| 118 | } | 132 | } |
| @@ -207,6 +221,15 @@ pub async fn set_username( | |||
| 207 | serde_json::json!({ "from": user.username }), | 221 | serde_json::json!({ "from": user.username }), |
| 208 | ) | 222 | ) |
| 209 | .await; | 223 | .await; |
| 224 | + notify_live( | ||
| 225 | + &config, | ||
| 226 | + serde_json::json!({ | ||
| 227 | + "admin": ["users", "audit"], | ||
| 228 | + "user_ids": [user.id], | ||
| 229 | + "account_ids": [user.id], | ||
| 230 | + }), | ||
| 231 | + ) | ||
| 232 | + .await; | ||
| 210 | println!("renamed {} to {}", user.username, display); | 233 | println!("renamed {} to {}", user.username, display); |
| 211 | Ok(()) | 234 | Ok(()) |
| 212 | } | 235 | } |
| @@ -216,7 +239,19 @@ pub async fn set_username( | |||
| 216 | pub async fn reset_password(config_path: &Path, username: &str) -> forge_core::Result<()> { | 239 | pub async fn reset_password(config_path: &Path, username: &str) -> forge_core::Result<()> { |
| 217 | let config = Config::load(config_path)?; | 240 | let config = Config::load(config_path)?; |
| 218 | let store = Store::open(&config.database).await?; | 241 | let store = Store::open(&config.database).await?; |
| 242 | + let user_id = store.user_by_username(username).await?.map(|u| u.id); | ||
| 219 | let (password, display) = reset_password_in(&store, username).await?; | 243 | let (password, display) = reset_password_in(&store, username).await?; |
| 244 | + if let Some(id) = user_id { | ||
| 245 | + notify_live( | ||
| 246 | + &config, | ||
| 247 | + serde_json::json!({ | ||
| 248 | + "admin": ["users", "audit"], | ||
| 249 | + "user_ids": [id], | ||
| 250 | + "account_ids": [id], | ||
| 251 | + }), | ||
| 252 | + ) | ||
| 253 | + .await; | ||
| 254 | + } | ||
| 220 | println!("temporary password for {display}: {password}"); | 255 | println!("temporary password for {display}: {password}"); |
| 221 | println!("all sessions of {display} were signed out; change this password after logging in"); | 256 | println!("all sessions of {display} were signed out; change this password after logging in"); |
| 222 | Ok(()) | 257 | Ok(()) |
| @@ -301,6 +336,9 @@ pub async fn audit_purge(config_path: &Path, days: u64) -> forge_core::Result<() | |||
| 301 | let cutoff = forge_core::time::stamp_ago(Duration::from_secs(days.saturating_mul(86_400))); | 336 | let cutoff = forge_core::time::stamp_ago(Duration::from_secs(days.saturating_mul(86_400))); |
| 302 | let removed = store.purge_audit_before(&cutoff).await?; | 337 | let removed = store.purge_audit_before(&cutoff).await?; |
| 303 | tracing::info!(removed, cutoff = %cutoff, "purged audit log entries"); | 338 | tracing::info!(removed, cutoff = %cutoff, "purged audit log entries"); |
| 339 | + if removed > 0 { | ||
| 340 | + notify_live(&config, serde_json::json!({ "admin": ["audit"] })).await; | ||
| 341 | + } | ||
| 304 | println!("purged {removed} audit log entries older than {days} days"); | 342 | println!("purged {removed} audit log entries older than {days} days"); |
| 305 | Ok(()) | 343 | Ok(()) |
| 306 | } | 344 | } |
crates/forge-web/src/admin_client.rsmodified+27 -0
| @@ -91,6 +91,33 @@ pub async fn running_server(config: &Config) -> Result<Option<AdminClient>> { | |||
| 91 | })) | 91 | })) |
| 92 | } | 92 | } |
| 93 | 93 | ||
| 94 | +/// How long a CLI write waits for the running server to answer a live notice. | ||
| 95 | +const NOTIFY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2); | ||
| 96 | + | ||
| 97 | +/// Tells the running server which open pages a CLI write changed (`/internal/admin/live`). Best | ||
| 98 | +/// effort: no server, a stale socket, a refusal or a timeout is logged at debug and ignored, so | ||
| 99 | +/// the command never fails because of it. | ||
| 100 | +pub async fn notify_live(config: &Config, body: Value) { | ||
| 101 | + let server = match running_server(config).await { | ||
| 102 | + Ok(Some(server)) => server, | ||
| 103 | + Ok(None) => return, | ||
| 104 | + Err(e) => { | ||
| 105 | + tracing::debug!(error = %e, "live: no server to notify"); | ||
| 106 | + return; | ||
| 107 | + } | ||
| 108 | + }; | ||
| 109 | + match tokio::time::timeout( | ||
| 110 | + NOTIFY_TIMEOUT, | ||
| 111 | + server.post::<Value>("/internal/admin/live", &body), | ||
| 112 | + ) | ||
| 113 | + .await | ||
| 114 | + { | ||
| 115 | + Ok(Ok(_)) => {} | ||
| 116 | + Ok(Err(e)) => tracing::debug!(error = %e, "live: the server refused the notice"), | ||
| 117 | + Err(_) => tracing::debug!("live: the server did not answer the notice in time"), | ||
| 118 | + } | ||
| 119 | +} | ||
| 120 | + | ||
| 94 | #[derive(serde::Deserialize)] | 121 | #[derive(serde::Deserialize)] |
| 95 | struct ErrorBody { | 122 | struct ErrorBody { |
| 96 | error: String, | 123 | error: String, |
crates/forge-web/src/alerts.rsmodified+15 -0
| @@ -327,6 +327,18 @@ pub async fn check_runners_at(state: &AppState, now: i64) { | |||
| 327 | } | 327 | } |
| 328 | }; | 328 | }; |
| 329 | let mut offline = std::collections::BTreeSet::new(); | 329 | let mut offline = std::collections::BTreeSet::new(); |
| 330 | + // The runners page dot flips on its own window, so a runner that goes quiet changes the page | ||
| 331 | + // here, not on its next report. Only a change wakes the page. | ||
| 332 | + for runner in &runners { | ||
| 333 | + let online = forge_core::store::health::runner_is_online( | ||
| 334 | + runner.disabled, | ||
| 335 | + runner.last_seen_at.as_deref(), | ||
| 336 | + now, | ||
| 337 | + ); | ||
| 338 | + state.ci_live.note_runner_online(&runner.id, online); | ||
| 339 | + } | ||
| 340 | + let ids: Vec<&str> = runners.iter().map(|r| r.id.as_str()).collect(); | ||
| 341 | + state.ci_live.forget_runners_except(&ids); | ||
| 330 | for runner in &runners { | 342 | for runner in &runners { |
| 331 | let seen = runner.last_seen_at.as_deref().and_then(stamp_to_unix); | 343 | let seen = runner.last_seen_at.as_deref().and_then(stamp_to_unix); |
| 332 | if runner.disabled || !alerts::runner_is_offline(now, seen, cfg.runner_offline_minutes) { | 344 | if runner.disabled || !alerts::runner_is_offline(now, seen, cfg.runner_offline_minutes) { |
| @@ -354,6 +366,9 @@ pub async fn check_slow(state: &AppState) { | |||
| 354 | check_disk(state).await; | 366 | check_disk(state).await; |
| 355 | check_backup_overdue(state, now_unix()).await; | 367 | check_backup_overdue(state, now_unix()).await; |
| 356 | check_replication(state, now_unix()).await; | 368 | check_replication(state, now_unix()).await; |
| 369 | + // A copy goes lagging by the clock alone, so the replication page is woken on this tick. Its | ||
| 370 | + // fingerprint drops the wake when no row changed. | ||
| 371 | + crate::live::admin().bump(&crate::live::Topic::AdminReplication); | ||
| 357 | let old = forge_core::time::stamp_ago(std::time::Duration::from_secs(90 * 86_400)); | 372 | let old = forge_core::time::stamp_ago(std::time::Duration::from_secs(90 * 86_400)); |
| 358 | if let Err(e) = state.store.prune_admin_alerts(&old).await { | 373 | if let Err(e) = state.store.prune_admin_alerts(&old).await { |
| 359 | tracing::error!(error = %e, "alerts: pruning failed"); | 374 | tracing::error!(error = %e, "alerts: pruning failed"); |
crates/forge-web/src/boot.rsmodified+1 -0
| @@ -159,6 +159,7 @@ pub async fn serve( | |||
| 159 | } | 159 | } |
| 160 | crate::alerts::on_boot(&state).await; | 160 | crate::alerts::on_boot(&state).await; |
| 161 | crate::ci::reaper::spawn(state.clone()); | 161 | crate::ci::reaper::spawn(state.clone()); |
| 162 | + crate::pages::admin_health::spawn_repo_size(state.clone()); | ||
| 162 | crate::ci::scheduled::spawn(state.clone()); | 163 | crate::ci::scheduled::spawn(state.clone()); |
| 163 | 164 | ||
| 164 | // Topcoat's builder-wide compression is off because it cannot filter by content type or path. | 165 | // Topcoat's builder-wide compression is off because it cannot filter by content type or path. |
crates/forge-web/src/ci/api.rsmodified+15 -0
| @@ -82,6 +82,8 @@ async fn runner_from(state: &AppState, headers: &HeaderMap) -> Result<CiRunner, | |||
| 82 | ))), | 82 | ))), |
| 83 | Ok(Some(runner)) => { | 83 | Ok(Some(runner)) => { |
| 84 | crate::alerts::runner_seen(state, &runner.id).await; | 84 | crate::alerts::runner_seen(state, &runner.id).await; |
| 85 | + // The stamp above is written, so a page that reads it after the wake sees it. | ||
| 86 | + state.ci_live.note_runner_online(&runner.id, true); | ||
| 85 | Ok(runner) | 87 | Ok(runner) |
| 86 | } | 88 | } |
| 87 | Ok(None) => Err(unauthorized()), | 89 | Ok(None) => Err(unauthorized()), |
| @@ -615,6 +617,12 @@ async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> { | |||
| 615 | if let Err(e) = state.store.touch_runner(runner_id).await { | 617 | if let Err(e) = state.store.touch_runner(runner_id).await { |
| 616 | tracing::warn!(error = %e, "ci: runner last-seen not stored"); | 618 | tracing::warn!(error = %e, "ci: runner last-seen not stored"); |
| 617 | } | 619 | } |
| 620 | + // A busy runner only heartbeats here. Its state is read only when it is not | ||
| 621 | + // recorded online, so a steady heartbeat costs a map lookup. | ||
| 622 | + if !state.ci_live.runner_recorded_online(runner_id) { | ||
| 623 | + let disabled = state.store.runner_disabled(runner_id).await.unwrap_or(false); | ||
| 624 | + state.ci_live.note_runner_online(runner_id, !disabled); | ||
| 625 | + } | ||
| 618 | let said = headers(cx) | 626 | let said = headers(cx) |
| 619 | .get(CONCURRENCY_HEADER) | 627 | .get(CONCURRENCY_HEADER) |
| 620 | .and_then(|v| v.to_str().ok()) | 628 | .and_then(|v| v.to_str().ok()) |
| @@ -836,6 +844,13 @@ async fn upload_artifact(cx: &Cx, body: Body) -> topcoat::Result<Response> { | |||
| 836 | } | 844 | } |
| 837 | match upload(state, &job, name, body).await { | 845 | match upload(state, &job, name, body).await { |
| 838 | Ok(artifact_id) => { | 846 | Ok(artifact_id) => { |
| 847 | + // The job's artifact list and its run's artifact list show the new one. The run page | ||
| 848 | + // follows its repo's stream, so the repo wakes too. | ||
| 849 | + state.ci_live.bump_job(&job.id); | ||
| 850 | + state.ci_live.bump_run(&job.run_id); | ||
| 851 | + if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await { | ||
| 852 | + state.ci_live.bump_repo(&run.repo_id); | ||
| 853 | + } | ||
| 839 | // A new artifact may push the store past its disk limit. Enforce it now, not at the | 854 | // A new artifact may push the store past its disk limit. Enforce it now, not at the |
| 840 | // next daily purge. The request does not wait for it. | 855 | // next daily purge. The request does not wait for it. |
| 841 | let state = state.clone(); | 856 | let state = state.clone(); |
crates/forge-web/src/ci/live.rsmodified+51 -0
| @@ -23,9 +23,43 @@ pub struct CiLive { | |||
| 23 | repos: Signals, | 23 | repos: Signals, |
| 24 | runners: Signals, | 24 | runners: Signals, |
| 25 | queues: Signals, | 25 | queues: Signals, |
| 26 | + /// The last online state each runner was seen in. Only a change wakes the runners pages. | ||
| 27 | + runner_online: Mutex<HashMap<String, bool>>, | ||
| 26 | } | 28 | } |
| 27 | 29 | ||
| 28 | impl CiLive { | 30 | impl CiLive { |
| 31 | + /// Records whether runner `runner_id` is online now. Wakes the runners pages only when that | ||
| 32 | + /// differs from the state last recorded, so a heartbeat of a runner that stays online costs one | ||
| 33 | + /// map lookup. | ||
| 34 | + pub fn note_runner_online(&self, runner_id: &str, online: bool) { | ||
| 35 | + let changed = self | ||
| 36 | + .runner_online | ||
| 37 | + .lock() | ||
| 38 | + .unwrap_or_else(PoisonError::into_inner) | ||
| 39 | + .insert(runner_id.to_owned(), online) | ||
| 40 | + != Some(online); | ||
| 41 | + if changed { | ||
| 42 | + self.bump_runners(); | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + /// Whether runner `runner_id` was last recorded online. | ||
| 47 | + pub fn runner_recorded_online(&self, runner_id: &str) -> bool { | ||
| 48 | + self.runner_online | ||
| 49 | + .lock() | ||
| 50 | + .unwrap_or_else(PoisonError::into_inner) | ||
| 51 | + .get(runner_id) | ||
| 52 | + == Some(&true) | ||
| 53 | + } | ||
| 54 | + | ||
| 55 | + /// Forgets the recorded state of every runner not in `keep`, so a deleted runner leaves no entry. | ||
| 56 | + pub fn forget_runners_except(&self, keep: &[&str]) { | ||
| 57 | + self.runner_online | ||
| 58 | + .lock() | ||
| 59 | + .unwrap_or_else(PoisonError::into_inner) | ||
| 60 | + .retain(|id, _| keep.contains(&id.as_str())); | ||
| 61 | + } | ||
| 62 | + | ||
| 29 | /// Subscribes to changes of the merge queue of repo `repo_id`: an entry was added, moved or | 63 | /// Subscribes to changes of the merge queue of repo `repo_id`: an entry was added, moved or |
| 30 | /// finished. Same rules as [`CiLive::subscribe_job`]. | 64 | /// finished. Same rules as [`CiLive::subscribe_job`]. |
| 31 | pub fn subscribe_queue(&self, repo_id: &str) -> watch::Receiver<u64> { | 65 | pub fn subscribe_queue(&self, repo_id: &str) -> watch::Receiver<u64> { |
| @@ -208,6 +242,23 @@ mod tests { | |||
| 208 | assert!(live.jobs.counters().is_empty()); | 242 | assert!(live.jobs.counters().is_empty()); |
| 209 | } | 243 | } |
| 210 | 244 | ||
| 245 | + #[tokio::test] | ||
| 246 | + async fn a_runner_wakes_the_pages_only_when_its_online_state_changes() { | ||
| 247 | + let live = CiLive::default(); | ||
| 248 | + let mut runners = live.subscribe_runners(); | ||
| 249 | + | ||
| 250 | + live.note_runner_online("runner-1", true); | ||
| 251 | + assert!(runners.has_changed().expect("open")); | ||
| 252 | + runners.borrow_and_update(); | ||
| 253 | + | ||
| 254 | + live.note_runner_online("runner-1", true); | ||
| 255 | + assert!(!runners.has_changed().expect("open")); | ||
| 256 | + | ||
| 257 | + live.note_runner_online("runner-1", false); | ||
| 258 | + assert!(runners.has_changed().expect("open")); | ||
| 259 | + assert!(!live.runner_recorded_online("runner-1")); | ||
| 260 | + } | ||
| 261 | + | ||
| 211 | #[tokio::test] | 262 | #[tokio::test] |
| 212 | async fn close_wakes_the_subscriber_once_and_then_ends_the_signal() { | 263 | async fn close_wakes_the_subscriber_once_and_then_ends_the_signal() { |
| 213 | let live = CiLive::default(); | 264 | let live = CiLive::default(); |
crates/forge-web/src/ci/reaper.rsmodified+21 -1
| @@ -21,6 +21,9 @@ const LOST_AFTER: Duration = Duration::from_secs(120); | |||
| 21 | const ALERTS_SLOW_EVERY: Duration = Duration::from_secs(5 * 60); | 21 | const ALERTS_SLOW_EVERY: Duration = Duration::from_secs(5 * 60); |
| 22 | /// How often retention runs. | 22 | /// How often retention runs. |
| 23 | const PURGE_EVERY: Duration = Duration::from_secs(24 * 60 * 60); | 23 | const PURGE_EVERY: Duration = Duration::from_secs(24 * 60 * 60); |
| 24 | +/// How often the health page is woken. Its disk, uptime and mail figures change with the clock and | ||
| 25 | +/// the disk, not with a write; its fingerprint drops a wake that changed nothing. | ||
| 26 | +const HEALTH_EVERY: Duration = Duration::from_secs(60); | ||
| 24 | 27 | ||
| 25 | /// Starts the reaper task. It runs until the process exits. | 28 | /// Starts the reaper task. It runs until the process exits. |
| 26 | pub fn spawn(state: AppState) { | 29 | pub fn spawn(state: AppState) { |
| @@ -33,10 +36,15 @@ async fn run(state: AppState) { | |||
| 33 | // Retention runs on the first pass after boot, then once a day. | 36 | // Retention runs on the first pass after boot, then once a day. |
| 34 | let mut next_purge = Instant::now(); | 37 | let mut next_purge = Instant::now(); |
| 35 | let mut next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY; | 38 | let mut next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY; |
| 39 | + let mut next_health = Instant::now() + HEALTH_EVERY; | ||
| 36 | loop { | 40 | loop { |
| 37 | tick.tick().await; | 41 | tick.tick().await; |
| 38 | reap_once(&state).await; | 42 | reap_once(&state).await; |
| 39 | crate::alerts::check_runners(&state).await; | 43 | crate::alerts::check_runners(&state).await; |
| 44 | + if Instant::now() >= next_health { | ||
| 45 | + crate::live::admin().bump(&crate::live::Topic::AdminHealth); | ||
| 46 | + next_health = Instant::now() + HEALTH_EVERY; | ||
| 47 | + } | ||
| 40 | if Instant::now() >= next_slow_alerts { | 48 | if Instant::now() >= next_slow_alerts { |
| 41 | crate::alerts::check_slow(&state).await; | 49 | crate::alerts::check_slow(&state).await; |
| 42 | next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY; | 50 | next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY; |
| @@ -105,7 +113,7 @@ pub async fn purge_once(state: &AppState) -> (usize, usize) { | |||
| 105 | let logs_before = stamp_ago(day(ci.log_retention_days)); | 113 | let logs_before = stamp_ago(day(ci.log_retention_days)); |
| 106 | let artifacts_before = stamp_ago(day(ci.artifact_retention_days)); | 114 | let artifacts_before = stamp_ago(day(ci.artifact_retention_days)); |
| 107 | let max_total_bytes = ci.artifact_max_total_mb.saturating_mul(1024 * 1024); | 115 | let max_total_bytes = ci.artifact_max_total_mb.saturating_mul(1024 * 1024); |
| 108 | - let (job_ids, artifact_ids) = match state | 116 | + let (job_ids, artifact_ids, run_ids) = match state |
| 109 | .store | 117 | .store |
| 110 | .purge_old( | 118 | .purge_old( |
| 111 | &logs_before, | 119 | &logs_before, |
| @@ -145,5 +153,17 @@ pub async fn purge_once(state: &AppState) -> (usize, usize) { | |||
| 145 | tracing::error!(error = %e, artifact_id = %id, "ci: deleting an artifact failed"); | 153 | tracing::error!(error = %e, artifact_id = %id, "ci: deleting an artifact failed"); |
| 146 | } | 154 | } |
| 147 | } | 155 | } |
| 156 | + // The rows are gone and the files too: the pages that list or show the logs and artifacts | ||
| 157 | + // re-read them now. | ||
| 158 | + for id in &job_ids { | ||
| 159 | + state.ci_live.bump_job(id); | ||
| 160 | + } | ||
| 161 | + for id in &run_ids { | ||
| 162 | + state.ci_live.bump_run(id); | ||
| 163 | + // The run page follows its repo's stream. | ||
| 164 | + if let Ok(Some(run)) = state.store.run_by_id(id).await { | ||
| 165 | + state.ci_live.bump_repo(&run.repo_id); | ||
| 166 | + } | ||
| 167 | + } | ||
| 148 | (log_count, artifact_count) | 168 | (log_count, artifact_count) |
| 149 | } | 169 | } |
crates/forge-web/src/importer/mod.rsmodified+22 -0
| @@ -29,6 +29,7 @@ use self::api::{ApiError, ExtAsset, ExtIssue, ExtRelease, GitHub, Notice, Remote | |||
| 29 | pub use self::remote::{ | 29 | pub use self::remote::{ |
| 30 | default_name, make_forgejo, make_github, make_gitlab, parse_remote, source_ref, | 30 | default_name, make_forgejo, make_github, make_gitlab, parse_remote, source_ref, |
| 31 | }; | 31 | }; |
| 32 | +use crate::live::Topic; | ||
| 32 | use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot}; | 33 | use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot}; |
| 33 | use crate::state::AppState; | 34 | use crate::state::AppState; |
| 34 | 35 | ||
| @@ -39,6 +40,8 @@ static SLOTS: Semaphore = Semaphore::const_new(2); | |||
| 39 | const IMPORTED_PR_LABEL: &str = "imported PR"; | 40 | const IMPORTED_PR_LABEL: &str = "imported PR"; |
| 40 | const IMPORTED_PR_COLOR: &str = "#8b7bd8"; | 41 | const IMPORTED_PR_COLOR: &str = "#8b7bd8"; |
| 41 | const FALLBACK_LABEL_COLOR: &str = "#8b949e"; | 42 | const FALLBACK_LABEL_COLOR: &str = "#8b949e"; |
| 43 | +/// Imported issues between two wakes of the repo's issue list. | ||
| 44 | +const IMPORT_BUMP_BATCH: usize = 25; | ||
| 42 | 45 | ||
| 43 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 46 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 44 | pub enum Source { | 47 | pub enum Source { |
| @@ -310,11 +313,14 @@ pub fn asset_name(name: &str) -> String { | |||
| 310 | 313 | ||
| 311 | /// Starts the job in the background. It waits for a free slot, then runs. | 314 | /// Starts the job in the background. It waits for a free slot, then runs. |
| 312 | pub fn spawn_job(state: AppState, job: ImportJob, spec: JobSpec) { | 315 | pub fn spawn_job(state: AppState, job: ImportJob, spec: JobSpec) { |
| 316 | + // The owner's import list shows the job as queued, then finished or failed (see `run_job`). | ||
| 317 | + state.live.bump(&Topic::Imports(job.user_id.clone())); | ||
| 313 | tokio::spawn(async move { | 318 | tokio::spawn(async move { |
| 314 | let Ok(_slot) = SLOTS.acquire().await else { | 319 | let Ok(_slot) = SLOTS.acquire().await else { |
| 315 | return; | 320 | return; |
| 316 | }; | 321 | }; |
| 317 | run_production(&state, &job, &spec).await; | 322 | run_production(&state, &job, &spec).await; |
| 323 | + state.live.bump(&Topic::Imports(job.user_id.clone())); | ||
| 318 | }); | 324 | }); |
| 319 | } | 325 | } |
| 320 | 326 | ||
| @@ -385,6 +391,7 @@ pub async fn run_job<A: RemoteApi>( | |||
| 385 | return; | 391 | return; |
| 386 | } | 392 | } |
| 387 | bump(&job.id); | 393 | bump(&job.id); |
| 394 | + state.live.bump(&Topic::Imports(job.user_id.clone())); | ||
| 388 | match run_steps(state, job, spec, api, transport, &rep).await { | 395 | match run_steps(state, job, spec, api, transport, &rep).await { |
| 389 | Ok(summary) => { | 396 | Ok(summary) => { |
| 390 | rep.log("info", summary).await; | 397 | rep.log("info", summary).await; |
| @@ -576,6 +583,12 @@ impl<A: RemoteApi> Run<'_, A> { | |||
| 576 | &self.state.store | 583 | &self.state.store |
| 577 | } | 584 | } |
| 578 | 585 | ||
| 586 | + /// Wakes the repo's issue list, labels, milestones and tabs. Called per batch and at the end of | ||
| 587 | + /// a phase, not per write. | ||
| 588 | + fn bump_issues(&self) { | ||
| 589 | + self.state.live.bump_repo_issues(&self.repo.id); | ||
| 590 | + } | ||
| 591 | + | ||
| 579 | async fn mapped(&self, kind: &str, ext: &str) -> Result<Option<ImportOrigin>, String> { | 592 | async fn mapped(&self, kind: &str, ext: &str) -> Result<Option<ImportOrigin>, String> { |
| 580 | self.store() | 593 | self.store() |
| 581 | .import_origin(&self.repo.id, kind, ext) | 594 | .import_origin(&self.repo.id, kind, ext) |
| @@ -626,6 +639,7 @@ impl<A: RemoteApi> Run<'_, A> { | |||
| 626 | } | 639 | } |
| 627 | } | 640 | } |
| 628 | } | 641 | } |
| 642 | + self.bump_issues(); | ||
| 629 | self.rep.log("info", format!("{total} labels read")).await; | 643 | self.rep.log("info", format!("{total} labels read")).await; |
| 630 | Ok(()) | 644 | Ok(()) |
| 631 | } | 645 | } |
| @@ -677,6 +691,7 @@ impl<A: RemoteApi> Run<'_, A> { | |||
| 677 | self.record("milestone", &m.id, &created.id, "", "").await; | 691 | self.record("milestone", &m.id, &created.id, "", "").await; |
| 678 | totals.milestones += 1; | 692 | totals.milestones += 1; |
| 679 | } | 693 | } |
| 694 | + self.bump_issues(); | ||
| 680 | Ok(()) | 695 | Ok(()) |
| 681 | } | 696 | } |
| 682 | 697 | ||
| @@ -749,6 +764,7 @@ impl<A: RemoteApi> Run<'_, A> { | |||
| 749 | format!("Importing {total} issues and pull requests"), | 764 | format!("Importing {total} issues and pull requests"), |
| 750 | ) | 765 | ) |
| 751 | .await; | 766 | .await; |
| 767 | + let mut created_since_bump = 0usize; | ||
| 752 | for (i, item) in items.iter().enumerate() { | 768 | for (i, item) in items.iter().enumerate() { |
| 753 | self.rep.stage("issues", i, total).await; | 769 | self.rep.stage("issues", i, total).await; |
| 754 | let kind = if item.is_pr { "pull" } else { "issue" }; | 770 | let kind = if item.is_pr { "pull" } else { "issue" }; |
| @@ -758,6 +774,11 @@ impl<A: RemoteApi> Run<'_, A> { | |||
| 758 | None => match self.create_item(item, &mut labels, &milestones).await { | 774 | None => match self.create_item(item, &mut labels, &milestones).await { |
| 759 | Ok(id) => { | 775 | Ok(id) => { |
| 760 | self.record(kind, &ext, &id, &item.author, &item.url).await; | 776 | self.record(kind, &ext, &id, &item.author, &item.url).await; |
| 777 | + created_since_bump += 1; | ||
| 778 | + if created_since_bump == IMPORT_BUMP_BATCH { | ||
| 779 | + created_since_bump = 0; | ||
| 780 | + self.bump_issues(); | ||
| 781 | + } | ||
| 761 | if item.is_pr { | 782 | if item.is_pr { |
| 762 | totals.pulls += 1; | 783 | totals.pulls += 1; |
| 763 | } else { | 784 | } else { |
| @@ -814,6 +835,7 @@ impl<A: RemoteApi> Run<'_, A> { | |||
| 814 | } | 835 | } |
| 815 | } | 836 | } |
| 816 | self.rep.stage("issues", total, total).await; | 837 | self.rep.stage("issues", total, total).await; |
| 838 | + self.bump_issues(); | ||
| 817 | Ok(()) | 839 | Ok(()) |
| 818 | } | 840 | } |
| 819 | 841 | ||
crates/forge-web/src/internal.rsmodified+97 -0
| @@ -28,6 +28,7 @@ use crate::admin_client::ADMIN_TOKEN_HEADER; | |||
| 28 | use crate::audit::{self, Actor, Target}; | 28 | use crate::audit::{self, Actor, Target}; |
| 29 | use crate::backup::scheduler::{run_backup_now, run_fsck_now}; | 29 | use crate::backup::scheduler::{run_backup_now, run_fsck_now}; |
| 30 | use crate::backup::{BackupOptions, Scope}; | 30 | use crate::backup::{BackupOptions, Scope}; |
| 31 | +use crate::live::{self, Topic}; | ||
| 31 | use crate::post_update::after_ref_update; | 32 | use crate::post_update::after_ref_update; |
| 32 | use crate::state::AppState; | 33 | use crate::state::AppState; |
| 33 | use forge_core::AuditAction; | 34 | use forge_core::AuditAction; |
| @@ -115,6 +116,11 @@ pub fn router(state: AppState) -> Router { | |||
| 115 | "/internal/admin/lfs-gc", | 116 | "/internal/admin/lfs-gc", |
| 116 | admin_lfs_gc, | 117 | admin_lfs_gc, |
| 117 | )) | 118 | )) |
| 119 | + .route(RouteFn::new( | ||
| 120 | + Method::POST, | ||
| 121 | + "/internal/admin/live", | ||
| 122 | + admin_live, | ||
| 123 | + )) | ||
| 118 | .app_context(state) | 124 | .app_context(state) |
| 119 | .build() | 125 | .build() |
| 120 | } | 126 | } |
| @@ -190,6 +196,66 @@ fn admin_lfs_gc(cx: &Cx, body: Body) -> RouteFuture<'_> { | |||
| 190 | Box::pin(async move { admin_lfs_gc_endpoint(cx, body).await }) | 196 | Box::pin(async move { admin_lfs_gc_endpoint(cx, body).await }) |
| 191 | } | 197 | } |
| 192 | 198 | ||
| 199 | +fn admin_live(cx: &Cx, body: Body) -> RouteFuture<'_> { | ||
| 200 | + Box::pin(async move { admin_live_endpoint(cx, body).await }) | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +/// Body of `POST /internal/admin/live`. The CLI names what its write changed, and the server | ||
| 204 | +/// wakes the same topics its own writers would. Every list may be empty. | ||
| 205 | +#[derive(Deserialize, Default)] | ||
| 206 | +struct AdminLiveRequest { | ||
| 207 | + /// Global admin topics by short name: `users`, `audit`, `backups`, `health`, `replication`, | ||
| 208 | + /// `server`. | ||
| 209 | + #[serde(default)] | ||
| 210 | + admin: Vec<String>, | ||
| 211 | + /// Users whose admin page and public profile changed. | ||
| 212 | + #[serde(default)] | ||
| 213 | + user_ids: Vec<String>, | ||
| 214 | + /// Accounts whose own settings (sessions, username) changed. | ||
| 215 | + #[serde(default)] | ||
| 216 | + account_ids: Vec<String>, | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +/// `POST /internal/admin/live`. Wakes the open pages of the running server for a write made by | ||
| 220 | +/// another process (the admin CLI). The body is small and the answer carries no data. | ||
| 221 | +async fn admin_live_endpoint(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 222 | + let state = app_context::<AppState>(cx); | ||
| 223 | + if !admin_authorized(cx, state) { | ||
| 224 | + return Err(forbidden().into()); | ||
| 225 | + } | ||
| 226 | + let bytes = to_bytes(body, MAX_BODY_BYTES).await?; | ||
| 227 | + let req: AdminLiveRequest = serde_json::from_slice(&bytes) | ||
| 228 | + .map_err(|e| bad_request(format!("invalid live request: {e}")))?; | ||
| 229 | + let mut admin_topics = Vec::with_capacity(req.admin.len()); | ||
| 230 | + for name in &req.admin { | ||
| 231 | + admin_topics.push(match name.as_str() { | ||
| 232 | + "users" => Topic::AdminUsers, | ||
| 233 | + "audit" => Topic::AdminAudit, | ||
| 234 | + "backups" => Topic::AdminBackups, | ||
| 235 | + "health" => Topic::AdminHealth, | ||
| 236 | + "replication" => Topic::AdminReplication, | ||
| 237 | + "server" => Topic::AdminServer, | ||
| 238 | + other => { | ||
| 239 | + return Ok(admin_error(&forge_core::Error::Invalid(format!( | ||
| 240 | + "unknown admin topic: {other}" | ||
| 241 | + )))); | ||
| 242 | + } | ||
| 243 | + }); | ||
| 244 | + } | ||
| 245 | + let hub = live::admin(); | ||
| 246 | + for topic in &admin_topics { | ||
| 247 | + hub.bump(topic); | ||
| 248 | + } | ||
| 249 | + for id in &req.user_ids { | ||
| 250 | + hub.bump(&Topic::AdminUser(id.clone())); | ||
| 251 | + state.live.bump(&Topic::User(id.clone())); | ||
| 252 | + } | ||
| 253 | + for id in &req.account_ids { | ||
| 254 | + state.live.bump(&Topic::Account(id.clone())); | ||
| 255 | + } | ||
| 256 | + Ok(admin_response(StatusCode::OK, serde_json::json!({ "ok": true }))) | ||
| 257 | +} | ||
| 258 | + | ||
| 193 | /// `POST /internal/admin/lfs-gc`. The body is ignored. | 259 | /// `POST /internal/admin/lfs-gc`. The body is ignored. |
| 194 | async fn admin_lfs_gc_endpoint(cx: &Cx, _body: Body) -> topcoat::Result<Response> { | 260 | async fn admin_lfs_gc_endpoint(cx: &Cx, _body: Body) -> topcoat::Result<Response> { |
| 195 | let state = app_context::<AppState>(cx); | 261 | let state = app_context::<AppState>(cx); |
| @@ -795,6 +861,37 @@ mod tests { | |||
| 795 | assert_eq!(res.status(), 200); | 861 | assert_eq!(res.status(), 200); |
| 796 | } | 862 | } |
| 797 | 863 | ||
| 864 | + /// The live route needs the admin token and wakes the topics it names on the right hub. | ||
| 865 | + #[tokio::test] | ||
| 866 | + async fn live_bump_wakes_the_named_topics() { | ||
| 867 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 868 | + let state = crate::test_support::test_state(dir.path()).await; | ||
| 869 | + let users = live::admin().subscribe(&Topic::AdminUsers); | ||
| 870 | + let profile = state.live.subscribe(&Topic::User("u1".to_owned())); | ||
| 871 | + let router = router(state); | ||
| 872 | + let body = r#"{"admin":["users"],"user_ids":["u1"]}"#; | ||
| 873 | + | ||
| 874 | + let refused = topcoat::router::request::Request::builder() | ||
| 875 | + .method("POST") | ||
| 876 | + .uri("/internal/admin/live") | ||
| 877 | + .header("content-type", "application/json") | ||
| 878 | + .header(ADMIN_TOKEN_HEADER, "wrong") | ||
| 879 | + .body(Body::from(body)) | ||
| 880 | + .expect("request"); | ||
| 881 | + assert_eq!(router.handle(refused).await.status(), 403); | ||
| 882 | + | ||
| 883 | + let req = topcoat::router::request::Request::builder() | ||
| 884 | + .method("POST") | ||
| 885 | + .uri("/internal/admin/live") | ||
| 886 | + .header("content-type", "application/json") | ||
| 887 | + .header(ADMIN_TOKEN_HEADER, crate::test_support::ADMIN_TOKEN) | ||
| 888 | + .body(Body::from(body)) | ||
| 889 | + .expect("request"); | ||
| 890 | + assert_eq!(router.handle(req).await.status(), 200); | ||
| 891 | + assert!(users.has_changed().expect("open")); | ||
| 892 | + assert!(profile.has_changed().expect("open")); | ||
| 893 | + } | ||
| 894 | + | ||
| 798 | #[tokio::test] | 895 | #[tokio::test] |
| 799 | async fn hook_routes_are_not_collected_by_discover() { | 896 | async fn hook_routes_are_not_collected_by_discover() { |
| 800 | // The public router uses `.discover()`. Hook routes are plain RouteFns and must not be in it. | 897 | // The public router uses `.discover()`. Hook routes are plain RouteFns and must not be in it. |
crates/forge-web/src/live.rsmodified+24 -4
| @@ -53,14 +53,25 @@ pub enum Topic { | |||
| 53 | /// One pull request, its conversation, commits and files. Keyed by the pull's issue id. | 53 | /// One pull request, its conversation, commits and files. Keyed by the pull's issue id. |
| 54 | /// Bumped by [`crate::pages::pull_live`]. | 54 | /// Bumped by [`crate::pages::pull_live`]. |
| 55 | Pull(String), | 55 | Pull(String), |
| 56 | - /// A repo's own state that its header shows: stars, watchers, forks, and its name and | 56 | + /// A repo's own state that its header shows: stars, watchers, forks, its name, description, |
| 57 | - /// description. Keyed by repo id. | 57 | + /// archived flag and default branch, the tab switches, and the mirror's last sync. Keyed by repo |
| 58 | + /// id. Bumped after the write, and also when a package linked to the repo publishes or yanks (the | ||
| 59 | + /// home page shows its newest version). The header's counts follow [`Topic::RepoIssues`] and | ||
| 60 | + /// [`Topic::PullList`] as well. | ||
| 58 | Repo(String), | 61 | Repo(String), |
| 59 | /// A user's repo listing, pins, contribution calendar and the signed-in sidebar's repo list. | 62 | /// A user's repo listing, pins, contribution calendar and the signed-in sidebar's repo list. |
| 60 | /// Keyed by user id (an organization is a user too). | 63 | /// Keyed by user id (an organization is a user too). |
| 61 | User(String), | 64 | User(String), |
| 62 | /// A user's inbox: a notification was added, read or marked read. Keyed by user id. | 65 | /// A user's inbox: a notification was added, read or marked read. Keyed by user id. |
| 63 | Inbox(String), | 66 | Inbox(String), |
| 67 | + /// A user's review requests: a pull request asked the user to review, a request was withdrawn, | ||
| 68 | + /// the user submitted a review, or a pull request with the user's request closed or merged. | ||
| 69 | + /// Keyed by the reviewer's user id. Streamed only to that user. Bumped by | ||
| 70 | + /// [`crate::pages::review_requests`] and [`crate::pages::pull_live`]. | ||
| 71 | + ReviewRequests(String), | ||
| 72 | + /// A user's import jobs: a job was queued, started, progressed or finished. Keyed by user id. | ||
| 73 | + /// Bumped by the importer when a job's state changes. Streamed only to that user. | ||
| 74 | + Imports(String), | ||
| 64 | /// The public repo listing: a public repo was added, changed, or starred. Global. | 75 | /// The public repo listing: a public repo was added, changed, or starred. Global. |
| 65 | Explore, | 76 | Explore, |
| 66 | /// The discussions of a repo as a list: a discussion was opened, or any discussion of the repo | 77 | /// The discussions of a repo as a list: a discussion was opened, or any discussion of the repo |
| @@ -101,7 +112,8 @@ pub enum Topic { | |||
| 101 | AdminServer, | 112 | AdminServer, |
| 102 | /// The releases of a repo: a release was created, edited or deleted, an asset was added, | 113 | /// The releases of a repo: a release was created, edited or deleted, an asset was added, |
| 103 | /// replaced or removed, or an asset was downloaded (its count). Keyed by repo id. The release | 114 | /// replaced or removed, or an asset was downloaded (its count). Keyed by repo id. The release |
| 104 | - /// list and the release pages follow it. Bumped by [`crate::release_ops`]. | 115 | + /// list, the release pages and the repo home page's latest release card follow it. Bumped by |
| 116 | + /// [`crate::release_ops`]. | ||
| 105 | RepoReleases(String), | 117 | RepoReleases(String), |
| 106 | /// A user's own settings: a profile, key, token, passkey, session, notification or appearance | 118 | /// 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 | 119 | /// setting changed, or a sign-in or a key or token use happened. Keyed by user id. Streamed only |
| @@ -114,6 +126,12 @@ pub enum Topic { | |||
| 114 | /// The commit statuses of a repo: a status was reported or replaced. Keyed by repo id. Bumped | 126 | /// The commit statuses of a repo: a status was reported or replaced. Keyed by repo id. Bumped |
| 115 | /// by the CI runner and the statuses API, after the write. | 127 | /// by the CI runner and the statuses API, after the write. |
| 116 | CommitStatuses(String), | 128 | CommitStatuses(String), |
| 129 | + /// The server settings that pages render (every `Kind::Live` setting, such as the banner, the | ||
| 130 | + /// registration mode or the limits): one was saved or reset. Global. Every page holds | ||
| 131 | + /// `/-/alive`, anonymous viewers included, and follows it there (see | ||
| 132 | + /// [`crate::pages::settings_live::alive_response`]). Bumped by the server settings after a save | ||
| 133 | + /// or reset. | ||
| 134 | + ServerSettings, | ||
| 117 | } | 135 | } |
| 118 | 136 | ||
| 119 | /// The hub of the admin pages. It is process-wide, not part of [`crate::state::AppState`]: the | 137 | /// The hub of the admin pages. It is process-wide, not part of [`crate::state::AppState`]: the |
| @@ -173,9 +191,11 @@ impl LiveHub { | |||
| 173 | 191 | ||
| 174 | /// A repo changed in a way its owner's pages, the explore list and its own header show: it | 192 | /// A repo changed in a way its owner's pages, the explore list and its own header show: it |
| 175 | /// was created, renamed, moved, re-described, starred, watched or forked. Call it once per | 193 | /// was created, renamed, moved, re-described, starred, watched or forked. Call it once per |
| 176 | - /// owner whose listing changed (a transfer has two). | 194 | + /// owner whose listing changed (a transfer has two). An organization owner's team pages list |
| 195 | + /// its repos too, so they are woken as well. | ||
| 177 | pub fn bump_repo(&self, owner_id: &str, repo_id: &str) { | 196 | pub fn bump_repo(&self, owner_id: &str, repo_id: &str) { |
| 178 | self.bump(&Topic::User(owner_id.to_owned())); | 197 | self.bump(&Topic::User(owner_id.to_owned())); |
| 198 | + self.bump(&Topic::Org(owner_id.to_owned())); | ||
| 179 | self.bump(&Topic::Explore); | 199 | self.bump(&Topic::Explore); |
| 180 | self.bump(&Topic::Repo(repo_id.to_owned())); | 200 | self.bump(&Topic::Repo(repo_id.to_owned())); |
| 181 | // The owner's repo count is on the admin page of the account. | 201 | // The owner's repo count is on the admin page of the account. |
crates/forge-web/src/mail/worker.rsmodified+6 -1
| @@ -68,7 +68,12 @@ async fn tick(state: &AppState) -> forge_core::Result<Duration> { | |||
| 68 | } | 68 | } |
| 69 | let now = now_stamp(); | 69 | let now = now_stamp(); |
| 70 | let lease_until = stamp_after(LEASE); | 70 | let lease_until = stamp_after(LEASE); |
| 71 | - for entry in state.store.lease_mail(&now, &lease_until, BATCH).await? { | 71 | + let leased = state.store.lease_mail(&now, &lease_until, BATCH).await?; |
| 72 | + if !leased.is_empty() { | ||
| 73 | + // The queue page shows these as Sending while the batch goes out. | ||
| 74 | + live::bump(); | ||
| 75 | + } | ||
| 76 | + for entry in leased { | ||
| 72 | deliver(state, &entry).await; | 77 | deliver(state, &entry).await; |
| 73 | } | 78 | } |
| 74 | let next = state.store.next_mail_due().await?; | 79 | let next = state.store.next_mail_due().await?; |
crates/forge-web/src/merge_queue.rsmodified+12 -10
| @@ -74,7 +74,7 @@ pub async fn enqueue( | |||
| 74 | .await | 74 | .await |
| 75 | { | 75 | { |
| 76 | Ok(entry) => { | 76 | Ok(entry) => { |
| 77 | - notify_changed(state, &repo.id); | 77 | + notify_entry(state, repo, &entry); |
| 78 | advance(state, repo, &pr.base_branch).await; | 78 | advance(state, repo, &pr.base_branch).await; |
| 79 | Ok(Ok(entry)) | 79 | Ok(Ok(entry)) |
| 80 | } | 80 | } |
| @@ -91,7 +91,7 @@ pub async fn remove(state: &AppState, repo: &Repo, entry: &QueueEntry, reason: & | |||
| 91 | .queue_finish(&entry.id, QueueState::Removed, reason) | 91 | .queue_finish(&entry.id, QueueState::Removed, reason) |
| 92 | .await | 92 | .await |
| 93 | { | 93 | { |
| 94 | - Ok(true) => notify_changed(state, &repo.id), | 94 | + Ok(true) => notify_entry(state, repo, entry), |
| 95 | Ok(false) => {} | 95 | Ok(false) => {} |
| 96 | Err(e) => { | 96 | Err(e) => { |
| 97 | tracing::error!(error = %e, repo_id = %repo.id, "merge queue: removing an entry failed"); | 97 | tracing::error!(error = %e, repo_id = %repo.id, "merge queue: removing an entry failed"); |
| @@ -235,7 +235,7 @@ async fn start( | |||
| 235 | { | 235 | { |
| 236 | return Ok(false); | 236 | return Ok(false); |
| 237 | } | 237 | } |
| 238 | - notify_changed(state, &repo.id); | 238 | + notify_entry(state, repo, entry); |
| 239 | // A run is created here only when the workflow runs for this candidate. Its statuses may | 239 | // A run is created here only when the workflow runs for this candidate. Its statuses may |
| 240 | // arrive before this returns; `evaluate` finds the run through its ref and commit. | 240 | // arrive before this returns; `evaluate` finds the run through its ref and commit. |
| 241 | merge_queue_run( | 241 | merge_queue_run( |
| @@ -354,12 +354,12 @@ async fn land( | |||
| 354 | Err(forge_git::error::Error::RefMoved(_)) => { | 354 | Err(forge_git::error::Error::RefMoved(_)) => { |
| 355 | // The target moved since the candidate was built: build it again on the new tip. | 355 | // The target moved since the candidate was built: build it again on the new tip. |
| 356 | state.store.queue_set_queued(&entry.id).await?; | 356 | state.store.queue_set_queued(&entry.id).await?; |
| 357 | - notify_changed(state, &repo.id); | 357 | + notify_entry(state, repo, entry); |
| 358 | return Ok(true); | 358 | return Ok(true); |
| 359 | } | 359 | } |
| 360 | Err(e) => { | 360 | Err(e) => { |
| 361 | state.store.queue_set_queued(&entry.id).await?; | 361 | state.store.queue_set_queued(&entry.id).await?; |
| 362 | - notify_changed(state, &repo.id); | 362 | + notify_entry(state, repo, entry); |
| 363 | return Err(e.into()); | 363 | return Err(e.into()); |
| 364 | } | 364 | } |
| 365 | } | 365 | } |
| @@ -379,7 +379,7 @@ async fn finish_removed( | |||
| 379 | .store | 379 | .store |
| 380 | .queue_finish(&entry.id, QueueState::Removed, reason) | 380 | .queue_finish(&entry.id, QueueState::Removed, reason) |
| 381 | .await?; | 381 | .await?; |
| 382 | - notify_changed(state, &repo.id); | 382 | + notify_entry(state, repo, entry); |
| 383 | Ok(()) | 383 | Ok(()) |
| 384 | } | 384 | } |
| 385 | 385 | ||
| @@ -399,7 +399,7 @@ async fn fail( | |||
| 399 | { | 399 | { |
| 400 | return Ok(()); | 400 | return Ok(()); |
| 401 | } | 401 | } |
| 402 | - notify_changed(state, &repo.id); | 402 | + notify_entry(state, repo, entry); |
| 403 | let who = match state.store.user_by_id(&entry.enqueued_by).await? { | 403 | let who = match state.store.user_by_id(&entry.enqueued_by).await? { |
| 404 | Some(user) => format!("@{}", user.username), | 404 | Some(user) => format!("@{}", user.username), |
| 405 | None => String::new(), | 405 | None => String::new(), |
| @@ -414,6 +414,7 @@ async fn fail( | |||
| 414 | .await | 414 | .await |
| 415 | { | 415 | { |
| 416 | Ok(_) => { | 416 | Ok(_) => { |
| 417 | + crate::pages::pull_live::bump_pull(state, &repo.id, &pr.issue.id); | ||
| 417 | notify::dispatch( | 418 | notify::dispatch( |
| 418 | state, | 419 | state, |
| 419 | repo, | 420 | repo, |
| @@ -431,7 +432,8 @@ async fn fail( | |||
| 431 | Ok(()) | 432 | Ok(()) |
| 432 | } | 433 | } |
| 433 | 434 | ||
| 434 | -/// Wakes the queue pages of `repo_id`. | 435 | +/// Wakes the queue pages of `repo_id`, and the pull page and list of the entry's pull request. |
| 435 | -pub fn notify_changed(state: &AppState, repo_id: &str) { | 436 | +fn notify_entry(state: &AppState, repo: &Repo, entry: &QueueEntry) { |
| 436 | - state.ci_live.bump_queue(repo_id); | 437 | + state.ci_live.bump_queue(&repo.id); |
| 438 | + crate::pages::pull_live::bump_pull(state, &repo.id, &entry.issue_id); | ||
| 437 | } | 439 | } |
crates/forge-web/src/mirrors/mod.rsmodified+3 -0
| @@ -22,6 +22,7 @@ use reqwest::Url; | |||
| 22 | use serde_json::json; | 22 | use serde_json::json; |
| 23 | 23 | ||
| 24 | use crate::audit::{self, Actor, Target}; | 24 | use crate::audit::{self, Actor, Target}; |
| 25 | +use crate::live::Topic; | ||
| 25 | use crate::pages::repo_settings_live::bump_settings; | 26 | use crate::pages::repo_settings_live::bump_settings; |
| 26 | use crate::post_update::after_ref_update; | 27 | use crate::post_update::after_ref_update; |
| 27 | use crate::state::AppState; | 28 | use crate::state::AppState; |
| @@ -281,6 +282,8 @@ pub async fn run_one(state: &AppState, mirror: &Mirror, policy: &WebhookPolicy) | |||
| 281 | } | 282 | } |
| 282 | // The mirror list and detail of the repo's settings show the sync state, so they wake now. | 283 | // The mirror list and detail of the repo's settings show the sync state, so they wake now. |
| 283 | bump_settings(&state.live, &mirror.repo_id); | 284 | bump_settings(&state.live, &mirror.repo_id); |
| 285 | + // The repo header shows the mirror's last sync and its result. | ||
| 286 | + state.live.bump(&Topic::Repo(mirror.repo_id.clone())); | ||
| 284 | if let Some(error) = &error { | 287 | if let Some(error) = &error { |
| 285 | tracing::warn!(mirror_id = %mirror.id, error = %error, "mirrors: sync failed"); | 288 | tracing::warn!(mirror_id = %mirror.id, error = %error, "mirrors: sync failed"); |
| 286 | if mirror.last_ok != Some(false) { | 289 | if mirror.last_ok != Some(false) { |
crates/forge-web/src/oci/manifests.rsmodified+4 -0
| @@ -13,6 +13,7 @@ use topcoat::router::{Body, StatusCode, to_bytes}; | |||
| 13 | use super::auth::{self, Caller, internal}; | 13 | use super::auth::{self, Caller, internal}; |
| 14 | use super::blobs::{insert, write_package}; | 14 | use super::blobs::{insert, write_package}; |
| 15 | use super::{gc, oci_error}; | 15 | use super::{gc, oci_error}; |
| 16 | +use crate::package_ops::bump_linked_repo; | ||
| 16 | use crate::state::AppState; | 17 | use crate::state::AppState; |
| 17 | 18 | ||
| 18 | /// Largest manifest accepted, in bytes. | 19 | /// Largest manifest accepted, in bytes. |
| @@ -184,6 +185,7 @@ pub async fn put_manifest( | |||
| 184 | return internal(e); | 185 | return internal(e); |
| 185 | } | 186 | } |
| 186 | state.packages_live.bump(&target.owner.id); | 187 | state.packages_live.bump(&target.owner.id); |
| 188 | + bump_linked_repo(state, &package.id).await; | ||
| 187 | let mut res = Response::new(Body::empty()); | 189 | let mut res = Response::new(Body::empty()); |
| 188 | *res.status_mut() = StatusCode::CREATED; | 190 | *res.status_mut() = StatusCode::CREATED; |
| 189 | insert( | 191 | insert( |
| @@ -281,6 +283,7 @@ pub async fn delete_manifest( | |||
| 281 | }, | 283 | }, |
| 282 | } | 284 | } |
| 283 | state.packages_live.bump(&target.owner.id); | 285 | state.packages_live.bump(&target.owner.id); |
| 286 | + bump_linked_repo(state, &package.id).await; | ||
| 284 | let mut res = Response::new(Body::empty()); | 287 | let mut res = Response::new(Body::empty()); |
| 285 | *res.status_mut() = StatusCode::ACCEPTED; | 288 | *res.status_mut() = StatusCode::ACCEPTED; |
| 286 | res | 289 | res |
| @@ -311,6 +314,7 @@ pub async fn remove_tag( | |||
| 311 | } | 314 | } |
| 312 | gc::sweep(state, &package.id).await?; | 315 | gc::sweep(state, &package.id).await?; |
| 313 | state.packages_live.bump(&owner.id); | 316 | state.packages_live.bump(&owner.id); |
| 317 | + bump_linked_repo(state, &package.id).await; | ||
| 314 | Ok(true) | 318 | Ok(true) |
| 315 | } | 319 | } |
| 316 | 320 | ||
crates/forge-web/src/package_ops.rsmodified+12 -0
| @@ -225,9 +225,20 @@ pub async fn publish( | |||
| 225 | return Err(PackageError::Internal(e.to_string())); | 225 | return Err(PackageError::Internal(e.to_string())); |
| 226 | } | 226 | } |
| 227 | state.packages_live.bump(&owner.id); | 227 | state.packages_live.bump(&owner.id); |
| 228 | + bump_linked_repo(state, &package.id).await; | ||
| 228 | Ok(()) | 229 | Ok(()) |
| 229 | } | 230 | } |
| 230 | 231 | ||
| 232 | +/// Wakes the repo that `package_id` is linked to, if any: its home page shows the package's newest | ||
| 233 | +/// version. A failed lookup skips the wake only, since the write has already happened. | ||
| 234 | +pub async fn bump_linked_repo(state: &AppState, package_id: &str) { | ||
| 235 | + if let Ok(Some(package)) = state.store.package(package_id).await | ||
| 236 | + && let Some(repo_id) = package.repo_id | ||
| 237 | + { | ||
| 238 | + state.live.bump(&crate::live::Topic::Repo(repo_id)); | ||
| 239 | + } | ||
| 240 | +} | ||
| 241 | + | ||
| 231 | /// Sets the yank state of a version. Yanked versions stay in the index and stay downloadable, | 242 | /// Sets the yank state of a version. Yanked versions stay in the index and stay downloadable, |
| 232 | /// marked as yanked, so existing lockfiles keep working. | 243 | /// marked as yanked, so existing lockfiles keep working. |
| 233 | pub async fn set_yanked( | 244 | pub async fn set_yanked( |
| @@ -255,6 +266,7 @@ pub async fn set_yanked( | |||
| 255 | return Err(PackageError::NotFound); | 266 | return Err(PackageError::NotFound); |
| 256 | } | 267 | } |
| 257 | state.packages_live.bump(&owner.id); | 268 | state.packages_live.bump(&owner.id); |
| 269 | + bump_linked_repo(state, &package.id).await; | ||
| 258 | Ok(()) | 270 | Ok(()) |
| 259 | } | 271 | } |
| 260 | 272 | ||
crates/forge-web/src/pages/admin_health.rsmodified+74 -17
| @@ -1,9 +1,11 @@ | |||
| 1 | //! Page: instance health for admins (`/admin/health`). A summary line, a storage card with the data | 1 | //! Page: instance health for admins (`/admin/health`). A summary line, a storage card with the data |
| 2 | //! disk's usage bar, and a services card. Every number is a cheap query or a short external probe | 2 | //! disk's usage bar, and a services card. Every number is a cheap query or a short external probe |
| 3 | -//! (`df`, `du`), so there is no polling; reloading the page, or opening it again, reads fresh values. | 3 | +//! (`df`), so there is no polling; reloading the page, or opening it again, reads fresh values. The |
| 4 | -//! Non-admins get 404. | 4 | +//! tree size of the repos (`du`) walks every repo, so a background task caches it (see |
| 5 | +//! [`spawn_repo_size`]) and the page only reads the cache. Non-admins get 404. | ||
| 5 | 6 | ||
| 6 | use std::path::Path; | 7 | use std::path::Path; |
| 8 | +use std::sync::Mutex; | ||
| 7 | use std::time::Duration; | 9 | use std::time::Duration; |
| 8 | 10 | ||
| 9 | use forge_core::mail::MailState; | 11 | use forge_core::mail::MailState; |
| @@ -143,8 +145,48 @@ async fn disk(path: &Path) -> Option<(u64, u64)> { | |||
| 143 | parse_df(&probe("df", &["-Pk"], path, Duration::from_secs(3)).await?) | 145 | parse_df(&probe("df", &["-Pk"], path, Duration::from_secs(3)).await?) |
| 144 | } | 146 | } |
| 145 | 147 | ||
| 146 | -async fn tree_size(path: &Path) -> Option<u64> { | 148 | +async fn tree_size(path: &Path, limit: Duration) -> Option<u64> { |
| 147 | - parse_du(&probe("du", &["-sk"], path, Duration::from_secs(4)).await?) | 149 | + parse_du(&probe("du", &["-sk"], path, limit).await?) |
| 150 | +} | ||
| 151 | + | ||
| 152 | +/// Total bytes of the repos, from the last background walk. `None` until the first walk finishes, | ||
| 153 | +/// or when every walk so far failed. | ||
| 154 | +static REPO_BYTES: Mutex<Option<u64>> = Mutex::new(None); | ||
| 155 | +/// How often the repos are walked again. | ||
| 156 | +const REPO_SIZE_EVERY: Duration = Duration::from_secs(10 * 60); | ||
| 157 | +/// The first walk, shortly after boot. | ||
| 158 | +const REPO_SIZE_FIRST: Duration = Duration::from_secs(30); | ||
| 159 | + | ||
| 160 | +fn cached_repo_bytes() -> Option<u64> { | ||
| 161 | + *REPO_BYTES.lock().unwrap_or_else(|e| e.into_inner()) | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +/// Starts the background walk of the repos' size: once shortly after boot, then every | ||
| 165 | +/// [`REPO_SIZE_EVERY`]. Runs until the process exits. `du` is a child process, so the walk does not | ||
| 166 | +/// block the executor. A changed size wakes the health page. | ||
| 167 | +pub fn spawn_repo_size(state: AppState) { | ||
| 168 | + tokio::spawn(async move { | ||
| 169 | + tokio::time::sleep(REPO_SIZE_FIRST).await; | ||
| 170 | + loop { | ||
| 171 | + refresh_repo_bytes(&state).await; | ||
| 172 | + tokio::time::sleep(REPO_SIZE_EVERY).await; | ||
| 173 | + } | ||
| 174 | + }); | ||
| 175 | +} | ||
| 176 | + | ||
| 177 | +async fn refresh_repo_bytes(state: &AppState) { | ||
| 178 | + let repos_dir = state.live().data_dir.join("repos"); | ||
| 179 | + // A failed or timed-out walk keeps the last good value. | ||
| 180 | + let Some(bytes) = tree_size(&repos_dir, Duration::from_secs(5 * 60)).await else { | ||
| 181 | + return; | ||
| 182 | + }; | ||
| 183 | + let previous = REPO_BYTES | ||
| 184 | + .lock() | ||
| 185 | + .unwrap_or_else(|e| e.into_inner()) | ||
| 186 | + .replace(bytes); | ||
| 187 | + if previous != Some(bytes) { | ||
| 188 | + crate::live::admin().bump(&Topic::AdminHealth); | ||
| 189 | + } | ||
| 148 | } | 190 | } |
| 149 | 191 | ||
| 150 | /// Seconds since the process started, from `/proc` (Linux). `None` elsewhere. | 192 | /// Seconds since the process started, from `/proc` (Linux). `None` elsewhere. |
| @@ -167,18 +209,17 @@ async fn gather(state: &AppState, lang: Lang, tz: &str) -> Result<Health> { | |||
| 167 | let live = state.live(); | 209 | let live = state.live(); |
| 168 | let now = now_unix(); | 210 | let now = now_unix(); |
| 169 | let data_dir = live.data_dir.clone(); | 211 | let data_dir = live.data_dir.clone(); |
| 170 | - let repos_dir = data_dir.join("repos"); | ||
| 171 | let backup_dir = live.backup.dir.clone(); | 212 | let backup_dir = live.backup.dir.clone(); |
| 172 | let database = live.database.clone(); | 213 | let database = live.database.clone(); |
| 173 | let backup_on = !backup_dir.as_os_str().is_empty(); | 214 | let backup_on = !backup_dir.as_os_str().is_empty(); |
| 174 | - let (data_space, repo_bytes, backup_space) = | 215 | + let (data_space, backup_space) = tokio::join!(disk(&data_dir), async { |
| 175 | - tokio::join!(disk(&data_dir), tree_size(&repos_dir), async { | 216 | + if backup_on { |
| 176 | - if backup_on { | 217 | + disk(&backup_dir).await |
| 177 | - disk(&backup_dir).await | 218 | + } else { |
| 178 | - } else { | 219 | + None |
| 179 | - None | 220 | + } |
| 180 | - } | 221 | + }); |
| 181 | - }); | 222 | + let repo_bytes = cached_repo_bytes(); |
| 182 | let counts = state.store.health_counts().await?; | 223 | let counts = state.store.health_counts().await?; |
| 183 | let mail = state | 224 | let mail = state |
| 184 | .store | 225 | .store |
| @@ -532,9 +573,10 @@ async fn health_page(cx: &Cx) -> Result<impl View> { | |||
| 532 | }) | 573 | }) |
| 533 | } | 574 | } |
| 534 | 575 | ||
| 535 | -/// What the event-driven parts of the health page show, as one string: the alerts, the counts and | 576 | +/// What the health page shows that can change between renders, as one string: the alerts, the |
| 536 | -/// the mail queue. The disk and tree probes (`df`, `du`) are not read here: they cost a process | 577 | +/// counts, the mail queue, the disk figures and the uptime, each as the page would display it. The |
| 537 | -/// each, so they run only when the page renders. | 578 | +/// disk figures come from `statvfs` (the same numbers `df` prints), not a process. The tree size |
| 579 | +/// of the repos is the cached value of the background walk, as the page displays it. | ||
| 538 | async fn health_fingerprint(state: &AppState) -> Result<String> { | 580 | async fn health_fingerprint(state: &AppState) -> Result<String> { |
| 539 | let counts = state.store.health_counts().await?; | 581 | let counts = state.store.health_counts().await?; |
| 540 | let mail = state | 582 | let mail = state |
| @@ -546,7 +588,22 @@ async fn health_fingerprint(state: &AppState) -> Result<String> { | |||
| 546 | .into_iter() | 588 | .into_iter() |
| 547 | .map(|alert| (alert.title, alert.body)) | 589 | .map(|alert| (alert.title, alert.body)) |
| 548 | .collect(); | 590 | .collect(); |
| 549 | - Ok(format!("{counts:?}|{mail:?}|{alerts:?}")) | 591 | + let live = state.live(); |
| 592 | + let disk_text = |path: &Path| { | ||
| 593 | + crate::alerts::disk_space(path).map(|(total, avail)| { | ||
| 594 | + let (pct, text) = space(Lang::En, total, avail); | ||
| 595 | + (pct, text, human_size(Lang::En, total.saturating_sub(avail))) | ||
| 596 | + }) | ||
| 597 | + }; | ||
| 598 | + let data = disk_text(&live.data_dir); | ||
| 599 | + let backup = (!live.backup.dir.as_os_str().is_empty()) | ||
| 600 | + .then(|| disk_text(&live.backup.dir)) | ||
| 601 | + .flatten(); | ||
| 602 | + let uptime = uptime_secs().map(duration_short); | ||
| 603 | + let repos = cached_repo_bytes().map(|b| human_size(Lang::En, b)); | ||
| 604 | + Ok(format!( | ||
| 605 | + "{counts:?}|{mail:?}|{alerts:?}|{data:?}|{backup:?}|{uptime:?}|{repos:?}" | ||
| 606 | + )) | ||
| 550 | } | 607 | } |
| 551 | 608 | ||
| 552 | /// The health page's change stream. Admins only. | 609 | /// The health page's change stream. Admins only. |
crates/forge-web/src/pages/admin_runners.rsmodified+2 -8
| @@ -9,7 +9,7 @@ | |||
| 9 | use forge_ci::build::{self, Freshness}; | 9 | use forge_ci::build::{self, Freshness}; |
| 10 | use forge_core::AuditAction; | 10 | use forge_core::AuditAction; |
| 11 | use forge_core::ci::{CiRunner, FieldKind, RUNNER_FIELDS, RestartMode, runner_field}; | 11 | use forge_core::ci::{CiRunner, FieldKind, RUNNER_FIELDS, RestartMode, runner_field}; |
| 12 | -use forge_core::store::health::RUNNER_ONLINE_SECS; | 12 | +use forge_core::store::health::runner_is_online; |
| 13 | use serde::Deserialize; | 13 | use serde::Deserialize; |
| 14 | use time::OffsetDateTime; | 14 | use time::OffsetDateTime; |
| 15 | use time::format_description::well_known::Rfc3339; | 15 | use time::format_description::well_known::Rfc3339; |
| @@ -197,13 +197,7 @@ fn dot_of(lang: Lang, runner: &CiRunner, now: i64) -> (&'static str, &'static st | |||
| 197 | if runner.disabled { | 197 | if runner.disabled { |
| 198 | return ("runner-dot is-disabled", g::t(lang, K::Disabled)); | 198 | return ("runner-dot is-disabled", g::t(lang, K::Disabled)); |
| 199 | } | 199 | } |
| 200 | - let limit = i64::try_from(RUNNER_ONLINE_SECS).unwrap_or(i64::MAX); | 200 | + if runner_is_online(false, runner.last_seen_at.as_deref(), now) { |
| 201 | - let online = runner | ||
| 202 | - .last_seen_at | ||
| 203 | - .as_deref() | ||
| 204 | - .and_then(|stamp| OffsetDateTime::parse(stamp, &Rfc3339).ok()) | ||
| 205 | - .is_some_and(|at| at.unix_timestamp() >= now.saturating_sub(limit)); | ||
| 206 | - if online { | ||
| 207 | ("runner-dot is-online", s(lang, "online", "çevrim içi")) | 201 | ("runner-dot is-online", s(lang, "online", "çevrim içi")) |
| 208 | } else { | 202 | } else { |
| 209 | ("runner-dot is-offline", s(lang, "offline", "çevrim dışı")) | 203 | ("runner-dot is-offline", s(lang, "offline", "çevrim dışı")) |
crates/forge-web/src/pages/admin_server.rsmodified+9 -0
| @@ -280,6 +280,13 @@ async fn server_view( | |||
| 280 | <option value=(option.value.as_str()) selected=(option.selected)>(option.label.as_str())</option> | 280 | <option value=(option.value.as_str()) selected=(option.selected)>(option.label.as_str())</option> |
| 281 | } | 281 | } |
| 282 | </select> | 282 | </select> |
| 283 | + } else if r.is_number && r.max.parse::<u64>().is_ok_and(|max| max <= 100) { | ||
| 284 | + // A small range steps with − and +, like the runner's Max. | ||
| 285 | + <div class="runner-pill"> | ||
| 286 | + <button type="button" class="runner-step" data-step="-1" aria-label=(s(lang, "Fewer", "Azalt"))>"−"</button> | ||
| 287 | + <input type="number" name=(r.key) value=(r.value.as_str()) min=(r.min.as_str()) max=(r.max.as_str()) step="1" inputmode="numeric" aria-label=(r.label)> | ||
| 288 | + <button type="button" class="runner-step" data-step="1" aria-label=(s(lang, "More", "Artır"))>"+"</button> | ||
| 289 | + </div> | ||
| 283 | } else if r.is_number { | 290 | } else if r.is_number { |
| 284 | <input type="number" name=(r.key) value=(r.value.as_str()) min=(r.min.as_str()) max=(r.max.as_str()) aria-label=(r.label)> | 291 | <input type="number" name=(r.key) value=(r.value.as_str()) min=(r.min.as_str()) max=(r.max.as_str()) aria-label=(r.label)> |
| 285 | } else if r.is_secret { | 292 | } else if r.is_secret { |
| @@ -414,6 +421,7 @@ async fn save( | |||
| 414 | state.store.clear_server_override(key).await?; | 421 | state.store.clear_server_override(key).await?; |
| 415 | } | 422 | } |
| 416 | state.settings.publish(&plan.overrides)?; | 423 | state.settings.publish(&plan.overrides)?; |
| 424 | + state.live.bump(&Topic::ServerSettings); | ||
| 417 | crate::live::admin().bump(&Topic::AdminServer); | 425 | crate::live::admin().bump(&Topic::AdminServer); |
| 418 | let keys: Vec<&str> = plan.sets.iter().map(|(k, _)| k.as_str()).collect(); | 426 | let keys: Vec<&str> = plan.sets.iter().map(|(k, _)| k.as_str()).collect(); |
| 419 | audit::record( | 427 | audit::record( |
| @@ -541,6 +549,7 @@ async fn reset( | |||
| 541 | let next = state.settings.plan_reset(&existing, key)?; | 549 | let next = state.settings.plan_reset(&existing, key)?; |
| 542 | state.store.clear_server_override(key).await?; | 550 | state.store.clear_server_override(key).await?; |
| 543 | state.settings.publish(&next)?; | 551 | state.settings.publish(&next)?; |
| 552 | + state.live.bump(&Topic::ServerSettings); | ||
| 544 | crate::live::admin().bump(&Topic::AdminServer); | 553 | crate::live::admin().bump(&Topic::AdminServer); |
| 545 | audit::record( | 554 | audit::record( |
| 546 | &state.store, | 555 | &state.store, |
crates/forge-web/src/pages/assets.rsmodified+3 -1
| @@ -167,7 +167,9 @@ async fn offline_js() -> Result<(StatusCode, HeaderMap, &'static str)> { | |||
| 167 | 167 | ||
| 168 | /// The stream every page and the offline page watch to learn that the server is back. It carries | 168 | /// The stream every page and the offline page watch to learn that the server is back. It carries |
| 169 | /// no data and needs no login: it sends `retry`, then holds the connection open with keep-alive | 169 | /// no data and needs no login: it sends `retry`, then holds the connection open with keep-alive |
| 170 | -/// comments. A signed-in viewer also gets `theme` events (see `settings_live::alive_response`). A dropped connection (or a proxy's 502 while forge restarts) is what the pages watch for. | 170 | +/// comments. Every viewer gets `settings` events when a live server setting changes, and a signed-in |
| 171 | +/// viewer also gets `theme` events (see `settings_live::alive_response`). A dropped connection (or a | ||
| 172 | +/// proxy's 502 while forge restarts) is what the pages watch for. | ||
| 171 | #[route(GET "/-/alive")] | 173 | #[route(GET "/-/alive")] |
| 172 | async fn alive(cx: &Cx) -> Result<Response> { | 174 | async fn alive(cx: &Cx) -> Result<Response> { |
| 173 | crate::pages::settings_live::alive_response(cx).await | 175 | crate::pages::settings_live::alive_response(cx).await |
crates/forge-web/src/pages/banner.rsmodified+3 -0
| @@ -29,6 +29,8 @@ pub struct BannerView { | |||
| 29 | pub message: String, | 29 | pub message: String, |
| 30 | pub warning: bool, | 30 | pub warning: bool, |
| 31 | pub hash: String, | 31 | pub hash: String, |
| 32 | + /// Unix seconds when the banner expires, or `None` for never. The page drops it at that time. | ||
| 33 | + pub expires: Option<i64>, | ||
| 32 | } | 34 | } |
| 33 | 35 | ||
| 34 | /// Short stable id of a message and level. | 36 | /// Short stable id of a message and level. |
| @@ -51,6 +53,7 @@ pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Opt | |||
| 51 | message, | 53 | message, |
| 52 | warning: config.level == "warning", | 54 | warning: config.level == "warning", |
| 53 | hash, | 55 | hash, |
| 56 | + expires: config.expires_unix(), | ||
| 54 | }) | 57 | }) |
| 55 | } | 58 | } |
| 56 | 59 | ||
crates/forge-web/src/pages/ci_job.rsmodified+75 -39
| @@ -1,10 +1,10 @@ | |||
| 1 | //! Pages: one CI job (`/{owner}/{repo}/ci/jobs/{job_id}`), its live log (`.../log.txt`) and its | 1 | //! Pages: one CI job (`/{owner}/{repo}/ci/jobs/{job_id}`), its live log (`.../log.txt`) and its |
| 2 | //! artifacts (`.../artifacts/{name}`). Reading follows repo Read, like the run pages. The job page | 2 | //! artifacts (`.../artifacts/{name}`). Reading follows repo Read, like the run pages. The job page |
| 3 | -//! shows the last 512 KiB of the log. While the job is not terminal the page is live: it carries a | 3 | +//! shows the last 512 KiB of the log. The page carries a `data-live` marker for its `.../events` |
| 4 | -//! `data-live` marker for its `.../events` stream, and nav.js re-renders it when the job's status | 4 | +//! stream, and `data-live-state` holds the job's fingerprint (status, artifact ids, log kept): nav.js |
| 5 | -//! changes. `log.txt` streams the whole log and keeps following it until the job is | 5 | +//! re-renders the page when the stream sends a different one. `log.txt` streams the whole log and |
| 6 | -//! terminal and the file is read to its end. Artifacts are blobs under `ci/<artifact id>` and are | 6 | +//! keeps following it until the job is terminal and the file is read to its end. Artifacts are blobs |
| 7 | -//! always served as attachments. | 7 | +//! under `ci/<artifact id>` and are always served as attachments. |
| 8 | 8 | ||
| 9 | use std::path::{Path, PathBuf}; | 9 | use std::path::{Path, PathBuf}; |
| 10 | use std::sync::Arc; | 10 | use std::sync::Arc; |
| @@ -34,8 +34,8 @@ use crate::i18n::{ | |||
| 34 | releases_ci::{self as g, K}, | 34 | releases_ci::{self as g, K}, |
| 35 | }; | 35 | }; |
| 36 | use crate::pages::ci_runs::{ | 36 | use crate::pages::ci_runs::{ |
| 37 | - age_text, can_write, changed_event, duration_text, events_response, job_href, job_status, | 37 | + age_text, can_write, changed_event, duration_text, events_response, job_href, run_href, |
| 38 | - run_href, state_text, | 38 | + state_text, |
| 39 | }; | 39 | }; |
| 40 | use crate::pages::repo::repo_head; | 40 | use crate::pages::repo::repo_head; |
| 41 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; | 41 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; |
| @@ -254,8 +254,8 @@ fn full_date(stamp: &str) -> String { | |||
| 254 | /// The job page's values, already shown as text. | 254 | /// The job page's values, already shown as text. |
| 255 | struct JobView { | 255 | struct JobView { |
| 256 | name: String, | 256 | name: String, |
| 257 | - /// The status word as the events carry it, for the live check. | 257 | + /// The fingerprint the events carry and the page renders as `data-live-state` (see `job_fingerprint`). |
| 258 | - status: String, | 258 | + fingerprint: String, |
| 259 | state: String, | 259 | state: String, |
| 260 | state_class: String, | 260 | state_class: String, |
| 261 | runner: String, | 261 | runner: String, |
| @@ -282,8 +282,35 @@ struct ArtifactRow { | |||
| 282 | size: String, | 282 | size: String, |
| 283 | } | 283 | } |
| 284 | 284 | ||
| 285 | -/// The job page body. A job that is not terminal carries `live`, the URL of its event stream, and | 285 | +/// The job's fingerprint: its status, the ids of its artifacts (by name) and whether its log is |
| 286 | -/// the status the page shows. The log tail carries the offset its text ends at. | 286 | +/// still kept. The events send it as `changed` data and the page renders it as `data-live-state`, |
| 287 | +/// so a status change, an artifact added or deleted, or a log deleted re-renders the page. The | ||
| 288 | +/// log's size is left out: a running job's log grows with every chunk, and the log stream carries | ||
| 289 | +/// that. Format: `{status}|{artifact ids joined by ','}|{log or nolog}`. | ||
| 290 | +fn job_fingerprint(status: &str, artifact_ids: &[&str], log_kept: bool) -> String { | ||
| 291 | + format!( | ||
| 292 | + "{status}|{}|{}", | ||
| 293 | + artifact_ids.join(","), | ||
| 294 | + if log_kept { "log" } else { "nolog" } | ||
| 295 | + ) | ||
| 296 | +} | ||
| 297 | + | ||
| 298 | +/// The job's fingerprint now. `None` when the job row is gone. | ||
| 299 | +async fn job_fingerprint_now(store: &Store, job_id: &str) -> Result<Option<String>> { | ||
| 300 | + let Some(job) = store.job_by_id(job_id).await? else { | ||
| 301 | + return Ok(None); | ||
| 302 | + }; | ||
| 303 | + let artifacts = store.list_artifacts(job_id).await?; | ||
| 304 | + let ids: Vec<&str> = artifacts.iter().map(|artifact| artifact.id.as_str()).collect(); | ||
| 305 | + Ok(Some(job_fingerprint( | ||
| 306 | + job.state.as_str(), | ||
| 307 | + &ids, | ||
| 308 | + job.log_bytes > 0, | ||
| 309 | + ))) | ||
| 310 | +} | ||
| 311 | + | ||
| 312 | +/// The job page body. Every job carries `live`, the URL of its event stream, so a finished job | ||
| 313 | +/// follows its artifacts and log too. The log tail carries the offset its text ends at. | ||
| 287 | #[component] | 314 | #[component] |
| 288 | async fn job_body( | 315 | async fn job_body( |
| 289 | head: RepoHead, | 316 | head: RepoHead, |
| @@ -294,11 +321,11 @@ async fn job_body( | |||
| 294 | first_line: String, | 321 | first_line: String, |
| 295 | truncated: bool, | 322 | truncated: bool, |
| 296 | artifacts: Vec<ArtifactRow>, | 323 | artifacts: Vec<ArtifactRow>, |
| 297 | - live: Option<String>, | 324 | + live: String, |
| 298 | ) -> Result<impl View> { | 325 | ) -> Result<impl View> { |
| 299 | Ok(view! { | 326 | Ok(view! { |
| 300 | repo_head(head: RepoHead { live: String::new(), ..head }) | 327 | repo_head(head: RepoHead { live: String::new(), ..head }) |
| 301 | - <div data-live=(live.as_deref()) data-live-state=(job.status.as_str())> | 328 | + <div data-live=(live.as_str()) data-live-state=(job.fingerprint.as_str())> |
| 302 | <p class="muted small"><a href=(job.run_href.as_str())>(g::t(lang, K::RunNumber)) (job.run_number)</a></p> | 329 | <p class="muted small"><a href=(job.run_href.as_str())>(g::t(lang, K::RunNumber)) (job.run_number)</a></p> |
| 303 | <section class="card"> | 330 | <section class="card"> |
| 304 | <h2>(job.name.as_str())</h2> | 331 | <h2>(job.name.as_str())</h2> |
| @@ -384,10 +411,10 @@ async fn job_page(cx: &Cx) -> Result<impl View> { | |||
| 384 | offset: log_offset, | 411 | offset: log_offset, |
| 385 | first_line, | 412 | first_line, |
| 386 | } = log_tail(&log_path(&state.config.data_dir, &job.id)).await?; | 413 | } = log_tail(&log_path(&state.config.data_dir, &job.id)).await?; |
| 387 | - let artifacts = state | 414 | + let listed = state.store.list_artifacts(&job.id).await?; |
| 388 | - .store | 415 | + let ids: Vec<&str> = listed.iter().map(|artifact| artifact.id.as_str()).collect(); |
| 389 | - .list_artifacts(&job.id) | 416 | + let fingerprint = job_fingerprint(job.state.as_str(), &ids, job.log_bytes > 0); |
| 390 | - .await? | 417 | + let artifacts = listed |
| 391 | .into_iter() | 418 | .into_iter() |
| 392 | .map(|artifact| ArtifactRow { | 419 | .map(|artifact| ArtifactRow { |
| 393 | href: format!( | 420 | href: format!( |
| @@ -411,10 +438,10 @@ async fn job_page(cx: &Cx) -> Result<impl View> { | |||
| 411 | None => String::new(), | 438 | None => String::new(), |
| 412 | }; | 439 | }; |
| 413 | let title = title_of(&ctx); | 440 | let title = title_of(&ctx); |
| 414 | - let live = (!job.state.is_terminal()).then(|| format!("{}/events", job_href(&title, &job.id))); | 441 | + let live = format!("{}/events", job_href(&title, &job.id)); |
| 415 | let view = JobView { | 442 | let view = JobView { |
| 416 | name: job.name.clone(), | 443 | name: job.name.clone(), |
| 417 | - status: job.state.as_str().to_owned(), | 444 | + fingerprint, |
| 418 | state: state_text(lang, job.state.as_str()), | 445 | state: state_text(lang, job.state.as_str()), |
| 419 | state_class: format!("ci-state ci-{}", job.state.as_str()), | 446 | state_class: format!("ci-state ci-{}", job.state.as_str()), |
| 420 | runner, | 447 | runner, |
| @@ -470,7 +497,8 @@ const LOG_EVENT_BYTES: u64 = 64 * 1024; | |||
| 470 | /// The job's live stream. It opens with the status, sends a `changed` event when the status changes | 497 | /// The job's live stream. It opens with the status, sends a `changed` event when the status changes |
| 471 | /// and a `log` event with each new run of log bytes. A `log` event's id is the offset past its text, | 498 | /// and a `log` event with each new run of log bytes. A `log` event's id is the offset past its text, |
| 472 | /// so a reconnect (`Last-Event-ID`) resumes there. A new stream starts at `?from=`, the offset the | 499 | /// so a reconnect (`Last-Event-ID`) resumes there. A new stream starts at `?from=`, the offset the |
| 473 | -/// page already shows. The stream ends once the job is terminal and its log is read to the end. | 500 | +/// page already shows. The stream stays open after the job is terminal and wakes only on a bump of |
| 501 | +/// this job (see `CiLive`), so a finished page still hears about deleted artifacts or logs. | ||
| 474 | #[route(GET "/{owner}/{repo}/ci/jobs/{job_id}/events")] | 502 | #[route(GET "/{owner}/{repo}/ci/jobs/{job_id}/events")] |
| 475 | async fn job_events(cx: &Cx) -> Result<Response> { | 503 | async fn job_events(cx: &Cx) -> Result<Response> { |
| 476 | let owner = path_param::<Owner>(cx); | 504 | let owner = path_param::<Owner>(cx); |
| @@ -491,11 +519,10 @@ async fn job_events(cx: &Cx) -> Result<Response> { | |||
| 491 | path: log_path(&state.config.data_dir, &job.id), | 519 | path: log_path(&state.config.data_dir, &job.id), |
| 492 | wake, | 520 | wake, |
| 493 | offset, | 521 | offset, |
| 494 | - status: None, | 522 | + fingerprint: None, |
| 495 | - terminal: false, | ||
| 496 | more: false, | 523 | more: false, |
| 497 | primed: false, | 524 | primed: false, |
| 498 | - pending_status: None, | 525 | + pending_fingerprint: None, |
| 499 | pending_log: None, | 526 | pending_log: None, |
| 500 | }; | 527 | }; |
| 501 | events_response(cx, job_stream(follow)) | 528 | events_response(cx, job_stream(follow)) |
| @@ -519,15 +546,13 @@ struct JobFollow { | |||
| 519 | wake: watch::Receiver<u64>, | 546 | wake: watch::Receiver<u64>, |
| 520 | /// The log offset read so far. The next read starts here. | 547 | /// The log offset read so far. The next read starts here. |
| 521 | offset: u64, | 548 | offset: u64, |
| 522 | - /// The status last read. | 549 | + /// The fingerprint last read (see `job_fingerprint`). |
| 523 | - status: Option<String>, | 550 | + fingerprint: Option<String>, |
| 524 | - /// The job was terminal at the last read. | ||
| 525 | - terminal: bool, | ||
| 526 | /// The last read sent log bytes, so more may be waiting. | 551 | /// The last read sent log bytes, so more may be waiting. |
| 527 | more: bool, | 552 | more: bool, |
| 528 | /// False until the first read. Later reads wait for a wake first, unless `more` is set. | 553 | /// False until the first read. Later reads wait for a wake first, unless `more` is set. |
| 529 | primed: bool, | 554 | primed: bool, |
| 530 | - pending_status: Option<String>, | 555 | + pending_fingerprint: Option<String>, |
| 531 | /// The text and the offset past it. | 556 | /// The text and the offset past it. |
| 532 | pending_log: Option<(String, u64)>, | 557 | pending_log: Option<(String, u64)>, |
| 533 | } | 558 | } |
| @@ -535,33 +560,31 @@ struct JobFollow { | |||
| 535 | fn job_stream(follow: JobFollow) -> impl Stream<Item = Result<Event>> + Send + 'static { | 560 | fn job_stream(follow: JobFollow) -> impl Stream<Item = Result<Event>> + Send + 'static { |
| 536 | futures_util::stream::unfold(follow, |mut f| async move { | 561 | futures_util::stream::unfold(follow, |mut f| async move { |
| 537 | loop { | 562 | loop { |
| 538 | - if let Some(status) = f.pending_status.take() { | 563 | + if let Some(fingerprint) = f.pending_fingerprint.take() { |
| 539 | - return Some((changed_event(status), f)); | 564 | + return Some((changed_event(fingerprint), f)); |
| 540 | } | 565 | } |
| 541 | if let Some((text, end)) = f.pending_log.take() { | 566 | if let Some((text, end)) = f.pending_log.take() { |
| 542 | let event = Event::new().event("log").data(text).id(end.to_string()); | 567 | let event = Event::new().event("log").data(text).id(end.to_string()); |
| 543 | return Some((Ok(event), f)); | 568 | return Some((Ok(event), f)); |
| 544 | } | 569 | } |
| 545 | - if f.terminal && !f.more { | 570 | + // A terminal job keeps the stream open too: its artifacts and log can still be deleted |
| 546 | - return None; | 571 | + // by the retention purge, and the wake of that purge is the only thing that wakes it. |
| 547 | - } | ||
| 548 | if f.primed && !f.more && f.wake.changed().await.is_err() { | 572 | if f.primed && !f.more && f.wake.changed().await.is_err() { |
| 549 | return None; | 573 | return None; |
| 550 | } | 574 | } |
| 551 | f.primed = true; | 575 | f.primed = true; |
| 552 | f.more = false; | 576 | f.more = false; |
| 553 | - let (status, terminal) = match job_status(&f.store, &f.job_id).await { | 577 | + let fingerprint = match job_fingerprint_now(&f.store, &f.job_id).await { |
| 554 | - Ok(Some(found)) => found, | 578 | + Ok(Some(fingerprint)) => fingerprint, |
| 555 | Ok(None) => return None, | 579 | Ok(None) => return None, |
| 556 | Err(e) => { | 580 | Err(e) => { |
| 557 | tracing::error!(error = %e, "ci: job stream could not read the job"); | 581 | tracing::error!(error = %e, "ci: job stream could not read the job"); |
| 558 | return None; | 582 | return None; |
| 559 | } | 583 | } |
| 560 | }; | 584 | }; |
| 561 | - f.terminal = terminal; | 585 | + if f.fingerprint.as_deref() != Some(fingerprint.as_str()) { |
| 562 | - if f.status.as_deref() != Some(status.as_str()) { | 586 | + f.fingerprint = Some(fingerprint.clone()); |
| 563 | - f.status = Some(status.clone()); | 587 | + f.pending_fingerprint = Some(fingerprint); |
| 564 | - f.pending_status = Some(status); | ||
| 565 | } | 588 | } |
| 566 | match read_log(&f.path, f.offset).await { | 589 | match read_log(&f.path, f.offset).await { |
| 567 | Ok(Some((text, end))) => { | 590 | Ok(Some((text, end))) => { |
| @@ -691,3 +714,16 @@ fn artifact_response( | |||
| 691 | ); | 714 | ); |
| 692 | Ok(res) | 715 | Ok(res) |
| 693 | } | 716 | } |
| 717 | + | ||
| 718 | +#[cfg(test)] | ||
| 719 | +mod tests { | ||
| 720 | + use super::job_fingerprint; | ||
| 721 | + | ||
| 722 | + #[test] | ||
| 723 | + fn an_artifact_or_the_log_changing_changes_the_fingerprint() { | ||
| 724 | + let base = job_fingerprint("success", &["a1"], true); | ||
| 725 | + assert_eq!(base, "success|a1|log"); | ||
| 726 | + assert_ne!(base, job_fingerprint("success", &[], true)); | ||
| 727 | + assert_ne!(base, job_fingerprint("success", &["a1"], false)); | ||
| 728 | + } | ||
| 729 | +} | ||
crates/forge-web/src/pages/ci_runs.rsmodified+0 -7
| @@ -1958,13 +1958,6 @@ pub(crate) async fn run_status(store: &Store, run_id: &str) -> Result<Status> { | |||
| 1958 | .map(|run| (run.state.as_str().to_owned(), run_finished(&run.state)))) | 1958 | .map(|run| (run.state.as_str().to_owned(), run_finished(&run.state)))) |
| 1959 | } | 1959 | } |
| 1960 | 1960 | ||
| 1961 | -pub(crate) async fn job_status(store: &Store, job_id: &str) -> Result<Status> { | ||
| 1962 | - Ok(store | ||
| 1963 | - .job_by_id(job_id) | ||
| 1964 | - .await? | ||
| 1965 | - .map(|job| (job.state.as_str().to_owned(), job.state.is_terminal()))) | ||
| 1966 | -} | ||
| 1967 | - | ||
| 1968 | /// One `changed` event carrying the status word. | 1961 | /// One `changed` event carrying the status word. |
| 1969 | pub(crate) fn changed_event(status: String) -> Result<Event> { | 1962 | pub(crate) fn changed_event(status: String) -> Result<Event> { |
| 1970 | Ok(Event::new().event("changed").data(status)) | 1963 | Ok(Event::new().event("changed").data(status)) |
crates/forge-web/src/pages/ci_tests.rsmodified+7 -6
| @@ -432,9 +432,10 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() { | |||
| 432 | 432 | ||
| 433 | finish_job(&fx).await; | 433 | finish_job(&fx).await; |
| 434 | let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; | 434 | let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; |
| 435 | + // A finished job stays live: a retention purge can still take its artifacts and log. | ||
| 435 | assert!( | 436 | assert!( |
| 436 | - !done.text().contains(&job_marker), | 437 | + done.text().contains(&job_marker), |
| 437 | - "job not live when finished" | 438 | + "job still live when finished" |
| 438 | ); | 439 | ); |
| 439 | assert!( | 440 | assert!( |
| 440 | !done.text().contains("http-equiv=\"refresh\""), | 441 | !done.text().contains("http-equiv=\"refresh\""), |
| @@ -472,7 +473,7 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() { | |||
| 472 | let first = next_event(&mut job_frames).await.expect("the job status"); | 473 | let first = next_event(&mut job_frames).await.expect("the job status"); |
| 473 | assert_eq!( | 474 | assert_eq!( |
| 474 | first, | 475 | first, |
| 475 | - format!("event: changed\ndata: {}\n\n", job.state.as_str()).into_bytes() | 476 | + format!("event: changed\ndata: {}||nolog\n\n", job.state.as_str()).into_bytes() |
| 476 | ); | 477 | ); |
| 477 | 478 | ||
| 478 | // A bump with no new log bytes and no status change sends nothing. | 479 | // A bump with no new log bytes and no status change sends nothing. |
| @@ -500,7 +501,7 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() { | |||
| 500 | let last = next_event(&mut job_frames).await.expect("the final status"); | 501 | let last = next_event(&mut job_frames).await.expect("the final status"); |
| 501 | assert_eq!( | 502 | assert_eq!( |
| 502 | last, | 503 | last, |
| 503 | - format!("event: changed\ndata: {}\n\n", JobState::Success.as_str()).into_bytes() | 504 | + format!("event: changed\ndata: {}||nolog\n\n", JobState::Success.as_str()).into_bytes() |
| 504 | ); | 505 | ); |
| 505 | assert!(next_event(&mut job_frames).await.is_none(), "stream ends"); | 506 | assert!(next_event(&mut job_frames).await.is_none(), "stream ends"); |
| 506 | } | 507 | } |
| @@ -618,7 +619,7 @@ async fn job_log_events() { | |||
| 618 | let first = next_event(&mut frames).await.expect("the status"); | 619 | let first = next_event(&mut frames).await.expect("the status"); |
| 619 | assert_eq!( | 620 | assert_eq!( |
| 620 | first, | 621 | first, |
| 621 | - format!("event: changed\ndata: {}\n\n", job.state.as_str()).into_bytes() | 622 | + format!("event: changed\ndata: {}||nolog\n\n", job.state.as_str()).into_bytes() |
| 622 | ); | 623 | ); |
| 623 | 624 | ||
| 624 | let mut file = std::fs::OpenOptions::new() | 625 | let mut file = std::fs::OpenOptions::new() |
| @@ -724,7 +725,7 @@ async fn job_page_log_tail() { | |||
| 724 | "tail offset" | 725 | "tail offset" |
| 725 | ); | 726 | ); |
| 726 | assert!( | 727 | assert!( |
| 727 | - text.contains(&format!("data-live-state=\"{}\"", job.state.as_str())), | 728 | + text.contains(&format!("data-live-state=\"{}|", job.state.as_str())), |
| 728 | "rendered status" | 729 | "rendered status" |
| 729 | ); | 730 | ); |
| 730 | } | 731 | } |
crates/forge-web/src/pages/code_live.rsmodified+137 -24
| @@ -1,14 +1,19 @@ | |||
| 1 | //! Live stream of a repo's pages, at `/{owner}/{repo}/events`. The repo header renders `data-live` | 1 | //! Live stream of a repo's pages, at `/{owner}/{repo}/events`. The repo header renders `data-live` |
| 2 | //! with this URL on every repo page (see `repo::repo_head`). A code view adds its branch to the | 2 | //! with this URL on every repo page (see `repo::repo_head`). A code view adds its branch to the |
| 3 | -//! URL. The stream sends `changed` when the header changes: stars, watchers, forks, or the repo's | 3 | +//! URL. The stream sends `changed` when the header changes: stars, watchers, forks, the repo's |
| 4 | -//! name, description or visibility. On a code view of a branch it also sends `changed` when the | 4 | +//! name, description, visibility, archived flag or default branch, the open issue and pull counts, |
| 5 | -//! branch moves, or when a branch or tag is created or deleted (the ref selector and the branch | 5 | +//! the discussions and wiki switches, the viewer's own watch level, or the mirror's last sync. The |
| 6 | -//! list depend on that). Moves of other refs send nothing. Commits and tags are not followed: they | 6 | +//! header follows the repo's issues and pulls, so an issue or pull opened or closed shows at once. |
| 7 | -//! do not move. | 7 | +//! On a code view of a branch it also sends `changed` when the branch moves, or when a branch or |
| 8 | +//! tag is created or deleted (the ref selector and the branch list depend on that). Moves of other | ||
| 9 | +//! refs send nothing. Commits and tags are not followed: they do not move. | ||
| 10 | +//! | ||
| 11 | +//! The repo home page (`home_live_url`) also follows the releases, and sends `changed` when the | ||
| 12 | +//! latest release or the linked packages' versions change. Other repo pages do not read those. | ||
| 8 | 13 | ||
| 9 | use std::path::PathBuf; | 14 | use std::path::PathBuf; |
| 10 | 15 | ||
| 11 | -use forge_core::Visibility; | 16 | +use forge_core::{Repo as RepoRecord, User, Visibility}; |
| 12 | use forge_git::browse::{RefInfo, RefKind}; | 17 | use forge_git::browse::{RefInfo, RefKind}; |
| 13 | use topcoat::Result; | 18 | use topcoat::Result; |
| 14 | use topcoat::context::{Cx, app_context}; | 19 | use topcoat::context::{Cx, app_context}; |
| @@ -17,6 +22,7 @@ use topcoat::router::{path_param, query_params, route}; | |||
| 17 | 22 | ||
| 18 | use crate::auth::percent_encode; | 23 | use crate::auth::percent_encode; |
| 19 | use crate::live::{Topic, stream_changes}; | 24 | use crate::live::{Topic, stream_changes}; |
| 25 | +use crate::pages::packages::repo_package_links; | ||
| 20 | use crate::pages::refs::load_refs; | 26 | use crate::pages::refs::load_refs; |
| 21 | use crate::pages::repo_ctx::{fork_count, load_repo}; | 27 | use crate::pages::repo_ctx::{fork_count, load_repo}; |
| 22 | use crate::state::AppState; | 28 | use crate::state::AppState; |
| @@ -27,6 +33,7 @@ path_param!(repo); | |||
| 27 | #[query_params(error = bad_request)] | 33 | #[query_params(error = bad_request)] |
| 28 | struct LiveQuery { | 34 | struct LiveQuery { |
| 29 | ref_name: Option<String>, | 35 | ref_name: Option<String>, |
| 36 | + home: Option<String>, | ||
| 30 | } | 37 | } |
| 31 | 38 | ||
| 32 | /// Whether a code view of `ref_name` follows the branch: the ref is a branch of the repo. | 39 | /// Whether a code view of `ref_name` follows the branch: the ref is a branch of the repo. |
| @@ -40,6 +47,12 @@ pub fn branch_live_url(owner: &str, repo: &str, branch: &str) -> String { | |||
| 40 | format!("/{owner}/{repo}/events?ref_name={}", percent_encode(branch)) | 47 | format!("/{owner}/{repo}/events?ref_name={}", percent_encode(branch)) |
| 41 | } | 48 | } |
| 42 | 49 | ||
| 50 | +/// The stream URL of the repo home page: the branch's stream, which also follows the releases and | ||
| 51 | +/// the linked packages. | ||
| 52 | +pub fn home_live_url(owner: &str, repo: &str, branch: &str) -> String { | ||
| 53 | + format!("{}&home=1", branch_live_url(owner, repo, branch)) | ||
| 54 | +} | ||
| 55 | + | ||
| 43 | /// The stream URL of a repo page. A code view of a branch adds the branch to it. | 56 | /// The stream URL of a repo page. A code view of a branch adds the branch to it. |
| 44 | pub fn live_url(owner: &str, repo: &str, refs: &[RefInfo], ref_name: &str) -> String { | 57 | pub fn live_url(owner: &str, repo: &str, refs: &[RefInfo], ref_name: &str) -> String { |
| 45 | if follows_branch(refs, ref_name) { | 58 | if follows_branch(refs, ref_name) { |
| @@ -66,19 +79,75 @@ async fn refs_fingerprint(path: PathBuf, branch: String) -> Result<String> { | |||
| 66 | } | 79 | } |
| 67 | 80 | ||
| 68 | /// The state the repo header shows. A repo that is gone reads as empty, which ends nothing: the | 81 | /// The state the repo header shows. A repo that is gone reads as empty, which ends nothing: the |
| 69 | -/// stream then sends `changed` once and the page's own re-read shows the 404. | 82 | +/// stream then sends `changed` once and the page's own re-read shows the 404. `viewer_id` is the |
| 70 | -async fn header_fingerprint(state: &AppState, repo_id: &str) -> Result<String> { | 83 | +/// signed-in viewer, whose watch level the header shows. |
| 84 | +async fn header_fingerprint( | ||
| 85 | + state: &AppState, | ||
| 86 | + repo_id: &str, | ||
| 87 | + viewer_id: Option<&str>, | ||
| 88 | +) -> Result<String> { | ||
| 71 | let Some(repo) = state.store.repo_by_id(repo_id).await? else { | 89 | let Some(repo) = state.store.repo_by_id(repo_id).await? else { |
| 72 | return Ok(String::new()); | 90 | return Ok(String::new()); |
| 73 | }; | 91 | }; |
| 74 | let stars = state.store.star_count(repo_id).await?; | 92 | let stars = state.store.star_count(repo_id).await?; |
| 75 | let watchers = state.store.watchers(repo_id).await?.len(); | 93 | let watchers = state.store.watchers(repo_id).await?.len(); |
| 76 | let forks = fork_count(state, repo_id).await?; | 94 | let forks = fork_count(state, repo_id).await?; |
| 95 | + let (open_issues, _) = state.store.issue_counts(repo_id).await?; | ||
| 96 | + let (open_pulls, _) = state.store.pull_counts(repo_id).await?; | ||
| 97 | + let discussions = state.store.discussions_enabled(repo_id).await?; | ||
| 98 | + let wiki = state.store.wiki_enabled(repo_id).await?; | ||
| 99 | + let watch = match viewer_id { | ||
| 100 | + Some(viewer) => format!("{:?}", state.store.watch_level(viewer, repo_id).await?), | ||
| 101 | + None => String::new(), | ||
| 102 | + }; | ||
| 103 | + let mirror = match state.store.pull_mirror(repo_id).await? { | ||
| 104 | + Some(m) => format!( | ||
| 105 | + "{} {} {:?}", | ||
| 106 | + m.url, | ||
| 107 | + m.last_sync_at.as_deref().unwrap_or(""), | ||
| 108 | + m.last_ok | ||
| 109 | + ), | ||
| 110 | + None => String::new(), | ||
| 111 | + }; | ||
| 112 | + Ok(header_text(&repo, [stars, watchers as u64, forks, open_issues, open_pulls], &format!( | ||
| 113 | + "{discussions} {wiki} {watch}\n{mirror}" | ||
| 114 | + ))) | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +/// Joins the header's fields into the fingerprint text. | ||
| 118 | +fn header_text(repo: &RepoRecord, counts: [u64; 5], rest: &str) -> String { | ||
| 77 | let public = repo.visibility == Visibility::Public; | 119 | let public = repo.visibility == Visibility::Public; |
| 78 | - Ok(format!( | 120 | + let [stars, watchers, forks, issues, pulls] = counts; |
| 79 | - "{}\n{}\n{public}\n{}\n{stars} {watchers} {forks}", | 121 | + format!( |
| 80 | - repo.owner_name, repo.name, repo.description | 122 | + "{}\n{}\n{public}\n{}\n{stars} {watchers} {forks} {issues} {pulls} {} {}\n{rest}", |
| 81 | - )) | 123 | + repo.owner_name, repo.name, repo.description, repo.archived, repo.default_branch |
| 124 | + ) | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +/// The state the home page's latest-release card and linked-package card show. | ||
| 128 | +async fn home_fingerprint(state: &AppState, repo_id: &str, viewer: Option<&User>) -> Result<String> { | ||
| 129 | + let mut release_text = String::new(); | ||
| 130 | + if let Some(release) = state.store.latest_release(repo_id).await? { | ||
| 131 | + let assets = state.store.list_release_assets(&release.id).await?; | ||
| 132 | + let names: Vec<String> = assets | ||
| 133 | + .iter() | ||
| 134 | + .map(|asset| format!("{} {}", asset.id, asset.name)) | ||
| 135 | + .collect(); | ||
| 136 | + release_text = format!( | ||
| 137 | + "{} {} {} {} {}", | ||
| 138 | + release.id, | ||
| 139 | + release.tag, | ||
| 140 | + release.title, | ||
| 141 | + release.published_at.as_deref().unwrap_or(""), | ||
| 142 | + names.join(" ") | ||
| 143 | + ); | ||
| 144 | + } | ||
| 145 | + let packages = repo_package_links(state, viewer, repo_id).await?; | ||
| 146 | + let package_text: Vec<String> = packages | ||
| 147 | + .iter() | ||
| 148 | + .map(|link| format!("{} {}", link.name, link.latest)) | ||
| 149 | + .collect(); | ||
| 150 | + Ok(format!("{release_text}\n{}", package_text.join("\n"))) | ||
| 82 | } | 151 | } |
| 83 | 152 | ||
| 84 | /// The repo's live stream. Auth is the repo read check of the page: a viewer who cannot read the | 153 | /// The repo's live stream. Auth is the repo read check of the page: a viewer who cannot read the |
| @@ -87,31 +156,75 @@ async fn header_fingerprint(state: &AppState, repo_id: &str) -> Result<String> { | |||
| 87 | async fn repo_events(cx: &Cx) -> Result<Response> { | 156 | async fn repo_events(cx: &Cx) -> Result<Response> { |
| 88 | let owner = path_param::<Owner>(cx); | 157 | let owner = path_param::<Owner>(cx); |
| 89 | let name = path_param::<Repo>(cx); | 158 | let name = path_param::<Repo>(cx); |
| 90 | - let branch = query_params::<LiveQuery>(cx)? | 159 | + let query = query_params::<LiveQuery>(cx)?; |
| 91 | - .ref_name | 160 | + let branch = query.ref_name.clone().unwrap_or_default(); |
| 92 | - .clone() | 161 | + let home = query.home.as_deref() == Some("1"); |
| 93 | - .unwrap_or_default(); | ||
| 94 | let ctx = load_repo(cx, owner, name).await?; | 162 | let ctx = load_repo(cx, owner, name).await?; |
| 95 | let state = app_context::<AppState>(cx).clone(); | 163 | let state = app_context::<AppState>(cx).clone(); |
| 96 | - let mut topics = vec![Topic::Repo(ctx.repo.id.clone())]; | 164 | + let repo_id = ctx.repo.id.clone(); |
| 165 | + let mut topics = vec![ | ||
| 166 | + Topic::Repo(repo_id.clone()), | ||
| 167 | + Topic::RepoIssues(repo_id.clone()), | ||
| 168 | + Topic::PullList(repo_id.clone()), | ||
| 169 | + ]; | ||
| 97 | if !branch.is_empty() { | 170 | if !branch.is_empty() { |
| 98 | - topics.push(Topic::RepoRefs(ctx.repo.id.clone())); | 171 | + topics.push(Topic::RepoRefs(repo_id.clone())); |
| 172 | + } | ||
| 173 | + if home { | ||
| 174 | + topics.push(Topic::RepoReleases(repo_id.clone())); | ||
| 99 | } | 175 | } |
| 176 | + let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone()); | ||
| 100 | let path = ctx.path.clone(); | 177 | let path = ctx.path.clone(); |
| 101 | - let repo_id = ctx.repo.id.clone(); | ||
| 102 | stream_changes(cx, &state.live.clone(), &topics, move || { | 178 | stream_changes(cx, &state.live.clone(), &topics, move || { |
| 103 | let state = state.clone(); | 179 | let state = state.clone(); |
| 104 | let repo_id = repo_id.clone(); | 180 | let repo_id = repo_id.clone(); |
| 105 | let path = path.clone(); | 181 | let path = path.clone(); |
| 106 | let branch = branch.clone(); | 182 | let branch = branch.clone(); |
| 183 | + let viewer = viewer.clone(); | ||
| 107 | async move { | 184 | async move { |
| 108 | - let header = header_fingerprint(&state, &repo_id).await?; | 185 | + let viewer_id = viewer.as_ref().map(|user| user.id.as_str()); |
| 109 | - if branch.is_empty() { | 186 | + let mut out = header_fingerprint(&state, &repo_id, viewer_id).await?; |
| 110 | - return Ok(header); | 187 | + if !branch.is_empty() { |
| 188 | + let refs = refs_fingerprint(path, branch).await?; | ||
| 189 | + out = format!("{out}\n{refs}"); | ||
| 111 | } | 190 | } |
| 112 | - let refs = refs_fingerprint(path, branch).await?; | 191 | + if home { |
| 113 | - Ok(format!("{header}\n{refs}")) | 192 | + let extra = home_fingerprint(&state, &repo_id, viewer.as_ref()).await?; |
| 193 | + out = format!("{out}\n{extra}"); | ||
| 194 | + } | ||
| 195 | + Ok(out) | ||
| 114 | } | 196 | } |
| 115 | }) | 197 | }) |
| 116 | .await | 198 | .await |
| 117 | } | 199 | } |
| 200 | + | ||
| 201 | +#[cfg(test)] | ||
| 202 | +mod tests { | ||
| 203 | + use super::*; | ||
| 204 | + | ||
| 205 | + #[tokio::test] | ||
| 206 | + async fn opening_an_issue_changes_the_header_state() { | ||
| 207 | + let dir = tempfile::tempdir().unwrap(); | ||
| 208 | + let state = crate::test_support::test_state(dir.path()).await; | ||
| 209 | + let user = state | ||
| 210 | + .store | ||
| 211 | + .create_user("tahinli", None, "x", false) | ||
| 212 | + .await | ||
| 213 | + .unwrap(); | ||
| 214 | + let repo = state | ||
| 215 | + .store | ||
| 216 | + .create_repo(&user.id, "demo", "", Visibility::Public, "main") | ||
| 217 | + .await | ||
| 218 | + .unwrap(); | ||
| 219 | + let before = header_fingerprint(&state, &repo.id, None).await.unwrap(); | ||
| 220 | + | ||
| 221 | + state | ||
| 222 | + .store | ||
| 223 | + .create_issue(&repo.id, &user.id, "Broken build", "") | ||
| 224 | + .await | ||
| 225 | + .unwrap(); | ||
| 226 | + | ||
| 227 | + let after = header_fingerprint(&state, &repo.id, None).await.unwrap(); | ||
| 228 | + assert_ne!(before, after); | ||
| 229 | + } | ||
| 230 | +} | ||
crates/forge-web/src/pages/code_search.rsmodified+3 -0
| @@ -15,6 +15,7 @@ use crate::i18n::{ | |||
| 15 | self, | 15 | self, |
| 16 | code::{self as g, K}, | 16 | code::{self as g, K}, |
| 17 | }; | 17 | }; |
| 18 | +use crate::pages::code_live::branch_live_url; | ||
| 18 | use crate::pages::commits::blocking; | 19 | use crate::pages::commits::blocking; |
| 19 | use crate::pages::repo::repo_head; | 20 | use crate::pages::repo::repo_head; |
| 20 | use crate::pages::repo_ctx::load_repo; | 21 | use crate::pages::repo_ctx::load_repo; |
| @@ -203,6 +204,8 @@ async fn search_page(cx: &Cx) -> Result<impl View> { | |||
| 203 | 204 | ||
| 204 | let mut header = ctx.head(state, "code").await?; | 205 | let mut header = ctx.head(state, "code").await?; |
| 205 | header.hide_search = true; | 206 | header.hide_search = true; |
| 207 | + // Results of a branch go stale when it moves: the header's stream follows that branch's head. | ||
| 208 | + header.live = branch_live_url(&owner_name, &repo_name, &ref_name); | ||
| 206 | Ok(view! { | 209 | Ok(view! { |
| 207 | shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), | 210 | shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), |
| 208 | repo_head(head: header) | 211 | repo_head(head: header) |
crates/forge-web/src/pages/compare.rsmodified+4 -0
| @@ -615,6 +615,10 @@ async fn pull_create(cx: &Cx, Form(form): Form<PullForm>) -> Result<impl View> { | |||
| 615 | pr | 615 | pr |
| 616 | }; | 616 | }; |
| 617 | emit_pull(state, &ctx.repo, &Sender::of(&user), "opened", &pr).await; | 617 | emit_pull(state, &ctx.repo, &Sender::of(&user), "opened", &pr).await; |
| 618 | + // The author's contribution calendar counts the pull request. | ||
| 619 | + state | ||
| 620 | + .live | ||
| 621 | + .bump(&crate::live::Topic::User(user.id.clone())); | ||
| 618 | if !as_draft { | 622 | if !as_draft { |
| 619 | // A draft tells nobody until it is marked ready for review. | 623 | // A draft tells nobody until it is marked ready for review. |
| 620 | notify::dispatch( | 624 | notify::dispatch( |
crates/forge-web/src/pages/discussion_settings.rsmodified+3 -0
| @@ -15,6 +15,7 @@ use crate::audit::{self, Actor, Target}; | |||
| 15 | use crate::auth::require_csrf; | 15 | use crate::auth::require_csrf; |
| 16 | use crate::i18n::Lang; | 16 | use crate::i18n::Lang; |
| 17 | use crate::i18n::community::{self as g, K}; | 17 | use crate::i18n::community::{self as g, K}; |
| 18 | +use crate::live::Topic; | ||
| 18 | use crate::pages::repo_ctx::load_repo; | 19 | use crate::pages::repo_ctx::load_repo; |
| 19 | use crate::state::AppState; | 20 | use crate::state::AppState; |
| 20 | use crate::views::repo_href; | 21 | use crate::views::repo_href; |
| @@ -69,6 +70,8 @@ async fn settings_discussions_save(cx: &Cx, Form(form): Form<ToggleForm>) -> Res | |||
| 69 | .store | 70 | .store |
| 70 | .set_discussions_enabled(&ctx.repo.id, enabled) | 71 | .set_discussions_enabled(&ctx.repo.id, enabled) |
| 71 | .await?; | 72 | .await?; |
| 73 | + // The repo header shows the Discussions tab. | ||
| 74 | + state.live.bump(&Topic::Repo(ctx.repo.id.clone())); | ||
| 72 | let name = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name); | 75 | let name = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name); |
| 73 | let action = if enabled { | 76 | let action = if enabled { |
| 74 | AuditAction::DiscussionsEnabled | 77 | AuditAction::DiscussionsEnabled |
crates/forge-web/src/pages/edit_history.rsmodified+7 -3
| @@ -19,6 +19,7 @@ use crate::i18n::issues::{self as g, K}; | |||
| 19 | use crate::i18n::{self, Lang}; | 19 | use crate::i18n::{self, Lang}; |
| 20 | use crate::pages::issue_parts::{ItemKind, When, item_for, parse_number}; | 20 | use crate::pages::issue_parts::{ItemKind, When, item_for, parse_number}; |
| 21 | use crate::pages::issues_live::item_live_url; | 21 | use crate::pages::issues_live::item_live_url; |
| 22 | +use crate::pages::pull_live::pull_live_url; | ||
| 22 | use crate::pages::repo::repo_head; | 23 | use crate::pages::repo::repo_head; |
| 23 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; | 24 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; |
| 24 | use crate::state::AppState; | 25 | use crate::state::AppState; |
| @@ -227,13 +228,16 @@ async fn history_page( | |||
| 227 | let heading = g::history_heading(lang, what); | 228 | let heading = g::history_heading(lang, what); |
| 228 | let back_label = g::back_to_item(lang, number); | 229 | let back_label = g::back_to_item(lang, number); |
| 229 | let count_label = g::earlier_versions(lang, entries.len()); | 230 | let count_label = g::earlier_versions(lang, entries.len()); |
| 230 | - // An issue's history follows the issue: a new edit adds a version to the list. | 231 | + // A history follows its item: a new edit adds a version to the list. |
| 231 | - let live = (kind_item == ItemKind::Issue).then(|| item_live_url(&owner, &name, number)); | 232 | + let live = match kind_item { |
| 233 | + ItemKind::Issue => item_live_url(&owner, &name, number), | ||
| 234 | + ItemKind::Pull => pull_live_url(&owner, &name, number), | ||
| 235 | + }; | ||
| 232 | 236 | ||
| 233 | Ok(view! { cx => | 237 | Ok(view! { cx => |
| 234 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), | 238 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), |
| 235 | repo_head(head: header) | 239 | repo_head(head: header) |
| 236 | - <section class="issue-head" data-live=(live.as_deref()) data-live-now=""> | 240 | + <section class="issue-head" data-live=(live.as_str()) data-live-now=""> |
| 237 | <h1 class="issue-heading">(heading.as_str())</h1> | 241 | <h1 class="issue-heading">(heading.as_str())</h1> |
| 238 | <p class="issue-byline"> | 242 | <p class="issue-byline"> |
| 239 | <a href=(back.as_str())>(back_label.as_str())</a> | 243 | <a href=(back.as_str())>(back_label.as_str())</a> |
crates/forge-web/src/pages/import.rsmodified+32 -1
| @@ -23,6 +23,7 @@ use crate::auth::{require_csrf, require_user}; | |||
| 23 | use crate::i18n::migrate::{self as g, K}; | 23 | use crate::i18n::migrate::{self as g, K}; |
| 24 | use crate::i18n::{self, Key, Lang}; | 24 | use crate::i18n::{self, Key, Lang}; |
| 25 | use crate::importer::api::{ApiError, RemoteApi}; | 25 | use crate::importer::api::{ApiError, RemoteApi}; |
| 26 | +use crate::live::{Topic, stream_changes}; | ||
| 26 | use crate::importer::{ | 27 | use crate::importer::{ |
| 27 | self, ImportOptions, JobSpec, Source, default_name, make_forgejo, make_github, make_gitlab, | 28 | self, ImportOptions, JobSpec, Source, default_name, make_forgejo, make_github, make_gitlab, |
| 28 | parse_remote, source_ref, | 29 | parse_remote, source_ref, |
| @@ -1037,7 +1038,7 @@ async fn jobs_list(lang: Lang, jobs: Vec<(ImportJob, Option<Repo>)>) -> Result<i | |||
| 1037 | let empty = jobs.is_empty(); | 1038 | let empty = jobs.is_empty(); |
| 1038 | Ok(view! { | 1039 | Ok(view! { |
| 1039 | newrepo_tabs(lang: lang, active: "import") | 1040 | newrepo_tabs(lang: lang, active: "import") |
| 1040 | - <section class="page-head"> | 1041 | + <section class="page-head" data-live="/import/events"> |
| 1041 | <h1>(g::t(lang, K::JobsTitle))</h1> | 1042 | <h1>(g::t(lang, K::JobsTitle))</h1> |
| 1042 | </section> | 1043 | </section> |
| 1043 | if empty { | 1044 | if empty { |
| @@ -1050,6 +1051,36 @@ async fn jobs_list(lang: Lang, jobs: Vec<(ImportJob, Option<Repo>)>) -> Result<i | |||
| 1050 | }) | 1051 | }) |
| 1051 | } | 1052 | } |
| 1052 | 1053 | ||
| 1054 | +/// What the import list shows for `user_id`: each job's id, state, source and repo, in list order. | ||
| 1055 | +async fn jobs_fingerprint(state: &AppState, user_id: &str) -> Result<String> { | ||
| 1056 | + let rows = load_job_rows(state, user_id, 50).await?; | ||
| 1057 | + Ok(rows | ||
| 1058 | + .iter() | ||
| 1059 | + .map(|(job, repo)| { | ||
| 1060 | + let repo = repo | ||
| 1061 | + .as_ref() | ||
| 1062 | + .map_or(String::new(), |repo| format!("{}/{}", repo.owner_name, repo.name)); | ||
| 1063 | + format!("{} {} {} {repo}", job.id, job.state.as_str(), job.source_ref) | ||
| 1064 | + }) | ||
| 1065 | + .collect::<Vec<_>>() | ||
| 1066 | + .join("\n")) | ||
| 1067 | +} | ||
| 1068 | + | ||
| 1069 | +/// The import list's change stream: the viewer's own jobs, from the session only. It sends when the | ||
| 1070 | +/// list would show something different (see [`Topic::Imports`]). | ||
| 1071 | +#[route(GET "/import/events")] | ||
| 1072 | +async fn jobs_events(cx: &Cx) -> Result<Response> { | ||
| 1073 | + let viewer = require_user(cx).await?; | ||
| 1074 | + let state = app_context::<AppState>(cx).clone(); | ||
| 1075 | + let user_id = viewer.0.id.clone(); | ||
| 1076 | + stream_changes(cx, &state.live.clone(), &[Topic::Imports(user_id.clone())], move || { | ||
| 1077 | + let state = state.clone(); | ||
| 1078 | + let user_id = user_id.clone(); | ||
| 1079 | + async move { jobs_fingerprint(&state, &user_id).await } | ||
| 1080 | + }) | ||
| 1081 | + .await | ||
| 1082 | +} | ||
| 1083 | + | ||
| 1053 | #[page("/import")] | 1084 | #[page("/import")] |
| 1054 | async fn jobs_page(cx: &Cx) -> Result<impl View> { | 1085 | async fn jobs_page(cx: &Cx) -> Result<impl View> { |
| 1055 | let viewer = require_user(cx).await?; | 1086 | let viewer = require_user(cx).await?; |
crates/forge-web/src/pages/issue_parts.rsmodified+2 -0
| @@ -1351,6 +1351,8 @@ pub(crate) async fn post_comment( | |||
| 1351 | if !pull { | 1351 | if !pull { |
| 1352 | state.live.bump_issue(&ctx.repo.id, &item.id); | 1352 | state.live.bump_issue(&ctx.repo.id, &item.id); |
| 1353 | } | 1353 | } |
| 1354 | + // The author's contribution calendar counts the comment. | ||
| 1355 | + state.live.bump(&crate::live::Topic::User(user.id.clone())); | ||
| 1354 | emit_comment(state, &ctx.repo, &sender, "created", pull, item, &comment).await; | 1356 | emit_comment(state, &ctx.repo, &sender, "created", pull, item, &comment).await; |
| 1355 | notify::dispatch( | 1357 | notify::dispatch( |
| 1356 | state, | 1358 | state, |
crates/forge-web/src/pages/issues_list.rsmodified+4 -0
| @@ -835,6 +835,10 @@ async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> { | |||
| 835 | .await?; | 835 | .await?; |
| 836 | } | 836 | } |
| 837 | state.live.bump_issue(&ctx.repo.id, &issue.id); | 837 | state.live.bump_issue(&ctx.repo.id, &issue.id); |
| 838 | + // The author's contribution calendar counts the issue. | ||
| 839 | + state | ||
| 840 | + .live | ||
| 841 | + .bump(&crate::live::Topic::User(viewer.0.id.clone())); | ||
| 838 | emit_issue(state, &ctx.repo, &Sender::of(&viewer.0), "opened", &issue).await; | 842 | emit_issue(state, &ctx.repo, &Sender::of(&viewer.0), "opened", &issue).await; |
| 839 | notify::dispatch( | 843 | notify::dispatch( |
| 840 | state, | 844 | state, |
crates/forge-web/src/pages/labels_page.rsmodified+10 -3
| @@ -17,6 +17,7 @@ use crate::i18n::{self, Lang}; | |||
| 17 | use crate::pages::issue_meta::{ | 17 | use crate::pages::issue_meta::{ |
| 18 | RepoFrame, action_error_at, issue_subnav, refusal_message, triage_guard, | 18 | RepoFrame, action_error_at, issue_subnav, refusal_message, triage_guard, |
| 19 | }; | 19 | }; |
| 20 | +use crate::pages::issues_live::list_live_url; | ||
| 20 | use crate::pages::repo::repo_head; | 21 | use crate::pages::repo::repo_head; |
| 21 | use crate::pages::repo_ctx::load_repo; | 22 | use crate::pages::repo_ctx::load_repo; |
| 22 | use crate::state::AppState; | 23 | use crate::state::AppState; |
| @@ -65,7 +66,12 @@ fn labels_href(title: &str) -> String { | |||
| 65 | 66 | ||
| 66 | /// The header, the label list and, for triage holders, the forms. | 67 | /// The header, the label list and, for triage holders, the forms. |
| 67 | #[component] | 68 | #[component] |
| 68 | -async fn labels_body(lang: Lang, frame: RepoFrame, rows: Vec<LabelRow>) -> Result<impl View> { | 69 | +async fn labels_body( |
| 70 | + lang: Lang, | ||
| 71 | + frame: RepoFrame, | ||
| 72 | + rows: Vec<LabelRow>, | ||
| 73 | + live: String, | ||
| 74 | +) -> Result<impl View> { | ||
| 69 | let labels_action = labels_href(&frame.title); | 75 | let labels_action = labels_href(&frame.title); |
| 70 | let defaults_action = format!("{labels_action}/defaults"); | 76 | let defaults_action = format!("{labels_action}/defaults"); |
| 71 | let empty = rows.is_empty(); | 77 | let empty = rows.is_empty(); |
| @@ -79,7 +85,7 @@ async fn labels_body(lang: Lang, frame: RepoFrame, rows: Vec<LabelRow>) -> Resul | |||
| 79 | if archived { | 85 | if archived { |
| 80 | <section class="card notice" role="status">(g::t(lang, K::LabelsArchived))</section> | 86 | <section class="card notice" role="status">(g::t(lang, K::LabelsArchived))</section> |
| 81 | } | 87 | } |
| 82 | - <section class="card"> | 88 | + <section class="card" data-live=(live.as_str()) data-live-now=""> |
| 83 | <h2>(g::t(lang, K::Labels))</h2> | 89 | <h2>(g::t(lang, K::Labels))</h2> |
| 84 | if empty { | 90 | if empty { |
| 85 | <p class="muted">(g::t(lang, K::NoLabelsYet))</p> | 91 | <p class="muted">(g::t(lang, K::NoLabelsYet))</p> |
| @@ -193,12 +199,13 @@ async fn labels_page(cx: &Cx) -> Result<impl View> { | |||
| 193 | } | 199 | } |
| 194 | }) | 200 | }) |
| 195 | .collect(); | 201 | .collect(); |
| 202 | + let live = list_live_url(&ctx.repo.owner_name, &ctx.repo.name); | ||
| 196 | let css_href = format!("/{}/labels.css", frame.title); | 203 | let css_href = format!("/{}/labels.css", frame.title); |
| 197 | let page_title = g::labels_title(lang, &frame.title); | 204 | let page_title = g::labels_title(lang, &frame.title); |
| 198 | Ok(view! { | 205 | Ok(view! { |
| 199 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), | 206 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), |
| 200 | extra_stylesheet: Some(css_href.as_str()), | 207 | extra_stylesheet: Some(css_href.as_str()), |
| 201 | - labels_body(lang: lang, frame: frame, rows: rows)) | 208 | + labels_body(lang: lang, frame: frame, rows: rows, live: live)) |
| 202 | }) | 209 | }) |
| 203 | } | 210 | } |
| 204 | 211 | ||
crates/forge-web/src/pages/milestones_page.rsmodified+5 -2
| @@ -20,6 +20,7 @@ use crate::i18n::{self, Lang}; | |||
| 20 | use crate::pages::issue_meta::{ | 20 | use crate::pages::issue_meta::{ |
| 21 | RepoFrame, action_error_at, can_triage, issue_subnav, refusal_message, triage_guard, | 21 | RepoFrame, action_error_at, can_triage, issue_subnav, refusal_message, triage_guard, |
| 22 | }; | 22 | }; |
| 23 | +use crate::pages::issues_live::list_live_url; | ||
| 23 | use crate::pages::repo::repo_head; | 24 | use crate::pages::repo::repo_head; |
| 24 | use crate::pages::repo_ctx::load_repo; | 25 | use crate::pages::repo_ctx::load_repo; |
| 25 | use crate::render::markdown::render_markdown; | 26 | use crate::render::markdown::render_markdown; |
| @@ -232,10 +233,11 @@ async fn milestones_page(cx: &Cx) -> Result<impl View> { | |||
| 232 | let csrf = frame.csrf.clone(); | 233 | let csrf = frame.csrf.clone(); |
| 233 | let can_create = frame.can_triage; | 234 | let can_create = frame.can_triage; |
| 234 | let create_action = milestones_href(&frame.title); | 235 | let create_action = milestones_href(&frame.title); |
| 236 | + let live = list_live_url(&ctx.repo.owner_name, &ctx.repo.name); | ||
| 235 | Ok(view! { | 237 | Ok(view! { |
| 236 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), | 238 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), |
| 237 | milestones_body(lang: lang, frame: frame, rows: rows, empty: empty, closed: closed, | 239 | milestones_body(lang: lang, frame: frame, rows: rows, empty: empty, closed: closed, |
| 238 | - csrf: csrf, can_create: can_create, create_action: create_action)) | 240 | + csrf: csrf, can_create: can_create, create_action: create_action, live: live)) |
| 239 | }) | 241 | }) |
| 240 | } | 242 | } |
| 241 | 243 | ||
| @@ -250,6 +252,7 @@ async fn milestones_body( | |||
| 250 | csrf: String, | 252 | csrf: String, |
| 251 | can_create: bool, | 253 | can_create: bool, |
| 252 | create_action: String, | 254 | create_action: String, |
| 255 | + live: String, | ||
| 253 | ) -> Result<impl View> { | 256 | ) -> Result<impl View> { |
| 254 | let title = frame.title.clone(); | 257 | let title = frame.title.clone(); |
| 255 | let can_triage = frame.can_triage; | 258 | let can_triage = frame.can_triage; |
| @@ -262,7 +265,7 @@ async fn milestones_body( | |||
| 262 | <section class="card notice" role="status">(g::t(lang, K::MilestonesArchived))</section> | 265 | <section class="card notice" role="status">(g::t(lang, K::MilestonesArchived))</section> |
| 263 | } | 266 | } |
| 264 | state_tabs(lang: lang, title: title.clone(), closed: closed) | 267 | state_tabs(lang: lang, title: title.clone(), closed: closed) |
| 265 | - <section class="card"> | 268 | + <section class="card" data-live=(live.as_str()) data-live-now=""> |
| 266 | if empty { | 269 | if empty { |
| 267 | <p class="muted">(if closed { g::t(lang, K::NoClosedMilestones) } else { g::t(lang, K::NoOpenMilestones) })</p> | 270 | <p class="muted">(if closed { g::t(lang, K::NoClosedMilestones) } else { g::t(lang, K::NoOpenMilestones) })</p> |
| 268 | } | 271 | } |
crates/forge-web/src/pages/notifications.rsmodified+8 -0
| @@ -797,6 +797,14 @@ async fn set_subscription(cx: &Cx, pull: bool, form: &SubscriptionForm) -> Resul | |||
| 797 | } | 797 | } |
| 798 | _ => return Err(bad_request("unknown subscription action").into()), | 798 | _ => return Err(bad_request("unknown subscription action").into()), |
| 799 | } | 799 | } |
| 800 | + // The page's button shows the viewer's subscription, so the page and its stream are woken. | ||
| 801 | + if pull { | ||
| 802 | + crate::pages::pull_live::bump_pull(state, &ctx.repo.id, &issue.id); | ||
| 803 | + } else { | ||
| 804 | + state | ||
| 805 | + .live | ||
| 806 | + .bump(&crate::live::Topic::Issue(issue.id.clone())); | ||
| 807 | + } | ||
| 800 | let section = if pull { "pulls" } else { "issues" }; | 808 | let section = if pull { "pulls" } else { "issues" }; |
| 801 | let href = repo_href( | 809 | let href = repo_href( |
| 802 | &ctx.repo.owner_name, | 810 | &ctx.repo.owner_name, |
crates/forge-web/src/pages/org_live.rsmodified+4 -2
| @@ -3,7 +3,8 @@ | |||
| 3 | //! a repo that is renamed or made private reaches the team page that names it. | 3 | //! a repo that is renamed or made private reaches the team page that names it. |
| 4 | //! | 4 | //! |
| 5 | //! Every POST under `/org/{org}/{members|teams|settings}` bumps the org's topic through | 5 | //! Every POST under `/org/{org}/{members|teams|settings}` bumps the org's topic through |
| 6 | -//! [`OrgWriteLayer`], after the handler ran. A refused write bumps too, as in the pull layer. The | 6 | +//! [`OrgWriteLayer`], after the handler ran, and the org's user topic too: its public profile shows |
| 7 | +//! the about text and the member and team counts. A refused write bumps too, as in the pull layer. The | ||
| 7 | //! streams send `changed` only when their fingerprint moves, so over-bumping is cheap. | 8 | //! streams send `changed` only when their fingerprint moves, so over-bumping is cheap. |
| 8 | //! | 9 | //! |
| 9 | //! Auth is the page's own: each stream runs the same `load_org` and role check as its page, so a | 10 | //! Auth is the page's own: each stream runs the same `load_org` and role check as its page, so a |
| @@ -232,7 +233,8 @@ async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Resul | |||
| 232 | }; | 233 | }; |
| 233 | let result = next.run(cx, body).await; | 234 | let result = next.run(cx, body).await; |
| 234 | if let Some(org_id) = org_id { | 235 | if let Some(org_id) = org_id { |
| 235 | - state.live.bump(&Topic::Org(org_id)); | 236 | + state.live.bump(&Topic::Org(org_id.clone())); |
| 237 | + state.live.bump(&Topic::User(org_id)); | ||
| 236 | } | 238 | } |
| 237 | result | 239 | result |
| 238 | } | 240 | } |
crates/forge-web/src/pages/org_new.rsmodified+3 -0
| @@ -16,6 +16,7 @@ use crate::audit::{self, Actor, Target}; | |||
| 16 | use crate::auth::{require_csrf, require_user}; | 16 | use crate::auth::{require_csrf, require_user}; |
| 17 | use crate::i18n::orgs::{self as g, K}; | 17 | use crate::i18n::orgs::{self as g, K}; |
| 18 | use crate::i18n::{self, Lang}; | 18 | use crate::i18n::{self, Lang}; |
| 19 | +use crate::live::Topic; | ||
| 19 | use crate::state::AppState; | 20 | use crate::state::AppState; |
| 20 | use crate::views::{alert, csrf_field, shell, user_facing_message}; | 21 | use crate::views::{alert, csrf_field, shell, user_facing_message}; |
| 21 | 22 | ||
| @@ -147,5 +148,7 @@ async fn create_org( | |||
| 147 | serde_json::Value::Null, | 148 | serde_json::Value::Null, |
| 148 | ) | 149 | ) |
| 149 | .await; | 150 | .await; |
| 151 | + // The explore list names the orgs too. | ||
| 152 | + state.live.bump(&Topic::Explore); | ||
| 150 | Ok(Ok(org)) | 153 | Ok(Ok(org)) |
| 151 | } | 154 | } |
crates/forge-web/src/pages/org_settings.rsmodified+5 -1
| @@ -15,6 +15,7 @@ use topcoat::view::{View, component, view}; | |||
| 15 | use crate::audit::{self, Actor, Target}; | 15 | use crate::audit::{self, Actor, Target}; |
| 16 | use crate::i18n::orgs::{self as g, K}; | 16 | use crate::i18n::orgs::{self as g, K}; |
| 17 | use crate::i18n::{self, Lang}; | 17 | use crate::i18n::{self, Lang}; |
| 18 | +use crate::live::Topic; | ||
| 18 | use crate::pages::org_ctx::{ | 19 | use crate::pages::org_ctx::{ |
| 19 | DEFAULT_ROLES, load_org, notice_href, org_head, org_notice, require_form_csrf, require_owner, | 20 | DEFAULT_ROLES, load_org, notice_href, org_head, org_notice, require_form_csrf, require_owner, |
| 20 | take_notice, | 21 | take_notice, |
| @@ -200,7 +201,10 @@ async fn org_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<SeeOther> { | |||
| 200 | return Ok(see_other(notice_href(&back, "confirm_name"))); | 201 | return Ok(see_other(notice_href(&back, "confirm_name"))); |
| 201 | } | 202 | } |
| 202 | match state.store.delete_org(&ctx.org.id).await { | 203 | match state.store.delete_org(&ctx.org.id).await { |
| 203 | - Ok(()) => {} | 204 | + Ok(()) => { |
| 205 | + // The explore list names the orgs too. | ||
| 206 | + state.live.bump(&Topic::Explore); | ||
| 207 | + } | ||
| 204 | Err(forge_core::Error::Conflict(_)) => { | 208 | Err(forge_core::Error::Conflict(_)) => { |
| 205 | return Ok(see_other(notice_href(&back, "has_repos"))); | 209 | return Ok(see_other(notice_href(&back, "has_repos"))); |
| 206 | } | 210 | } |
crates/forge-web/src/pages/profile.rsmodified+18 -0
| @@ -276,6 +276,24 @@ async fn profile_fingerprint( | |||
| 276 | .await? | 276 | .await? |
| 277 | .to_string(), | 277 | .to_string(), |
| 278 | ]; | 278 | ]; |
| 279 | + // The header's about text and avatar, read fresh: the stream's `user` is a snapshot from connect. | ||
| 280 | + let about = state | ||
| 281 | + .store | ||
| 282 | + .user_by_id(&user.id) | ||
| 283 | + .await? | ||
| 284 | + .map(|fresh| fresh.about) | ||
| 285 | + .unwrap_or_default(); | ||
| 286 | + lines.push(format!("about {about}")); | ||
| 287 | + lines.push(format!( | ||
| 288 | + "avatar {}", | ||
| 289 | + state.store.avatar_hash(&user.id).await?.unwrap_or_default() | ||
| 290 | + )); | ||
| 291 | + // An organization's page shows its member and team counts. | ||
| 292 | + if user.is_org() { | ||
| 293 | + let members = state.store.org_members(&user.id).await?.len(); | ||
| 294 | + let teams = state.store.teams_for_org(&user.id).await?.len(); | ||
| 295 | + lines.push(format!("org {members} {teams}")); | ||
| 296 | + } | ||
| 279 | let pins = readable( | 297 | let pins = readable( |
| 280 | state, | 298 | state, |
| 281 | actor, | 299 | actor, |
crates/forge-web/src/pages/profile_pins.rsmodified+52 -4
| @@ -4,17 +4,19 @@ | |||
| 4 | //! after a save. | 4 | //! after a save. |
| 5 | 5 | ||
| 6 | use forge_core::store::profile_pins::MAX_PROFILE_PINS; | 6 | use forge_core::store::profile_pins::MAX_PROFILE_PINS; |
| 7 | -use forge_core::{Repo, Session, User}; | 7 | +use forge_core::{Repo, Session, Store, User}; |
| 8 | use topcoat::Result; | 8 | use topcoat::Result; |
| 9 | use topcoat::context::{Cx, app_context}; | 9 | use topcoat::context::{Cx, app_context}; |
| 10 | use topcoat::router::content::RawForm; | 10 | use topcoat::router::content::RawForm; |
| 11 | use topcoat::router::error::see_other; | 11 | use topcoat::router::error::see_other; |
| 12 | -use topcoat::router::{page, path_param}; | 12 | +use topcoat::router::response::Response; |
| 13 | +use topcoat::router::{page, path_param, route}; | ||
| 13 | use topcoat::view::{View, component, view}; | 14 | use topcoat::view::{View, component, view}; |
| 14 | 15 | ||
| 15 | use crate::auth::{require_csrf, require_user}; | 16 | use crate::auth::{require_csrf, require_user}; |
| 16 | use crate::i18n::orgs::{self as g, K}; | 17 | use crate::i18n::orgs::{self as g, K}; |
| 17 | use crate::i18n::{self, Lang}; | 18 | use crate::i18n::{self, Lang}; |
| 19 | +use crate::live::{Topic, stream_changes}; | ||
| 18 | use crate::pages::issue_meta::{form_all, form_field, form_pairs}; | 20 | use crate::pages::issue_meta::{form_all, form_field, form_pairs}; |
| 19 | use crate::pages::org_ctx::{load_org, require_form_csrf, require_owner}; | 21 | use crate::pages::org_ctx::{load_org, require_form_csrf, require_owner}; |
| 20 | use crate::state::AppState; | 22 | use crate::state::AppState; |
| @@ -69,9 +71,11 @@ async fn pins_form( | |||
| 69 | let csrf = viewer.1.csrf_token.clone(); | 71 | let csrf = viewer.1.csrf_token.clone(); |
| 70 | let title = g::t(lang, K::CustomizePins); | 72 | let title = g::t(lang, K::CustomizePins); |
| 71 | let error = error.map(str::to_owned); | 73 | let error = error.map(str::to_owned); |
| 74 | + // The form follows the owner's topic: a pin or a repo of the owner changed elsewhere re-renders it. | ||
| 75 | + let live = format!("{action}/events"); | ||
| 72 | Ok(view! { cx => | 76 | Ok(view! { cx => |
| 73 | shell(title: title, viewer: Some(&viewer), | 77 | shell(title: title, viewer: Some(&viewer), |
| 74 | - pins_body(lang: lang, action: action, csrf: csrf, options: options, error: error)) | 78 | + pins_body(lang: lang, action: action, live: live, csrf: csrf, options: options, error: error)) |
| 75 | }) | 79 | }) |
| 76 | } | 80 | } |
| 77 | 81 | ||
| @@ -79,6 +83,7 @@ async fn pins_form( | |||
| 79 | async fn pins_body( | 83 | async fn pins_body( |
| 80 | lang: Lang, | 84 | lang: Lang, |
| 81 | action: String, | 85 | action: String, |
| 86 | + live: String, | ||
| 82 | csrf: String, | 87 | csrf: String, |
| 83 | options: Vec<PinOption>, | 88 | options: Vec<PinOption>, |
| 84 | error: Option<String>, | 89 | error: Option<String>, |
| @@ -88,7 +93,7 @@ async fn pins_body( | |||
| 88 | let empty = g::t(lang, K::NoPinnableRepos); | 93 | let empty = g::t(lang, K::NoPinnableRepos); |
| 89 | let save = g::t(lang, K::SavePins); | 94 | let save = g::t(lang, K::SavePins); |
| 90 | Ok(view! { | 95 | Ok(view! { |
| 91 | - <section class="profile-pins-edit"> | 96 | + <section class="profile-pins-edit" data-live=(live.as_str())> |
| 92 | <h1>(g::t(lang, K::CustomizePins))</h1> | 97 | <h1>(g::t(lang, K::CustomizePins))</h1> |
| 93 | <p class="muted">(intro)</p> | 98 | <p class="muted">(intro)</p> |
| 94 | if let Some(message) = error { | 99 | if let Some(message) = error { |
| @@ -139,6 +144,33 @@ async fn save_pins( | |||
| 139 | Err(see_other(back).into()) | 144 | Err(see_other(back).into()) |
| 140 | } | 145 | } |
| 141 | 146 | ||
| 147 | +/// What the pin form shows: the owner's pinned repos in order, then each repo the owner may pin. | ||
| 148 | +async fn pins_fingerprint(store: &Store, owner_id: &str) -> Result<String> { | ||
| 149 | + let mut lines = Vec::new(); | ||
| 150 | + for repo in store.profile_pins(owner_id).await? { | ||
| 151 | + lines.push(format!("pin {}", repo.id)); | ||
| 152 | + } | ||
| 153 | + for repo in store.list_repos_by_owner(owner_id).await? { | ||
| 154 | + lines.push(format!("repo {} {}/{}", repo.id, repo.owner_name, repo.name)); | ||
| 155 | + } | ||
| 156 | + Ok(lines.join("\n")) | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +/// The pin form's change stream for the signed-in user. Its own page only, as the form. | ||
| 160 | +#[route(GET "/settings/pins/events")] | ||
| 161 | +async fn pins_events(cx: &Cx) -> Result<Response> { | ||
| 162 | + let viewer = require_user(cx).await?; | ||
| 163 | + let state = app_context::<AppState>(cx); | ||
| 164 | + let owner_id = viewer.0.id.clone(); | ||
| 165 | + let store = state.store.clone(); | ||
| 166 | + stream_changes(cx, &state.live, &[Topic::User(owner_id.clone())], move || { | ||
| 167 | + let store = store.clone(); | ||
| 168 | + let owner_id = owner_id.clone(); | ||
| 169 | + async move { pins_fingerprint(&store, &owner_id).await } | ||
| 170 | + }) | ||
| 171 | + .await | ||
| 172 | +} | ||
| 173 | + | ||
| 142 | /// Gets the pin form for the signed-in user's own profile. | 174 | /// Gets the pin form for the signed-in user's own profile. |
| 143 | #[page("/settings/pins")] | 175 | #[page("/settings/pins")] |
| 144 | async fn pins_page(cx: &Cx) -> Result<impl View> { | 176 | async fn pins_page(cx: &Cx) -> Result<impl View> { |
| @@ -160,6 +192,22 @@ async fn pins_save(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> { | |||
| 160 | save_pins(cx, viewer, owner, "/settings/pins".to_owned(), chosen, back).await | 192 | save_pins(cx, viewer, owner, "/settings/pins".to_owned(), chosen, back).await |
| 161 | } | 193 | } |
| 162 | 194 | ||
| 195 | +/// The pin form's change stream for an organization. Owners only, as the form. | ||
| 196 | +#[route(GET "/org/{org}/settings/pins/events")] | ||
| 197 | +async fn org_pins_events(cx: &Cx) -> Result<Response> { | ||
| 198 | + let ctx = load_org(cx, path_param::<Org>(cx)).await?; | ||
| 199 | + require_owner(&ctx)?; | ||
| 200 | + let state = app_context::<AppState>(cx); | ||
| 201 | + let owner_id = ctx.org.id.clone(); | ||
| 202 | + let store = state.store.clone(); | ||
| 203 | + stream_changes(cx, &state.live, &[Topic::User(owner_id.clone())], move || { | ||
| 204 | + let store = store.clone(); | ||
| 205 | + let owner_id = owner_id.clone(); | ||
| 206 | + async move { pins_fingerprint(&store, &owner_id).await } | ||
| 207 | + }) | ||
| 208 | + .await | ||
| 209 | +} | ||
| 210 | + | ||
| 163 | /// Gets the pin form for an organization. Owners only. | 211 | /// Gets the pin form for an organization. Owners only. |
| 164 | #[page("/org/{org}/settings/pins")] | 212 | #[page("/org/{org}/settings/pins")] |
| 165 | async fn org_pins_page(cx: &Cx) -> Result<impl View> { | 213 | async fn org_pins_page(cx: &Cx) -> Result<impl View> { |
crates/forge-web/src/pages/pull_live.rsmodified+48 -1
| @@ -15,6 +15,7 @@ | |||
| 15 | //! [`list_fingerprint`]). A bump that changes none of it sends nothing, so over-bumping is cheap. | 15 | //! [`list_fingerprint`]). A bump that changes none of it sends nothing, so over-bumping is cheap. |
| 16 | 16 | ||
| 17 | use forge_core::PullRequest; | 17 | use forge_core::PullRequest; |
| 18 | +use forge_core::reactions::ReactionTarget; | ||
| 18 | use forge_core::store::Store; | 19 | use forge_core::store::Store; |
| 19 | use topcoat::Result; | 20 | use topcoat::Result; |
| 20 | use topcoat::context::{Cx, app_context}; | 21 | use topcoat::context::{Cx, app_context}; |
| @@ -92,6 +93,28 @@ pub(crate) async fn pull_fingerprint( | |||
| 92 | let reviews = store.list_reviews(id).await?; | 93 | let reviews = store.list_reviews(id).await?; |
| 93 | let threads = store.review_threads(id, viewer).await?; | 94 | let threads = store.review_threads(id, viewer).await?; |
| 94 | let statuses = store.statuses_for(repo_id, &pr.head_oid).await?; | 95 | let statuses = store.statuses_for(repo_id, &pr.head_oid).await?; |
| 96 | + // The reactions of the body, then of each comment in the comments' order. A map's own order is | ||
| 97 | + // not stable, so each target is looked up by its id. | ||
| 98 | + let comment_ids: Vec<String> = comments.iter().map(|c| c.id.clone()).collect(); | ||
| 99 | + let body_reactions = store | ||
| 100 | + .reactions_for(ReactionTarget::Issue, &[id.to_owned()], viewer) | ||
| 101 | + .await?; | ||
| 102 | + let comment_reactions = store | ||
| 103 | + .reactions_for(ReactionTarget::Comment, &comment_ids, viewer) | ||
| 104 | + .await?; | ||
| 105 | + let mut reaction_digest = vec![format!("{:?}", body_reactions.get(id))]; | ||
| 106 | + reaction_digest.extend( | ||
| 107 | + comment_ids | ||
| 108 | + .iter() | ||
| 109 | + .map(|cid| format!("{:?}", comment_reactions.get(cid))), | ||
| 110 | + ); | ||
| 111 | + let events = store.list_events(id).await?; | ||
| 112 | + // The merge gate reads the repo's protection rules, so a rule change changes the page. | ||
| 113 | + let rules = store.list_branch_rules(repo_id).await?; | ||
| 114 | + let subscription = match viewer { | ||
| 115 | + Some(viewer) => store.subscription(viewer, id).await?, | ||
| 116 | + None => None, | ||
| 117 | + }; | ||
| 95 | 118 | ||
| 96 | let mut lines = vec![ | 119 | let mut lines = vec![ |
| 97 | format!( | 120 | format!( |
| @@ -103,6 +126,18 @@ pub(crate) async fn pull_fingerprint( | |||
| 103 | pr.issue.comment_count | 126 | pr.issue.comment_count |
| 104 | ), | 127 | ), |
| 105 | format!("body {}", pr.issue.body), | 128 | format!("body {}", pr.issue.body), |
| 129 | + format!( | ||
| 130 | + "milestone {:?} locked {} {:?}", | ||
| 131 | + pr.issue.milestone_id, pr.issue.locked, pr.issue.lock_reason | ||
| 132 | + ), | ||
| 133 | + format!("reactions {}", reaction_digest.join(" ")), | ||
| 134 | + format!( | ||
| 135 | + "events {} last {:?}", | ||
| 136 | + events.len(), | ||
| 137 | + events.last().map(|e| e.id.as_str()) | ||
| 138 | + ), | ||
| 139 | + format!("subscription {subscription:?}"), | ||
| 140 | + format!("rules {rules:?}"), | ||
| 106 | format!( | 141 | format!( |
| 107 | "draft {} head {} base {} {:?} {:?} {:?} {:?}", | 142 | "draft {} head {} base {} {:?} {:?} {:?} {:?}", |
| 108 | pr.draft, | 143 | pr.draft, |
| @@ -159,6 +194,11 @@ async fn pull_read( | |||
| 159 | 194 | ||
| 160 | // Streams | 195 | // Streams |
| 161 | 196 | ||
| 197 | +/// The stream URL of one pull request, for its page and its edit history. | ||
| 198 | +pub fn pull_live_url(owner: &str, repo: &str, number: i64) -> String { | ||
| 199 | + format!("/{owner}/{repo}/pulls/{number}/events") | ||
| 200 | +} | ||
| 201 | + | ||
| 162 | /// The pull list's change stream. Auth is the repo read check of the list page. | 202 | /// The pull list's change stream. Auth is the repo read check of the list page. |
| 163 | #[route(GET "/{owner}/{repo}/pulls/events")] | 203 | #[route(GET "/{owner}/{repo}/pulls/events")] |
| 164 | async fn pulls_events(cx: &Cx) -> Result<Response> { | 204 | async fn pulls_events(cx: &Cx) -> Result<Response> { |
| @@ -265,7 +305,14 @@ async fn bump_written(state: &AppState, target: Written) { | |||
| 265 | }; | 305 | }; |
| 266 | match target { | 306 | match target { |
| 267 | Written::Pull { number, .. } => match state.store.pull_by_number(&repo.id, number).await { | 307 | Written::Pull { number, .. } => match state.store.pull_by_number(&repo.id, number).await { |
| 268 | - Ok(Some(pr)) => bump_pull(state, &repo.id, &pr.issue.id), | 308 | + Ok(Some(pr)) => { |
| 309 | + bump_pull(state, &repo.id, &pr.issue.id); | ||
| 310 | + // A closed or merged pull leaves its reviewers' request lists. | ||
| 311 | + if pr.issue.state != forge_core::IssueState::Open || pr.merged_at.is_some() { | ||
| 312 | + crate::pages::review_requests::bump_pending_reviewers(state, &pr.issue.id) | ||
| 313 | + .await; | ||
| 314 | + } | ||
| 315 | + } | ||
| 269 | Ok(None) => {} | 316 | Ok(None) => {} |
| 270 | Err(e) => tracing::error!(error = %e, number, "live: loading the pull to bump failed"), | 317 | Err(e) => tracing::error!(error = %e, number, "live: loading the pull to bump failed"), |
| 271 | }, | 318 | }, |
crates/forge-web/src/pages/pull_reviews.rsmodified+2 -0
| @@ -735,6 +735,8 @@ async fn review_submit(cx: &Cx, Form(form): Form<ReviewForm>) -> Result<SeeOther | |||
| 735 | ) | 735 | ) |
| 736 | .await; | 736 | .await; |
| 737 | crate::automerge::on_pull(state, &ctx.repo, number).await; | 737 | crate::automerge::on_pull(state, &ctx.repo, number).await; |
| 738 | + // The submitted review clears the viewer's own request, so their list changes. | ||
| 739 | + crate::pages::review_requests::bump_review_requests(state, &user.id); | ||
| 738 | Ok(see_other(format!("{tab}#review-{}", review.id))) | 740 | Ok(see_other(format!("{tab}#review-{}", review.id))) |
| 739 | } | 741 | } |
| 740 | Err(forge_core::Error::Forbidden(_)) => Ok(refusal(&tab, ERR_OWN_PR, "")), | 742 | Err(forge_core::Error::Forbidden(_)) => Ok(refusal(&tab, ERR_OWN_PR, "")), |
crates/forge-web/src/pages/repo.rsmodified+2 -2
| @@ -20,7 +20,7 @@ use topcoat::view::{View, component, view}; | |||
| 20 | 20 | ||
| 21 | use crate::i18n::code::{self as g, K}; | 21 | use crate::i18n::code::{self as g, K}; |
| 22 | use crate::i18n::{self, Lang}; | 22 | use crate::i18n::{self, Lang}; |
| 23 | -use crate::pages::code_live::{branch_live_url, follows_branch}; | 23 | +use crate::pages::code_live::{follows_branch, home_live_url}; |
| 24 | use crate::pages::dashboard::badge_class; | 24 | use crate::pages::dashboard::badge_class; |
| 25 | use crate::pages::finder::file_finder; | 25 | use crate::pages::finder::file_finder; |
| 26 | use crate::pages::issue_parts::stamp_unix; | 26 | use crate::pages::issue_parts::stamp_unix; |
| @@ -468,7 +468,7 @@ async fn repo_page(cx: &Cx) -> Result<impl View> { | |||
| 468 | } | 468 | } |
| 469 | let follows = follows_branch(&refs, &branch); | 469 | let follows = follows_branch(&refs, &branch); |
| 470 | // The home page follows the default branch even before its first push, so that push goes live. | 470 | // The home page follows the default branch even before its first push, so that push goes live. |
| 471 | - let live = branch_live_url(&repo.owner_name, &repo.name, &branch); | 471 | + let live = home_live_url(&repo.owner_name, &repo.name, &branch); |
| 472 | let owner_name = repo.owner_name.clone(); | 472 | let owner_name = repo.owner_name.clone(); |
| 473 | let repo_name = repo.name.clone(); | 473 | let repo_name = repo.name.clone(); |
| 474 | let branches_href = repo_href(&owner_name, &repo_name, "branches", ""); | 474 | let branches_href = repo_href(&owner_name, &repo_name, "branches", ""); |
crates/forge-web/src/pages/repo_settings.rsmodified+10 -4
| @@ -34,6 +34,7 @@ use crate::i18n::merge_queue as mq; | |||
| 34 | use crate::i18n::repo_admin::{self as g, K}; | 34 | use crate::i18n::repo_admin::{self as g, K}; |
| 35 | use crate::i18n::{self, Lang}; | 35 | use crate::i18n::{self, Lang}; |
| 36 | use crate::pages::discussion_settings::discussions_card; | 36 | use crate::pages::discussion_settings::discussions_card; |
| 37 | +use crate::pages::passkeys; | ||
| 37 | use crate::pages::refs::load_refs; | 38 | use crate::pages::refs::load_refs; |
| 38 | use crate::pages::repo::repo_head; | 39 | use crate::pages::repo::repo_head; |
| 39 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; | 40 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; |
| @@ -645,13 +646,17 @@ async fn branch_rule_form( | |||
| 645 | <fieldset class="rule-section"> | 646 | <fieldset class="rule-section"> |
| 646 | <legend>(g::t(lang, K::SectionMerging))</legend> | 647 | <legend>(g::t(lang, K::SectionMerging))</legend> |
| 647 | <div class="switch-list"> | 648 | <div class="switch-list"> |
| 648 | - <label class="switch-row"> | 649 | + <div class="switch-row stepper-row"> |
| 649 | <span class="switch-text"> | 650 | <span class="switch-text"> |
| 650 | - <span class="switch-title">(g::t(lang, K::RequiredApprovals))</span> | 651 | + <span class="switch-title" id="required-approvals-label">(g::t(lang, K::RequiredApprovals))</span> |
| 651 | <span class="switch-desc">(g::t(lang, K::ApprovalsHelp))</span> | 652 | <span class="switch-desc">(g::t(lang, K::ApprovalsHelp))</span> |
| 652 | </span> | 653 | </span> |
| 653 | - <input type="number" name="required_approvals" min="0" max="20" step="1" inputmode="numeric" value=(required_approvals.as_str())> | 654 | + <div class="runner-pill"> |
| 654 | - </label> | 655 | + <button type="button" class="runner-step" data-step="-1" aria-label=(passkeys::s(lang, "Fewer", "Azalt"))>"−"</button> |
| 656 | + <input type="number" name="required_approvals" min="0" max="20" step="1" inputmode="numeric" value=(required_approvals.as_str()) aria-labelledby="required-approvals-label"> | ||
| 657 | + <button type="button" class="runner-step" data-step="1" aria-label=(passkeys::s(lang, "More", "Artır"))>"+"</button> | ||
| 658 | + </div> | ||
| 659 | + </div> | ||
| 655 | switch_row(name: "block_on_changes_requested".to_owned(), checked: block_on_changes_requested, | 660 | switch_row(name: "block_on_changes_requested".to_owned(), checked: block_on_changes_requested, |
| 656 | title: g::t(lang, K::BlockWhileChanges).to_owned(), description: None) | 661 | title: g::t(lang, K::BlockWhileChanges).to_owned(), description: None) |
| 657 | switch_row(name: "require_up_to_date".to_owned(), checked: require_up_to_date, | 662 | switch_row(name: "require_up_to_date".to_owned(), checked: require_up_to_date, |
| @@ -1035,6 +1040,7 @@ async fn settings_archive_save(cx: &Cx, Form(form): Form<ArchiveForm>) -> Result | |||
| 1035 | .store | 1040 | .store |
| 1036 | .set_repo_archived(&ctx.repo.id, archived) | 1041 | .set_repo_archived(&ctx.repo.id, archived) |
| 1037 | .await?; | 1042 | .await?; |
| 1043 | + state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id); | ||
| 1038 | let action = if archived { | 1044 | let action = if archived { |
| 1039 | AuditAction::RepoArchived | 1045 | AuditAction::RepoArchived |
| 1040 | } else { | 1046 | } else { |
crates/forge-web/src/pages/repo_settings_live.rsmodified+8 -1
| @@ -143,7 +143,14 @@ async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> Result<Respons | |||
| 143 | }; | 143 | }; |
| 144 | let result = next.run(cx, body).await; | 144 | let result = next.run(cx, body).await; |
| 145 | if let Some(repo_id) = repo_id { | 145 | if let Some(repo_id) = repo_id { |
| 146 | - bump_settings(&app_context::<AppState>(cx).live, &repo_id); | 146 | + let state = app_context::<AppState>(cx); |
| 147 | + bump_settings(&state.live, &repo_id); | ||
| 148 | + // The repo header shows settings too (the mirror line, the archived notice, the tabs); its | ||
| 149 | + // stream sends nothing when its fingerprint holds. | ||
| 150 | + state.live.bump(&crate::live::Topic::Repo(repo_id.clone())); | ||
| 151 | + // The merge gate of a pull page reads the branch protection rules, so every pull of the | ||
| 152 | + // repo may show a different gate. A pull's stream sends nothing when its fingerprint holds. | ||
| 153 | + crate::pages::pull_live::bump_repo_pulls(state, &repo_id).await; | ||
| 147 | } | 154 | } |
| 148 | result | 155 | result |
| 149 | } | 156 | } |
crates/forge-web/src/pages/review_requests.rsmodified+45 -3
| @@ -11,12 +11,14 @@ use topcoat::context::{Cx, app_context}; | |||
| 11 | use topcoat::router::content::Form; | 11 | use topcoat::router::content::Form; |
| 12 | use topcoat::router::error::{SeeOther, forbidden, not_found, see_other}; | 12 | use topcoat::router::error::{SeeOther, forbidden, not_found, see_other}; |
| 13 | use topcoat::router::request::uri; | 13 | use topcoat::router::request::uri; |
| 14 | -use topcoat::router::{page, path_param, route}; | 14 | +use topcoat::router::response::Response; |
| 15 | +use topcoat::router::{Body, StatusCode, page, path_param, route}; | ||
| 15 | use topcoat::view::{View, component, view}; | 16 | use topcoat::view::{View, component, view}; |
| 16 | 17 | ||
| 17 | -use crate::auth::require_user; | 18 | +use crate::auth::{current_user, require_user}; |
| 18 | use crate::i18n::authoring::{self as ga, K as AK}; | 19 | use crate::i18n::authoring::{self as ga, K as AK}; |
| 19 | use crate::i18n::{self, Lang}; | 20 | use crate::i18n::{self, Lang}; |
| 21 | +use crate::live::{Topic, stream_wakes}; | ||
| 20 | use crate::notify; | 22 | use crate::notify; |
| 21 | use crate::pages::issue_parts::{ItemKind, check_write, may_change, parse_number}; | 23 | use crate::pages::issue_parts::{ItemKind, check_write, may_change, parse_number}; |
| 22 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; | 24 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; |
| @@ -38,6 +40,44 @@ struct ReviewerForm { | |||
| 38 | username: String, | 40 | username: String, |
| 39 | } | 41 | } |
| 40 | 42 | ||
| 43 | +/// Wakes the review-request list of `user_id`: a request was added or withdrawn, or the user | ||
| 44 | +/// submitted a review (which clears their own request). | ||
| 45 | +pub fn bump_review_requests(state: &AppState, user_id: &str) { | ||
| 46 | + state.live.bump(&Topic::ReviewRequests(user_id.to_owned())); | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// Wakes the review-request lists of everyone with a pending request on the pull request. Call it | ||
| 50 | +/// after the pull closed or merged, which drops it from those lists. | ||
| 51 | +pub async fn bump_pending_reviewers(state: &AppState, issue_id: &str) { | ||
| 52 | + let names = match state.store.requested_reviewers(issue_id).await { | ||
| 53 | + Ok(names) => names, | ||
| 54 | + Err(e) => { | ||
| 55 | + tracing::error!(error = %e, issue_id, "live: listing reviewers to bump failed"); | ||
| 56 | + return; | ||
| 57 | + } | ||
| 58 | + }; | ||
| 59 | + for name in names { | ||
| 60 | + match state.store.user_by_username(&name).await { | ||
| 61 | + Ok(Some(user)) => bump_review_requests(state, &user.id), | ||
| 62 | + Ok(None) => {} | ||
| 63 | + Err(e) => tracing::error!(error = %e, name, "live: loading a reviewer to bump failed"), | ||
| 64 | + } | ||
| 65 | + } | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/// The review-request list's stream. The viewer comes from the session only, so a user follows only | ||
| 69 | +/// their own list. Without a session: 401. | ||
| 70 | +#[route(GET "/review-requests/events")] | ||
| 71 | +async fn review_requests_events(cx: &Cx) -> Result<Response> { | ||
| 72 | + let Some((user, _)) = current_user(cx).await? else { | ||
| 73 | + let mut res = Response::new(Body::empty()); | ||
| 74 | + *res.status_mut() = StatusCode::UNAUTHORIZED; | ||
| 75 | + return Ok(res); | ||
| 76 | + }; | ||
| 77 | + let state = app_context::<AppState>(cx); | ||
| 78 | + stream_wakes(cx, &state.live, &[Topic::ReviewRequests(user.id)]) | ||
| 79 | +} | ||
| 80 | + | ||
| 41 | /// Why a request was refused, as the `reviewer_error` query word the pull page shows. | 81 | /// Why a request was refused, as the `reviewer_error` query word the pull page shows. |
| 42 | fn refusal(code: &str, href: &str) -> SeeOther { | 82 | fn refusal(code: &str, href: &str) -> SeeOther { |
| 43 | see_other(format!("{href}?reviewer_error={code}#reviewers")) | 83 | see_other(format!("{href}?reviewer_error={code}#reviewers")) |
| @@ -72,6 +112,7 @@ async fn reviewers_save(cx: &Cx, Form(form): Form<ReviewerForm>) -> Result<SeeOt | |||
| 72 | .store | 112 | .store |
| 73 | .withdraw_review_request(&pull.id, &target.id) | 113 | .withdraw_review_request(&pull.id, &target.id) |
| 74 | .await?; | 114 | .await?; |
| 115 | + bump_review_requests(state, &target.id); | ||
| 75 | return Ok(see_other(format!("{href}#reviewers"))); | 116 | return Ok(see_other(format!("{href}#reviewers"))); |
| 76 | } | 117 | } |
| 77 | if pull.state != forge_core::IssueState::Open { | 118 | if pull.state != forge_core::IssueState::Open { |
| @@ -97,6 +138,7 @@ async fn reviewers_save(cx: &Cx, Form(form): Form<ReviewerForm>) -> Result<SeeOt | |||
| 97 | .request_review(&pull.id, &target.id, &user.id) | 138 | .request_review(&pull.id, &target.id, &user.id) |
| 98 | .await? | 139 | .await? |
| 99 | { | 140 | { |
| 141 | + bump_review_requests(state, &target.id); | ||
| 100 | notify::dispatch_review_requested(state, &ctx.repo, &pull, &user.id, &target.id).await; | 142 | notify::dispatch_review_requested(state, &ctx.repo, &pull, &user.id, &target.id).await; |
| 101 | } else { | 143 | } else { |
| 102 | return Ok(refusal("already", &href)); | 144 | return Ok(refusal("already", &href)); |
| @@ -243,7 +285,7 @@ async fn review_requests(cx: &Cx) -> Result<impl View> { | |||
| 243 | let empty = rows.is_empty(); | 285 | let empty = rows.is_empty(); |
| 244 | Ok(view! { | 286 | Ok(view! { |
| 245 | shell(title: heading, viewer: Some(&viewer), | 287 | shell(title: heading, viewer: Some(&viewer), |
| 246 | - <section class="page-head"> | 288 | + <section class="page-head" data-live="/review-requests/events"> |
| 247 | <h1>(heading)</h1> | 289 | <h1>(heading)</h1> |
| 248 | </section> | 290 | </section> |
| 249 | if empty { | 291 | if empty { |
crates/forge-web/src/pages/settings_live.rsmodified+248 -41
| @@ -15,15 +15,19 @@ | |||
| 15 | //! A session revoked elsewhere is caught the same way. The re-read finds no session, so the page | 15 | //! A session revoked elsewhere is caught the same way. The re-read finds no session, so the page |
| 16 | //! leaves for the login page. | 16 | //! leaves for the login page. |
| 17 | //! | 17 | //! |
| 18 | -//! Every page also holds `/-/alive` (see [`alive_response`]). For a signed-in viewer that stream | 18 | +//! Every page also holds `/-/alive` (see [`alive_response`]). That stream follows |
| 19 | -//! sends a `theme` event with the appearance attributes when they change, so a tab applies a theme, | 19 | +//! [`Topic::ServerSettings`] for every viewer, anonymous included: a `settings` event when a live |
| 20 | -//! accent or sidebar change made elsewhere without a reload. | 20 | +//! server setting changes, so the open page re-renders. For a signed-in viewer it also sends a |
| 21 | +//! `theme` event with the appearance attributes when they change, so a tab applies a theme, accent | ||
| 22 | +//! or sidebar change made elsewhere without a reload. | ||
| 21 | 23 | ||
| 22 | use std::collections::VecDeque; | 24 | use std::collections::VecDeque; |
| 23 | 25 | ||
| 26 | +use forge_core::server_settings::{self, FIELDS, Kind}; | ||
| 24 | use futures_util::stream; | 27 | use futures_util::stream; |
| 28 | +use tokio::sync::watch; | ||
| 25 | use topcoat::Result; | 29 | use topcoat::Result; |
| 26 | -use topcoat::context::{Cx, app_context}; | 30 | +use topcoat::context::{Cx, app_context, try_app_context}; |
| 27 | use topcoat::router::content::sse::Event; | 31 | use topcoat::router::content::sse::Event; |
| 28 | use topcoat::router::request::{method, uri}; | 32 | use topcoat::router::request::{method, uri}; |
| 29 | use topcoat::router::response::Response; | 33 | use topcoat::router::response::Response; |
| @@ -57,11 +61,17 @@ async fn settings_events(cx: &Cx) -> Result<Response> { | |||
| 57 | /// a tab that applies it shows what a fresh load of the page would show. The last pair, `custom_css`, | 61 | /// a tab that applies it shows what a fresh load of the page would show. The last pair, `custom_css`, |
| 58 | /// is the stylesheet of the hue choices (empty for presets only); `nav.js` applies only `data-*` | 62 | /// is the stylesheet of the hue choices (empty for presets only); `nav.js` applies only `data-*` |
| 59 | /// pairs, so it reads this one itself. | 63 | /// pairs, so it reads this one itself. |
| 60 | -/// The account state the alive stream compares: the appearance (see below) and the language | 64 | +/// The account state the alive stream compares: the appearance (see below), the language |
| 61 | -/// preference, which changes the page text rather than its attributes. | 65 | +/// preference, which changes the page text rather than its attributes, and the identity the |
| 62 | -pub async fn account_state(state: &AppState, user_id: &str) -> Result<(String, String)> { | 66 | +/// header shows (the username, the avatar's hash, admin rights) with whether the viewer's session |
| 67 | +/// still exists. A session revoked elsewhere makes that last part change. | ||
| 68 | +pub async fn account_state( | ||
| 69 | + state: &AppState, | ||
| 70 | + user_id: &str, | ||
| 71 | + session_id: &str, | ||
| 72 | +) -> Result<AccountState> { | ||
| 63 | let Some(user) = state.store.user_by_id(user_id).await? else { | 73 | let Some(user) = state.store.user_by_id(user_id).await? else { |
| 64 | - return Ok((String::new(), String::new())); | 74 | + return Ok((String::new(), String::new(), String::new())); |
| 65 | }; | 75 | }; |
| 66 | let theme = match crate::theme::resolve_preference(&user.theme) { | 76 | let theme = match crate::theme::resolve_preference(&user.theme) { |
| 67 | "auto" => "", | 77 | "auto" => "", |
| @@ -83,55 +93,177 @@ pub async fn account_state(state: &AppState, user_id: &str) -> Result<(String, S | |||
| 83 | let appearance = format!( | 93 | let appearance = format!( |
| 84 | "data-theme={theme};data-accent-light={accent_light};data-accent-dark={accent_dark};data-base-light={base_light};data-base-dark={base_dark};data-sidebar={sidebar};custom_css={custom_css}", | 94 | "data-theme={theme};data-accent-light={accent_light};data-accent-dark={accent_dark};data-base-light={base_light};data-base-dark={base_dark};data-sidebar={sidebar};custom_css={custom_css}", |
| 85 | ); | 95 | ); |
| 86 | - Ok((appearance, user.language.clone())) | 96 | + let avatar = state.store.avatar_hash(user_id).await?.unwrap_or_default(); |
| 97 | + let session_open = state | ||
| 98 | + .store | ||
| 99 | + .list_sessions(user_id) | ||
| 100 | + .await? | ||
| 101 | + .iter() | ||
| 102 | + .any(|session| session.id == session_id); | ||
| 103 | + let identity = format!( | ||
| 104 | + "{}\n{avatar}\n{}\n{session_open}", | ||
| 105 | + user.username, user.is_admin | ||
| 106 | + ); | ||
| 107 | + Ok((appearance, user.language.clone(), identity)) | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// The account state the alive stream compares: appearance, language, identity (see | ||
| 111 | +/// [`account_state`]). | ||
| 112 | +pub type AccountState = (String, String, String); | ||
| 113 | + | ||
| 114 | +/// The viewer's account as the alive stream follows it: the user and session ids, the wake of its | ||
| 115 | +/// topic, and the account state last sent. | ||
| 116 | +struct AccountFollow { | ||
| 117 | + user_id: String, | ||
| 118 | + session_id: String, | ||
| 119 | + wake: watch::Receiver<u64>, | ||
| 120 | + last: AccountState, | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// What the alive stream holds between events. | ||
| 124 | +struct Alive { | ||
| 125 | + state: AppState, | ||
| 126 | + /// Present for a signed-in viewer only. | ||
| 127 | + account: Option<AccountFollow>, | ||
| 128 | + server_wake: watch::Receiver<u64>, | ||
| 129 | + /// The server settings fingerprint last sent or seen (see [`settings_fingerprint`]). | ||
| 130 | + settings_last: String, | ||
| 131 | + queue: VecDeque<Event>, | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// What woke the alive stream. | ||
| 135 | +enum Wake { | ||
| 136 | + Account, | ||
| 137 | + Settings, | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +/// The server settings the pages render, as one fingerprint: the values of every `Kind::Live` | ||
| 141 | +/// setting, in field order. A `settings` event goes out when it differs from the last one sent. | ||
| 142 | +pub fn settings_fingerprint(state: &AppState) -> String { | ||
| 143 | + let live = state.live(); | ||
| 144 | + FIELDS | ||
| 145 | + .iter() | ||
| 146 | + .filter(|f| f.kind == Kind::Live) | ||
| 147 | + .map(|f| server_settings::get(&live, f.key)) | ||
| 148 | + .collect::<Vec<_>>() | ||
| 149 | + .join("\n") | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +/// Waits for the viewer's account topic. A stream with no signed-in viewer waits on nothing. | ||
| 153 | +async fn wait_account(account: &mut Option<AccountFollow>) -> bool { | ||
| 154 | + match account { | ||
| 155 | + Some(follow) => follow.wake.changed().await.is_ok(), | ||
| 156 | + None => std::future::pending().await, | ||
| 157 | + } | ||
| 87 | } | 158 | } |
| 88 | 159 | ||
| 89 | -/// The response of `GET /-/alive`, the stream every page holds. Anonymous: it only stays open, as | 160 | +/// The response of `GET /-/alive`, the stream every page holds. Every viewer follows the server |
| 90 | -/// before. A signed-in viewer also follows their account topic, and each time the appearance differs | 161 | +/// settings topic: a change to a live setting sends a `settings` event, and the page re-renders |
| 91 | -/// from the last one sent it gets a `theme` event carrying the new attributes (see `nav.js`). The | 162 | +/// (see `nav.js`). A signed-in viewer also follows their account topic: each time the appearance |
| 92 | -/// stream still opens with `retry`, and its open still means the server is back. | 163 | +/// differs from the last one sent it gets a `theme` event carrying the new attributes, a language |
| 164 | +/// change a `language` event, and a change of the header's identity (username, avatar, admin) or a | ||
| 165 | +/// revoked session an `account` event. The stream still opens with `retry`, and its open still | ||
| 166 | +/// means the server is back. | ||
| 93 | pub async fn alive_response(cx: &Cx) -> Result<Response> { | 167 | pub async fn alive_response(cx: &Cx) -> Result<Response> { |
| 94 | - let Some((user, _)) = current_user(cx).await? else { | 168 | + // A router with no app state (the asset tests) has nothing to follow: the stream only stays open. |
| 169 | + let Some(state) = try_app_context::<AppState>(cx).cloned() else { | ||
| 95 | return events_response(cx, stream::pending::<Result<Event>>()); | 170 | return events_response(cx, stream::pending::<Result<Event>>()); |
| 96 | }; | 171 | }; |
| 97 | - let state = app_context::<AppState>(cx).clone(); | 172 | + let viewer = current_user(cx) |
| 98 | - let user_id = user.id; | 173 | + .await? |
| 99 | - // Subscribed before the baseline is read, so a change in between is not lost. | 174 | + .map(|(user, session)| (user.id, session.id)); |
| 100 | - let wake = state.live.subscribe(&Topic::Account(user_id.clone())); | 175 | + // Subscribed before each baseline is read, so a change in between is not lost. |
| 101 | - let last = account_state(&state, &user_id).await?; | 176 | + let server_wake = state.live.subscribe(&Topic::ServerSettings); |
| 102 | - // One change can move both the appearance and the language: each gets its event, in that order. | 177 | + let settings_last = settings_fingerprint(&state); |
| 103 | - let events = stream::unfold( | 178 | + let account = match viewer { |
| 104 | - (wake, last, VecDeque::<Event>::new(), state, user_id), | 179 | + Some((user_id, session_id)) => { |
| 105 | - |(mut wake, mut last, mut queue, state, user_id)| async move { | 180 | + let wake = state.live.subscribe(&Topic::Account(user_id.clone())); |
| 106 | - loop { | 181 | + let last = account_state(&state, &user_id, &session_id).await?; |
| 107 | - if let Some(event) = queue.pop_front() { | 182 | + Some(AccountFollow { |
| 108 | - return Some((Ok(event), (wake, last, queue, state, user_id))); | 183 | + user_id, |
| 184 | + session_id, | ||
| 185 | + wake, | ||
| 186 | + last, | ||
| 187 | + }) | ||
| 188 | + } | ||
| 189 | + None => None, | ||
| 190 | + }; | ||
| 191 | + let alive = Alive { | ||
| 192 | + state, | ||
| 193 | + account, | ||
| 194 | + server_wake, | ||
| 195 | + settings_last, | ||
| 196 | + queue: VecDeque::new(), | ||
| 197 | + }; | ||
| 198 | + events_response(cx, stream::unfold(alive, next_alive_event)) | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +/// Waits for the next event of the alive stream. A wake that changes nothing the viewer sees sends | ||
| 202 | +/// nothing. None when a topic is gone, which ends the stream. | ||
| 203 | +async fn next_alive_event(mut alive: Alive) -> Option<(Result<Event>, Alive)> { | ||
| 204 | + loop { | ||
| 205 | + if let Some(event) = alive.queue.pop_front() { | ||
| 206 | + return Some((Ok(event), alive)); | ||
| 207 | + } | ||
| 208 | + let Alive { | ||
| 209 | + state, | ||
| 210 | + account, | ||
| 211 | + server_wake, | ||
| 212 | + settings_last, | ||
| 213 | + queue, | ||
| 214 | + } = &mut alive; | ||
| 215 | + let wake = tokio::select! { | ||
| 216 | + woke = wait_account(account) => { | ||
| 217 | + if !woke { | ||
| 218 | + return None; | ||
| 109 | } | 219 | } |
| 110 | - if wake.changed().await.is_err() { | 220 | + Wake::Account |
| 221 | + } | ||
| 222 | + woke = server_wake.changed() => { | ||
| 223 | + if woke.is_err() { | ||
| 111 | return None; | 224 | return None; |
| 112 | } | 225 | } |
| 113 | - let now = match account_state(&state, &user_id).await { | 226 | + Wake::Settings |
| 227 | + } | ||
| 228 | + }; | ||
| 229 | + match wake { | ||
| 230 | + Wake::Settings => { | ||
| 231 | + let now = settings_fingerprint(state); | ||
| 232 | + if now != *settings_last { | ||
| 233 | + queue.push_back(Event::new().event("settings").data("1")); | ||
| 234 | + *settings_last = now; | ||
| 235 | + } | ||
| 236 | + } | ||
| 237 | + Wake::Account => { | ||
| 238 | + let Some(follow) = account.as_mut() else { | ||
| 239 | + continue; | ||
| 240 | + }; | ||
| 241 | + let now = match account_state(state, &follow.user_id, &follow.session_id).await { | ||
| 114 | Ok(now) => now, | 242 | Ok(now) => now, |
| 115 | Err(e) => { | 243 | Err(e) => { |
| 116 | tracing::error!(error = %e, "live: could not read the account state"); | 244 | tracing::error!(error = %e, "live: could not read the account state"); |
| 117 | return None; | 245 | return None; |
| 118 | } | 246 | } |
| 119 | }; | 247 | }; |
| 120 | - if now == last { | 248 | + let last = &mut follow.last; |
| 121 | - continue; | 249 | + if now != *last { |
| 122 | - } | 250 | + // One change can move several parts: each gets its own event. |
| 123 | - if now.0 != last.0 { | 251 | + if now.0 != last.0 { |
| 124 | - queue.push_back(Event::new().event("theme").data(now.0.clone())); | 252 | + queue.push_back(Event::new().event("theme").data(now.0.clone())); |
| 125 | - } | 253 | + } |
| 126 | - if now.1 != last.1 { | 254 | + if now.1 != last.1 { |
| 127 | - // The page text is re-rendered by the client (a soft refresh, see `nav.js`). | 255 | + // The page text is re-rendered by the client (a soft refresh, see `nav.js`). |
| 128 | - queue.push_back(Event::new().event("language").data("1")); | 256 | + queue.push_back(Event::new().event("language").data("1")); |
| 257 | + } | ||
| 258 | + if now.2 != last.2 { | ||
| 259 | + // The header or the session changed: the page re-renders (see `nav.js`). | ||
| 260 | + queue.push_back(Event::new().event("account").data("1")); | ||
| 261 | + } | ||
| 262 | + *last = now; | ||
| 129 | } | 263 | } |
| 130 | - last = now; | ||
| 131 | } | 264 | } |
| 132 | - }, | 265 | + } |
| 133 | - ); | 266 | + } |
| 134 | - events_response(cx, events) | ||
| 135 | } | 267 | } |
| 136 | 268 | ||
| 137 | /// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router | 269 | /// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router |
| @@ -169,6 +301,8 @@ async fn bump_after_settings_write(cx: &Cx, body: Body, next: Next<'_>) -> Resul | |||
| 169 | 301 | ||
| 170 | #[cfg(test)] | 302 | #[cfg(test)] |
| 171 | mod tests { | 303 | mod tests { |
| 304 | + use std::collections::BTreeMap; | ||
| 305 | + | ||
| 172 | use futures_util::StreamExt; | 306 | use futures_util::StreamExt; |
| 173 | use topcoat::router::request::Request; | 307 | use topcoat::router::request::Request; |
| 174 | use topcoat::router::{Body, to_bytes}; | 308 | use topcoat::router::{Body, to_bytes}; |
| @@ -345,4 +479,77 @@ mod tests { | |||
| 345 | "alive stream: language event" | 479 | "alive stream: language event" |
| 346 | ); | 480 | ); |
| 347 | } | 481 | } |
| 482 | + | ||
| 483 | + /// An anonymous page holds `/-/alive` too. A live server setting that changes, then a bump of the | ||
| 484 | + /// server settings topic, sends one `settings` event. | ||
| 485 | + #[tokio::test] | ||
| 486 | + async fn the_alive_stream_sends_settings_to_anonymous_viewers() { | ||
| 487 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 488 | + let state = test_state(dir.path()).await; | ||
| 489 | + let live = state.live.clone(); | ||
| 490 | + let settings = state.settings.clone(); | ||
| 491 | + let router = app_router(state); | ||
| 492 | + | ||
| 493 | + let request = Request::builder() | ||
| 494 | + .method("GET") | ||
| 495 | + .uri("/-/alive") | ||
| 496 | + .body(Body::empty()) | ||
| 497 | + .expect("request"); | ||
| 498 | + let res = router.handle(request).await; | ||
| 499 | + let mut frames = res.into_body().into_data_stream(); | ||
| 500 | + let retry = frames.next().await.expect("a frame").expect("data"); | ||
| 501 | + assert!(retry.starts_with(b"retry: 1000"), "alive stream: {retry:?}"); | ||
| 502 | + | ||
| 503 | + let overrides = BTreeMap::from([( | ||
| 504 | + "banner.message".to_owned(), | ||
| 505 | + "maintenance tonight".to_owned(), | ||
| 506 | + )]); | ||
| 507 | + settings.publish(&overrides).expect("publish"); | ||
| 508 | + live.bump(&Topic::ServerSettings); | ||
| 509 | + let event = frames.next().await.expect("a frame").expect("data"); | ||
| 510 | + assert_eq!( | ||
| 511 | + &event[..], | ||
| 512 | + b"event: settings\ndata: 1\n\n", | ||
| 513 | + "alive stream: settings event" | ||
| 514 | + ); | ||
| 515 | + } | ||
| 516 | + | ||
| 517 | + /// A new avatar on the signed-in viewer's account reaches the alive stream as one `account` event, | ||
| 518 | + /// so the header re-renders. | ||
| 519 | + #[tokio::test] | ||
| 520 | + async fn the_alive_stream_sends_account_when_the_header_changes() { | ||
| 521 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 522 | + let state = test_state(dir.path()).await; | ||
| 523 | + let store = state.store.clone(); | ||
| 524 | + let live = state.live.clone(); | ||
| 525 | + let owner = store | ||
| 526 | + .create_user("tahinli", None, "h", false) | ||
| 527 | + .await | ||
| 528 | + .expect("user"); | ||
| 529 | + create_session(&store, &owner.id, "owner-token", CSRF).await; | ||
| 530 | + let router = app_router(state); | ||
| 531 | + | ||
| 532 | + let request = Request::builder() | ||
| 533 | + .method("GET") | ||
| 534 | + .uri("/-/alive") | ||
| 535 | + .header("cookie", format!("__Host-{SESSION_COOKIE}=owner-token")) | ||
| 536 | + .body(Body::empty()) | ||
| 537 | + .expect("request"); | ||
| 538 | + let res = router.handle(request).await; | ||
| 539 | + let mut alive = res.into_body().into_data_stream(); | ||
| 540 | + let retry = alive.next().await.expect("a frame").expect("data"); | ||
| 541 | + assert!(retry.starts_with(b"retry: 1000"), "alive stream: {retry:?}"); | ||
| 542 | + | ||
| 543 | + store | ||
| 544 | + .set_avatar(&owner.id, b"png", "avatar-two") | ||
| 545 | + .await | ||
| 546 | + .expect("avatar"); | ||
| 547 | + live.bump(&Topic::Account(owner.id.clone())); | ||
| 548 | + let event = alive.next().await.expect("a frame").expect("data"); | ||
| 549 | + assert_eq!( | ||
| 550 | + &event[..], | ||
| 551 | + b"event: account\ndata: 1\n\n", | ||
| 552 | + "alive stream: account event" | ||
| 553 | + ); | ||
| 554 | + } | ||
| 348 | } | 555 | } |
crates/forge-web/src/pages/settings_profile.rsmodified+15 -5
| @@ -19,6 +19,7 @@ use topcoat::view::{View, component, view}; | |||
| 19 | use crate::audit::{self, Actor, Target}; | 19 | use crate::audit::{self, Actor, Target}; |
| 20 | use crate::auth::{require_csrf, require_user}; | 20 | use crate::auth::{require_csrf, require_user}; |
| 21 | use crate::i18n::{self, Key, Lang, about_too_long, display_name_too_long, t}; | 21 | use crate::i18n::{self, Key, Lang, about_too_long, display_name_too_long, t}; |
| 22 | +use crate::live::Topic; | ||
| 22 | use crate::state::AppState; | 23 | use crate::state::AppState; |
| 23 | use crate::views::{alert, avatar_url, shell, user_facing_message}; | 24 | use crate::views::{alert, avatar_url, shell, user_facing_message}; |
| 24 | 25 | ||
| @@ -390,6 +391,11 @@ async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl Vie | |||
| 390 | ) | 391 | ) |
| 391 | .await; | 392 | .await; |
| 392 | } | 393 | } |
| 394 | + // The public profile shows the name, the username and the about text: its viewers follow the | ||
| 395 | + // user's topic too. | ||
| 396 | + app_context::<AppState>(cx) | ||
| 397 | + .live | ||
| 398 | + .bump(&Topic::User(viewer.0.id.clone())); | ||
| 393 | Err(see_other("/settings/profile?saved=1").into()) | 399 | Err(see_other("/settings/profile?saved=1").into()) |
| 394 | } | 400 | } |
| 395 | 401 | ||
| @@ -411,7 +417,12 @@ async fn avatar_upload(cx: &Cx, mut multipart: Multipart) -> Result<impl View> { | |||
| 411 | let store = &app_context::<AppState>(cx).store; | 417 | let store = &app_context::<AppState>(cx).store; |
| 412 | 418 | ||
| 413 | let message = match store_avatar(store, &viewer.0.id, image, lang).await { | 419 | let message = match store_avatar(store, &viewer.0.id, image, lang).await { |
| 414 | - Ok(()) => return Err(see_other("/settings/profile?saved=avatar").into()), | 420 | + Ok(()) => { |
| 421 | + app_context::<AppState>(cx) | ||
| 422 | + .live | ||
| 423 | + .bump(&Topic::User(viewer.0.id.clone())); | ||
| 424 | + return Err(see_other("/settings/profile?saved=avatar").into()); | ||
| 425 | + } | ||
| 415 | Err(e) => match user_facing_message(&e) { | 426 | Err(e) => match user_facing_message(&e) { |
| 416 | Some(message) => message, | 427 | Some(message) => message, |
| 417 | None => return Err(e.into()), | 428 | None => return Err(e.into()), |
| @@ -430,10 +441,9 @@ async fn avatar_upload(cx: &Cx, mut multipart: Multipart) -> Result<impl View> { | |||
| 430 | #[route(POST "/settings/profile/avatar/delete")] | 441 | #[route(POST "/settings/profile/avatar/delete")] |
| 431 | async fn avatar_remove(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | 442 | async fn avatar_remove(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { |
| 432 | let viewer = require_csrf(cx, &form.csrf).await?; | 443 | let viewer = require_csrf(cx, &form.csrf).await?; |
| 433 | - app_context::<AppState>(cx) | 444 | + let state = app_context::<AppState>(cx); |
| 434 | - .store | 445 | + state.store.delete_avatar(&viewer.0.id).await?; |
| 435 | - .delete_avatar(&viewer.0.id) | 446 | + state.live.bump(&Topic::User(viewer.0.id.clone())); |
| 436 | - .await?; | ||
| 437 | Ok(see_other("/settings/profile?saved=avatar-removed")) | 447 | Ok(see_other("/settings/profile?saved=avatar-removed")) |
| 438 | } | 448 | } |
| 439 | 449 | ||
crates/forge-web/src/pages/wiki.rsmodified+3 -0
| @@ -23,6 +23,7 @@ use crate::audit::{self, Actor, Target}; | |||
| 23 | use crate::auth::{require_csrf, require_user}; | 23 | use crate::auth::{require_csrf, require_user}; |
| 24 | use crate::i18n::community::{self as g, K}; | 24 | use crate::i18n::community::{self as g, K}; |
| 25 | use crate::i18n::{self, Lang}; | 25 | use crate::i18n::{self, Lang}; |
| 26 | +use crate::live::Topic; | ||
| 26 | use crate::pages::repo::repo_head; | 27 | use crate::pages::repo::repo_head; |
| 27 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; | 28 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; |
| 28 | use crate::pages::wiki_live::{bump_wiki, page_live_url, wiki_live_url}; | 29 | use crate::pages::wiki_live::{bump_wiki, page_live_url, wiki_live_url}; |
| @@ -748,6 +749,8 @@ async fn wiki_settings_post(cx: &Cx, Form(form): Form<WikiSettingsForm>) -> Resu | |||
| 748 | let enable = form.enabled.is_some(); | 749 | let enable = form.enabled.is_some(); |
| 749 | let before = state.store.wiki_enabled(&ctx.repo.id).await?; | 750 | let before = state.store.wiki_enabled(&ctx.repo.id).await?; |
| 750 | state.store.set_wiki_enabled(&ctx.repo.id, enable).await?; | 751 | state.store.set_wiki_enabled(&ctx.repo.id, enable).await?; |
| 752 | + // The repo header shows the Wiki tab. | ||
| 753 | + state.live.bump(&Topic::Repo(ctx.repo.id.clone())); | ||
| 751 | if before != enable { | 754 | if before != enable { |
| 752 | let action = if enable { | 755 | let action = if enable { |
| 753 | AuditAction::WikiEnabled | 756 | AuditAction::WikiEnabled |
crates/forge-web/src/post_update.rsmodified+9 -0
| @@ -62,6 +62,10 @@ pub async fn after_ref_update( | |||
| 62 | .live | 62 | .live |
| 63 | .bump(&crate::live::Topic::User(repo.owner_id.clone())); | 63 | .bump(&crate::live::Topic::User(repo.owner_id.clone())); |
| 64 | } | 64 | } |
| 65 | + // The explore list shows each public repo's last activity, so a push moves it there. | ||
| 66 | + if repo.visibility == forge_core::Visibility::Public { | ||
| 67 | + state.live.bump(&crate::live::Topic::Explore); | ||
| 68 | + } | ||
| 65 | crate::ci::on_ref_update(state, repo, actor_id, refname, new).await; | 69 | crate::ci::on_ref_update(state, repo, actor_id, refname, new).await; |
| 66 | if (refname.starts_with("refs/heads/") || refname.starts_with("refs/tags/")) | 70 | if (refname.starts_with("refs/heads/") || refname.starts_with("refs/tags/")) |
| 67 | && let Err(e) = crate::mirrors::enqueue_push_mirrors(state, &repo.id).await | 71 | && let Err(e) = crate::mirrors::enqueue_push_mirrors(state, &repo.id).await |
| @@ -228,6 +232,9 @@ async fn apply_commit_refs( | |||
| 228 | ) | 232 | ) |
| 229 | .await?; | 233 | .await?; |
| 230 | if closed { | 234 | if closed { |
| 235 | + state.live.bump_issue(&repo.id, &issue.id); | ||
| 236 | + // A pull is an issue row too, so a keyword can close one. | ||
| 237 | + crate::pages::pull_live::bump_pull(state, &repo.id, &issue.id); | ||
| 231 | emit_item_action(state, repo, sender, false, number, "closed").await; | 238 | emit_item_action(state, repo, sender, false, number, "closed").await; |
| 232 | notify::dispatch( | 239 | notify::dispatch( |
| 233 | state, | 240 | state, |
| @@ -249,6 +256,8 @@ async fn apply_commit_refs( | |||
| 249 | store | 256 | store |
| 250 | .add_event(&issue.id, actor, "referenced", json!({"commit": oid})) | 257 | .add_event(&issue.id, actor, "referenced", json!({"commit": oid})) |
| 251 | .await?; | 258 | .await?; |
| 259 | + state.live.bump_issue(&repo.id, &issue.id); | ||
| 260 | + crate::pages::pull_live::bump_pull(state, &repo.id, &issue.id); | ||
| 252 | } | 261 | } |
| 253 | } | 262 | } |
| 254 | Ok(()) | 263 | Ok(()) |
crates/forge-web/src/views/mod.rsmodified+1 -1
| @@ -391,7 +391,7 @@ pub async fn shell( | |||
| 391 | } | 391 | } |
| 392 | </header> | 392 | </header> |
| 393 | if let Some(banner) = banner { | 393 | if let Some(banner) = banner { |
| 394 | - <div class=(if banner.warning { "site-banner warning" } else { "site-banner" }) role="status"> | 394 | + <div class=(if banner.warning { "site-banner warning" } else { "site-banner" }) role="status" data-expires=(banner.expires.map(|t| t.to_string()))> |
| 395 | <p>(banner.message.as_str())</p> | 395 | <p>(banner.message.as_str())</p> |
| 396 | <form method="post" action="/-/banner/dismiss"> | 396 | <form method="post" action="/-/banner/dismiss"> |
| 397 | <input type="hidden" name="hash" value=(banner.hash.as_str())> | 397 | <input type="hidden" name="hash" value=(banner.hash.as_str())> |