forge
Explore
Log in

Don't you dare go Hollow

Wiki and snippet pages update live

Browse files at this commit

aedd20e16846a8571a2e8464830a9adda1e5225dAhmet Kaan GümüşParent: 6388b13
  • feat
    • wiki and snippet pages update live
Show full message
⚡ feat: wiki and snippet pages update live

Wiki home, page list, page view and history follow Topic::Wiki (saves and wiki pushes bump it).
Snippet list and snippet page with revisions follow Topic::Snippets and Topic::Snippet.
Edit and new forms carry no data-live.
crates/forge-web/src/internal.rsmodified+1 -0
@@ -164,6 +164,7 @@ async fn hook_endpoint(
164164 // A wiki push changes neither the code repo's refs nor its CI, pull requests or events.
165165 // It still goes to the standby.
166166 record_wiki_push(&state.store, &req).await;
167+ crate::pages::wiki_live::bump_wiki(state, &req.repo_id);
167168 crate::replication::enqueue_repo(state, &req.repo_id);
168169 HookResponse::allow()
169170 }
crates/forge-web/src/live.rsmodified+8 -0
@@ -70,6 +70,14 @@ pub enum Topic {
7070 /// One discussion: its body, comments, reactions, answer and lock state. Keyed by discussion
7171 /// id. Bumped by [`crate::pages::discussion_live`].
7272 Discussion(String),
73+ /// A repo's wiki: a page was saved, or a push changed the wiki's main branch. Keyed by repo id.
74+ /// Bumped by [`crate::pages::wiki_live`] and by the wiki push hook.
75+ Wiki(String),
76+ /// The snippet list: a snippet was created, changed or deleted. Global; each viewer's list is
77+ /// fingerprinted, so a bump that changes nothing the viewer sees sends nothing.
78+ Snippets,
79+ /// One snippet: its files, title, visibility and revisions. Keyed by snippet id.
80+ Snippet(String),
7381 }
7482
7583 /// The open topics, each with the counter its subscribers wait on.
crates/forge-web/src/pages/mod.rsmodified+2 -0
@@ -125,7 +125,9 @@ pub mod settings_tokens;
125125 pub mod setup;
126126 pub mod snippet_raw;
127127 pub mod snippets;
128+pub mod snippets_live;
128129 pub mod star;
129130 pub mod theme_cookie;
130131 pub mod tree;
131132 pub mod wiki;
133+pub mod wiki_live;
crates/forge-web/src/pages/snippets.rsmodified+23 -8
@@ -23,6 +23,7 @@ use crate::auth::{current_user, require_csrf, require_user};
2323 use crate::i18n::community::{self as g, K};
2424 use crate::i18n::{self, Lang};
2525 use crate::pages::snippet_raw::snippet_raw_url;
26+use crate::pages::snippets_live::{bump_snippet, item_live_url, list_live_url};
2627 use crate::render::highlight::highlight_lines;
2728 use crate::render::markdown::render_markdown;
2829 use crate::state::AppState;
@@ -244,7 +245,11 @@ fn short_time(stamp: &str) -> String {
244245 }
245246
246247 /// The snippet if the viewer may read it, else 404.
247-async fn readable(cx: &Cx, viewer_id: Option<&str>, snippet_id: &str) -> Result<Snippet> {
248+pub(crate) async fn readable(
249+ cx: &Cx,
250+ viewer_id: Option<&str>,
251+ snippet_id: &str,
252+) -> Result<Snippet> {
248253 let store = &app_context::<AppState>(cx).store;
249254 match store.get_snippet(snippet_id).await? {
250255 Some(snippet) if snippet.is_visible_to(viewer_id) => Ok(snippet),
@@ -262,9 +267,14 @@ async fn owned(cx: &Cx, user: &User, snippet_id: &str) -> Result<Snippet> {
262267 }
263268
264269 #[component]
265-async fn snippet_list_body(lang: Lang, rows: Vec<ListRow>, signed_in: bool) -> Result<impl View> {
270+async fn snippet_list_body(
271+ lang: Lang,
272+ rows: Vec<ListRow>,
273+ signed_in: bool,
274+ live: Option<String>,
275+) -> Result<impl View> {
266276 Ok(view! {
267- <section class="page-head">
277+ <section class="page-head" data-live=(live.as_deref())>
268278 <h1>(g::t(lang, K::Snippets))</h1>
269279 if signed_in {
270280 <a class="button primary" href="/snippets/new">(g::t(lang, K::NewSnippet))</a>
@@ -445,13 +455,14 @@ async fn snippet_body(
445455 updated: &str,
446456 files: Vec<FileView>,
447457 owner_csrf: Option<String>,
458+ live: Option<String>,
448459 ) -> Result<impl View> {
449460 let is_owner = owner_csrf.is_some();
450461 let edit_href = format!("/snippets/{snippet_id}/edit");
451462 let history_href = format!("/snippets/{snippet_id}/revisions");
452463 let delete_action = format!("/snippets/{snippet_id}/delete");
453464 Ok(view! {
454- <section class="page-head snippet-view-head">
465+ <section class="page-head snippet-view-head" data-live=(live.as_deref())>
455466 <h1>(title)</h1>
456467 <span class="muted small">(owner) " · " (visibility) " · " (g::updated_on(lang, updated))</span>
457468 </section>
@@ -497,11 +508,12 @@ async fn revisions_body(
497508 snippet_id: &str,
498509 title: &str,
499510 revisions: Vec<RevisionView>,
511+ live: Option<String>,
500512 ) -> Result<impl View> {
501513 let back = format!("/snippets/{snippet_id}");
502514 let heading = g::revisions_of(lang, title);
503515 Ok(view! {
504- <section class="page-head">
516+ <section class="page-head" data-live=(live.as_deref())>
505517 <h1>(heading.as_str())</h1>
506518 <a href=(back)>(g::t(lang, K::BackToSnippet))</a>
507519 </section>
@@ -573,7 +585,7 @@ async fn snippets_list(cx: &Cx) -> Result<impl View> {
573585 let title = g::t(lang, K::Snippets);
574586 Ok(view! {
575587 shell(title: title, viewer: viewer.as_ref(),
576- snippet_list_body(lang: lang, rows: rows, signed_in: signed_in)
588+ snippet_list_body(lang: lang, rows: rows, signed_in: signed_in, live: Some(list_live_url().to_owned()))
577589 )
578590 })
579591 }
@@ -632,6 +644,7 @@ async fn snippet_create(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R
632644 serde_json::Value::Null,
633645 )
634646 .await;
647+ bump_snippet(app_context::<AppState>(cx), &snippet.id);
635648 return Err(see_other(format!("/snippets/{}", snippet.id)).into());
636649 }
637650 Err(message) => error = Some(message),
@@ -669,7 +682,7 @@ async fn snippet_view(cx: &Cx) -> Result<impl View> {
669682 snippet_body(lang: lang, snippet_id: snippet.id.as_str(), title: snippet.title.as_str(),
670683 owner: snippet.owner_name.as_str(), description: snippet.description.as_str(),
671684 visibility: visibility, updated: updated.as_str(), files: files,
672- owner_csrf: owner_csrf)
685+ owner_csrf: owner_csrf, live: Some(item_live_url(snippet.id.as_str())))
673686 )
674687 })
675688 }
@@ -735,6 +748,7 @@ async fn snippet_update(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R
735748 serde_json::Value::Null,
736749 )
737750 .await;
751+ bump_snippet(app_context::<AppState>(cx), &snippet.id);
738752 return Err(see_other(format!("/snippets/{}", snippet.id)).into());
739753 }
740754 Err(message) => error = Some(message),
@@ -778,7 +792,7 @@ async fn snippet_revisions(cx: &Cx) -> Result<impl View> {
778792 Ok(view! {
779793 shell(title: snippet.title.as_str(), viewer: viewer.as_ref(),
780794 revisions_body(lang: lang, snippet_id: snippet.id.as_str(), title: snippet.title.as_str(),
781- revisions: rows)
795+ revisions: rows, live: Some(item_live_url(snippet.id.as_str())))
782796 )
783797 })
784798 }
@@ -803,6 +817,7 @@ async fn snippet_delete(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R
803817 serde_json::Value::Null,
804818 )
805819 .await;
820+ bump_snippet(app_context::<AppState>(cx), &snippet.id);
806821 }
807822 Ok(see_other("/snippets"))
808823 }
crates/forge-web/src/pages/snippets_live.rsadded+125 -0
@@ -0,0 +1,125 @@
1+//! Live snippets. The snippet list (`/snippets`) follows [`Topic::Snippets`] at `/snippets/events`,
2+//! and a snippet page and its revisions follow [`Topic::Snippet`] at `/snippets/{id}/events`. Both
3+//! fingerprint what the viewer sees, so a bump that changes nothing visible sends nothing.
4+//!
5+//! Every write bumps after the store call succeeded, through [`bump_snippet`], from the create,
6+//! update and delete routes of `snippets.rs`. The new and edit forms carry no `data-live`: a form
7+//! is never redrawn while someone types in it.
8+//!
9+//! Auth is the page's own: the list is the viewer's list, and a snippet stream answers the same
10+//! 404 as the page to a viewer who cannot read the snippet (a private one, unless it is theirs).
11+
12+use forge_core::store::Store;
13+use forge_core::store::snippets::{Snippet, SnippetSummary};
14+use topcoat::Result;
15+use topcoat::context::{Cx, app_context};
16+use topcoat::router::response::Response;
17+use topcoat::router::{path_param, route};
18+
19+use crate::auth::current_user;
20+use crate::live::{Topic, stream_changes};
21+use crate::pages::snippets::readable;
22+use crate::state::AppState;
23+
24+path_param!(id);
25+
26+/// The stream URL of the snippet list.
27+pub fn list_live_url() -> &'static str {
28+ "/snippets/events"
29+}
30+
31+/// The stream URL of one snippet, for its page and its revisions.
32+pub fn item_live_url(snippet_id: &str) -> String {
33+ format!("/snippets/{snippet_id}/events")
34+}
35+
36+/// A snippet was created, changed or deleted: the list and the snippet's own pages follow it.
37+pub fn bump_snippet(state: &AppState, snippet_id: &str) {
38+ state.live.bump(&Topic::Snippets);
39+ state.live.bump(&Topic::Snippet(snippet_id.to_owned()));
40+}
41+
42+/// What the list shows the viewer, as one string.
43+async fn list_fingerprint(store: &Store, viewer_id: Option<&str>) -> Result<String> {
44+ let summaries: Vec<SnippetSummary> = store.list_snippets(viewer_id).await?;
45+ Ok(summaries
46+ .iter()
47+ .map(|s| {
48+ format!(
49+ "{} {} {} {} {} {}",
50+ s.id,
51+ s.title,
52+ s.owner_name,
53+ s.visibility.as_str(),
54+ s.updated_at,
55+ s.file_count
56+ )
57+ })
58+ .collect::<Vec<_>>()
59+ .join("\n"))
60+}
61+
62+/// What one snippet page shows the viewer, as one string. `gone` when the viewer cannot read it.
63+fn snippet_fingerprint(viewer_id: Option<&str>, snippet: Option<Snippet>) -> String {
64+ match snippet {
65+ Some(s) if s.is_visible_to(viewer_id) => {
66+ let files: Vec<String> = s
67+ .files
68+ .iter()
69+ .map(|f| format!("{}\n{}", f.name, f.content))
70+ .collect();
71+ format!(
72+ "{}\n{}\n{}\n{}\n{}\n{}",
73+ s.title,
74+ s.description,
75+ s.owner_name,
76+ s.visibility.as_str(),
77+ s.updated_at,
78+ files.join("\n")
79+ )
80+ }
81+ _ => "gone".to_owned(),
82+ }
83+}
84+
85+/// The change stream of the snippet list. Auth is the list's: the viewer's own visible snippets.
86+#[route(GET "/snippets/events")]
87+async fn snippets_events(cx: &Cx) -> Result<Response> {
88+ let viewer = current_user(cx).await?;
89+ let viewer_id = viewer.as_ref().map(|(user, _)| user.id.clone());
90+ let state = app_context::<AppState>(cx);
91+ let store = state.store.clone();
92+ stream_changes(cx, &state.live, &[Topic::Snippets], move || {
93+ let store = store.clone();
94+ let viewer_id = viewer_id.clone();
95+ async move { list_fingerprint(&store, viewer_id.as_deref()).await }
96+ })
97+ .await
98+}
99+
100+/// The change stream of one snippet, its page and its revisions. Auth is the page's: the snippet
101+/// must be readable by the viewer.
102+#[route(GET "/snippets/{id}/events")]
103+async fn snippet_events(cx: &Cx) -> Result<Response> {
104+ let snippet_id = path_param::<Id>(cx).to_owned();
105+ let viewer = current_user(cx).await?;
106+ let viewer_id = viewer.as_ref().map(|(user, _)| user.id.clone());
107+ readable(cx, viewer_id.as_deref(), &snippet_id).await?;
108+ let state = app_context::<AppState>(cx);
109+ let store = state.store.clone();
110+ stream_changes(
111+ cx,
112+ &state.live,
113+ &[Topic::Snippet(snippet_id.clone())],
114+ move || {
115+ let store = store.clone();
116+ let viewer_id = viewer_id.clone();
117+ let snippet_id = snippet_id.clone();
118+ async move {
119+ let snippet = store.get_snippet(&snippet_id).await?;
120+ Ok(snippet_fingerprint(viewer_id.as_deref(), snippet))
121+ }
122+ },
123+ )
124+ .await
125+}
crates/forge-web/src/pages/wiki.rsmodified+11 -8
@@ -25,6 +25,7 @@ use crate::i18n::community::{self as g, K};
2525 use crate::i18n::{self, Lang};
2626 use crate::pages::repo::repo_head;
2727 use crate::pages::repo_ctx::{RepoCtx, load_repo};
28+use crate::pages::wiki_live::{bump_wiki, page_live_url, wiki_live_url};
2829 use crate::render::markdown::render_markdown;
2930 use crate::state::AppState;
3031 use crate::views::{alert, repo_href, shell};
@@ -62,12 +63,12 @@ where
6263 }
6364
6465 /// The wiki directory of the repo, whether or not it exists yet.
65-fn wiki_dir(state: &AppState, ctx: &RepoCtx) -> Result<PathBuf> {
66+pub(crate) fn wiki_dir(state: &AppState, ctx: &RepoCtx) -> Result<PathBuf> {
6667 Ok(wiki_path(&state.config.data_dir, &ctx.repo.id).map_err(forge_core::Error::from)?)
6768 }
6869
6970 /// 404 unless the repo's wiki is on. The header tab is hidden in the same case.
70-async fn ensure_enabled(state: &AppState, ctx: &RepoCtx) -> Result<()> {
71+pub(crate) async fn ensure_enabled(state: &AppState, ctx: &RepoCtx) -> Result<()> {
7172 if state.store.wiki_enabled(&ctx.repo.id).await? {
7273 Ok(())
7374 } else {
@@ -155,12 +156,13 @@ async fn wiki_head(
155156 can_write: bool,
156157 title: String,
157158 extra: Vec<(String, String)>,
159+ live: Option<String>,
158160 ) -> Result<impl View> {
159161 let home = repo_href(&owner, &repo, "wiki", "");
160162 let pages = repo_href(&owner, &repo, "wiki", "-/pages");
161163 let new = repo_href(&owner, &repo, "wiki", "-/new");
162164 Ok(view! {
163- <section class="page-head wiki-head">
165+ <section class="page-head wiki-head" data-live=(live.as_deref())>
164166 <h1>(title.as_str())</h1>
165167 <nav class="wiki-actions" aria-label=(g::t(lang, K::PageNav))>
166168 <a class="button" href=(home)>(g::t(lang, K::Home))</a>
@@ -363,7 +365,7 @@ async fn wiki_home(cx: &Cx) -> Result<impl View> {
363365 Ok(view! { cx =>
364366 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
365367 repo_head(head: header)
366- wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write, title: head_title.clone(), extra: links.clone())
368+ wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write, title: head_title.clone(), extra: links.clone(), live: Some(wiki_live_url(&owner_name, &repo_name)))
367369 if let Some(html) = body_html.clone() {
368370 wiki_view_body(html: html)
369371 }
@@ -397,7 +399,7 @@ async fn wiki_pages(cx: &Cx) -> Result<impl View> {
397399 Ok(view! { cx =>
398400 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
399401 repo_head(head: header)
400- wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write, title: g::t(lang, K::AllPages).to_owned(), extra: Vec::new())
402+ wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write, title: g::t(lang, K::AllPages).to_owned(), extra: Vec::new(), live: Some(wiki_live_url(&owner_name, &repo_name)))
401403 wiki_list_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), names: names)
402404 )
403405 })
@@ -434,7 +436,7 @@ async fn wiki_page_view(cx: &Cx) -> Result<impl View> {
434436 Ok(view! { cx =>
435437 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
436438 repo_head(head: header)
437- wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write, title: page_name.replace('-', " "), extra: page_links(lang, &owner_name, &repo_name, &page_name, can_write))
439+ wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write, title: page_name.replace('-', " "), extra: page_links(lang, &owner_name, &repo_name, &page_name, can_write), live: Some(page_live_url(&owner_name, &repo_name, &page_name)))
438440 wiki_view_body(html: html)
439441 )
440442 })
@@ -469,7 +471,7 @@ async fn wiki_page_history(cx: &Cx) -> Result<impl View> {
469471 Ok(view! { cx =>
470472 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
471473 repo_head(head: header)
472- wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: ctx.can_write(), title: format!("{} \u{b7} {}", page_name.replace('-', " "), g::t(lang, K::History)), extra: vec![(g::t(lang, K::BackToPage).to_owned(), repo_href(&owner_name, &repo_name, "wiki", &page_name))])
474+ wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: ctx.can_write(), title: format!("{} \u{b7} {}", page_name.replace('-', " "), g::t(lang, K::History)), extra: vec![(g::t(lang, K::BackToPage).to_owned(), repo_href(&owner_name, &repo_name, "wiki", &page_name))], live: Some(page_live_url(&owner_name, &repo_name, &page_name)))
473475 wiki_history_body(lang: lang, rows: rows)
474476 )
475477 })
@@ -518,7 +520,7 @@ async fn edit_screen(
518520 Ok(view! { cx =>
519521 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
520522 repo_head(head: header)
521- wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: !is_new, title: head_title.clone(), extra: Vec::new())
523+ wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: !is_new, title: head_title.clone(), extra: Vec::new(), live: None)
522524 wiki_edit_body(lang: lang, action: action, csrf: csrf, base: base, name: name.clone(), is_new: is_new, content: content, error: error)
523525 )
524526 })
@@ -667,6 +669,7 @@ async fn save(cx: &Cx, ctx: &RepoCtx, form: &EditForm, name: &str) -> Result<Sav
667669 serde_json::json!({ "page": name, "commit": commit }),
668670 )
669671 .await;
672+ bump_wiki(state, &ctx.repo.id);
670673 crate::replication::enqueue_repo(state, &ctx.repo.id);
671674 tracing::info!(actor_id = %user.id, repo_id = %ctx.repo.id, page = %name, "wiki page saved");
672675 Ok(SaveOutcome::Saved(page_href(ctx, name)))
crates/forge-web/src/pages/wiki_live.rsadded+100 -0
@@ -0,0 +1,100 @@
1+//! Live wiki pages. The wiki home and the page list follow the wiki as a whole, at
2+//! `/{o}/{r}/wiki/-/events`, and fingerprint it by the head commit of the wiki's main branch. A page
3+//! and its history follow that one page, at `/{o}/{r}/wiki/{page}/events`, and fingerprint its text
4+//! and its commits, so a change to another page sends nothing. Both follow [`Topic::Wiki`].
5+//!
6+//! Every write reaches the topic through one of these paths:
7+//! - A save from the web editor: [`bump_wiki`], called by `wiki::save` after the commit.
8+//! - A push to the wiki repo: [`bump_wiki`], from the wiki branch of the post-receive hook.
9+//!
10+//! Both streams take the wiki read check of their page: a viewer who cannot read the repo, or a
11+//! wiki that is off, gets the same 404 as the page.
12+
13+use std::path::{Path, PathBuf};
14+
15+use forge_git::GitEnv;
16+use forge_git::wiki::{self, valid_page_name};
17+use topcoat::Result;
18+use topcoat::context::{Cx, app_context};
19+use topcoat::router::error::not_found;
20+use topcoat::router::response::Response;
21+use topcoat::router::{path_param, route};
22+
23+use crate::live::{Topic, stream_changes};
24+use crate::pages::repo_ctx::load_repo;
25+use crate::pages::wiki::{ensure_enabled, wiki_dir};
26+use crate::state::AppState;
27+
28+path_param!(owner);
29+path_param!(repo);
30+path_param!(wiki_page);
31+
32+/// The stream URL of the wiki as a whole: the home page and the page list follow it.
33+pub fn wiki_live_url(owner: &str, repo: &str) -> String {
34+ format!("/{owner}/{repo}/wiki/-/events")
35+}
36+
37+/// The stream URL of one wiki page, for its page and its history.
38+pub fn page_live_url(owner: &str, repo: &str, page: &str) -> String {
39+ format!("/{owner}/{repo}/wiki/{page}/events")
40+}
41+
42+/// A write changed the wiki of `repo_id`: a page was saved, or a push moved its main branch.
43+pub fn bump_wiki(state: &AppState, repo_id: &str) {
44+ state.live.bump(&Topic::Wiki(repo_id.to_owned()));
45+}
46+
47+/// The head commit of the wiki's main branch, or empty for a wiki with no pages.
48+async fn head_fingerprint(dir: PathBuf) -> Result<String> {
49+ let head = tokio::task::spawn_blocking(move || wiki::head_commit(&dir)).await??;
50+ Ok(head.unwrap_or_default())
51+}
52+
53+/// The state one page shows: its text, and the commits that touched it. `gone` when it is absent.
54+async fn page_fingerprint(git: &GitEnv, dir: &Path, name: &str) -> Result<String> {
55+ let revs = wiki::page_history(git, dir, name).await?;
56+ let (dir, name) = (dir.to_path_buf(), name.to_owned());
57+ let text = tokio::task::spawn_blocking(move || wiki::read_page(&dir, &name)).await??;
58+ let commits: Vec<&str> = revs.iter().map(|rev| rev.oid.as_str()).collect();
59+ Ok(match text {
60+ Some(text) => format!("{text}\n{}", commits.join(" ")),
61+ None => "gone".to_owned(),
62+ })
63+}
64+
65+/// The change stream of the wiki home and the page list. Auth is the repo read check, then the
66+/// wiki's on switch.
67+#[route(GET "/{owner}/{repo}/wiki/-/events")]
68+async fn wiki_events(cx: &Cx) -> Result<Response> {
69+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
70+ let state = app_context::<AppState>(cx);
71+ ensure_enabled(state, &ctx).await?;
72+ let dir = wiki_dir(state, &ctx)?;
73+ let topic = Topic::Wiki(ctx.repo.id.clone());
74+ stream_changes(cx, &state.live, &[topic], move || {
75+ head_fingerprint(dir.clone())
76+ })
77+ .await
78+}
79+
80+/// The change stream of one wiki page, its page view and its history.
81+#[route(GET "/{owner}/{repo}/wiki/{wiki_page}/events")]
82+async fn wiki_page_events(cx: &Cx) -> Result<Response> {
83+ let page_name = path_param::<WikiPage>(cx).to_owned();
84+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
85+ let state = app_context::<AppState>(cx);
86+ ensure_enabled(state, &ctx).await?;
87+ if !valid_page_name(&page_name) {
88+ return Err(not_found().into());
89+ }
90+ let dir = wiki_dir(state, &ctx)?;
91+ let git = state.git.clone();
92+ let topic = Topic::Wiki(ctx.repo.id.clone());
93+ stream_changes(cx, &state.live, &[topic], move || {
94+ let git = git.clone();
95+ let dir = dir.clone();
96+ let page_name = page_name.clone();
97+ async move { page_fingerprint(&git, &dir, &page_name).await }
98+ })
99+ .await
100+}
crates/forge-web/tests/wiki_e2e.rsmodified+138 -0
@@ -440,3 +440,141 @@ async fn wiki_end_to_end() {
440440
441441 drop(server);
442442 }
443+
444+/// Opens a wiki stream as `cookie` (or anonymously) and reads its `retry` field.
445+async fn open_wiki_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::Response {
446+ let mut req = http.client.get(format!("{}{path}", http.base));
447+ if let Some(cookie) = cookie {
448+ req = req.header(COOKIE, cookie);
449+ }
450+ let mut res = req.send().await.expect("stream request");
451+ assert_eq!(res.status().as_u16(), 200, "stream {path}");
452+ let retry = tokio::time::timeout(Duration::from_secs(5), res.chunk())
453+ .await
454+ .expect("the retry field")
455+ .expect("stream chunk")
456+ .expect("stream still open");
457+ assert!(String::from_utf8_lossy(&retry).contains("retry: 1000"));
458+ res
459+}
460+
461+/// Waits for the next event of a wiki stream, which must be `changed`.
462+async fn next_wiki_change(res: &mut reqwest::Response, what: &str) {
463+ let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk())
464+ .await
465+ .unwrap_or_else(|_| panic!("no event after {what}"))
466+ .expect("stream chunk")
467+ .expect("stream still open");
468+ let text = String::from_utf8_lossy(&chunk);
469+ assert!(text.contains("event: changed"), "{what}: {text}");
470+}
471+
472+/// The wiki pages render their streams. A save from the web and a push from the wiki repo each
473+/// wake the wiki streams, and a viewer who cannot read the repo gets 404 from them.
474+#[tokio::test]
475+async fn wiki_streams_follow_saves_and_pushes() {
476+ if !tool_on_path("git") {
477+ eprintln!("SKIP wiki live: `git` was not found on PATH");
478+ return;
479+ }
480+
481+ let root = tempfile::Builder::new()
482+ .prefix("fwl")
483+ .tempdir_in("/tmp")
484+ .expect("temp dir");
485+ let dir = root.path().to_path_buf();
486+ let ports = pick_ports();
487+ let config = write_config(&dir, ports);
488+
489+ admin(&config, &["create-user", "tahinli", "--admin"]);
490+ for name in ["bob", "dave"] {
491+ admin(&config, &["create-user", name]);
492+ }
493+ {
494+ let store = Store::open(&dir.join("forge.db"))
495+ .await
496+ .expect("open store");
497+ let bob = store.user_by_username("bob").await.unwrap().expect("bob");
498+ let proj = store
499+ .create_repo(&bob.id, "proj", "", Visibility::Public, "main")
500+ .await
501+ .expect("repo");
502+ init_bare(&dir, &proj.id);
503+ let vault = store
504+ .create_repo(&bob.id, "vault", "", Visibility::Private, "main")
505+ .await
506+ .expect("private repo");
507+ init_bare(&dir, &vault.id);
508+ }
509+
510+ let (server, ports) = launch(&dir, ports).await;
511+ let http = Http::new(ports.http);
512+ let bob = login(&http, "bob").await;
513+ let dave = login(&http, "dave").await;
514+
515+ // The page list follows the wiki stream.
516+ let listing = page_body(&http, "/bob/proj/wiki/-/pages", Some(&bob)).await;
517+ assert!(
518+ listing
519+ .body
520+ .contains(r#"data-live="/bob/proj/wiki/-/events""#),
521+ "page list follows the wiki stream"
522+ );
523+
524+ // Bob opens the wiki stream, then creates Home on the web: the stream wakes.
525+ let mut wiki_events = open_wiki_stream(&http, "/bob/proj/wiki/-/events", Some(&bob)).await;
526+ let csrf = input_value(
527+ &http.get("/bob/proj/wiki/-/new", Some(&bob)).await.body,
528+ "csrf",
529+ );
530+ let created = http
531+ .post_form(
532+ "/bob/proj/wiki/-/new",
533+ &[
534+ ("csrf", &csrf),
535+ ("name", "Home"),
536+ ("base", ""),
537+ ("content", "# Welcome\n"),
538+ ("message", "first page"),
539+ ],
540+ Some(&bob),
541+ )
542+ .await;
543+ assert_eq!(created.status, 303, "create Home: {}", created.body);
544+ next_wiki_change(&mut wiki_events, "a web save").await;
545+
546+ // The page's own stream follows Home, and a push from git wakes it.
547+ let home = page_body(&http, "/bob/proj/wiki/Home", Some(&bob)).await;
548+ assert!(
549+ home.body
550+ .contains(r#"data-live="/bob/proj/wiki/Home/events""#),
551+ "wiki page follows its stream"
552+ );
553+ let mut home_events = open_wiki_stream(&http, "/bob/proj/wiki/Home/events", Some(&bob)).await;
554+ let token = create_token(&http, &bob, "wiki-live").await;
555+ let work = dir.join("wiki-live-work");
556+ let url = format!(
557+ "http://bob:{token}@127.0.0.1:{}/bob/proj.wiki.git",
558+ ports.http
559+ );
560+ ok(
561+ &git(&dir, &["clone", "-q", &url, path_str(&work)]),
562+ "clone wiki over HTTPS",
563+ );
564+ commit_file(&work, "Home.md", "# Pushed\n", "edit from git");
565+ ok(
566+ &git(&work, &["push", "-q", "origin", "HEAD:main"]),
567+ "push to wiki",
568+ );
569+ next_wiki_change(&mut home_events, "a push to the wiki").await;
570+
571+ // A viewer who cannot read the private repo gets 404 from its streams.
572+ for path in ["/bob/vault/wiki/-/events", "/bob/vault/wiki/Home/events"] {
573+ let res = http.get(path, Some(&dave)).await;
574+ assert_eq!(res.status, 404, "{path} for a non-member");
575+ let anon = http.get(path, None).await;
576+ assert_eq!(anon.status, 404, "{path} anonymously");
577+ }
578+
579+ drop(server);
580+}