forge
Explore
Log in

Don't you dare go Hollow

The router layers move from pages into layers.rs, so the test router and boot build the layer stack without reaching into pages

Browse files at this commit

0e737250aedc757495d059b76c006d2f9efa9cc1Ahmet Kaan GümüşParent: 575873e
  • refactor
    • the router layers move from pages into layers.rs, so the test router and boot build the layer stack without reaching into pages
Show full message
♻️ refactor: the router layers move from pages into layers.rs, so the test router and boot build the layer stack without reaching into pages
crates/forge-web/src/boot.rsmodified+7 -7
@@ -170,14 +170,14 @@ pub async fn serve(
170 let public: Router = Router::builder()170 let public: Router = Router::builder()
171 .discover()171 .discover()
172 .with(state.clone())172 .with(state.clone())
173- .layer(crate::pages::settings_live::AccountWriteLayer)173+ .layer(crate::layers::AccountWriteLayer)
174 .layer(CookieLayer::new())174 .layer(CookieLayer::new())
175- .layer(crate::pages::repo_ctx::RepoMovedLayer)175+ .layer(crate::layers::RepoMovedLayer)
176- .layer(crate::pages::pull_live::PullWriteLayer)176+ .layer(crate::layers::PullWriteLayer)
177- .layer(crate::pages::discussion_live::DiscussionWriteLayer)177+ .layer(crate::layers::DiscussionWriteLayer)
178- .layer(crate::pages::org_live::OrgWriteLayer)178+ .layer(crate::layers::OrgWriteLayer)
179- .layer(crate::pages::repo_settings_live::RepoSettingsWriteLayer)179+ .layer(crate::layers::RepoSettingsWriteLayer)
180- .layer(crate::pages::not_found_page::NotFoundLayer)180+ .layer(crate::layers::NotFoundLayer)
181 .layer(TowerLayer::new(crate::compression::ResponseCompression))181 .layer(TowerLayer::new(crate::compression::ResponseCompression))
182 .with(Compression::disable())182 .with(Compression::disable())
183 .build();183 .build();
crates/forge-web/src/layers.rsadded+610 -0
@@ -0,0 +1,610 @@
1+use std::fmt;
2+
3+use crate::live::Topic;
4+use crate::state::AppState;
5+
6+pub use discussion_write::DiscussionWriteLayer;
7+pub use not_found_layer::NotFoundLayer;
8+pub use org_write::OrgWriteLayer;
9+pub use pull_write::PullWriteLayer;
10+pub use repo_moved::RepoMovedLayer;
11+pub use repo_settings_write::RepoSettingsWriteLayer;
12+pub use settings_write::AccountWriteLayer;
13+
14+/// Raised by `load_repo` when the requested owner/name is a past name of a repo the viewer may
15+/// read. The `repo_moved` layer turns it into a 307 to `location`.
16+#[derive(Debug)]
17+pub struct RepoMoved {
18+ pub location: String,
19+}
20+
21+impl fmt::Display for RepoMoved {
22+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23+ f.write_str("repository moved")
24+ }
25+}
26+
27+impl std::error::Error for RepoMoved {}
28+
29+/// A plain-text download (a `.patch` or `.diff`) raised by a page handler that cannot return a
30+/// response of its own. The `repo_moved` layer turns it into a 200 with these bytes.
31+#[derive(Debug, Clone)]
32+pub struct RawDownload {
33+ pub content_type: &'static str,
34+ /// File name offered to the browser.
35+ pub filename: String,
36+ pub data: Vec<u8>,
37+}
38+
39+impl fmt::Display for RawDownload {
40+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41+ f.write_str("raw download")
42+ }
43+}
44+
45+impl std::error::Error for RawDownload {}
46+
47+/// Wakes the review-request list of `user_id`: a request was added or withdrawn, or the user
48+/// submitted a review (which clears their own request).
49+pub fn bump_review_requests(state: &AppState, user_id: &str) {
50+ state.live.bump(&Topic::ReviewRequests(user_id.to_owned()));
51+}
52+
53+/// Wakes the review-request lists of everyone with a pending request on the pull request. Call it
54+/// after the pull closed or merged, which drops it from those lists.
55+pub async fn bump_pending_reviewers(state: &AppState, issue_id: &str) {
56+ let names = match state.store.requested_reviewers(issue_id).await {
57+ Ok(names) => names,
58+ Err(e) => {
59+ tracing::error!(error = %e, issue_id, "live: listing reviewers to bump failed");
60+ return;
61+ }
62+ };
63+ for name in names {
64+ match state.store.user_by_username(&name).await {
65+ Ok(Some(user)) => bump_review_requests(state, &user.id),
66+ Ok(None) => {}
67+ Err(e) => tracing::error!(error = %e, name, "live: loading a reviewer to bump failed"),
68+ }
69+ }
70+}
71+
72+mod settings_write {
73+ use topcoat::Result;
74+ use topcoat::context::{Cx, context};
75+ use topcoat::router::request::{method, uri};
76+ use topcoat::router::response::Response;
77+ use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path};
78+
79+ use crate::auth::current_user;
80+ use crate::live::bump_account;
81+ use crate::state::AppState;
82+
83+ /// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router
84+ /// in `boot.rs` and the test router. It sits on a path, so it runs inside the cookie layer (a
85+ /// pathless layer would run outside it, where the session cannot be read).
86+ pub struct AccountWriteLayer;
87+
88+ impl Layer for AccountWriteLayer {
89+ fn path(&self) -> Option<&Path> {
90+ Some(Path::new("/settings"))
91+ }
92+
93+ fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
94+ Box::pin(bump_after_settings_write(cx, body, next))
95+ }
96+ }
97+
98+ /// Bumps the viewer's topic once the handler has run. The viewer is read before the handler, so a
99+ /// write that ends the viewer's own session (a revoke of the current one) still wakes the tabs.
100+ async fn bump_after_settings_write(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> {
101+ if *method(cx) != Method::POST || !uri(cx).path().starts_with("/settings/") {
102+ return next.run(cx, body).await;
103+ }
104+ let viewer = current_user(cx)
105+ .await
106+ .ok()
107+ .flatten()
108+ .map(|(user, _)| user.id);
109+ let result = next.run(cx, body).await;
110+ if let Some(user_id) = viewer {
111+ bump_account(context::<AppState>(cx), &user_id);
112+ }
113+ result
114+ }
115+}
116+
117+mod repo_moved {
118+ use http::{
119+ HeaderValue,
120+ header::{CACHE_CONTROL, LOCATION},
121+ };
122+ use topcoat::Result;
123+ use topcoat::context::Cx;
124+ use topcoat::router::error::not_found;
125+ use topcoat::router::response::Response;
126+ use topcoat::router::{Body, Layer, LayerFuture, Next, Path, StatusCode};
127+
128+ use super::{RawDownload, RepoMoved};
129+
130+ /// Wraps every request (no path) so a `RepoMoved` error becomes a 307. Registered explicitly on the
131+ /// public router in `boot.rs`: a `#[layer("/")]` would clash with the security-headers layer.
132+ pub struct RepoMovedLayer;
133+
134+ impl Layer for RepoMovedLayer {
135+ fn path(&self) -> Option<&Path> {
136+ None
137+ }
138+
139+ fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
140+ Box::pin(repo_moved(cx, body, next))
141+ }
142+ }
143+
144+ /// Turns a `RepoMoved` error from a handler into a 307 with the new location, and a `RawDownload`
145+ /// into its plain-text response. Other errors pass through unchanged.
146+ async fn repo_moved(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> {
147+ let error = match next.run(cx, body).await {
148+ Ok(response) => return Ok(response),
149+ Err(error) => error,
150+ };
151+ let error = match error.downcast_cloned::<RawDownload>() {
152+ Ok(download) => {
153+ return raw_download_response(download).ok_or_else(|| not_found().into());
154+ }
155+ Err(error) => error,
156+ };
157+ match error.downcast_ref::<RepoMoved>() {
158+ Some(moved) => {
159+ let mut response = Response::new(Body::empty());
160+ // Temporary and uncached: an old name can be taken by a new repo later, and a browser
161+ // that cached a 301 would keep sending its visitors to the renamed repo.
162+ *response.status_mut() = StatusCode::TEMPORARY_REDIRECT;
163+ // Owner and repo names are plain ASCII and the query came from a valid URI, so this
164+ // only fails on a corrupt location; a 404 is the safe answer then.
165+ let Ok(location) = HeaderValue::from_str(&moved.location) else {
166+ return Err(not_found().into());
167+ };
168+ response.headers_mut().insert(LOCATION, location);
169+ response
170+ .headers_mut()
171+ .insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
172+ Ok(response)
173+ }
174+ None => Err(error),
175+ }
176+ }
177+
178+ /// The 200 response for a [`RawDownload`]. `None` when the file name is not a valid header value.
179+ fn raw_download_response(download: RawDownload) -> Option<Response> {
180+ let mut response = Response::new(Body::from(download.data));
181+ let headers = response.headers_mut();
182+ headers.insert(
183+ http::header::CONTENT_TYPE,
184+ HeaderValue::from_static(download.content_type),
185+ );
186+ headers.insert(
187+ http::header::CONTENT_DISPOSITION,
188+ HeaderValue::from_str(&format!("inline; filename=\"{}\"", download.filename)).ok()?,
189+ );
190+ headers.insert(
191+ http::header::X_CONTENT_TYPE_OPTIONS,
192+ HeaderValue::from_static("nosniff"),
193+ );
194+ headers.insert(
195+ http::header::CACHE_CONTROL,
196+ HeaderValue::from_static("private, no-cache"),
197+ );
198+ Some(response)
199+ }
200+}
201+
202+mod pull_write {
203+ use topcoat::context::{Cx, context};
204+ use topcoat::router::request::{method, uri};
205+ use topcoat::router::response::Response;
206+ use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path};
207+
208+ use super::bump_pending_reviewers;
209+ use crate::live::{bump_list, bump_pull, bump_repo_pulls};
210+ use crate::state::AppState;
211+
212+ /// Which topic a POST under the pulls paths writes to.
213+ enum Written {
214+ /// A write to one pull request (`/{o}/{r}/pulls/{n}/...`).
215+ Pull {
216+ owner: String,
217+ repo: String,
218+ number: i64,
219+ },
220+ /// A new pull request (`/{o}/{r}/pulls`).
221+ New { owner: String, repo: String },
222+ /// A repo-wide change the pulls show: a label or milestone edit.
223+ Repo { owner: String, repo: String },
224+ }
225+
226+ /// The write a request makes to the pull side, when it is a POST that can change one.
227+ fn written(cx: &Cx) -> Option<Written> {
228+ if *method(cx) != Method::POST {
229+ return None;
230+ }
231+ let path = uri(cx).path().to_owned();
232+ let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
233+ let [owner, repo, kind, rest @ ..] = parts.as_slice() else {
234+ return None;
235+ };
236+ let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned());
237+ match (*kind, rest) {
238+ ("pulls", []) => Some(Written::New { owner, repo }),
239+ ("pulls", [number, ..]) => number.parse().ok().map(|number| Written::Pull {
240+ owner,
241+ repo,
242+ number,
243+ }),
244+ ("labels" | "milestones", _) => Some(Written::Repo { owner, repo }),
245+ _ => None,
246+ }
247+ }
248+
249+ /// Wraps every request. Only a POST under the pulls paths, or to a label or milestone route, does
250+ /// anything. Registered on the public router in `boot.rs`, next to the other request layers.
251+ pub struct PullWriteLayer;
252+
253+ impl Layer for PullWriteLayer {
254+ fn path(&self) -> Option<&Path> {
255+ None
256+ }
257+
258+ fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
259+ Box::pin(bump_after_write(cx, body, next))
260+ }
261+ }
262+
263+ /// Bumps the topics a write named, once the handler has run. The handler's result passes through
264+ /// unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and agrees.
265+ async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> {
266+ let target = written(cx);
267+ let result = next.run(cx, body).await;
268+ if let Some(target) = target {
269+ bump_written(context::<AppState>(cx), target).await;
270+ }
271+ result
272+ }
273+
274+ async fn bump_written(state: &AppState, target: Written) {
275+ let (owner, name) = match &target {
276+ Written::Pull { owner, repo, .. }
277+ | Written::New { owner, repo }
278+ | Written::Repo { owner, repo } => (owner.as_str(), repo.as_str()),
279+ };
280+ let repo = match state.store.repo_by_owner_and_name(owner, name).await {
281+ Ok(Some(repo)) => repo,
282+ Ok(None) => return,
283+ Err(e) => {
284+ tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed");
285+ return;
286+ }
287+ };
288+ match target {
289+ Written::Pull { number, .. } => {
290+ match state.store.pull_by_number(&repo.id, number).await {
291+ Ok(Some(pr)) => {
292+ bump_pull(state, &repo.id, &pr.issue.id);
293+ // A closed or merged pull leaves its reviewers' request lists.
294+ if pr.issue.state != forge_core::IssueState::Open || pr.merged_at.is_some()
295+ {
296+ bump_pending_reviewers(state, &pr.issue.id).await;
297+ }
298+ }
299+ Ok(None) => {}
300+ Err(e) => {
301+ tracing::error!(error = %e, number, "live: loading the pull to bump failed")
302+ }
303+ }
304+ }
305+ Written::New { .. } => bump_list(state, &repo.id),
306+ Written::Repo { .. } => bump_repo_pulls(state, &repo.id).await,
307+ }
308+ }
309+}
310+
311+mod discussion_write {
312+ use topcoat::context::{Cx, context};
313+ use topcoat::router::request::{method, uri};
314+ use topcoat::router::response::Response;
315+ use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path};
316+
317+ use crate::live::Topic;
318+ use crate::state::AppState;
319+
320+ /// Which topics a discussion write reaches.
321+ enum Written {
322+ /// A new discussion, or the discussions toggle of the repo settings: the list.
323+ List { owner: String, repo: String },
324+ /// A write to one discussion (`/{o}/{r}/discussions/{n}/...`): the list and the discussion.
325+ Discussion {
326+ owner: String,
327+ repo: String,
328+ number: String,
329+ },
330+ }
331+
332+ /// The write a request makes to the discussion side, when it is a POST that can change one.
333+ fn written(cx: &Cx) -> Option<Written> {
334+ if *method(cx) != Method::POST {
335+ return None;
336+ }
337+ let path = uri(cx).path().to_owned();
338+ let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
339+ let [owner, repo, kind, rest @ ..] = parts.as_slice() else {
340+ return None;
341+ };
342+ let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned());
343+ match (*kind, rest) {
344+ ("discussions", ["new"]) => Some(Written::List { owner, repo }),
345+ ("discussions", [number, ..]) => Some(Written::Discussion {
346+ owner,
347+ repo,
348+ number: (*number).to_owned(),
349+ }),
350+ ("settings", ["discussions"]) => Some(Written::List { owner, repo }),
351+ _ => None,
352+ }
353+ }
354+
355+ /// The topics a write reaches, looked up before the handler runs. A repo or discussion that does
356+ /// not exist yields nothing, and a failed lookup is logged.
357+ async fn topics_of(state: &AppState, target: Written) -> Vec<Topic> {
358+ let (owner, name) = match &target {
359+ Written::List { owner, repo } | Written::Discussion { owner, repo, .. } => {
360+ (owner.as_str(), repo.as_str())
361+ }
362+ };
363+ let repo = match state.store.repo_by_owner_and_name(owner, name).await {
364+ Ok(Some(repo)) => repo,
365+ Ok(None) => return Vec::new(),
366+ Err(e) => {
367+ tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed");
368+ return Vec::new();
369+ }
370+ };
371+ let mut topics = vec![Topic::Discussions(repo.id.clone())];
372+ if let Written::Discussion { number, .. } = target
373+ && let Ok(number) = number.parse::<i64>()
374+ {
375+ match state.store.discussion_by_number(&repo.id, number).await {
376+ Ok(Some(discussion)) => topics.push(Topic::Discussion(discussion.id)),
377+ Ok(None) => {}
378+ Err(e) => {
379+ tracing::error!(error = %e, number, "live: loading the discussion to bump failed")
380+ }
381+ }
382+ }
383+ topics
384+ }
385+
386+ /// Wraps every request. Only a POST under the discussions paths, or the discussions settings
387+ /// toggle, does anything. Registered on the public router in `boot.rs`, next to the other layers.
388+ pub struct DiscussionWriteLayer;
389+
390+ impl Layer for DiscussionWriteLayer {
391+ fn path(&self) -> Option<&Path> {
392+ None
393+ }
394+
395+ fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
396+ Box::pin(bump_after_write(cx, body, next))
397+ }
398+ }
399+
400+ /// Bumps the topics a write reaches, once the handler has run. The handler's result passes
401+ /// through unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and
402+ /// agrees.
403+ async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> {
404+ let state = context::<AppState>(cx);
405+ let topics = match written(cx) {
406+ Some(target) => topics_of(state, target).await,
407+ None => Vec::new(),
408+ };
409+ let result = next.run(cx, body).await;
410+ for topic in &topics {
411+ state.live.bump(topic);
412+ }
413+ result
414+ }
415+}
416+
417+mod org_write {
418+ use topcoat::context::{Cx, context};
419+ use topcoat::router::request::{method, uri};
420+ use topcoat::router::response::Response;
421+ use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path};
422+
423+ use crate::live::Topic;
424+ use crate::state::AppState;
425+
426+ /// The org a POST under `/org/{org}/{members|teams|settings}` writes to, by its name.
427+ fn written_org(cx: &Cx) -> Option<String> {
428+ if *method(cx) != Method::POST {
429+ return None;
430+ }
431+ let path = uri(cx).path().to_owned();
432+ let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
433+ let ["org", name, kind, ..] = parts.as_slice() else {
434+ return None;
435+ };
436+ matches!(*kind, "members" | "teams" | "settings").then(|| (*name).to_owned())
437+ }
438+
439+ /// Wraps every request. Only a POST under an org's members, teams or settings does anything.
440+ /// Registered on the public router in `boot.rs`, next to the pull write layer.
441+ pub struct OrgWriteLayer;
442+
443+ impl Layer for OrgWriteLayer {
444+ fn path(&self) -> Option<&Path> {
445+ None
446+ }
447+
448+ fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
449+ Box::pin(bump_after_write(cx, body, next))
450+ }
451+ }
452+
453+ /// Bumps the org's topic after the handler ran. The org is looked up before the handler, so a
454+ /// write that removes the org (its deletion) still reaches the streams that follow it. The
455+ /// handler's result passes through unchanged.
456+ async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> {
457+ let Some(name) = written_org(cx) else {
458+ return next.run(cx, body).await;
459+ };
460+ let state = context::<AppState>(cx);
461+ let org_id = match state.store.user_by_username(&name).await {
462+ Ok(Some(org)) if org.is_org() => Some(org.id),
463+ Ok(_) => None,
464+ Err(e) => {
465+ tracing::error!(error = %e, name, "live: loading the org to bump failed");
466+ None
467+ }
468+ };
469+ let result = next.run(cx, body).await;
470+ if let Some(org_id) = org_id {
471+ state.live.bump(&Topic::Org(org_id.clone()));
472+ state.live.bump(&Topic::User(org_id));
473+ }
474+ result
475+ }
476+}
477+
478+mod repo_settings_write {
479+ use topcoat::Result;
480+ use topcoat::context::{Cx, context};
481+ use topcoat::router::request::{method, uri};
482+ use topcoat::router::response::Response;
483+ use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path};
484+
485+ use crate::live::{Topic, bump_repo_pulls, bump_settings};
486+ use crate::state::AppState;
487+
488+ /// Wraps every request. Only a POST under the settings or security paths does anything. Registered
489+ /// on the public router in `boot.rs`, and on the test router, next to the other request layers.
490+ pub struct RepoSettingsWriteLayer;
491+
492+ impl Layer for RepoSettingsWriteLayer {
493+ fn path(&self) -> Option<&Path> {
494+ None
495+ }
496+
497+ fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
498+ Box::pin(bump_after_write(cx, body, next))
499+ }
500+ }
501+
502+ /// The `(owner, name)` of a POST under `/{o}/{r}/settings/...` or `/{o}/{r}/security/...`.
503+ fn written(cx: &Cx) -> Option<(String, String)> {
504+ if *method(cx) != Method::POST {
505+ return None;
506+ }
507+ let path = uri(cx).path().to_owned();
508+ let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
509+ match parts.as_slice() {
510+ [owner, name, "settings" | "security", ..] => {
511+ Some(((*owner).to_owned(), (*name).to_owned()))
512+ }
513+ _ => None,
514+ }
515+ }
516+
517+ /// Bumps the settings topic once the handler has run. The repo is looked up before the handler,
518+ /// because a rename moves its name away. The handler's result passes through unchanged, so a
519+ /// refused write bumps too: the page re-reads and agrees.
520+ async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> {
521+ let repo_id = match written(cx) {
522+ Some((owner, name)) => {
523+ let state = context::<AppState>(cx);
524+ match state.store.repo_by_owner_and_name(&owner, &name).await {
525+ Ok(repo) => repo.map(|repo| repo.id),
526+ Err(e) => {
527+ tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed");
528+ None
529+ }
530+ }
531+ }
532+ None => None,
533+ };
534+ let result = next.run(cx, body).await;
535+ if let Some(repo_id) = repo_id {
536+ let state = context::<AppState>(cx);
537+ bump_settings(&state.live, &repo_id);
538+ // The repo header shows settings too (the mirror line, the archived notice, the tabs); its
539+ // stream sends nothing when its fingerprint holds.
540+ state.live.bump(&Topic::Repo(repo_id.clone()));
541+ // The merge gate of a pull page reads the branch protection rules, so every pull of the
542+ // repo may show a different gate. A pull's stream sends nothing when its fingerprint holds.
543+ bump_repo_pulls(state, &repo_id).await;
544+ }
545+ result
546+ }
547+}
548+
549+mod not_found_layer {
550+ use http::header::ACCEPT;
551+ use topcoat::Result;
552+ use topcoat::context::Cx;
553+ use topcoat::router::error::{ForbiddenError, NotFoundError, rewrite};
554+ use topcoat::router::request::headers;
555+ use topcoat::router::response::Response;
556+ use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path};
557+
558+ use crate::auth::percent_encode;
559+
560+ /// The styled 404 and 403 pages. Topcoat answers `not_found()` and `forbidden()` with a bare text
561+ /// body, so this layer swaps that body for the regular shell plus a short message, for browser
562+ /// requests only. A signed-out visitor refused a page is sent to log in first, as every page that
563+ /// needs an account does.
564+ pub struct NotFoundLayer;
565+
566+ impl Layer for NotFoundLayer {
567+ fn path(&self) -> Option<&Path> {
568+ None
569+ }
570+
571+ fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
572+ Box::pin(styled_not_found(cx, body, next))
573+ }
574+ }
575+
576+ async fn styled_not_found(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> {
577+ let is_get = *topcoat::router::request::method(cx) == Method::GET;
578+ let result = next.run(cx, body).await;
579+ let is_not_found = matches!(&result, Err(e) if e.downcast_ref::<NotFoundError>().is_some());
580+ let is_forbidden =
581+ matches!(&result, Err(e) if e.downcast_ref::<ForbiddenError>().is_some());
582+ let wants_html = headers(cx)
583+ .get(ACCEPT)
584+ .and_then(|v| v.to_str().ok())
585+ .is_some_and(|v| v.contains("text/html"));
586+ if !wants_html || !(is_not_found || is_forbidden) {
587+ return result;
588+ }
589+ if is_forbidden {
590+ // The cookies are not readable out here, so the page itself decides whether the visitor
591+ // must log in first; a refused GET hands it the address to come back to.
592+ let target = if is_get {
593+ let path = topcoat::router::request::uri(cx)
594+ .path_and_query()
595+ .map_or("/", |p| p.as_str());
596+ format!("{FORBIDDEN_PATH}?next={}", percent_encode(path))
597+ } else {
598+ FORBIDDEN_PATH.to_owned()
599+ };
600+ return Err(rewrite(target, Body::empty()).method(Method::GET).into());
601+ }
602+ Err(rewrite(PATH, Body::empty()).method(Method::GET).into())
603+ }
604+
605+ /// Where the layer sends a browser's 403. The page answers with status 403 itself.
606+ const FORBIDDEN_PATH: &str = "/-/forbidden";
607+
608+ /// Where the layer sends a browser's 404. The page answers with status 404 itself.
609+ const PATH: &str = "/-/not-found";
610+}
crates/forge-web/src/main.rsmodified+1 -0
@@ -33,6 +33,7 @@ mod git_http;
33 mod hook_cmd;33 mod hook_cmd;
34 mod importer;34 mod importer;
35 mod internal;35 mod internal;
36+mod layers;
36 mod lfs;37 mod lfs;
37 mod lfs_pointer;38 mod lfs_pointer;
38 mod live;39 mod live;
crates/forge-web/src/pages/commit.rsmodified+2 -1
@@ -12,10 +12,11 @@ use topcoat::view::{View, view};
12 12
13 use crate::i18n::code::{self as g, K};13 use crate::i18n::code::{self as g, K};
14 use crate::i18n::{self};14 use crate::i18n::{self};
15+use crate::layers::RawDownload;
15 use crate::pages::commits::{SigBadgeView, blocking, iso_time, now_secs, short_oid};16 use crate::pages::commits::{SigBadgeView, blocking, iso_time, now_secs, short_oid};
16 use crate::pages::ref_live;17 use crate::pages::ref_live;
17 use crate::pages::repo::repo_head;18 use crate::pages::repo::repo_head;
18-use crate::pages::repo_ctx::{RawDownload, load_repo};19+use crate::pages::repo_ctx::load_repo;
19 use crate::render::commit_message::CommitMessage;20 use crate::render::commit_message::CommitMessage;
20 use crate::render::emoji::emojify;21 use crate::render::emoji::emojify;
21 use crate::signatures;22 use crate::signatures;
crates/forge-web/src/pages/discussion_live.rsmodified+1 -98
@@ -14,9 +14,8 @@
14 14
15 use topcoat::Result;15 use topcoat::Result;
16 use topcoat::context::{Cx, context};16 use topcoat::context::{Cx, context};
17-use topcoat::router::request::{method, uri};
18 use topcoat::router::response::Response;17 use topcoat::router::response::Response;
19-use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route};18+use topcoat::router::{path_param, route};
20 19
21 use crate::live::{Topic, stream_wakes};20 use crate::live::{Topic, stream_wakes};
22 use crate::pages::discussions::{discussion_by_number, ensure_enabled};21 use crate::pages::discussions::{discussion_by_number, ensure_enabled};
@@ -57,99 +56,3 @@ async fn discussion_live(cx: &Cx) -> Result<Response> {
57 }56 }
58 57
59 // The write layer58 // The write layer
60-
61-/// Which topics a discussion write reaches.
62-enum Written {
63- /// A new discussion, or the discussions toggle of the repo settings: the list.
64- List { owner: String, repo: String },
65- /// A write to one discussion (`/{o}/{r}/discussions/{n}/...`): the list and the discussion.
66- Discussion {
67- owner: String,
68- repo: String,
69- number: String,
70- },
71-}
72-
73-/// The write a request makes to the discussion side, when it is a POST that can change one.
74-fn written(cx: &Cx) -> Option<Written> {
75- if *method(cx) != Method::POST {
76- return None;
77- }
78- let path = uri(cx).path().to_owned();
79- let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
80- let [owner, repo, kind, rest @ ..] = parts.as_slice() else {
81- return None;
82- };
83- let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned());
84- match (*kind, rest) {
85- ("discussions", ["new"]) => Some(Written::List { owner, repo }),
86- ("discussions", [number, ..]) => Some(Written::Discussion {
87- owner,
88- repo,
89- number: (*number).to_owned(),
90- }),
91- ("settings", ["discussions"]) => Some(Written::List { owner, repo }),
92- _ => None,
93- }
94-}
95-
96-/// The topics a write reaches, looked up before the handler runs. A repo or discussion that does
97-/// not exist yields nothing, and a failed lookup is logged.
98-async fn topics_of(state: &AppState, target: Written) -> Vec<Topic> {
99- let (owner, name) = match &target {
100- Written::List { owner, repo } | Written::Discussion { owner, repo, .. } => {
101- (owner.as_str(), repo.as_str())
102- }
103- };
104- let repo = match state.store.repo_by_owner_and_name(owner, name).await {
105- Ok(Some(repo)) => repo,
106- Ok(None) => return Vec::new(),
107- Err(e) => {
108- tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed");
109- return Vec::new();
110- }
111- };
112- let mut topics = vec![Topic::Discussions(repo.id.clone())];
113- if let Written::Discussion { number, .. } = target
114- && let Ok(number) = number.parse::<i64>()
115- {
116- match state.store.discussion_by_number(&repo.id, number).await {
117- Ok(Some(discussion)) => topics.push(Topic::Discussion(discussion.id)),
118- Ok(None) => {}
119- Err(e) => {
120- tracing::error!(error = %e, number, "live: loading the discussion to bump failed")
121- }
122- }
123- }
124- topics
125-}
126-
127-/// Bumps the topics a write reaches, once the handler has run. The handler's result passes
128-/// through unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and
129-/// agrees.
130-async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> {
131- let state = context::<AppState>(cx);
132- let topics = match written(cx) {
133- Some(target) => topics_of(state, target).await,
134- None => Vec::new(),
135- };
136- let result = next.run(cx, body).await;
137- for topic in &topics {
138- state.live.bump(topic);
139- }
140- result
141-}
142-
143-/// Wraps every request. Only a POST under the discussions paths, or the discussions settings
144-/// toggle, does anything. Registered on the public router in `boot.rs`, next to the other layers.
145-pub struct DiscussionWriteLayer;
146-
147-impl Layer for DiscussionWriteLayer {
148- fn path(&self) -> Option<&Path> {
149- None
150- }
151-
152- fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
153- Box::pin(bump_after_write(cx, body, next))
154- }
155-}
crates/forge-web/src/pages/not_found_page.rsmodified+2 -52
@@ -3,33 +3,17 @@
3 //! requests only. A signed-out visitor refused a page is sent to log in first, as every page that3 //! requests only. A signed-out visitor refused a page is sent to log in first, as every page that
4 //! needs an account does.4 //! needs an account does.
5 5
6-use http::header::ACCEPT;
7 use topcoat::Result;6 use topcoat::Result;
8 use topcoat::context::Cx;7 use topcoat::context::Cx;
9-use topcoat::router::error::{ForbiddenError, NotFoundError, rewrite};8+use topcoat::router::StatusCode;
10 use topcoat::router::page;9 use topcoat::router::page;
11-use topcoat::router::request::headers;
12-use topcoat::router::response::Response;
13-use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode};
14 use topcoat::view::{View, component, view};10 use topcoat::view::{View, component, view};
15 11
16-use crate::auth::{current_user, percent_encode};12+use crate::auth::current_user;
17 use crate::i18n::{self, Lang};13 use crate::i18n::{self, Lang};
18 use crate::views::parts::{SubPart, head};14 use crate::views::parts::{SubPart, head};
19 use crate::views::shell;15 use crate::views::shell;
20 16
21-pub struct NotFoundLayer;
22-
23-impl Layer for NotFoundLayer {
24- fn path(&self) -> Option<&Path> {
25- None
26- }
27-
28- fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
29- Box::pin(styled_not_found(cx, body, next))
30- }
31-}
32-
33 fn texts(lang: Lang) -> (&'static str, &'static str, &'static str) {17 fn texts(lang: Lang) -> (&'static str, &'static str, &'static str) {
34 match lang {18 match lang {
35 Lang::En => (19 Lang::En => (
@@ -54,37 +38,6 @@ async fn not_found_body(cx: &Cx, lang: Lang) -> Result<impl View> {
54 })38 })
55 }39 }
56 40
57-async fn styled_not_found(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> {
58- let is_get = *topcoat::router::request::method(cx) == Method::GET;
59- let result = next.run(cx, body).await;
60- let is_not_found = matches!(&result, Err(e) if e.downcast_ref::<NotFoundError>().is_some());
61- let is_forbidden = matches!(&result, Err(e) if e.downcast_ref::<ForbiddenError>().is_some());
62- let wants_html = headers(cx)
63- .get(ACCEPT)
64- .and_then(|v| v.to_str().ok())
65- .is_some_and(|v| v.contains("text/html"));
66- if !wants_html || !(is_not_found || is_forbidden) {
67- return result;
68- }
69- if is_forbidden {
70- // The cookies are not readable out here, so the page itself decides whether the visitor
71- // must log in first; a refused GET hands it the address to come back to.
72- let target = if is_get {
73- let path = topcoat::router::request::uri(cx)
74- .path_and_query()
75- .map_or("/", |p| p.as_str());
76- format!("{FORBIDDEN_PATH}?next={}", percent_encode(path))
77- } else {
78- FORBIDDEN_PATH.to_owned()
79- };
80- return Err(rewrite(target, Body::empty()).method(Method::GET).into());
81- }
82- Err(rewrite(PATH, Body::empty()).method(Method::GET).into())
83-}
84-
85-/// Where the layer sends a browser's 403. The page answers with status 403 itself.
86-const FORBIDDEN_PATH: &str = "/-/forbidden";
87-
88 fn forbidden_texts(lang: Lang) -> (&'static str, &'static str, &'static str) {41 fn forbidden_texts(lang: Lang) -> (&'static str, &'static str, &'static str) {
89 match lang {42 match lang {
90 Lang::En => (43 Lang::En => (
@@ -129,9 +82,6 @@ async fn forbidden_page(cx: &Cx) -> Result<impl View> {
129 })82 })
130 }83 }
131 84
132-/// Where the layer sends a browser's 404. The page answers with status 404 itself.
133-const PATH: &str = "/-/not-found";
134-
135 #[page("/-/not-found")]85 #[page("/-/not-found")]
136 async fn not_found_page(cx: &Cx) -> Result<impl View> {86 async fn not_found_page(cx: &Cx) -> Result<impl View> {
137 let viewer = current_user(cx).await?;87 let viewer = current_user(cx).await?;
crates/forge-web/src/pages/org_live.rsmodified+1 -55
@@ -16,9 +16,8 @@ use forge_core::store::Store;
16 use forge_core::store::orgs::OrgMemberRole;16 use forge_core::store::orgs::OrgMemberRole;
17 use topcoat::Result;17 use topcoat::Result;
18 use topcoat::context::{Cx, context};18 use topcoat::context::{Cx, context};
19-use topcoat::router::request::{method, uri};
20 use topcoat::router::response::Response;19 use topcoat::router::response::Response;
21-use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route};20+use topcoat::router::{path_param, route};
22 21
23 use crate::live::{Topic, stream_changes};22 use crate::live::{Topic, stream_changes};
24 use crate::pages::org_ctx::{load_org, member_role_word, require_member, require_owner};23 use crate::pages::org_ctx::{load_org, member_role_word, require_member, require_owner};
@@ -199,56 +198,3 @@ async fn org_settings_events(cx: &Cx) -> Result<Response> {
199 })198 })
200 .await199 .await
201 }200 }
202-
203-// The write layer
204-
205-/// The org a POST under `/org/{org}/{members|teams|settings}` writes to, by its name.
206-fn written_org(cx: &Cx) -> Option<String> {
207- if *method(cx) != Method::POST {
208- return None;
209- }
210- let path = uri(cx).path().to_owned();
211- let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
212- let ["org", name, kind, ..] = parts.as_slice() else {
213- return None;
214- };
215- matches!(*kind, "members" | "teams" | "settings").then(|| (*name).to_owned())
216-}
217-
218-/// Bumps the org's topic after the handler ran. The org is looked up before the handler, so a
219-/// write that removes the org (its deletion) still reaches the streams that follow it. The
220-/// handler's result passes through unchanged.
221-async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> {
222- let Some(name) = written_org(cx) else {
223- return next.run(cx, body).await;
224- };
225- let state = context::<AppState>(cx);
226- let org_id = match state.store.user_by_username(&name).await {
227- Ok(Some(org)) if org.is_org() => Some(org.id),
228- Ok(_) => None,
229- Err(e) => {
230- tracing::error!(error = %e, name, "live: loading the org to bump failed");
231- None
232- }
233- };
234- let result = next.run(cx, body).await;
235- if let Some(org_id) = org_id {
236- state.live.bump(&Topic::Org(org_id.clone()));
237- state.live.bump(&Topic::User(org_id));
238- }
239- result
240-}
241-
242-/// Wraps every request. Only a POST under an org's members, teams or settings does anything.
243-/// Registered on the public router in `boot.rs`, next to the pull write layer.
244-pub struct OrgWriteLayer;
245-
246-impl Layer for OrgWriteLayer {
247- fn path(&self) -> Option<&Path> {
248- None
249- }
250-
251- fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
252- Box::pin(bump_after_write(cx, body, next))
253- }
254-}
crates/forge-web/src/pages/pull_live.rsmodified+2 -99
@@ -20,11 +20,10 @@ use forge_core::reactions::ReactionTarget;
20 use forge_core::store::Store;20 use forge_core::store::Store;
21 use topcoat::Result;21 use topcoat::Result;
22 use topcoat::context::{Cx, context};22 use topcoat::context::{Cx, context};
23-use topcoat::router::request::{method, uri};
24 use topcoat::router::response::Response;23 use topcoat::router::response::Response;
25-use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route};24+use topcoat::router::{path_param, route};
26 25
27-use crate::live::{Topic, bump_list, bump_pull, bump_repo_pulls, stream_changes};26+use crate::live::{Topic, stream_changes};
28 use crate::pages::issue_parts::parse_number;27 use crate::pages::issue_parts::parse_number;
29 use crate::pages::repo_ctx::load_repo;28 use crate::pages::repo_ctx::load_repo;
30 use crate::state::AppState;29 use crate::state::AppState;
@@ -196,99 +195,3 @@ async fn pull_events(cx: &Cx) -> Result<Response> {
196 })195 })
197 .await196 .await
198 }197 }
199-
200-// The write layer
201-
202-/// Which topic a POST under the pulls paths writes to.
203-enum Written {
204- /// A write to one pull request (`/{o}/{r}/pulls/{n}/...`).
205- Pull {
206- owner: String,
207- repo: String,
208- number: i64,
209- },
210- /// A new pull request (`/{o}/{r}/pulls`).
211- New { owner: String, repo: String },
212- /// A repo-wide change the pulls show: a label or milestone edit.
213- Repo { owner: String, repo: String },
214-}
215-
216-/// The write a request makes to the pull side, when it is a POST that can change one.
217-fn written(cx: &Cx) -> Option<Written> {
218- if *method(cx) != Method::POST {
219- return None;
220- }
221- let path = uri(cx).path().to_owned();
222- let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
223- let [owner, repo, kind, rest @ ..] = parts.as_slice() else {
224- return None;
225- };
226- let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned());
227- match (*kind, rest) {
228- ("pulls", []) => Some(Written::New { owner, repo }),
229- ("pulls", [number, ..]) => number.parse().ok().map(|number| Written::Pull {
230- owner,
231- repo,
232- number,
233- }),
234- ("labels" | "milestones", _) => Some(Written::Repo { owner, repo }),
235- _ => None,
236- }
237-}
238-
239-/// Bumps the topics a write named, once the handler has run. The handler's result passes through
240-/// unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and agrees.
241-async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> {
242- let target = written(cx);
243- let result = next.run(cx, body).await;
244- if let Some(target) = target {
245- bump_written(context::<AppState>(cx), target).await;
246- }
247- result
248-}
249-
250-async fn bump_written(state: &AppState, target: Written) {
251- let (owner, name) = match &target {
252- Written::Pull { owner, repo, .. }
253- | Written::New { owner, repo }
254- | Written::Repo { owner, repo } => (owner.as_str(), repo.as_str()),
255- };
256- let repo = match state.store.repo_by_owner_and_name(owner, name).await {
257- Ok(Some(repo)) => repo,
258- Ok(None) => return,
259- Err(e) => {
260- tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed");
261- return;
262- }
263- };
264- match target {
265- Written::Pull { number, .. } => match state.store.pull_by_number(&repo.id, number).await {
266- Ok(Some(pr)) => {
267- bump_pull(state, &repo.id, &pr.issue.id);
268- // A closed or merged pull leaves its reviewers' request lists.
269- if pr.issue.state != forge_core::IssueState::Open || pr.merged_at.is_some() {
270- crate::pages::review_requests::bump_pending_reviewers(state, &pr.issue.id)
271- .await;
272- }
273- }
274- Ok(None) => {}
275- Err(e) => tracing::error!(error = %e, number, "live: loading the pull to bump failed"),
276- },
277- Written::New { .. } => bump_list(state, &repo.id),
278- Written::Repo { .. } => bump_repo_pulls(state, &repo.id).await,
279- }
280-}
281-
282-/// Wraps every request. Only a POST under the pulls paths, or to a label or milestone route, does
283-/// anything. Registered on the public router in `boot.rs`, next to the other request layers.
284-pub struct PullWriteLayer;
285-
286-impl Layer for PullWriteLayer {
287- fn path(&self) -> Option<&Path> {
288- None
289- }
290-
291- fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
292- Box::pin(bump_after_write(cx, body, next))
293- }
294-}
crates/forge-web/src/pages/pull_reviews.rsmodified+1 -1
@@ -735,7 +735,7 @@ async fn review_submit(cx: &Cx, Form(form): Form<ReviewForm>) -> Result<SeeOther
735 .await;735 .await;
736 crate::automerge::on_pull(state, &ctx.repo, number).await;736 crate::automerge::on_pull(state, &ctx.repo, number).await;
737 // The submitted review clears the viewer's own request, so their list changes.737 // The submitted review clears the viewer's own request, so their list changes.
738- crate::pages::review_requests::bump_review_requests(state, &user.id);738+ crate::layers::bump_review_requests(state, &user.id);
739 Ok(see_other(format!("{tab}#review-{}", review.id)))739 Ok(see_other(format!("{tab}#review-{}", review.id)))
740 }740 }
741 Err(forge_core::Error::Forbidden(_)) => Ok(refusal(&tab, ERR_OWN_PR, "")),741 Err(forge_core::Error::Forbidden(_)) => Ok(refusal(&tab, ERR_OWN_PR, "")),
crates/forge-web/src/pages/pulls_merge.rsmodified+5 -1
@@ -161,10 +161,14 @@ fn refusal(status: StatusCode, message: &str) -> Response {
161 161
162 #[cfg(test)]162 #[cfg(test)]
163 mod tests {163 mod tests {
164+ use forge_core::ReviewState;
165+
164 use std::path::{Path, PathBuf};166 use std::path::{Path, PathBuf};
165 use std::time::Duration;167 use std::time::Duration;
166 168
167- use forge_core::{IssueState, Repo, Role, Store, Visibility};169+ use forge_core::protection::Protection;
170+ use forge_core::store::commit_status::StatusState;
171+ use forge_core::{IssueState, PullRequest, Repo, Role, Store, User, Visibility};
168 use forge_git::repo::{init_bare, repo_path};172 use forge_git::repo::{init_bare, repo_path};
169 use topcoat::router::request::Request;173 use topcoat::router::request::Request;
170 use topcoat::router::{Body, Router, to_bytes};174 use topcoat::router::{Body, Router, to_bytes};
crates/forge-web/src/pages/repo_ctx.rsmodified+1 -110
@@ -8,19 +8,14 @@ use std::path::PathBuf;
8 use forge_core::authz::{Action, authorize};8 use forge_core::authz::{Action, authorize};
9 use forge_core::{Repo, Role, Session, Store, User, Visibility, WatchLevel};9 use forge_core::{Repo, Role, Session, Store, User, Visibility, WatchLevel};
10 use forge_git::repo::repo_path;10 use forge_git::repo::repo_path;
11-use http::{
12- HeaderValue,
13- header::{CACHE_CONTROL, LOCATION},
14-};
15 use topcoat::Result;11 use topcoat::Result;
16 use topcoat::context::{Cx, context};12 use topcoat::context::{Cx, context};
17 use topcoat::router::error::not_found;13 use topcoat::router::error::not_found;
18 use topcoat::router::request::uri;14 use topcoat::router::request::uri;
19-use topcoat::router::response::Response;
20-use topcoat::router::{Body, Layer, LayerFuture, Next, Path, StatusCode};
21 15
22 use crate::auth::current_user;16 use crate::auth::current_user;
23 use crate::i18n::{self, Lang};17 use crate::i18n::{self, Lang};
18+use crate::layers::RepoMoved;
24 use crate::pages::repo_mirrors::redacted_url;19 use crate::pages::repo_mirrors::redacted_url;
25 use crate::state::AppState;20 use crate::state::AppState;
26 use crate::views::repo_href;21 use crate::views::repo_href;
@@ -125,39 +120,6 @@ pub struct WatchButton {
125 pub csrf: String,120 pub csrf: String,
126 }121 }
127 122
128-/// Raised by `load_repo` when the requested owner/name is a past name of a repo the viewer may
129-/// read. The `repo_moved` layer turns it into a 307 to `location`.
130-#[derive(Debug)]
131-pub struct RepoMoved {
132- pub location: String,
133-}
134-
135-impl std::fmt::Display for RepoMoved {
136- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137- f.write_str("repository moved")
138- }
139-}
140-
141-impl std::error::Error for RepoMoved {}
142-
143-/// A plain-text download (a `.patch` or `.diff`) raised by a page handler that cannot return a
144-/// response of its own. The `repo_moved` layer turns it into a 200 with these bytes.
145-#[derive(Debug, Clone)]
146-pub struct RawDownload {
147- pub content_type: &'static str,
148- /// File name offered to the browser.
149- pub filename: String,
150- pub data: Vec<u8>,
151-}
152-
153-impl std::fmt::Display for RawDownload {
154- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155- f.write_str("raw download")
156- }
157-}
158-
159-impl std::error::Error for RawDownload {}
160-
161 impl RepoCtx {123 impl RepoCtx {
162 /// Whether the viewer may delete this repo: its owner or an instance admin only.124 /// Whether the viewer may delete this repo: its owner or an instance admin only.
163 pub fn can_delete(&self) -> bool {125 pub fn can_delete(&self) -> bool {
@@ -426,74 +388,3 @@ async fn moved_location(
426 target.owner_name, target.name388 target.owner_name, target.name
427 )))389 )))
428 }390 }
429-
430-/// Wraps every request (no path) so a `RepoMoved` error becomes a 307. Registered explicitly on the
431-/// public router in `boot.rs`: a `#[layer("/")]` would clash with the security-headers layer.
432-pub struct RepoMovedLayer;
433-
434-impl Layer for RepoMovedLayer {
435- fn path(&self) -> Option<&Path> {
436- None
437- }
438-
439- fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
440- Box::pin(repo_moved(cx, body, next))
441- }
442-}
443-
444-/// Turns a `RepoMoved` error from a handler into a 307 with the new location, and a `RawDownload`
445-/// into its plain-text response. Other errors pass through unchanged.
446-async fn repo_moved(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> {
447- let error = match next.run(cx, body).await {
448- Ok(response) => return Ok(response),
449- Err(error) => error,
450- };
451- let error = match error.downcast_cloned::<RawDownload>() {
452- Ok(download) => {
453- return raw_download_response(download).ok_or_else(|| not_found().into());
454- }
455- Err(error) => error,
456- };
457- match error.downcast_ref::<RepoMoved>() {
458- Some(moved) => {
459- let mut response = Response::new(Body::empty());
460- // Temporary and uncached: an old name can be taken by a new repo later, and a browser
461- // that cached a 301 would keep sending its visitors to the renamed repo.
462- *response.status_mut() = StatusCode::TEMPORARY_REDIRECT;
463- // Owner and repo names are plain ASCII and the query came from a valid URI, so this
464- // only fails on a corrupt location; a 404 is the safe answer then.
465- let Ok(location) = HeaderValue::from_str(&moved.location) else {
466- return Err(not_found().into());
467- };
468- response.headers_mut().insert(LOCATION, location);
469- response
470- .headers_mut()
471- .insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
472- Ok(response)
473- }
474- None => Err(error),
475- }
476-}
477-
478-/// The 200 response for a [`RawDownload`]. `None` when the file name is not a valid header value.
479-fn raw_download_response(download: RawDownload) -> Option<Response> {
480- let mut response = Response::new(Body::from(download.data));
481- let headers = response.headers_mut();
482- headers.insert(
483- http::header::CONTENT_TYPE,
484- HeaderValue::from_static(download.content_type),
485- );
486- headers.insert(
487- http::header::CONTENT_DISPOSITION,
488- HeaderValue::from_str(&format!("inline; filename=\"{}\"", download.filename)).ok()?,
489- );
490- headers.insert(
491- http::header::X_CONTENT_TYPE_OPTIONS,
492- HeaderValue::from_static("nosniff"),
493- );
494- headers.insert(
495- http::header::CACHE_CONTROL,
496- HeaderValue::from_static("private, no-cache"),
497- );
498- Some(response)
499-}
crates/forge-web/src/pages/repo_settings_live.rsmodified+2 -65
@@ -17,12 +17,11 @@
17 use topcoat::Result;17 use topcoat::Result;
18 use topcoat::context::{Cx, context};18 use topcoat::context::{Cx, context};
19 use topcoat::router::error::forbidden;19 use topcoat::router::error::forbidden;
20-use topcoat::router::request::{method, uri};
21 use topcoat::router::response::Response;20 use topcoat::router::response::Response;
22-use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route};21+use topcoat::router::{path_param, route};
23 22
24 use crate::auth::require_user;23 use crate::auth::require_user;
25-use crate::live::{Topic, bump_settings, stream_wakes};24+use crate::live::{Topic, stream_wakes};
26 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};25 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
27 use crate::state::AppState;26 use crate::state::AppState;
28 27
@@ -72,65 +71,3 @@ async fn security_live(cx: &Cx) -> Result<Response> {
72 let state = context::<AppState>(cx);71 let state = context::<AppState>(cx);
73 stream_wakes(cx, &state.live, &[Topic::RepoSettings(ctx.repo.id.clone())])72 stream_wakes(cx, &state.live, &[Topic::RepoSettings(ctx.repo.id.clone())])
74 }73 }
75-
76-// The write layer
77-
78-/// Wraps every request. Only a POST under the settings or security paths does anything. Registered
79-/// on the public router in `boot.rs`, and on the test router, next to the other request layers.
80-pub struct RepoSettingsWriteLayer;
81-
82-impl Layer for RepoSettingsWriteLayer {
83- fn path(&self) -> Option<&Path> {
84- None
85- }
86-
87- fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
88- Box::pin(bump_after_write(cx, body, next))
89- }
90-}
91-
92-/// The `(owner, name)` of a POST under `/{o}/{r}/settings/...` or `/{o}/{r}/security/...`.
93-fn written(cx: &Cx) -> Option<(String, String)> {
94- if *method(cx) != Method::POST {
95- return None;
96- }
97- let path = uri(cx).path().to_owned();
98- let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
99- match parts.as_slice() {
100- [owner, name, "settings" | "security", ..] => {
101- Some(((*owner).to_owned(), (*name).to_owned()))
102- }
103- _ => None,
104- }
105-}
106-
107-/// Bumps the settings topic once the handler has run. The repo is looked up before the handler,
108-/// because a rename moves its name away. The handler's result passes through unchanged, so a
109-/// refused write bumps too: the page re-reads and agrees.
110-async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> {
111- let repo_id = match written(cx) {
112- Some((owner, name)) => {
113- let state = context::<AppState>(cx);
114- match state.store.repo_by_owner_and_name(&owner, &name).await {
115- Ok(repo) => repo.map(|repo| repo.id),
116- Err(e) => {
117- tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed");
118- None
119- }
120- }
121- }
122- None => None,
123- };
124- let result = next.run(cx, body).await;
125- if let Some(repo_id) = repo_id {
126- let state = context::<AppState>(cx);
127- bump_settings(&state.live, &repo_id);
128- // The repo header shows settings too (the mirror line, the archived notice, the tabs); its
129- // stream sends nothing when its fingerprint holds.
130- state.live.bump(&crate::live::Topic::Repo(repo_id.clone()));
131- // The merge gate of a pull page reads the branch protection rules, so every pull of the
132- // repo may show a different gate. A pull's stream sends nothing when its fingerprint holds.
133- crate::live::bump_repo_pulls(state, &repo_id).await;
134- }
135- result
136-}
crates/forge-web/src/pages/review_requests.rsmodified+1 -25
@@ -19,6 +19,7 @@ use crate::auth::{current_user, require_user};
19 use crate::i18n::authoring::{self as ga, K as AK};19 use crate::i18n::authoring::{self as ga, K as AK};
20 use crate::i18n::issues::{self as ig, K as IK};20 use crate::i18n::issues::{self as ig, K as IK};
21 use crate::i18n::{self, Lang};21 use crate::i18n::{self, Lang};
22+use crate::layers::bump_review_requests;
22 use crate::live::{Topic, stream_wakes};23 use crate::live::{Topic, stream_wakes};
23 use crate::notify;24 use crate::notify;
24 use crate::pages::issue_parts::{ItemKind, check_write, may_change, parse_number};25 use crate::pages::issue_parts::{ItemKind, check_write, may_change, parse_number};
@@ -42,31 +43,6 @@ struct ReviewerForm {
42 username: String,43 username: String,
43 }44 }
44 45
45-/// Wakes the review-request list of `user_id`: a request was added or withdrawn, or the user
46-/// submitted a review (which clears their own request).
47-pub fn bump_review_requests(state: &AppState, user_id: &str) {
48- state.live.bump(&Topic::ReviewRequests(user_id.to_owned()));
49-}
50-
51-/// Wakes the review-request lists of everyone with a pending request on the pull request. Call it
52-/// after the pull closed or merged, which drops it from those lists.
53-pub async fn bump_pending_reviewers(state: &AppState, issue_id: &str) {
54- let names = match state.store.requested_reviewers(issue_id).await {
55- Ok(names) => names,
56- Err(e) => {
57- tracing::error!(error = %e, issue_id, "live: listing reviewers to bump failed");
58- return;
59- }
60- };
61- for name in names {
62- match state.store.user_by_username(&name).await {
63- Ok(Some(user)) => bump_review_requests(state, &user.id),
64- Ok(None) => {}
65- Err(e) => tracing::error!(error = %e, name, "live: loading a reviewer to bump failed"),
66- }
67- }
68-}
69-
70 /// The review-request list's stream. The viewer comes from the session only, so a user follows only46 /// The review-request list's stream. The viewer comes from the session only, so a user follows only
71 /// their own list. Without a session: 401.47 /// their own list. Without a session: 401.
72 #[route(GET "/review-requests/events")]48 #[route(GET "/review-requests/events")]
crates/forge-web/src/pages/settings_live.rsmodified+2 -36
@@ -29,12 +29,11 @@ use tokio::sync::watch;
29 use topcoat::Result;29 use topcoat::Result;
30 use topcoat::context::{Cx, context, try_context};30 use topcoat::context::{Cx, context, try_context};
31 use topcoat::router::content::sse::Event;31 use topcoat::router::content::sse::Event;
32-use topcoat::router::request::{method, uri};
33 use topcoat::router::response::Response;32 use topcoat::router::response::Response;
34-use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode, route};33+use topcoat::router::{Body, StatusCode, route};
35 34
36 use crate::auth::current_user;35 use crate::auth::current_user;
37-use crate::live::{LiveHub, Topic, bump_account, events_response, stream_wakes};36+use crate::live::{LiveHub, Topic, events_response, stream_wakes};
38 use crate::state::AppState;37 use crate::state::AppState;
39 38
40 /// The change stream of the viewer's settings. The viewer comes from the session only, so a user39 /// The change stream of the viewer's settings. The viewer comes from the session only, so a user
@@ -271,39 +270,6 @@ async fn next_alive_event(mut alive: Alive) -> Option<(Result<Event>, Alive)> {
271 }270 }
272 }271 }
273 272
274-/// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router
275-/// in `boot.rs` and the test router. It sits on a path, so it runs inside the cookie layer (a
276-/// pathless layer would run outside it, where the session cannot be read).
277-pub struct AccountWriteLayer;
278-
279-impl Layer for AccountWriteLayer {
280- fn path(&self) -> Option<&Path> {
281- Some(Path::new("/settings"))
282- }
283-
284- fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
285- Box::pin(bump_after_settings_write(cx, body, next))
286- }
287-}
288-
289-/// Bumps the viewer's topic once the handler has run. The viewer is read before the handler, so a
290-/// write that ends the viewer's own session (a revoke of the current one) still wakes the tabs.
291-async fn bump_after_settings_write(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> {
292- if *method(cx) != Method::POST || !uri(cx).path().starts_with("/settings/") {
293- return next.run(cx, body).await;
294- }
295- let viewer = current_user(cx)
296- .await
297- .ok()
298- .flatten()
299- .map(|(user, _)| user.id);
300- let result = next.run(cx, body).await;
301- if let Some(user_id) = viewer {
302- bump_account(context::<AppState>(cx), &user_id);
303- }
304- result
305-}
306-
307 #[cfg(test)]273 #[cfg(test)]
308 mod tests {274 mod tests {
309 use std::collections::BTreeMap;275 use std::collections::BTreeMap;
crates/forge-web/src/test_support.rsmodified+6 -6
@@ -17,7 +17,7 @@ use topcoat::cookie::CookieLayer;
17 use topcoat::router::tower::TowerLayer;17 use topcoat::router::tower::TowerLayer;
18 use topcoat::router::{Compression, Router, RouterBuilderDiscoverExt};18 use topcoat::router::{Compression, Router, RouterBuilderDiscoverExt};
19 19
20-use crate::pages::repo_ctx::RepoMovedLayer;20+use crate::layers::RepoMovedLayer;
21 use crate::state::AppState;21 use crate::state::AppState;
22 use crate::throttle::Throttle;22 use crate::throttle::Throttle;
23 23
@@ -105,13 +105,13 @@ pub fn app_router(state: AppState) -> Router {
105 Router::builder()105 Router::builder()
106 .discover()106 .discover()
107 .with(state)107 .with(state)
108- .layer(crate::pages::settings_live::AccountWriteLayer)108+ .layer(crate::layers::AccountWriteLayer)
109 .layer(CookieLayer::new())109 .layer(CookieLayer::new())
110 .layer(RepoMovedLayer)110 .layer(RepoMovedLayer)
111- .layer(crate::pages::repo_settings_live::RepoSettingsWriteLayer)111+ .layer(crate::layers::RepoSettingsWriteLayer)
112- .layer(crate::pages::pull_live::PullWriteLayer)112+ .layer(crate::layers::PullWriteLayer)
113- .layer(crate::pages::discussion_live::DiscussionWriteLayer)113+ .layer(crate::layers::DiscussionWriteLayer)
114- .layer(crate::pages::org_live::OrgWriteLayer)114+ .layer(crate::layers::OrgWriteLayer)
115 .layer(TowerLayer::new(crate::compression::ResponseCompression))115 .layer(TowerLayer::new(crate::compression::ResponseCompression))
116 .with(Compression::disable())116 .with(Compression::disable())
117 .build()117 .build()