forge
Explore
Log in

Don't you dare go Hollow

Issues update live

Browse files at this commit

fac9525427ea6b26c86501d4d944cce482b517d2Ahmet Kaan GümüşParent: ac2aa27
  • feat
    • issues update live
Show full message
⚡ feat: issues update live
crates/forge-web/assets/nav.jsmodified+3 -2
@@ -990,8 +990,9 @@
990 // A job page's stream opens with the status the page already shows: nothing to re-render then.990 // A job page's stream opens with the status the page already shows: nothing to re-render then.
991 var wrap = document.querySelector('[data-live]');991 var wrap = document.querySelector('[data-live]');
992 if (document.querySelector('[data-live-log]') && wrap && wrap.getAttribute('data-live-state') === e.data) { return; }992 if (document.querySelector('[data-live-log]') && wrap && wrap.getAttribute('data-live-state') === e.data) { return; }
993- // A code view re-renders at once. Events that come while a fetch is on the wire share the next one.993+ // A code view or an issue page re-renders at once (data-live-now). Events that come while a fetch
994- if (document.querySelector('[data-live-code]')) { refreshLive(); return; }994+ // is on the wire share the next one.
995+ if (document.querySelector('[data-live-code], [data-live-now]')) { refreshLive(); return; }
995 // The run list changes on every log chunk of every job: refresh at most once a second.996 // The run list changes on every log chunk of every job: refresh at most once a second.
996 if (document.querySelector('[data-live-log]')) { refreshLive(); return; }997 if (document.querySelector('[data-live-log]')) { refreshLive(); return; }
997 if (liveTimer) { return; }998 if (liveTimer) { return; }
crates/forge-web/src/live.rsmodified+38 -0
@@ -14,6 +14,10 @@
14 //! one, so a bump that changes nothing visible sends nothing.14 //! one, so a bump that changes nothing visible sends nothing.
15 //! 4. Render `data-live="<the route URL>"` on the page's element that the client follows.15 //! 4. Render `data-live="<the route URL>"` on the page's element that the client follows.
16 //!16 //!
17+//! A page whose state is cheap to compare can use `stream_changes` (the fingerprint). A page
18+//! whose every bump is a visible change (the issue pages) uses [`stream_wakes`] instead: one
19+//! `changed` per wake, several bumps in a row coalesced into one.
20+//!
17 //! The hub is in-process only, like [`crate::notify_hub::NotifyHub`]. [`crate::ci::CiLive`] keeps21 //! The hub is in-process only, like [`crate::notify_hub::NotifyHub`]. [`crate::ci::CiLive`] keeps
18 //! its own counters for CI and is not on this hub.22 //! its own counters for CI and is not on this hub.
19 23
@@ -35,6 +39,11 @@ use crate::pages::ci_runs::events_response;
35 pub enum Topic {39 pub enum Topic {
36 /// The refs of a repo: a branch or tag was created, deleted or moved. Keyed by repo id.40 /// The refs of a repo: a branch or tag was created, deleted or moved. Keyed by repo id.
37 RepoRefs(String),41 RepoRefs(String),
42+ /// The issues of a repo as a list: an issue, label or milestone changed, or a count moved.
43+ /// Keyed by repo id. The labels and milestones pages and the repo tabs follow it too.
44+ RepoIssues(String),
45+ /// One issue: its body, comments, events, state, labels, reactions. Keyed by issue id.
46+ Issue(String),
38 }47 }
39 48
40 /// The open topics, each with the counter its subscribers wait on.49 /// The open topics, each with the counter its subscribers wait on.
@@ -71,6 +80,19 @@ impl LiveHub {
71 topics.remove(topic);80 topics.remove(topic);
72 }81 }
73 }82 }
83+
84+ /// Wakes the issue list and the labels, milestones and tabs that follow the repo's issues. Call
85+ /// it after a change to a label or milestone of `repo_id`.
86+ pub fn bump_repo_issues(&self, repo_id: &str) {
87+ self.bump(&Topic::RepoIssues(repo_id.to_owned()));
88+ }
89+
90+ /// Wakes the issue list of `repo_id` and the page of `issue_id`. Call it after an issue write
91+ /// has succeeded, with the repo the issue belongs to.
92+ pub fn bump_issue(&self, repo_id: &str, issue_id: &str) {
93+ self.bump(&Topic::RepoIssues(repo_id.to_owned()));
94+ self.bump(&Topic::Issue(issue_id.to_owned()));
95+ }
74 }96 }
75 97
76 /// The state a stream follows between wakes: the fingerprint last sent or seen.98 /// The state a stream follows between wakes: the fingerprint last sent or seen.
@@ -85,6 +107,22 @@ fn changed_event() -> Result<Event> {
85 Ok(Event::new().event("changed").data("1"))107 Ok(Event::new().event("changed").data("1"))
86 }108 }
87 109
110+/// The response of a live stream for any of `topics`. It sends `changed` after each wake, with no
111+/// fingerprint: the caller bumps only after a write that changes the page. Nothing is sent on
112+/// connect. The stream ends when a topic is gone, which cannot happen while the stream holds it.
113+pub fn stream_wakes(cx: &Cx, hub: &LiveHub, topics: &[Topic]) -> Result<Response> {
114+ let wakes: Vec<watch::Receiver<u64>> = topics.iter().map(|t| hub.subscribe(t)).collect();
115+ let events = stream::unfold(wakes, |mut wakes| async move {
116+ // The futures of the topics not woken are dropped with this statement.
117+ let (woken, _, _) =
118+ futures_util::future::select_all(wakes.iter_mut().map(|wake| Box::pin(wake.changed())))
119+ .await;
120+ woken.ok()?;
121+ Some((changed_event(), wakes))
122+ });
123+ events_response(cx, events)
124+}
125+
88 /// The response of a live stream for `topic`. It sends `changed` after each wake whose126 /// The response of a live stream for `topic`. It sends `changed` after each wake whose
89 /// fingerprint differs from the last one. Nothing is sent on connect: the page already shows the127 /// fingerprint differs from the last one. Nothing is sent on connect: the page already shows the
90 /// state the first read saw. The stream ends if the read fails.128 /// state the first read saw. The stream ends if the read fails.
crates/forge-web/src/pages/edit_history.rsmodified+4 -1
@@ -18,6 +18,7 @@ use topcoat::view::{View, component, view};
18 use crate::i18n::issues::{self as g, K};18 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::repo::repo_head;22 use crate::pages::repo::repo_head;
22 use crate::pages::repo_ctx::{RepoCtx, load_repo};23 use crate::pages::repo_ctx::{RepoCtx, load_repo};
23 use crate::state::AppState;24 use crate::state::AppState;
@@ -226,11 +227,13 @@ async fn history_page(
226 let heading = g::history_heading(lang, what);227 let heading = g::history_heading(lang, what);
227 let back_label = g::back_to_item(lang, number);228 let back_label = g::back_to_item(lang, number);
228 let count_label = g::earlier_versions(lang, entries.len());229 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+ let live = (kind_item == ItemKind::Issue).then(|| item_live_url(&owner, &name, number));
229 232
230 Ok(view! { cx =>233 Ok(view! { cx =>
231 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),234 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),
232 repo_head(head: header)235 repo_head(head: header)
233- <section class="issue-head">236+ <section class="issue-head" data-live=(live.as_deref()) data-live-now="">
234 <h1 class="issue-heading">(heading.as_str())</h1>237 <h1 class="issue-heading">(heading.as_str())</h1>
235 <p class="issue-byline">238 <p class="issue-byline">
236 <a href=(back.as_str())>(back_label.as_str())</a>239 <a href=(back.as_str())>(back_label.as_str())</a>
crates/forge-web/src/pages/issue_meta.rsmodified+8 -2
@@ -19,7 +19,7 @@ use crate::auth::require_csrf;
19 use crate::i18n::issues::{self as g, K};19 use crate::i18n::issues::{self as g, K};
20 use crate::i18n::{self, Lang};20 use crate::i18n::{self, Lang};
21 use crate::notify;21 use crate::notify;
22-use crate::pages::issue_parts::ItemKind;22+use crate::pages::issue_parts::{ItemKind, bump_live};
23 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};23 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
24 use crate::state::AppState;24 use crate::state::AppState;
25 use crate::views::{alert, shell, user_facing_message};25 use crate::views::{alert, shell, user_facing_message};
@@ -96,8 +96,10 @@ pub(crate) async fn issue_subnav(lang: Lang, title: String, active: String) -> R
96 let issues = format!("/{title}/issues");96 let issues = format!("/{title}/issues");
97 let labels = format!("/{title}/labels");97 let labels = format!("/{title}/labels");
98 let milestones = format!("/{title}/milestones");98 let milestones = format!("/{title}/milestones");
99+ // The repo's issue stream: the labels and milestones pages follow it (see `issues_live`).
100+ let live = format!("/{title}/issues/live");
99 Ok(view! {101 Ok(view! {
100- <nav class="subnav" aria-label=(g::t(lang, K::IssuePages))>102+ <nav class="subnav" aria-label=(g::t(lang, K::IssuePages)) data-live=(live.as_str()) data-live-now="">
101 <a class=(subnav_class(&active, "issues")) href=(issues.as_str())>(g::t(lang, K::Issues))</a>103 <a class=(subnav_class(&active, "issues")) href=(issues.as_str())>(g::t(lang, K::Issues))</a>
102 <a class=(subnav_class(&active, "labels")) href=(labels.as_str())>(g::t(lang, K::Labels))</a>104 <a class=(subnav_class(&active, "labels")) href=(labels.as_str())>(g::t(lang, K::Labels))</a>
103 <a class=(subnav_class(&active, "milestones")) href=(milestones.as_str())>(g::t(lang, K::Milestones))</a>105 <a class=(subnav_class(&active, "milestones")) href=(milestones.as_str())>(g::t(lang, K::Milestones))</a>
@@ -228,6 +230,7 @@ async fn labels_save(cx: &Cx, kind: ItemKind, fields: Vec<(String, String)>) ->
228 action_error_at(lang: lang, message: message, back: back))230 action_error_at(lang: lang, message: message, back: back))
229 });231 });
230 }232 }
233+ bump_live(state, &ctx.repo.id, &item, kind);
231 let after = item_labels(state, &item.id).await;234 let after = item_labels(state, &item.id).await;
232 let sender = Sender::of(&user);235 let sender = Sender::of(&user);
233 emit_label_changes(state, &ctx.repo, &sender, pull, &item, &before, &after).await;236 emit_label_changes(state, &ctx.repo, &sender, pull, &item, &before, &after).await;
@@ -275,6 +278,7 @@ async fn assignees_save(
275 action_error_at(lang: lang, message: message, back: back))278 action_error_at(lang: lang, message: message, back: back))
276 });279 });
277 }280 }
281+ bump_live(state, &ctx.repo.id, &item, kind);
278 let after = assignee_names(state, &item.id).await;282 let after = assignee_names(state, &item.id).await;
279 let sender = Sender::of(&user);283 let sender = Sender::of(&user);
280 emit_assignee_changes(state, &ctx.repo, &sender, pull, &item, &before, &after).await;284 emit_assignee_changes(state, &ctx.repo, &sender, pull, &item, &before, &after).await;
@@ -343,6 +347,7 @@ async fn lock_save(cx: &Cx, kind: ItemKind, fields: Vec<(String, String)>) -> Re
343 }347 }
344 };348 };
345 if changed {349 if changed {
350+ bump_live(state, &ctx.repo.id, &item, kind);
346 let action = if locked { "locked" } else { "unlocked" };351 let action = if locked { "locked" } else { "unlocked" };
347 let pull = matches!(kind, ItemKind::Pull);352 let pull = matches!(kind, ItemKind::Pull);
348 let sender = Sender::of(&user);353 let sender = Sender::of(&user);
@@ -394,6 +399,7 @@ async fn milestone_save(
394 Some(id) => milestone_title(state, &ctx.repo.id, id).await,399 Some(id) => milestone_title(state, &ctx.repo.id, id).await,
395 None => None,400 None => None,
396 };401 };
402+ bump_live(state, &ctx.repo.id, &item, kind);
397 let sender = Sender::of(&user);403 let sender = Sender::of(&user);
398 let pull = matches!(kind, ItemKind::Pull);404 let pull = matches!(kind, ItemKind::Pull);
399 emit_milestone_change(405 emit_milestone_change(
crates/forge-web/src/pages/issue_parts.rsmodified+14 -0
@@ -123,6 +123,14 @@ pub(crate) fn parse_number(raw: &str) -> Result<i64> {
123 }123 }
124 }124 }
125 125
126+/// Wakes the live pages of an issue after a successful write to it. Pull requests have no live
127+/// page, so their writes wake nothing.
128+pub(crate) fn bump_live(state: &AppState, repo_id: &str, item: &Issue, kind: ItemKind) {
129+ if kind == ItemKind::Issue {
130+ state.live.bump_issue(repo_id, &item.id);
131+ }
132+}
133+
126 pub(crate) async fn issue_for(state: &AppState, ctx: &RepoCtx, number: i64) -> Result<Issue> {134 pub(crate) async fn issue_for(state: &AppState, ctx: &RepoCtx, number: i64) -> Result<Issue> {
127 match state.store.issue_by_number(&ctx.repo.id, number).await? {135 match state.store.issue_by_number(&ctx.repo.id, number).await? {
128 Some(issue) => Ok(issue),136 Some(issue) => Ok(issue),
@@ -1334,6 +1342,9 @@ pub(crate) async fn post_comment(
1334 .store1342 .store
1335 .add_comment(&item.id, &user.id, &form.body)1343 .add_comment(&item.id, &user.id, &form.body)
1336 .await?;1344 .await?;
1345+ if !pull {
1346+ state.live.bump_issue(&ctx.repo.id, &item.id);
1347+ }
1337 emit_comment(state, &ctx.repo, &sender, "created", pull, item, &comment).await;1348 emit_comment(state, &ctx.repo, &sender, "created", pull, item, &comment).await;
1338 notify::dispatch(1349 notify::dispatch(
1339 state,1350 state,
@@ -1351,6 +1362,9 @@ pub(crate) async fn post_comment(
1351 .store1362 .store
1352 .set_issue_state(&item.id, Some(&user.id), next, reason, Json::Null)1363 .set_issue_state(&item.id, Some(&user.id), next, reason, Json::Null)
1353 .await?;1364 .await?;
1365+ if changed && !pull {
1366+ state.live.bump_issue(&ctx.repo.id, &item.id);
1367+ }
1354 if changed {1368 if changed {
1355 let (action, activity) = if next == IssueState::Closed {1369 let (action, activity) = if next == IssueState::Closed {
1356 ("closed", Activity::Closed)1370 ("closed", Activity::Closed)
crates/forge-web/src/pages/issue_pin.rsmodified+2 -1
@@ -17,7 +17,7 @@ use crate::i18n::{self, Lang};
17 use crate::pages::issue_meta::{17 use crate::pages::issue_meta::{
18 action_error_at, item_from_path, item_href, refusal_message, triage_guard,18 action_error_at, item_from_path, item_href, refusal_message, triage_guard,
19 };19 };
20-use crate::pages::issue_parts::ItemKind;20+use crate::pages::issue_parts::{ItemKind, bump_live};
21 use crate::pages::repo_ctx::load_repo;21 use crate::pages::repo_ctx::load_repo;
22 use crate::state::AppState;22 use crate::state::AppState;
23 use crate::views::shell;23 use crate::views::shell;
@@ -60,6 +60,7 @@ async fn issue_pin_save(cx: &Cx, Form(form): Form<PinForm>) -> Result<impl View>
60 .store60 .store
61 .add_event(&issue.id, Some(&user.id), kind, Json::Null)61 .add_event(&issue.id, Some(&user.id), kind, Json::Null)
62 .await?;62 .await?;
63+ bump_live(state, &ctx.repo.id, &issue, ItemKind::Issue);
63 }64 }
64 }65 }
65 Err(e) => {66 Err(e) => {
crates/forge-web/src/pages/issue_view.rsmodified+7 -2
@@ -20,11 +20,12 @@ use crate::i18n;
20 use crate::i18n::issues::{self as g, K};20 use crate::i18n::issues::{self as g, K};
21 use crate::notify;21 use crate::notify;
22 use crate::pages::issue_parts::{22 use crate::pages::issue_parts::{
23- CommentForm, ItemKind, Posted, check_write, comment_for, comment_form, csrf_of,23+ CommentForm, ItemKind, Posted, bump_live, check_write, comment_for, comment_form, csrf_of,
24 discussion_timeline, issue_for, item_for, item_sidebar, load_discussion, load_sidebar,24 discussion_timeline, issue_for, item_for, item_sidebar, load_discussion, load_sidebar,
25 lock_message, may_change, may_converse, parse_number, post_comment, triage,25 lock_message, may_change, may_converse, parse_number, post_comment, triage,
26 };26 };
27 use crate::pages::issue_pin::pin_box;27 use crate::pages::issue_pin::pin_box;
28+use crate::pages::issues_live::item_live_url;
28 use crate::pages::notifications::notify_box_for;29 use crate::pages::notifications::notify_box_for;
29 use crate::pages::repo::repo_head;30 use crate::pages::repo::repo_head;
30 use crate::pages::repo_ctx::{RepoCtx, load_repo};31 use crate::pages::repo_ctx::{RepoCtx, load_repo};
@@ -86,12 +87,13 @@ async fn issue_page(
86 let login_href = "/login".to_owned();87 let login_href = "/login".to_owned();
87 let comment_action = format!("{issue_href}/comment");88 let comment_action = format!("{issue_href}/comment");
88 let labels_href = repo_href(&owner, &name, "labels.css", "");89 let labels_href = repo_href(&owner, &name, "labels.css", "");
90+ let live_href = item_live_url(&owner, &name, number);
89 91
90 let header = ctx.head(state, "issues").await?;92 let header = ctx.head(state, "issues").await?;
91 Ok(view! { cx =>93 Ok(view! { cx =>
92 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(labels_href.as_str()),94 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(labels_href.as_str()),
93 repo_head(head: header)95 repo_head(head: header)
94- <section class="issue-head">96+ <section class="issue-head" data-live=(live_href.as_str()) data-live-now="">
95 <h1 class="issue-heading">(issue.title.as_str()) " " <span class="issue-number">(number_label.as_str())</span></h1>97 <h1 class="issue-heading">(issue.title.as_str()) " " <span class="issue-number">(number_label.as_str())</span></h1>
96 <p class="issue-byline">98 <p class="issue-byline">
97 <span class=(state_class)>(state_text)</span>99 <span class=(state_class)>(state_text)</span>
@@ -286,6 +288,7 @@ async fn item_edit_save(cx: &Cx, kind: ItemKind, form: IssueForm) -> Result<impl
286 .store288 .store
287 .edit_issue(&item.id, &user.id, &title, &form.body)289 .edit_issue(&item.id, &user.id, &title, &form.body)
288 .await?;290 .await?;
291+ bump_live(state, &ctx.repo.id, &item, kind);
289 let pull = matches!(kind, ItemKind::Pull);292 let pull = matches!(kind, ItemKind::Pull);
290 emit_item_action(state, &ctx.repo, &Sender::of(&user), pull, number, "edited").await;293 emit_item_action(state, &ctx.repo, &Sender::of(&user), pull, number, "edited").await;
291 notify::dispatch_edit(state, &ctx.repo, &item, &user.id, &item.body, &form.body).await;294 notify::dispatch_edit(state, &ctx.repo, &item, &user.id, &item.body, &form.body).await;
@@ -415,6 +418,7 @@ async fn item_comment_edit_save(cx: &Cx, kind: ItemKind, form: CommentForm) -> R
415 .store418 .store
416 .edit_comment(&comment.id, &user.id, &form.body)419 .edit_comment(&comment.id, &user.id, &form.body)
417 .await?;420 .await?;
421+ bump_live(state, &ctx.repo.id, &item, kind);
418 let edited = Comment {422 let edited = Comment {
419 body: form.body.clone(),423 body: form.body.clone(),
420 edited: true,424 edited: true,
@@ -453,6 +457,7 @@ async fn item_comment_delete(cx: &Cx, kind: ItemKind, form: CsrfForm) -> Result<
453 return Err(forbidden().into());457 return Err(forbidden().into());
454 }458 }
455 state.store.delete_comment(&comment.id).await?;459 state.store.delete_comment(&comment.id).await?;
460+ bump_live(state, &ctx.repo.id, &item, kind);
456 let pull = matches!(kind, ItemKind::Pull);461 let pull = matches!(kind, ItemKind::Pull);
457 emit_comment(462 emit_comment(
458 state,463 state,
crates/forge-web/src/pages/issues_list.rsmodified+4 -1
@@ -20,6 +20,7 @@ use crate::i18n::issues::{self as g, K};
20 use crate::i18n::{self, Lang};20 use crate::i18n::{self, Lang};
21 use crate::notify::{self, Activity};21 use crate::notify::{self, Activity};
22 use crate::pages::issue_meta::{can_triage, form_all, form_field, form_pairs};22 use crate::pages::issue_meta::{can_triage, form_all, form_field, form_pairs};
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::{RepoHead, load_repo};25 use crate::pages::repo_ctx::{RepoHead, load_repo};
25 use crate::state::AppState;26 use crate::state::AppState;
@@ -486,11 +487,12 @@ async fn issues_list_page(cx: &Cx) -> Result<impl View> {
486 let empty_text = g::t(lang, K::NoIssuesMatch);487 let empty_text = g::t(lang, K::NoIssuesMatch);
487 let state_word = sel.state;488 let state_word = sel.state;
488 489
490+ let live_href = list_live_url(&owner_name, &repo_name);
489 let header = ctx.head(state, "issues").await?;491 let header = ctx.head(state, "issues").await?;
490 Ok(view! {492 Ok(view! {
491 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(labels_href.as_str()),493 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(labels_href.as_str()),
492 repo_head(head: header)494 repo_head(head: header)
493- <div class="issue-toolbar">495+ <div class="issue-toolbar" data-live=(live_href.as_str()) data-live-now="">
494 <nav class="issue-tabs" aria-label=(g::t(lang, K::IssuesByState))>496 <nav class="issue-tabs" aria-label=(g::t(lang, K::IssuesByState))>
495 <a class=(state_tab_class(state_word == "open")) href=(open_href.as_str())>(open_text.as_str())</a>497 <a class=(state_tab_class(state_word == "open")) href=(open_href.as_str())>(open_text.as_str())</a>
496 <a class=(state_tab_class(state_word == "closed")) href=(closed_href.as_str())>(closed_text.as_str())</a>498 <a class=(state_tab_class(state_word == "closed")) href=(closed_href.as_str())>(closed_text.as_str())</a>
@@ -832,6 +834,7 @@ async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> {
832 .set_issue_labels(&issue.id, &viewer.0.id, &ids)834 .set_issue_labels(&issue.id, &viewer.0.id, &ids)
833 .await?;835 .await?;
834 }836 }
837+ state.live.bump_issue(&ctx.repo.id, &issue.id);
835 emit_issue(state, &ctx.repo, &Sender::of(&viewer.0), "opened", &issue).await;838 emit_issue(state, &ctx.repo, &Sender::of(&viewer.0), "opened", &issue).await;
836 notify::dispatch(839 notify::dispatch(
837 state,840 state,
crates/forge-web/src/pages/issues_live.rsadded+55 -0
@@ -0,0 +1,55 @@
1+//! Live streams of the issue pages. The issue list, the labels and milestones pages and the repo
2+//! tabs follow the repo's issues (`/{owner}/{repo}/issues/live`). An issue page and its edit
3+//! history follow the issue (`/{owner}/{repo}/issues/{number}/live`), and also the repo's issues,
4+//! since its tabs show the counts. A `changed` event makes the page re-render in place (see
5+//! `nav.js`). Both streams take the repo read check of their page: a viewer who cannot read the
6+//! repo, or an issue that is not there, gets the same 404 as the page.
7+
8+use topcoat::Result;
9+use topcoat::context::{Cx, app_context};
10+use topcoat::router::error::not_found;
11+use topcoat::router::response::Response;
12+use topcoat::router::{path_param, route};
13+
14+use crate::live::{Topic, stream_wakes};
15+use crate::pages::issue_parts::parse_number;
16+use crate::pages::repo_ctx::load_repo;
17+use crate::state::AppState;
18+
19+path_param!(owner);
20+path_param!(repo);
21+path_param!(number);
22+
23+/// The stream URL of the issue list of `owner/repo`, and of its labels and milestones pages.
24+pub fn list_live_url(owner: &str, repo: &str) -> String {
25+ format!("/{owner}/{repo}/issues/live")
26+}
27+
28+/// The stream URL of one issue, for its page and its edit history.
29+pub fn item_live_url(owner: &str, repo: &str, number: i64) -> String {
30+ format!("/{owner}/{repo}/issues/{number}/live")
31+}
32+
33+/// The change stream of the issue list, labels and milestones pages.
34+#[route(GET "/{owner}/{repo}/issues/live")]
35+async fn issues_live(cx: &Cx) -> Result<Response> {
36+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
37+ let state = app_context::<AppState>(cx);
38+ stream_wakes(cx, &state.live, &[Topic::RepoIssues(ctx.repo.id.clone())])
39+}
40+
41+/// The change stream of one issue page.
42+#[route(GET "/{owner}/{repo}/issues/{number}/live")]
43+async fn issue_live(cx: &Cx) -> Result<Response> {
44+ let number = parse_number(path_param::<Number>(cx))?;
45+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
46+ let state = app_context::<AppState>(cx);
47+ let Some(issue) = state.store.issue_by_number(&ctx.repo.id, number).await? else {
48+ return Err(not_found().into());
49+ };
50+ let topics = [
51+ Topic::RepoIssues(ctx.repo.id.clone()),
52+ Topic::Issue(issue.id.clone()),
53+ ];
54+ stream_wakes(cx, &state.live, &topics)
55+}
crates/forge-web/src/pages/labels_page.rsmodified+24 -4
@@ -216,7 +216,12 @@ async fn label_create(cx: &Cx, Form(form): Form<LabelForm>) -> Result<impl View>
216 .create_label(&ctx.repo.id, &form.name, &form.color, &form.description)216 .create_label(&ctx.repo.id, &form.name, &form.color, &form.description)
217 .await;217 .await;
218 match result {218 match result {
219- Ok(_) => Err(see_other(back).into()),219+ Ok(_) => {
220+ app_context::<AppState>(cx)
221+ .live
222+ .bump_repo_issues(&ctx.repo.id);
223+ Err(see_other(back).into())
224+ }
220 Err(e) => {225 Err(e) => {
221 let message = refusal_message(e)?;226 let message = refusal_message(e)?;
222 Ok(view! {227 Ok(view! {
@@ -242,7 +247,12 @@ async fn label_update(cx: &Cx, Form(form): Form<LabelForm>) -> Result<impl View>
242 .update_label(&ctx.repo.id, id, &form.name, &form.color, &form.description)247 .update_label(&ctx.repo.id, id, &form.name, &form.color, &form.description)
243 .await;248 .await;
244 match result {249 match result {
245- Ok(()) => Err(see_other(back).into()),250+ Ok(()) => {
251+ app_context::<AppState>(cx)
252+ .live
253+ .bump_repo_issues(&ctx.repo.id);
254+ Err(see_other(back).into())
255+ }
246 Err(e) => {256 Err(e) => {
247 let message = refusal_message(e)?;257 let message = refusal_message(e)?;
248 Ok(view! {258 Ok(view! {
@@ -268,7 +278,12 @@ async fn label_defaults(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<impl View
268 .create_default_labels(&ctx.repo.id)278 .create_default_labels(&ctx.repo.id)
269 .await;279 .await;
270 match result {280 match result {
271- Ok(_) => Err(see_other(back).into()),281+ Ok(_) => {
282+ app_context::<AppState>(cx)
283+ .live
284+ .bump_repo_issues(&ctx.repo.id);
285+ Err(see_other(back).into())
286+ }
272 Err(e) => {287 Err(e) => {
273 let message = refusal_message(e)?;288 let message = refusal_message(e)?;
274 Ok(view! {289 Ok(view! {
@@ -294,7 +309,12 @@ async fn label_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<impl View>
294 .delete_label(&ctx.repo.id, id)309 .delete_label(&ctx.repo.id, id)
295 .await;310 .await;
296 match result {311 match result {
297- Ok(()) => Err(see_other(back).into()),312+ Ok(()) => {
313+ app_context::<AppState>(cx)
314+ .live
315+ .bump_repo_issues(&ctx.repo.id);
316+ Err(see_other(back).into())
317+ }
298 Err(e) => {318 Err(e) => {
299 let message = refusal_message(e)?;319 let message = refusal_message(e)?;
300 Ok(view! {320 Ok(view! {
crates/forge-web/src/pages/milestones_page.rsmodified+18 -3
@@ -297,7 +297,12 @@ async fn milestone_create(cx: &Cx, Form(form): Form<MilestoneForm>) -> Result<im
297 )297 )
298 .await;298 .await;
299 match result {299 match result {
300- Ok(_) => Err(see_other(back).into()),300+ Ok(_) => {
301+ app_context::<AppState>(cx)
302+ .live
303+ .bump_repo_issues(&ctx.repo.id);
304+ Err(see_other(back).into())
305+ }
301 Err(e) => {306 Err(e) => {
302 let message = refusal_message(e)?;307 let message = refusal_message(e)?;
303 Ok(view! {308 Ok(view! {
@@ -415,7 +420,12 @@ async fn milestone_edit_save(cx: &Cx, Form(form): Form<MilestoneForm>) -> Result
415 )420 )
416 .await;421 .await;
417 match result {422 match result {
418- Ok(()) => Err(see_other(back).into()),423+ Ok(()) => {
424+ app_context::<AppState>(cx)
425+ .live
426+ .bump_repo_issues(&ctx.repo.id);
427+ Err(see_other(back).into())
428+ }
419 Err(e) => {429 Err(e) => {
420 let message = refusal_message(e)?;430 let message = refusal_message(e)?;
421 Ok(view! {431 Ok(view! {
@@ -441,7 +451,12 @@ async fn milestone_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<impl Vi
441 .delete_milestone(&ctx.repo.id, id)451 .delete_milestone(&ctx.repo.id, id)
442 .await;452 .await;
443 match result {453 match result {
444- Ok(()) => Err(see_other(back).into()),454+ Ok(()) => {
455+ app_context::<AppState>(cx)
456+ .live
457+ .bump_repo_issues(&ctx.repo.id);
458+ Err(see_other(back).into())
459+ }
445 Err(e) => {460 Err(e) => {
446 let message = refusal_message(e)?;461 let message = refusal_message(e)?;
447 Ok(view! {462 Ok(view! {
crates/forge-web/src/pages/mod.rsmodified+1 -0
@@ -56,6 +56,7 @@ pub mod issue_pin;
56 mod issue_pin_tests;56 mod issue_pin_tests;
57 pub mod issue_view;57 pub mod issue_view;
58 pub mod issues_list;58 pub mod issues_list;
59+pub mod issues_live;
59 pub mod labels_css;60 pub mod labels_css;
60 pub mod labels_page;61 pub mod labels_page;
61 pub mod login;62 pub mod login;
crates/forge-web/src/pages/reactions.rsmodified+4 -1
@@ -13,7 +13,9 @@ use topcoat::router::error::{SeeOther, bad_request, forbidden, not_found, see_ot
13 use topcoat::router::{path_param, route};13 use topcoat::router::{path_param, route};
14 14
15 use crate::auth::require_csrf;15 use crate::auth::require_csrf;
16-use crate::pages::issue_parts::{ItemKind, comment_for, item_for, may_converse, parse_number};16+use crate::pages::issue_parts::{
17+ ItemKind, bump_live, comment_for, item_for, may_converse, parse_number,
18+};
17 use crate::pages::repo_ctx::load_repo;19 use crate::pages::repo_ctx::load_repo;
18 use crate::state::AppState;20 use crate::state::AppState;
19 use crate::views::repo_href;21 use crate::views::repo_href;
@@ -80,6 +82,7 @@ async fn react(cx: &Cx, kind: ItemKind, form: ReactionForm) -> Result<SeeOther>
80 .store82 .store
81 .toggle_reaction(target, &form.target_id, &user.id, reaction)83 .toggle_reaction(target, &form.target_id, &user.id, reaction)
82 .await?;84 .await?;
85+ bump_live(state, &ctx.repo.id, &item, kind);
83 let href = repo_href(86 let href = repo_href(
84 &ctx.repo.owner_name,87 &ctx.repo.owner_name,
85 &ctx.repo.name,88 &ctx.repo.name,
crates/forge-web/tests/browse_e2e.rsmodified+148 -0
@@ -766,3 +766,151 @@ async fn code_view_stream_follows_pushes() {
766 "private stream for its owner"766 "private stream for its owner"
767 );767 );
768 }768 }
769+
770+/// Reads the next event of `stream` and checks it is a `changed` event for `what`.
771+async fn assert_changed(stream: &mut reqwest::Response, what: &str) {
772+ let event = next_chunk(stream)
773+ .await
774+ .unwrap_or_else(|| panic!("no event after {what}"));
775+ assert!(event.contains("event: changed"), "{what}: {event}");
776+}
777+
778+/// Posts a form that must succeed with a redirect.
779+async fn post_redirect(http: &Http, path: &str, form: &[(&str, &str)], session: &str) {
780+ let res = http.post_form(path, form, Some(session)).await;
781+ assert_eq!(res.status, 303, "POST {path}: {}", res.body());
782+}
783+
784+#[tokio::test]
785+async fn issue_streams_follow_writes() {
786+ if !tool_on_path("git") {
787+ eprintln!("SKIP browse_e2e: `git` was not found on PATH, so the stream test is skipped");
788+ return;
789+ }
790+
791+ let root = tempfile::Builder::new()
792+ .prefix("filive")
793+ .tempdir_in("/tmp")
794+ .expect("temp dir");
795+ let dir = root.path().to_path_buf();
796+ let ports = pick_ports();
797+ let config = write_config(&dir, ports);
798+ run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
799+ let (_server, ports) = launch(&dir, ports).await;
800+ let http = Http::new(ports.http);
801+
802+ let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
803+ create_repo(&http, &tahinli, "pub", "public").await;
804+ create_repo(&http, &tahinli, "priv", "private").await;
805+
806+ // The list follows the repo's issues. Anyone can follow a public repo.
807+ let list_page = http.get("/tahinli/pub/issues", None).await;
808+ assert!(
809+ list_page
810+ .body()
811+ .contains(r#"data-live="/tahinli/pub/issues/live""#),
812+ "the list follows the repo"
813+ );
814+ let mut list = open_stream(&http, "/tahinli/pub/issues/live", None).await;
815+ assert_eq!(list.status().as_u16(), 200);
816+
817+ // Creating an issue wakes the list.
818+ let new_page = http.get("/tahinli/pub/issues/new", Some(&tahinli)).await;
819+ let csrf = input_value(&new_page.body(), "csrf");
820+ post_redirect(
821+ &http,
822+ "/tahinli/pub/issues/new",
823+ &[("csrf", &csrf), ("title", "First issue"), ("body", "Hello")],
824+ &tahinli,
825+ )
826+ .await;
827+ assert_changed(&mut list, "creating an issue").await;
828+
829+ // The issue page follows the issue, and the list stays subscribed to the repo's issues.
830+ let mut issue = open_stream(&http, "/tahinli/pub/issues/1/live", None).await;
831+ assert_eq!(issue.status().as_u16(), 200);
832+ let view = http.get("/tahinli/pub/issues/1", Some(&tahinli)).await;
833+ assert!(
834+ view.body()
835+ .contains(r#"data-live="/tahinli/pub/issues/1/live""#),
836+ "the issue page follows the issue"
837+ );
838+ let target = input_value(&view.body(), "target_id");
839+
840+ let writes: [(&str, &[(&str, &str)], &str); 8] = [
841+ (
842+ "/tahinli/pub/issues/1/comment",
843+ &[
844+ ("csrf", &csrf),
845+ ("action", "comment"),
846+ ("body", "A comment"),
847+ ],
848+ "a comment",
849+ ),
850+ (
851+ "/tahinli/pub/issues/1/edit",
852+ &[
853+ ("csrf", &csrf),
854+ ("title", "First issue, edited"),
855+ ("body", "Hello again"),
856+ ],
857+ "an edit of the issue",
858+ ),
859+ (
860+ "/tahinli/pub/issues/1/comment",
861+ &[("csrf", &csrf), ("action", "close_completed"), ("body", "")],
862+ "closing the issue",
863+ ),
864+ (
865+ "/tahinli/pub/issues/1/comment",
866+ &[("csrf", &csrf), ("action", "reopen"), ("body", "")],
867+ "reopening the issue",
868+ ),
869+ (
870+ "/tahinli/pub/issues/1/pin",
871+ &[("csrf", &csrf), ("pinned", "1")],
872+ "pinning the issue",
873+ ),
874+ (
875+ "/tahinli/pub/issues/1/reactions",
876+ &[
877+ ("csrf", &csrf),
878+ ("target_kind", "issue"),
879+ ("target_id", &target),
880+ ("reaction", "heart"),
881+ ],
882+ "a reaction",
883+ ),
884+ (
885+ "/tahinli/pub/labels",
886+ &[("csrf", &csrf), ("name", "bug"), ("color", "#d73a4a")],
887+ "a new label",
888+ ),
889+ (
890+ "/tahinli/pub/milestones",
891+ &[("csrf", &csrf), ("title", "v1")],
892+ "a new milestone",
893+ ),
894+ ];
895+ for (path, form, what) in writes {
896+ post_redirect(&http, path, form, &tahinli).await;
897+ assert_changed(&mut list, what).await;
898+ assert_changed(&mut issue, what).await;
899+ }
900+
901+ // A private repo streams only to a viewer who can read it.
902+ let anonymous = open_stream(&http, "/tahinli/priv/issues/live", None).await;
903+ assert_eq!(
904+ anonymous.status().as_u16(),
905+ 404,
906+ "private list without a session"
907+ );
908+ let anonymous_issue = open_stream(&http, "/tahinli/priv/issues/1/live", None).await;
909+ assert_eq!(
910+ anonymous_issue.status().as_u16(),
911+ 404,
912+ "private issue without a session"
913+ );
914+ let member = open_stream(&http, "/tahinli/priv/issues/live", Some(tahinli.as_str())).await;
915+ assert_eq!(member.status().as_u16(), 200, "private list for its owner");
916+}
docs/architecture.mdmodified+4 -0
@@ -246,6 +246,10 @@ Topcoat's builder-wide compression is off on the public router, so it cannot com
246 246
247 Content types outside the list (`application/x-git-*`, `application/octet-stream`, archives, images) are never compressed. The raw user-content listener has compression off because its ETag and Content-Length must match the stored bytes.247 Content types outside the list (`application/x-git-*`, `application/octet-stream`, archives, images) are never compressed. The raw user-content listener has compression off because its ETag and Content-Length must match the stored bytes.
248 248
249+### Live pages
250+
251+A page that shows changing state renders `data-live="<stream URL>"`. The browser opens one EventSource for it (`assets/nav.js`). The server bumps a topic in `LiveHub` (`crates/forge-web/src/live.rs`) after each successful write, and the stream sends one `changed` event per wake. The page then re-renders in place, with the scroll, open dropdowns and the text and caret of every edited field kept. Nothing polls. Issue pages follow two topics: the repo's issues (the list, labels, milestones and tabs) and the one issue. A stream checks the same read permission as its page, so a private repo answers 404 to a viewer who cannot read it. The code view follows its branch and the refs of its repo. Pull request pages do not follow yet.
252+
249 ## 6. Authorization model253 ## 6. Authorization model
250 254
251 One function: `forge_core::authz::authorize(actor: Option<&User>, repo: &Repo, collaborator_role: Option<Role>, action: Action) -> Result<(), Denied>`.255 One function: `forge_core::authz::authorize(actor: Option<&User>, repo: &Repo, collaborator_role: Option<Role>, action: Action) -> Result<(), Denied>`.