forge
Explore
Log in

Don't you dare go Hollow

The release list and release pages update live

Browse files at this commit

72169d54722e4a5f8dc0e2dcdfa8cf0c7dd4b6f6Ahmet Kaan GümüşParent: 07bdd5d
  • feat
    • the release list and release pages update live
Show full message
⚡ feat: the release list and release pages update live
crates/forge-web/src/live.rsmodified+4 -0
@@ -99,6 +99,10 @@ pub enum Topic {
99 /// The server settings: a value was saved or reset, or a restart was requested. Global.99 /// The server settings: a value was saved or reset, or a restart was requested. Global.
100 /// Admin pages only, on [`admin`].100 /// Admin pages only, on [`admin`].
101 AdminServer,101 AdminServer,
102+ /// 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
104+ /// list and the release pages follow it. Bumped by [`crate::release_ops`].
105+ RepoReleases(String),
102 }106 }
103 107
104 /// The hub of the admin pages. It is process-wide, not part of [`crate::state::AppState`]: the108 /// The hub of the admin pages. It is process-wide, not part of [`crate::state::AppState`]: the
crates/forge-web/src/pages/mod.rsmodified+1 -0
@@ -99,6 +99,7 @@ mod reactions_tests;
99 pub mod refs;99 pub mod refs;
100 pub mod register;100 pub mod register;
101 pub mod releases;101 pub mod releases;
102+pub mod releases_live;
102 #[cfg(test)]103 #[cfg(test)]
103 mod releases_tests;104 mod releases_tests;
104 pub mod repo;105 pub mod repo;
crates/forge-web/src/pages/releases.rsmodified+11 -4
@@ -35,6 +35,7 @@ use crate::i18n::{
35 releases_ci::{self as g, K},35 releases_ci::{self as g, K},
36 };36 };
37 use crate::pages::refs::load_refs;37 use crate::pages::refs::load_refs;
38+use crate::pages::releases_live;
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};
40 use crate::pages::repo_mirrors::stamp_in_tz;41 use crate::pages::repo_mirrors::stamp_in_tz;
@@ -75,7 +76,7 @@ fn viewer_user(ctx: &RepoCtx) -> Option<&User> {
75 }76 }
76 77
77 /// Whether the viewer may change releases of this repo. Archived repos refuse.78 /// Whether the viewer may change releases of this repo. Archived repos refuse.
78-fn can_write(ctx: &RepoCtx) -> bool {79+pub(crate) fn can_write(ctx: &RepoCtx) -> bool {
79 authorize(80 authorize(
80 viewer_user(ctx),81 viewer_user(ctx),
81 &ctx.repo,82 &ctx.repo,
@@ -494,6 +495,7 @@ async fn list_body(
494 notice: Option<(&'static str, bool)>,495 notice: Option<(&'static str, bool)>,
495 new_href: Option<String>,496 new_href: Option<String>,
496 cards: Vec<ReleaseCard>,497 cards: Vec<ReleaseCard>,
498+ live: String,
497 ) -> Result<impl View> {499 ) -> Result<impl View> {
498 Ok(view! {500 Ok(view! {
499 repo_head(head: head)501 repo_head(head: head)
@@ -504,7 +506,7 @@ async fn list_body(
504 <section class="card notice" role="status">(text)</section>506 <section class="card notice" role="status">(text)</section>
505 }507 }
506 }508 }
507- <section class="card">509+ <section class="card" data-live=(live.as_str())>
508 <div class="release-list-head">510 <div class="release-list-head">
509 <h2>(g::t(lang, K::Releases))</h2>511 <h2>(g::t(lang, K::Releases))</h2>
510 if let Some(href) = new_href {512 if let Some(href) = new_href {
@@ -578,9 +580,10 @@ async fn releases_list_page(cx: &Cx) -> Result<impl View> {
578 let new_href = writer.then(|| format!("{}/new", releases_href(&title_of(&ctx))));580 let new_href = writer.then(|| format!("{}/new", releases_href(&title_of(&ctx))));
579 let notice = notice_from_query(cx, lang);581 let notice = notice_from_query(cx, lang);
580 let head = ctx.head(state, "releases").await?;582 let head = ctx.head(state, "releases").await?;
583+ let live = releases_live::list_live_url(&title_of(&ctx));
581 Ok(view! {584 Ok(view! {
582 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),585 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
583- list_body(head: head, lang: lang, notice: notice, new_href: new_href, cards: cards))586+ list_body(head: head, lang: lang, notice: notice, new_href: new_href, cards: cards, live: live))
584 })587 })
585 }588 }
586 589
@@ -767,6 +770,7 @@ async fn release_tag_page(cx: &Cx) -> Result<impl View> {
767 let head = ctx.head(state, "releases").await?;770 let head = ctx.head(state, "releases").await?;
768 let notice = notice_from_query(cx, lang);771 let notice = notice_from_query(cx, lang);
769 let delete_href = format!("/{title}/releases/{}/delete", enc(&release.id));772 let delete_href = format!("/{title}/releases/{}/delete", enc(&release.id));
773+ let live = releases_live::tag_live_url(&title, &release.tag);
770 let csrf = match crate::auth::current_user(cx).await? {774 let csrf = match crate::auth::current_user(cx).await? {
771 Some((_, session)) => session.csrf_token.clone(),775 Some((_, session)) => session.csrf_token.clone(),
772 None => String::new(),776 None => String::new(),
@@ -781,7 +785,7 @@ async fn release_tag_page(cx: &Cx) -> Result<impl View> {
781 <section class="card notice" role="status">(text)</section>785 <section class="card notice" role="status">(text)</section>
782 }786 }
783 }787 }
784- <section class="card">788+ <section class="card" data-live=(live.as_str())>
785 <p class="muted small">789 <p class="muted small">
786 <a href=(all_href.as_str())>(g::t(lang, K::AllReleases))</a>790 <a href=(all_href.as_str())>(g::t(lang, K::AllReleases))</a>
787 </p>791 </p>
@@ -1302,6 +1306,9 @@ async fn stream_asset(
1302 if let Err(e) = state.store.count_asset_download(&asset.id).await {1306 if let Err(e) = state.store.count_asset_download(&asset.id).await {
1303 tracing::error!(error = %e, asset_id = %asset.id, "releases: could not count a download");1307 tracing::error!(error = %e, asset_id = %asset.id, "releases: could not count a download");
1304 }1308 }
1309+ state
1310+ .live
1311+ .bump(&crate::live::Topic::RepoReleases(repo.id.clone()));
1305 let chunks = read.stream.map_ok(Frame::data);1312 let chunks = read.stream.map_ok(Frame::data);
1306 let mut res = Response::new(Body::new(StreamBody::new(chunks)));1313 let mut res = Response::new(Body::new(StreamBody::new(chunks)));
1307 *res.status_mut() = StatusCode::OK;1314 *res.status_mut() = StatusCode::OK;
crates/forge-web/src/pages/releases_live.rsadded+126 -0
@@ -0,0 +1,126 @@
1+//! Live releases. The release list (`/{o}/{r}/releases`) and a release page
2+//! (`/{o}/{r}/releases/tag/{tag}`) follow [`Topic::RepoReleases`]. The pages render `data-live`
3+//! with the URL of their stream, and a `changed` event re-renders them in place (see `nav.js`).
4+//!
5+//! Every write to a release or an asset, and every download (its counter), bumps the topic from
6+//! [`crate::release_ops`] or [`crate::pages::releases`] after the write has succeeded. Those are the
7+//! only places that bump it, so the web form, the REST API, CI and the importer all reach the pages.
8+//!
9+//! What a stream compares is a fingerprint of what the page shows, so a bump that changes nothing
10+//! visible (another repo's counter, a download of a draft a reader cannot see) sends nothing.
11+
12+use forge_core::store::Store;
13+use topcoat::Result;
14+use topcoat::context::{Cx, app_context};
15+use topcoat::router::error::not_found;
16+use topcoat::router::response::Response;
17+use topcoat::router::{path_param, route};
18+
19+use crate::live::{Topic, stream_changes};
20+use crate::pages::releases::can_write;
21+use crate::pages::repo_ctx::load_repo;
22+use crate::state::AppState;
23+use crate::views::enc;
24+
25+path_param!(owner);
26+path_param!(repo);
27+path_param!(tag);
28+
29+/// The stream URL the release list follows. `title` is `owner/repo`.
30+pub fn list_live_url(title: &str) -> String {
31+ format!("/{title}/releases/events")
32+}
33+
34+/// The stream URL a release page follows. `title` is `owner/repo`.
35+pub fn tag_live_url(title: &str, tag: &str) -> String {
36+ format!("/{title}/releases/tag/{}/events", enc(tag))
37+}
38+
39+// Fingerprints. Each reads what the page shows; any change to it changes the string. `writer`
40+// decides whether drafts are part of it, the same way the pages decide.
41+
42+/// What the release list shows: the latest release and every release the viewer may see, with
43+/// their assets (names, sizes, download counts).
44+pub(crate) async fn list_fingerprint(store: &Store, repo_id: &str, writer: bool) -> Result<String> {
45+ let latest = store
46+ .latest_release(repo_id)
47+ .await?
48+ .map(|release| release.id);
49+ let mut lines = vec![format!("latest {latest:?}")];
50+ for release in store.list_releases(repo_id).await? {
51+ if release.draft && !writer {
52+ continue;
53+ }
54+ lines.push(format!("{release:?}"));
55+ for asset in store.list_release_assets(&release.id).await? {
56+ lines.push(format!("asset {asset:?}"));
57+ }
58+ }
59+ Ok(lines.join("\n"))
60+}
61+
62+/// What one release page shows. `gone` once the release is missing, or is a draft the viewer may
63+/// not see (the page answers 404 for both).
64+pub(crate) async fn release_fingerprint(
65+ store: &Store,
66+ repo_id: &str,
67+ tag: &str,
68+ writer: bool,
69+) -> Result<String> {
70+ let Some(release) = store.release_by_tag(repo_id, tag).await? else {
71+ return Ok("gone".to_owned());
72+ };
73+ if release.draft && !writer {
74+ return Ok("gone".to_owned());
75+ }
76+ let mut lines = vec![format!("{release:?}")];
77+ for asset in store.list_release_assets(&release.id).await? {
78+ lines.push(format!("asset {asset:?}"));
79+ }
80+ Ok(lines.join("\n"))
81+}
82+
83+// Streams. Auth is the page's: the repo read check (`load_repo`), then the draft rule.
84+
85+/// The release list's change stream.
86+#[route(GET "/{owner}/{repo}/releases/events")]
87+async fn releases_events(cx: &Cx) -> Result<Response> {
88+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
89+ let state = app_context::<AppState>(cx);
90+ let writer = can_write(&ctx);
91+ let topic = Topic::RepoReleases(ctx.repo.id.clone());
92+ let store = state.store.clone();
93+ let repo_id = ctx.repo.id.clone();
94+ stream_changes(cx, &state.live, &[topic], move || {
95+ let store = store.clone();
96+ let repo_id = repo_id.clone();
97+ async move { list_fingerprint(&store, &repo_id, writer).await }
98+ })
99+ .await
100+}
101+
102+/// One release page's change stream. A release the viewer cannot open gets the page's 404.
103+#[route(GET "/{owner}/{repo}/releases/tag/{tag}/events")]
104+async fn release_events(cx: &Cx) -> Result<Response> {
105+ let tag = path_param::<Tag>(cx).to_owned();
106+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
107+ let state = app_context::<AppState>(cx);
108+ let writer = can_write(&ctx);
109+ let visible = match state.store.release_by_tag(&ctx.repo.id, &tag).await? {
110+ Some(release) => writer || !release.draft,
111+ None => false,
112+ };
113+ if !visible {
114+ return Err(not_found().into());
115+ }
116+ let topic = Topic::RepoReleases(ctx.repo.id.clone());
117+ let store = state.store.clone();
118+ let repo_id = ctx.repo.id.clone();
119+ stream_changes(cx, &state.live, &[topic], move || {
120+ let store = store.clone();
121+ let repo_id = repo_id.clone();
122+ let tag = tag.clone();
123+ async move { release_fingerprint(&store, &repo_id, &tag, writer).await }
124+ })
125+ .await
126+}
crates/forge-web/src/pages/releases_tests.rsmodified+110 -0
@@ -1069,3 +1069,113 @@ async fn replace_keeps_the_asset_name_whatever_the_new_file_is_called() {
1069 .await;1069 .await;
1070 assert_eq!(got.body, b"second bytes");1070 assert_eq!(got.body, b"second bytes");
1071 }1071 }
1072+
1073+/// The live streams of the release list and a release page: a change from another session wakes
1074+/// them, and a reader without the access the page needs gets the page's 404.
1075+mod live_tests {
1076+ use super::*;
1077+ use futures_util::StreamExt;
1078+ use topcoat::router::response::Response;
1079+
1080+ /// Sends a GET for a stream. The body is not read here: a stream never ends.
1081+ async fn open(fx: &Fixture, uri: &str, cookie: Option<&str>) -> Response {
1082+ let mut builder = Request::builder().method("GET").uri(uri);
1083+ if let Some(cookie) = cookie {
1084+ builder = builder.header("cookie", cookie);
1085+ }
1086+ fx.app
1087+ .handle(builder.body(Body::empty()).expect("request"))
1088+ .await
1089+ }
1090+
1091+ const CHANGED: &[u8] = b"event: changed\ndata: 1\n\n";
1092+
1093+ #[tokio::test]
1094+ async fn an_edit_wakes_the_release_list_and_the_release_page() {
1095+ let fx = fixture(None).await;
1096+ let rel = fx.release("v1.0", false).await;
1097+ let list = open(&fx, "/tahinli/proj/releases/events", None).await;
1098+ assert_eq!(list.status().as_u16(), 200);
1099+ let mut list = list.into_body().into_data_stream();
1100+ let page = open(&fx, "/tahinli/proj/releases/tag/v1.0/events", None).await;
1101+ assert_eq!(page.status().as_u16(), 200);
1102+ let mut page = page.into_body().into_data_stream();
1103+ let retry = list.next().await.expect("a frame").expect("data");
1104+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
1105+ let retry = page.next().await.expect("a frame").expect("data");
1106+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
1107+
1108+ let edit = EditRelease {
1109+ title: "Renamed".to_owned(),
1110+ ..keep(&rel)
1111+ };
1112+ release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &rel, edit)
1113+ .await
1114+ .expect("edited");
1115+
1116+ assert_eq!(
1117+ &list.next().await.expect("a frame").expect("data")[..],
1118+ CHANGED
1119+ );
1120+ assert_eq!(
1121+ &page.next().await.expect("a frame").expect("data")[..],
1122+ CHANGED
1123+ );
1124+ }
1125+
1126+ #[tokio::test]
1127+ async fn an_asset_upload_and_a_download_each_wake_the_list() {
1128+ let fx = fixture(None).await;
1129+ let rel = fx.release("v1.0", false).await;
1130+ let mut list = open(&fx, "/tahinli/proj/releases/events", None)
1131+ .await
1132+ .into_body()
1133+ .into_data_stream();
1134+ let retry = list.next().await.expect("a frame").expect("data");
1135+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
1136+
1137+ let uploaded = fx
1138+ .upload(&rel.id, "app.tar.gz", b"bytes", &fx.tahinli_cookie)
1139+ .await;
1140+ assert_eq!(uploaded.status, 303, "body: {}", uploaded.text());
1141+ assert_eq!(
1142+ &list.next().await.expect("a frame").expect("data")[..],
1143+ CHANGED
1144+ );
1145+
1146+ let download = send(
1147+ &fx.app,
1148+ "GET",
1149+ "/tahinli/proj/releases/download/v1.0/app.tar.gz",
1150+ None,
1151+ None,
1152+ Vec::new(),
1153+ )
1154+ .await;
1155+ assert_eq!(download.status, 200);
1156+ assert_eq!(
1157+ &list.next().await.expect("a frame").expect("data")[..],
1158+ CHANGED
1159+ );
1160+ }
1161+
1162+ #[tokio::test]
1163+ async fn a_draft_is_not_streamed_to_a_reader_and_its_page_is_404() {
1164+ let fx = fixture(None).await;
1165+ fx.release("v2.0", true).await;
1166+ let uri = "/tahinli/proj/releases/tag/v2.0/events";
1167+
1168+ assert_eq!(open(&fx, uri, None).await.status().as_u16(), 404);
1169+ assert_eq!(
1170+ open(&fx, uri, Some(&fx.bob_cookie)).await.status().as_u16(),
1171+ 404
1172+ );
1173+ assert_eq!(
1174+ open(&fx, uri, Some(&fx.tahinli_cookie))
1175+ .await
1176+ .status()
1177+ .as_u16(),
1178+ 200
1179+ );
1180+ }
1181+}
crates/forge-web/src/release_ops.rsmodified+11 -0
@@ -26,10 +26,16 @@ use futures_util::{Stream, StreamExt};
26 use http::StatusCode;26 use http::StatusCode;
27 27
28 use crate::blobs::asset_key;28 use crate::blobs::asset_key;
29+use crate::live::Topic;
29 use crate::post_update::after_ref_update;30 use crate::post_update::after_ref_update;
30 use crate::state::AppState;31 use crate::state::AppState;
31 use crate::webhooks::emit::{Sender, emit};32 use crate::webhooks::emit::{Sender, emit};
32 33
34+/// Wakes the release list and the release pages of `repo`. Called after each write has succeeded.
35+fn bump(state: &AppState, repo: &Repo) {
36+ state.live.bump(&Topic::RepoReleases(repo.id.clone()));
37+}
38+
33 /// Why a release operation failed. `NotFound` also covers a release or asset that belongs to a39 /// Why a release operation failed. `NotFound` also covers a release or asset that belongs to a
34 /// different repo, so callers cannot probe other repos through these functions.40 /// different repo, so callers cannot probe other repos through these functions.
35 #[derive(Debug)]41 #[derive(Debug)]
@@ -284,6 +290,7 @@ pub async fn create(
284 author_id: &actor.id,290 author_id: &actor.id,
285 })291 })
286 .await?;292 .await?;
293+ bump(state, repo);
287 if !created.draft {294 if !created.draft {
288 emit_release(state, repo, actor, "published", &created).await;295 emit_release(state, repo, actor, "published", &created).await;
289 }296 }
@@ -384,6 +391,7 @@ pub async fn update(
384 if !state.store.update_release(&release.id, &fields).await? {391 if !state.store.update_release(&release.id, &fields).await? {
385 return Err(ReleaseError::NotFound);392 return Err(ReleaseError::NotFound);
386 }393 }
394+ bump(state, repo);
387 let after = state395 let after = state
388 .store396 .store
389 .release(&release.id)397 .release(&release.id)
@@ -417,6 +425,7 @@ pub async fn delete(
417 tracing::error!(error = %e, asset_id, "releases: could not delete an asset blob");425 tracing::error!(error = %e, asset_id, "releases: could not delete an asset blob");
418 }426 }
419 }427 }
428+ bump(state, repo);
420 if !release.draft {429 if !release.draft {
421 emit_release(state, repo, actor, "deleted", release).await;430 emit_release(state, repo, actor, "deleted", release).await;
422 }431 }
@@ -443,6 +452,7 @@ pub async fn delete_asset(
443 if let Err(e) = state.blobs.delete(&asset_key(&row.id)).await {452 if let Err(e) = state.blobs.delete(&asset_key(&row.id)).await {
444 tracing::error!(error = %e, asset_id = %row.id, "releases: could not delete an asset blob");453 tracing::error!(error = %e, asset_id = %row.id, "releases: could not delete an asset blob");
445 }454 }
455+ bump(state, repo);
446 Ok(())456 Ok(())
447 }457 }
448 458
@@ -523,5 +533,6 @@ pub async fn put_asset(
523 {533 {
524 tracing::error!(error = %e, asset_id = %old_id, "releases: could not delete a replaced blob");534 tracing::error!(error = %e, asset_id = %old_id, "releases: could not delete a replaced blob");
525 }535 }
536+ bump(state, repo);
526 Ok((stored, previous.is_some()))537 Ok((stored, previous.is_some()))
527 }538 }
docs/architecture.mdmodified+1 -1
@@ -277,7 +277,7 @@ The org streams follow the same access as their pages: a non-member gets 404, an
277 277
278 The user topics are keyed by user id, and their streams take the viewer from the session, so no URL names another user's inbox. Repo streams follow the same visibility as the repo page (a private repo answers 404 to a viewer who cannot read it). Explore lists public repos only. The admin streams answer 404 to anyone who is not an instance admin, like the admin pages they serve. Every audited write also wakes the account pages of the users it names, so a login or a passkey change updates the account's facts. The admin pages' hub is process-wide (`live::admin()`), because the audit writer has no app state.278 The user topics are keyed by user id, and their streams take the viewer from the session, so no URL names another user's inbox. Repo streams follow the same visibility as the repo page (a private repo answers 404 to a viewer who cannot read it). Explore lists public repos only. The admin streams answer 404 to anyone who is not an instance admin, like the admin pages they serve. Every audited write also wakes the account pages of the users it names, so a login or a passkey change updates the account's facts. The admin pages' hub is process-wide (`live::admin()`), because the audit writer has no app state.
279 279
280-A page can hold several streams at once: the repo header (`/{owner}/{repo}/events`) sits above the page's own list, issue, pull or run. `nav.js` opens one EventSource for each distinct `data-live` URL in the page, so each of them updates the page.280+The release list and release pages follow `RepoReleases` (`/{owner}/{repo}/releases/events` and `/{owner}/{repo}/releases/tag/{tag}/events`). A page can hold several streams at once: the repo header (`/{owner}/{repo}/events`) sits above the page's own list, issue, pull or run. `nav.js` opens one EventSource for each distinct `data-live` URL in the page, so each of them updates the page.
281 281
282 ### 5.8 Restart resilience282 ### 5.8 Restart resilience
283 283
docs/ci.mdmodified+3 -0
@@ -299,6 +299,9 @@ rule and only deploys a run whose every job succeeded.
299 For scripted control, use the REST API with a personal access token stored as a repo secret. See299 For scripted control, use the REST API with a personal access token stored as a repo secret. See
300 [api.md](api.md).300 [api.md](api.md).
301 301
302+The release list and each release page update live: a release created, edited or deleted by CI or by
303+hand, an asset added or removed, and a download count moving all appear without a reload.
304+
302 | Key | Type | Default | Meaning |305 | Key | Type | Default | Meaning |
303 |--------------|------------------------|-----------|---------|306 |--------------|------------------------|-----------|---------|
304 | `assets` | array of string | `[]` | `"<job>:<glob>"` entries. The glob matches that job's **flattened** artifact names (see below). Max 32. A job named here must exist and declare `artifacts`. |307 | `assets` | array of string | `[]` | `"<job>:<glob>"` entries. The glob matches that job's **flattened** artifact names (see below). Max 32. A job named here must exist and declare `artifacts`. |