From 0e737250aedc757495d059b76c006d2f9efa9cc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 1 Dec 2026 06:41:28 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20the=20router?= =?UTF-8?q?=20layers=20move=20from=20pages=20into=20layers.rs,=20so=20the?= =?UTF-8?q?=20test=20router=20and=20boot=20build=20the=20layer=20stack=20w?= =?UTF-8?q?ithout=20reaching=20into=20pages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-web/src/boot.rs | 14 +- crates/forge-web/src/layers.rs | 610 ++++++++++++++++++ crates/forge-web/src/main.rs | 1 + crates/forge-web/src/pages/commit.rs | 3 +- crates/forge-web/src/pages/discussion_live.rs | 99 +-- crates/forge-web/src/pages/not_found_page.rs | 54 +- crates/forge-web/src/pages/org_live.rs | 56 +- crates/forge-web/src/pages/pull_live.rs | 101 +-- crates/forge-web/src/pages/pull_reviews.rs | 2 +- crates/forge-web/src/pages/pulls_merge.rs | 6 +- crates/forge-web/src/pages/repo_ctx.rs | 111 +--- .../forge-web/src/pages/repo_settings_live.rs | 67 +- crates/forge-web/src/pages/review_requests.rs | 26 +- crates/forge-web/src/pages/settings_live.rs | 38 +- crates/forge-web/src/test_support.rs | 12 +- 15 files changed, 644 insertions(+), 556 deletions(-) create mode 100644 crates/forge-web/src/layers.rs diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 45dcc8d..6b16f44 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -170,14 +170,14 @@ pub async fn serve( let public: Router = Router::builder() .discover() .with(state.clone()) - .layer(crate::pages::settings_live::AccountWriteLayer) + .layer(crate::layers::AccountWriteLayer) .layer(CookieLayer::new()) - .layer(crate::pages::repo_ctx::RepoMovedLayer) - .layer(crate::pages::pull_live::PullWriteLayer) - .layer(crate::pages::discussion_live::DiscussionWriteLayer) - .layer(crate::pages::org_live::OrgWriteLayer) - .layer(crate::pages::repo_settings_live::RepoSettingsWriteLayer) - .layer(crate::pages::not_found_page::NotFoundLayer) + .layer(crate::layers::RepoMovedLayer) + .layer(crate::layers::PullWriteLayer) + .layer(crate::layers::DiscussionWriteLayer) + .layer(crate::layers::OrgWriteLayer) + .layer(crate::layers::RepoSettingsWriteLayer) + .layer(crate::layers::NotFoundLayer) .layer(TowerLayer::new(crate::compression::ResponseCompression)) .with(Compression::disable()) .build(); diff --git a/crates/forge-web/src/layers.rs b/crates/forge-web/src/layers.rs new file mode 100644 index 0000000..b7091ee --- /dev/null +++ b/crates/forge-web/src/layers.rs @@ -0,0 +1,610 @@ +use std::fmt; + +use crate::live::Topic; +use crate::state::AppState; + +pub use discussion_write::DiscussionWriteLayer; +pub use not_found_layer::NotFoundLayer; +pub use org_write::OrgWriteLayer; +pub use pull_write::PullWriteLayer; +pub use repo_moved::RepoMovedLayer; +pub use repo_settings_write::RepoSettingsWriteLayer; +pub use settings_write::AccountWriteLayer; + +/// Raised by `load_repo` when the requested owner/name is a past name of a repo the viewer may +/// read. The `repo_moved` layer turns it into a 307 to `location`. +#[derive(Debug)] +pub struct RepoMoved { + pub location: String, +} + +impl fmt::Display for RepoMoved { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("repository moved") + } +} + +impl std::error::Error for RepoMoved {} + +/// A plain-text download (a `.patch` or `.diff`) raised by a page handler that cannot return a +/// response of its own. The `repo_moved` layer turns it into a 200 with these bytes. +#[derive(Debug, Clone)] +pub struct RawDownload { + pub content_type: &'static str, + /// File name offered to the browser. + pub filename: String, + pub data: Vec, +} + +impl fmt::Display for RawDownload { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("raw download") + } +} + +impl std::error::Error for RawDownload {} + +/// Wakes the review-request list of `user_id`: a request was added or withdrawn, or the user +/// submitted a review (which clears their own request). +pub fn bump_review_requests(state: &AppState, user_id: &str) { + state.live.bump(&Topic::ReviewRequests(user_id.to_owned())); +} + +/// Wakes the review-request lists of everyone with a pending request on the pull request. Call it +/// after the pull closed or merged, which drops it from those lists. +pub async fn bump_pending_reviewers(state: &AppState, issue_id: &str) { + let names = match state.store.requested_reviewers(issue_id).await { + Ok(names) => names, + Err(e) => { + tracing::error!(error = %e, issue_id, "live: listing reviewers to bump failed"); + return; + } + }; + for name in names { + match state.store.user_by_username(&name).await { + Ok(Some(user)) => bump_review_requests(state, &user.id), + Ok(None) => {} + Err(e) => tracing::error!(error = %e, name, "live: loading a reviewer to bump failed"), + } + } +} + +mod settings_write { + use topcoat::Result; + use topcoat::context::{Cx, context}; + use topcoat::router::request::{method, uri}; + use topcoat::router::response::Response; + use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; + + use crate::auth::current_user; + use crate::live::bump_account; + use crate::state::AppState; + + /// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router + /// in `boot.rs` and the test router. It sits on a path, so it runs inside the cookie layer (a + /// pathless layer would run outside it, where the session cannot be read). + pub struct AccountWriteLayer; + + impl Layer for AccountWriteLayer { + fn path(&self) -> Option<&Path> { + Some(Path::new("/settings")) + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(bump_after_settings_write(cx, body, next)) + } + } + + /// Bumps the viewer's topic once the handler has run. The viewer is read before the handler, so a + /// write that ends the viewer's own session (a revoke of the current one) still wakes the tabs. + async fn bump_after_settings_write(cx: &Cx, body: Body, next: Next<'_>) -> Result { + if *method(cx) != Method::POST || !uri(cx).path().starts_with("/settings/") { + return next.run(cx, body).await; + } + let viewer = current_user(cx) + .await + .ok() + .flatten() + .map(|(user, _)| user.id); + let result = next.run(cx, body).await; + if let Some(user_id) = viewer { + bump_account(context::(cx), &user_id); + } + result + } +} + +mod repo_moved { + use http::{ + HeaderValue, + header::{CACHE_CONTROL, LOCATION}, + }; + use topcoat::Result; + use topcoat::context::Cx; + use topcoat::router::error::not_found; + use topcoat::router::response::Response; + use topcoat::router::{Body, Layer, LayerFuture, Next, Path, StatusCode}; + + use super::{RawDownload, RepoMoved}; + + /// Wraps every request (no path) so a `RepoMoved` error becomes a 307. Registered explicitly on the + /// public router in `boot.rs`: a `#[layer("/")]` would clash with the security-headers layer. + pub struct RepoMovedLayer; + + impl Layer for RepoMovedLayer { + fn path(&self) -> Option<&Path> { + None + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(repo_moved(cx, body, next)) + } + } + + /// Turns a `RepoMoved` error from a handler into a 307 with the new location, and a `RawDownload` + /// into its plain-text response. Other errors pass through unchanged. + async fn repo_moved(cx: &Cx, body: Body, next: Next<'_>) -> Result { + let error = match next.run(cx, body).await { + Ok(response) => return Ok(response), + Err(error) => error, + }; + let error = match error.downcast_cloned::() { + Ok(download) => { + return raw_download_response(download).ok_or_else(|| not_found().into()); + } + Err(error) => error, + }; + match error.downcast_ref::() { + Some(moved) => { + let mut response = Response::new(Body::empty()); + // Temporary and uncached: an old name can be taken by a new repo later, and a browser + // that cached a 301 would keep sending its visitors to the renamed repo. + *response.status_mut() = StatusCode::TEMPORARY_REDIRECT; + // Owner and repo names are plain ASCII and the query came from a valid URI, so this + // only fails on a corrupt location; a 404 is the safe answer then. + let Ok(location) = HeaderValue::from_str(&moved.location) else { + return Err(not_found().into()); + }; + response.headers_mut().insert(LOCATION, location); + response + .headers_mut() + .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); + Ok(response) + } + None => Err(error), + } + } + + /// The 200 response for a [`RawDownload`]. `None` when the file name is not a valid header value. + fn raw_download_response(download: RawDownload) -> Option { + let mut response = Response::new(Body::from(download.data)); + let headers = response.headers_mut(); + headers.insert( + http::header::CONTENT_TYPE, + HeaderValue::from_static(download.content_type), + ); + headers.insert( + http::header::CONTENT_DISPOSITION, + HeaderValue::from_str(&format!("inline; filename=\"{}\"", download.filename)).ok()?, + ); + headers.insert( + http::header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + headers.insert( + http::header::CACHE_CONTROL, + HeaderValue::from_static("private, no-cache"), + ); + Some(response) + } +} + +mod pull_write { + use topcoat::context::{Cx, context}; + use topcoat::router::request::{method, uri}; + use topcoat::router::response::Response; + use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; + + use super::bump_pending_reviewers; + use crate::live::{bump_list, bump_pull, bump_repo_pulls}; + use crate::state::AppState; + + /// Which topic a POST under the pulls paths writes to. + enum Written { + /// A write to one pull request (`/{o}/{r}/pulls/{n}/...`). + Pull { + owner: String, + repo: String, + number: i64, + }, + /// A new pull request (`/{o}/{r}/pulls`). + New { owner: String, repo: String }, + /// A repo-wide change the pulls show: a label or milestone edit. + Repo { owner: String, repo: String }, + } + + /// The write a request makes to the pull side, when it is a POST that can change one. + fn written(cx: &Cx) -> Option { + if *method(cx) != Method::POST { + return None; + } + let path = uri(cx).path().to_owned(); + let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); + let [owner, repo, kind, rest @ ..] = parts.as_slice() else { + return None; + }; + let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned()); + match (*kind, rest) { + ("pulls", []) => Some(Written::New { owner, repo }), + ("pulls", [number, ..]) => number.parse().ok().map(|number| Written::Pull { + owner, + repo, + number, + }), + ("labels" | "milestones", _) => Some(Written::Repo { owner, repo }), + _ => None, + } + } + + /// Wraps every request. Only a POST under the pulls paths, or to a label or milestone route, does + /// anything. Registered on the public router in `boot.rs`, next to the other request layers. + pub struct PullWriteLayer; + + impl Layer for PullWriteLayer { + fn path(&self) -> Option<&Path> { + None + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(bump_after_write(cx, body, next)) + } + } + + /// Bumps the topics a write named, once the handler has run. The handler's result passes through + /// unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and agrees. + async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result { + let target = written(cx); + let result = next.run(cx, body).await; + if let Some(target) = target { + bump_written(context::(cx), target).await; + } + result + } + + async fn bump_written(state: &AppState, target: Written) { + let (owner, name) = match &target { + Written::Pull { owner, repo, .. } + | Written::New { owner, repo } + | Written::Repo { owner, repo } => (owner.as_str(), repo.as_str()), + }; + let repo = match state.store.repo_by_owner_and_name(owner, name).await { + Ok(Some(repo)) => repo, + Ok(None) => return, + Err(e) => { + tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed"); + return; + } + }; + match target { + Written::Pull { number, .. } => { + match state.store.pull_by_number(&repo.id, number).await { + Ok(Some(pr)) => { + bump_pull(state, &repo.id, &pr.issue.id); + // A closed or merged pull leaves its reviewers' request lists. + if pr.issue.state != forge_core::IssueState::Open || pr.merged_at.is_some() + { + bump_pending_reviewers(state, &pr.issue.id).await; + } + } + Ok(None) => {} + Err(e) => { + tracing::error!(error = %e, number, "live: loading the pull to bump failed") + } + } + } + Written::New { .. } => bump_list(state, &repo.id), + Written::Repo { .. } => bump_repo_pulls(state, &repo.id).await, + } + } +} + +mod discussion_write { + use topcoat::context::{Cx, context}; + use topcoat::router::request::{method, uri}; + use topcoat::router::response::Response; + use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; + + use crate::live::Topic; + use crate::state::AppState; + + /// Which topics a discussion write reaches. + enum Written { + /// A new discussion, or the discussions toggle of the repo settings: the list. + List { owner: String, repo: String }, + /// A write to one discussion (`/{o}/{r}/discussions/{n}/...`): the list and the discussion. + Discussion { + owner: String, + repo: String, + number: String, + }, + } + + /// The write a request makes to the discussion side, when it is a POST that can change one. + fn written(cx: &Cx) -> Option { + if *method(cx) != Method::POST { + return None; + } + let path = uri(cx).path().to_owned(); + let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); + let [owner, repo, kind, rest @ ..] = parts.as_slice() else { + return None; + }; + let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned()); + match (*kind, rest) { + ("discussions", ["new"]) => Some(Written::List { owner, repo }), + ("discussions", [number, ..]) => Some(Written::Discussion { + owner, + repo, + number: (*number).to_owned(), + }), + ("settings", ["discussions"]) => Some(Written::List { owner, repo }), + _ => None, + } + } + + /// The topics a write reaches, looked up before the handler runs. A repo or discussion that does + /// not exist yields nothing, and a failed lookup is logged. + async fn topics_of(state: &AppState, target: Written) -> Vec { + let (owner, name) = match &target { + Written::List { owner, repo } | Written::Discussion { owner, repo, .. } => { + (owner.as_str(), repo.as_str()) + } + }; + let repo = match state.store.repo_by_owner_and_name(owner, name).await { + Ok(Some(repo)) => repo, + Ok(None) => return Vec::new(), + Err(e) => { + tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed"); + return Vec::new(); + } + }; + let mut topics = vec![Topic::Discussions(repo.id.clone())]; + if let Written::Discussion { number, .. } = target + && let Ok(number) = number.parse::() + { + match state.store.discussion_by_number(&repo.id, number).await { + Ok(Some(discussion)) => topics.push(Topic::Discussion(discussion.id)), + Ok(None) => {} + Err(e) => { + tracing::error!(error = %e, number, "live: loading the discussion to bump failed") + } + } + } + topics + } + + /// Wraps every request. Only a POST under the discussions paths, or the discussions settings + /// toggle, does anything. Registered on the public router in `boot.rs`, next to the other layers. + pub struct DiscussionWriteLayer; + + impl Layer for DiscussionWriteLayer { + fn path(&self) -> Option<&Path> { + None + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(bump_after_write(cx, body, next)) + } + } + + /// Bumps the topics a write reaches, once the handler has run. The handler's result passes + /// through unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and + /// agrees. + async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result { + let state = context::(cx); + let topics = match written(cx) { + Some(target) => topics_of(state, target).await, + None => Vec::new(), + }; + let result = next.run(cx, body).await; + for topic in &topics { + state.live.bump(topic); + } + result + } +} + +mod org_write { + use topcoat::context::{Cx, context}; + use topcoat::router::request::{method, uri}; + use topcoat::router::response::Response; + use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; + + use crate::live::Topic; + use crate::state::AppState; + + /// The org a POST under `/org/{org}/{members|teams|settings}` writes to, by its name. + fn written_org(cx: &Cx) -> Option { + if *method(cx) != Method::POST { + return None; + } + let path = uri(cx).path().to_owned(); + let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); + let ["org", name, kind, ..] = parts.as_slice() else { + return None; + }; + matches!(*kind, "members" | "teams" | "settings").then(|| (*name).to_owned()) + } + + /// Wraps every request. Only a POST under an org's members, teams or settings does anything. + /// Registered on the public router in `boot.rs`, next to the pull write layer. + pub struct OrgWriteLayer; + + impl Layer for OrgWriteLayer { + fn path(&self) -> Option<&Path> { + None + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(bump_after_write(cx, body, next)) + } + } + + /// Bumps the org's topic after the handler ran. The org is looked up before the handler, so a + /// write that removes the org (its deletion) still reaches the streams that follow it. The + /// handler's result passes through unchanged. + async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result { + let Some(name) = written_org(cx) else { + return next.run(cx, body).await; + }; + let state = context::(cx); + let org_id = match state.store.user_by_username(&name).await { + Ok(Some(org)) if org.is_org() => Some(org.id), + Ok(_) => None, + Err(e) => { + tracing::error!(error = %e, name, "live: loading the org to bump failed"); + None + } + }; + let result = next.run(cx, body).await; + if let Some(org_id) = org_id { + state.live.bump(&Topic::Org(org_id.clone())); + state.live.bump(&Topic::User(org_id)); + } + result + } +} + +mod repo_settings_write { + use topcoat::Result; + use topcoat::context::{Cx, context}; + use topcoat::router::request::{method, uri}; + use topcoat::router::response::Response; + use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; + + use crate::live::{Topic, bump_repo_pulls, bump_settings}; + use crate::state::AppState; + + /// Wraps every request. Only a POST under the settings or security paths does anything. Registered + /// on the public router in `boot.rs`, and on the test router, next to the other request layers. + pub struct RepoSettingsWriteLayer; + + impl Layer for RepoSettingsWriteLayer { + fn path(&self) -> Option<&Path> { + None + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(bump_after_write(cx, body, next)) + } + } + + /// The `(owner, name)` of a POST under `/{o}/{r}/settings/...` or `/{o}/{r}/security/...`. + fn written(cx: &Cx) -> Option<(String, String)> { + if *method(cx) != Method::POST { + return None; + } + let path = uri(cx).path().to_owned(); + let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); + match parts.as_slice() { + [owner, name, "settings" | "security", ..] => { + Some(((*owner).to_owned(), (*name).to_owned())) + } + _ => None, + } + } + + /// Bumps the settings topic once the handler has run. The repo is looked up before the handler, + /// because a rename moves its name away. The handler's result passes through unchanged, so a + /// refused write bumps too: the page re-reads and agrees. + async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> Result { + let repo_id = match written(cx) { + Some((owner, name)) => { + let state = context::(cx); + match state.store.repo_by_owner_and_name(&owner, &name).await { + Ok(repo) => repo.map(|repo| repo.id), + Err(e) => { + tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed"); + None + } + } + } + None => None, + }; + let result = next.run(cx, body).await; + if let Some(repo_id) = repo_id { + let state = context::(cx); + bump_settings(&state.live, &repo_id); + // The repo header shows settings too (the mirror line, the archived notice, the tabs); its + // stream sends nothing when its fingerprint holds. + state.live.bump(&Topic::Repo(repo_id.clone())); + // The merge gate of a pull page reads the branch protection rules, so every pull of the + // repo may show a different gate. A pull's stream sends nothing when its fingerprint holds. + bump_repo_pulls(state, &repo_id).await; + } + result + } +} + +mod not_found_layer { + use http::header::ACCEPT; + use topcoat::Result; + use topcoat::context::Cx; + use topcoat::router::error::{ForbiddenError, NotFoundError, rewrite}; + use topcoat::router::request::headers; + use topcoat::router::response::Response; + use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; + + use crate::auth::percent_encode; + + /// The styled 404 and 403 pages. Topcoat answers `not_found()` and `forbidden()` with a bare text + /// body, so this layer swaps that body for the regular shell plus a short message, for browser + /// requests only. A signed-out visitor refused a page is sent to log in first, as every page that + /// needs an account does. + pub struct NotFoundLayer; + + impl Layer for NotFoundLayer { + fn path(&self) -> Option<&Path> { + None + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(styled_not_found(cx, body, next)) + } + } + + async fn styled_not_found(cx: &Cx, body: Body, next: Next<'_>) -> Result { + let is_get = *topcoat::router::request::method(cx) == Method::GET; + let result = next.run(cx, body).await; + let is_not_found = matches!(&result, Err(e) if e.downcast_ref::().is_some()); + let is_forbidden = + matches!(&result, Err(e) if e.downcast_ref::().is_some()); + let wants_html = headers(cx) + .get(ACCEPT) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.contains("text/html")); + if !wants_html || !(is_not_found || is_forbidden) { + return result; + } + if is_forbidden { + // The cookies are not readable out here, so the page itself decides whether the visitor + // must log in first; a refused GET hands it the address to come back to. + let target = if is_get { + let path = topcoat::router::request::uri(cx) + .path_and_query() + .map_or("/", |p| p.as_str()); + format!("{FORBIDDEN_PATH}?next={}", percent_encode(path)) + } else { + FORBIDDEN_PATH.to_owned() + }; + return Err(rewrite(target, Body::empty()).method(Method::GET).into()); + } + Err(rewrite(PATH, Body::empty()).method(Method::GET).into()) + } + + /// Where the layer sends a browser's 403. The page answers with status 403 itself. + const FORBIDDEN_PATH: &str = "/-/forbidden"; + + /// Where the layer sends a browser's 404. The page answers with status 404 itself. + const PATH: &str = "/-/not-found"; +} diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index 324f0f4..4815bb6 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -33,6 +33,7 @@ mod git_http; mod hook_cmd; mod importer; mod internal; +mod layers; mod lfs; mod lfs_pointer; mod live; diff --git a/crates/forge-web/src/pages/commit.rs b/crates/forge-web/src/pages/commit.rs index 350c049..77998d2 100644 --- a/crates/forge-web/src/pages/commit.rs +++ b/crates/forge-web/src/pages/commit.rs @@ -12,10 +12,11 @@ use topcoat::view::{View, view}; use crate::i18n::code::{self as g, K}; use crate::i18n::{self}; +use crate::layers::RawDownload; use crate::pages::commits::{SigBadgeView, blocking, iso_time, now_secs, short_oid}; use crate::pages::ref_live; use crate::pages::repo::repo_head; -use crate::pages::repo_ctx::{RawDownload, load_repo}; +use crate::pages::repo_ctx::load_repo; use crate::render::commit_message::CommitMessage; use crate::render::emoji::emojify; use crate::signatures; diff --git a/crates/forge-web/src/pages/discussion_live.rs b/crates/forge-web/src/pages/discussion_live.rs index ea9f744..647507b 100644 --- a/crates/forge-web/src/pages/discussion_live.rs +++ b/crates/forge-web/src/pages/discussion_live.rs @@ -14,9 +14,8 @@ use topcoat::Result; use topcoat::context::{Cx, context}; -use topcoat::router::request::{method, uri}; use topcoat::router::response::Response; -use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route}; +use topcoat::router::{path_param, route}; use crate::live::{Topic, stream_wakes}; use crate::pages::discussions::{discussion_by_number, ensure_enabled}; @@ -57,99 +56,3 @@ async fn discussion_live(cx: &Cx) -> Result { } // The write layer - -/// Which topics a discussion write reaches. -enum Written { - /// A new discussion, or the discussions toggle of the repo settings: the list. - List { owner: String, repo: String }, - /// A write to one discussion (`/{o}/{r}/discussions/{n}/...`): the list and the discussion. - Discussion { - owner: String, - repo: String, - number: String, - }, -} - -/// The write a request makes to the discussion side, when it is a POST that can change one. -fn written(cx: &Cx) -> Option { - if *method(cx) != Method::POST { - return None; - } - let path = uri(cx).path().to_owned(); - let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); - let [owner, repo, kind, rest @ ..] = parts.as_slice() else { - return None; - }; - let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned()); - match (*kind, rest) { - ("discussions", ["new"]) => Some(Written::List { owner, repo }), - ("discussions", [number, ..]) => Some(Written::Discussion { - owner, - repo, - number: (*number).to_owned(), - }), - ("settings", ["discussions"]) => Some(Written::List { owner, repo }), - _ => None, - } -} - -/// The topics a write reaches, looked up before the handler runs. A repo or discussion that does -/// not exist yields nothing, and a failed lookup is logged. -async fn topics_of(state: &AppState, target: Written) -> Vec { - let (owner, name) = match &target { - Written::List { owner, repo } | Written::Discussion { owner, repo, .. } => { - (owner.as_str(), repo.as_str()) - } - }; - let repo = match state.store.repo_by_owner_and_name(owner, name).await { - Ok(Some(repo)) => repo, - Ok(None) => return Vec::new(), - Err(e) => { - tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed"); - return Vec::new(); - } - }; - let mut topics = vec![Topic::Discussions(repo.id.clone())]; - if let Written::Discussion { number, .. } = target - && let Ok(number) = number.parse::() - { - match state.store.discussion_by_number(&repo.id, number).await { - Ok(Some(discussion)) => topics.push(Topic::Discussion(discussion.id)), - Ok(None) => {} - Err(e) => { - tracing::error!(error = %e, number, "live: loading the discussion to bump failed") - } - } - } - topics -} - -/// Bumps the topics a write reaches, once the handler has run. The handler's result passes -/// through unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and -/// agrees. -async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result { - let state = context::(cx); - let topics = match written(cx) { - Some(target) => topics_of(state, target).await, - None => Vec::new(), - }; - let result = next.run(cx, body).await; - for topic in &topics { - state.live.bump(topic); - } - result -} - -/// Wraps every request. Only a POST under the discussions paths, or the discussions settings -/// toggle, does anything. Registered on the public router in `boot.rs`, next to the other layers. -pub struct DiscussionWriteLayer; - -impl Layer for DiscussionWriteLayer { - fn path(&self) -> Option<&Path> { - None - } - - fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { - Box::pin(bump_after_write(cx, body, next)) - } -} diff --git a/crates/forge-web/src/pages/not_found_page.rs b/crates/forge-web/src/pages/not_found_page.rs index c28bd7e..54c7eed 100644 --- a/crates/forge-web/src/pages/not_found_page.rs +++ b/crates/forge-web/src/pages/not_found_page.rs @@ -3,33 +3,17 @@ //! requests only. A signed-out visitor refused a page is sent to log in first, as every page that //! needs an account does. -use http::header::ACCEPT; use topcoat::Result; use topcoat::context::Cx; -use topcoat::router::error::{ForbiddenError, NotFoundError, rewrite}; +use topcoat::router::StatusCode; use topcoat::router::page; -use topcoat::router::request::headers; -use topcoat::router::response::Response; -use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode}; use topcoat::view::{View, component, view}; -use crate::auth::{current_user, percent_encode}; +use crate::auth::current_user; use crate::i18n::{self, Lang}; use crate::views::parts::{SubPart, head}; use crate::views::shell; -pub struct NotFoundLayer; - -impl Layer for NotFoundLayer { - fn path(&self) -> Option<&Path> { - None - } - - fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { - Box::pin(styled_not_found(cx, body, next)) - } -} - fn texts(lang: Lang) -> (&'static str, &'static str, &'static str) { match lang { Lang::En => ( @@ -54,37 +38,6 @@ async fn not_found_body(cx: &Cx, lang: Lang) -> Result { }) } -async fn styled_not_found(cx: &Cx, body: Body, next: Next<'_>) -> Result { - let is_get = *topcoat::router::request::method(cx) == Method::GET; - let result = next.run(cx, body).await; - let is_not_found = matches!(&result, Err(e) if e.downcast_ref::().is_some()); - let is_forbidden = matches!(&result, Err(e) if e.downcast_ref::().is_some()); - let wants_html = headers(cx) - .get(ACCEPT) - .and_then(|v| v.to_str().ok()) - .is_some_and(|v| v.contains("text/html")); - if !wants_html || !(is_not_found || is_forbidden) { - return result; - } - if is_forbidden { - // The cookies are not readable out here, so the page itself decides whether the visitor - // must log in first; a refused GET hands it the address to come back to. - let target = if is_get { - let path = topcoat::router::request::uri(cx) - .path_and_query() - .map_or("/", |p| p.as_str()); - format!("{FORBIDDEN_PATH}?next={}", percent_encode(path)) - } else { - FORBIDDEN_PATH.to_owned() - }; - return Err(rewrite(target, Body::empty()).method(Method::GET).into()); - } - Err(rewrite(PATH, Body::empty()).method(Method::GET).into()) -} - -/// Where the layer sends a browser's 403. The page answers with status 403 itself. -const FORBIDDEN_PATH: &str = "/-/forbidden"; - fn forbidden_texts(lang: Lang) -> (&'static str, &'static str, &'static str) { match lang { Lang::En => ( @@ -129,9 +82,6 @@ async fn forbidden_page(cx: &Cx) -> Result { }) } -/// Where the layer sends a browser's 404. The page answers with status 404 itself. -const PATH: &str = "/-/not-found"; - #[page("/-/not-found")] async fn not_found_page(cx: &Cx) -> Result { let viewer = current_user(cx).await?; diff --git a/crates/forge-web/src/pages/org_live.rs b/crates/forge-web/src/pages/org_live.rs index 3c6b2df..1132b69 100644 --- a/crates/forge-web/src/pages/org_live.rs +++ b/crates/forge-web/src/pages/org_live.rs @@ -16,9 +16,8 @@ use forge_core::store::Store; use forge_core::store::orgs::OrgMemberRole; use topcoat::Result; use topcoat::context::{Cx, context}; -use topcoat::router::request::{method, uri}; use topcoat::router::response::Response; -use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route}; +use topcoat::router::{path_param, route}; use crate::live::{Topic, stream_changes}; 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 { }) .await } - -// The write layer - -/// The org a POST under `/org/{org}/{members|teams|settings}` writes to, by its name. -fn written_org(cx: &Cx) -> Option { - if *method(cx) != Method::POST { - return None; - } - let path = uri(cx).path().to_owned(); - let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); - let ["org", name, kind, ..] = parts.as_slice() else { - return None; - }; - matches!(*kind, "members" | "teams" | "settings").then(|| (*name).to_owned()) -} - -/// Bumps the org's topic after the handler ran. The org is looked up before the handler, so a -/// write that removes the org (its deletion) still reaches the streams that follow it. The -/// handler's result passes through unchanged. -async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result { - let Some(name) = written_org(cx) else { - return next.run(cx, body).await; - }; - let state = context::(cx); - let org_id = match state.store.user_by_username(&name).await { - Ok(Some(org)) if org.is_org() => Some(org.id), - Ok(_) => None, - Err(e) => { - tracing::error!(error = %e, name, "live: loading the org to bump failed"); - None - } - }; - let result = next.run(cx, body).await; - if let Some(org_id) = org_id { - state.live.bump(&Topic::Org(org_id.clone())); - state.live.bump(&Topic::User(org_id)); - } - result -} - -/// Wraps every request. Only a POST under an org's members, teams or settings does anything. -/// Registered on the public router in `boot.rs`, next to the pull write layer. -pub struct OrgWriteLayer; - -impl Layer for OrgWriteLayer { - fn path(&self) -> Option<&Path> { - None - } - - fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { - Box::pin(bump_after_write(cx, body, next)) - } -} diff --git a/crates/forge-web/src/pages/pull_live.rs b/crates/forge-web/src/pages/pull_live.rs index fcb478b..6708520 100644 --- a/crates/forge-web/src/pages/pull_live.rs +++ b/crates/forge-web/src/pages/pull_live.rs @@ -20,11 +20,10 @@ use forge_core::reactions::ReactionTarget; use forge_core::store::Store; use topcoat::Result; use topcoat::context::{Cx, context}; -use topcoat::router::request::{method, uri}; use topcoat::router::response::Response; -use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route}; +use topcoat::router::{path_param, route}; -use crate::live::{Topic, bump_list, bump_pull, bump_repo_pulls, stream_changes}; +use crate::live::{Topic, stream_changes}; use crate::pages::issue_parts::parse_number; use crate::pages::repo_ctx::load_repo; use crate::state::AppState; @@ -196,99 +195,3 @@ async fn pull_events(cx: &Cx) -> Result { }) .await } - -// The write layer - -/// Which topic a POST under the pulls paths writes to. -enum Written { - /// A write to one pull request (`/{o}/{r}/pulls/{n}/...`). - Pull { - owner: String, - repo: String, - number: i64, - }, - /// A new pull request (`/{o}/{r}/pulls`). - New { owner: String, repo: String }, - /// A repo-wide change the pulls show: a label or milestone edit. - Repo { owner: String, repo: String }, -} - -/// The write a request makes to the pull side, when it is a POST that can change one. -fn written(cx: &Cx) -> Option { - if *method(cx) != Method::POST { - return None; - } - let path = uri(cx).path().to_owned(); - let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); - let [owner, repo, kind, rest @ ..] = parts.as_slice() else { - return None; - }; - let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned()); - match (*kind, rest) { - ("pulls", []) => Some(Written::New { owner, repo }), - ("pulls", [number, ..]) => number.parse().ok().map(|number| Written::Pull { - owner, - repo, - number, - }), - ("labels" | "milestones", _) => Some(Written::Repo { owner, repo }), - _ => None, - } -} - -/// Bumps the topics a write named, once the handler has run. The handler's result passes through -/// unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and agrees. -async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result { - let target = written(cx); - let result = next.run(cx, body).await; - if let Some(target) = target { - bump_written(context::(cx), target).await; - } - result -} - -async fn bump_written(state: &AppState, target: Written) { - let (owner, name) = match &target { - Written::Pull { owner, repo, .. } - | Written::New { owner, repo } - | Written::Repo { owner, repo } => (owner.as_str(), repo.as_str()), - }; - let repo = match state.store.repo_by_owner_and_name(owner, name).await { - Ok(Some(repo)) => repo, - Ok(None) => return, - Err(e) => { - tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed"); - return; - } - }; - match target { - Written::Pull { number, .. } => match state.store.pull_by_number(&repo.id, number).await { - Ok(Some(pr)) => { - bump_pull(state, &repo.id, &pr.issue.id); - // A closed or merged pull leaves its reviewers' request lists. - if pr.issue.state != forge_core::IssueState::Open || pr.merged_at.is_some() { - crate::pages::review_requests::bump_pending_reviewers(state, &pr.issue.id) - .await; - } - } - Ok(None) => {} - Err(e) => tracing::error!(error = %e, number, "live: loading the pull to bump failed"), - }, - Written::New { .. } => bump_list(state, &repo.id), - Written::Repo { .. } => bump_repo_pulls(state, &repo.id).await, - } -} - -/// Wraps every request. Only a POST under the pulls paths, or to a label or milestone route, does -/// anything. Registered on the public router in `boot.rs`, next to the other request layers. -pub struct PullWriteLayer; - -impl Layer for PullWriteLayer { - fn path(&self) -> Option<&Path> { - None - } - - fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { - Box::pin(bump_after_write(cx, body, next)) - } -} diff --git a/crates/forge-web/src/pages/pull_reviews.rs b/crates/forge-web/src/pages/pull_reviews.rs index 267dc7e..b24ce1d 100644 --- a/crates/forge-web/src/pages/pull_reviews.rs +++ b/crates/forge-web/src/pages/pull_reviews.rs @@ -735,7 +735,7 @@ async fn review_submit(cx: &Cx, Form(form): Form) -> Result Ok(refusal(&tab, ERR_OWN_PR, "")), diff --git a/crates/forge-web/src/pages/pulls_merge.rs b/crates/forge-web/src/pages/pulls_merge.rs index 0091980..49b2488 100644 --- a/crates/forge-web/src/pages/pulls_merge.rs +++ b/crates/forge-web/src/pages/pulls_merge.rs @@ -161,10 +161,14 @@ fn refusal(status: StatusCode, message: &str) -> Response { #[cfg(test)] mod tests { + use forge_core::ReviewState; + use std::path::{Path, PathBuf}; use std::time::Duration; - use forge_core::{IssueState, Repo, Role, Store, Visibility}; + use forge_core::protection::Protection; + use forge_core::store::commit_status::StatusState; + use forge_core::{IssueState, PullRequest, Repo, Role, Store, User, Visibility}; use forge_git::repo::{init_bare, repo_path}; use topcoat::router::request::Request; use topcoat::router::{Body, Router, to_bytes}; diff --git a/crates/forge-web/src/pages/repo_ctx.rs b/crates/forge-web/src/pages/repo_ctx.rs index baef154..72365a4 100644 --- a/crates/forge-web/src/pages/repo_ctx.rs +++ b/crates/forge-web/src/pages/repo_ctx.rs @@ -8,19 +8,14 @@ use std::path::PathBuf; use forge_core::authz::{Action, authorize}; use forge_core::{Repo, Role, Session, Store, User, Visibility, WatchLevel}; use forge_git::repo::repo_path; -use http::{ - HeaderValue, - header::{CACHE_CONTROL, LOCATION}, -}; use topcoat::Result; use topcoat::context::{Cx, context}; use topcoat::router::error::not_found; use topcoat::router::request::uri; -use topcoat::router::response::Response; -use topcoat::router::{Body, Layer, LayerFuture, Next, Path, StatusCode}; use crate::auth::current_user; use crate::i18n::{self, Lang}; +use crate::layers::RepoMoved; use crate::pages::repo_mirrors::redacted_url; use crate::state::AppState; use crate::views::repo_href; @@ -125,39 +120,6 @@ pub struct WatchButton { pub csrf: String, } -/// Raised by `load_repo` when the requested owner/name is a past name of a repo the viewer may -/// read. The `repo_moved` layer turns it into a 307 to `location`. -#[derive(Debug)] -pub struct RepoMoved { - pub location: String, -} - -impl std::fmt::Display for RepoMoved { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("repository moved") - } -} - -impl std::error::Error for RepoMoved {} - -/// A plain-text download (a `.patch` or `.diff`) raised by a page handler that cannot return a -/// response of its own. The `repo_moved` layer turns it into a 200 with these bytes. -#[derive(Debug, Clone)] -pub struct RawDownload { - pub content_type: &'static str, - /// File name offered to the browser. - pub filename: String, - pub data: Vec, -} - -impl std::fmt::Display for RawDownload { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("raw download") - } -} - -impl std::error::Error for RawDownload {} - impl RepoCtx { /// Whether the viewer may delete this repo: its owner or an instance admin only. pub fn can_delete(&self) -> bool { @@ -426,74 +388,3 @@ async fn moved_location( target.owner_name, target.name ))) } - -/// Wraps every request (no path) so a `RepoMoved` error becomes a 307. Registered explicitly on the -/// public router in `boot.rs`: a `#[layer("/")]` would clash with the security-headers layer. -pub struct RepoMovedLayer; - -impl Layer for RepoMovedLayer { - fn path(&self) -> Option<&Path> { - None - } - - fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { - Box::pin(repo_moved(cx, body, next)) - } -} - -/// Turns a `RepoMoved` error from a handler into a 307 with the new location, and a `RawDownload` -/// into its plain-text response. Other errors pass through unchanged. -async fn repo_moved(cx: &Cx, body: Body, next: Next<'_>) -> Result { - let error = match next.run(cx, body).await { - Ok(response) => return Ok(response), - Err(error) => error, - }; - let error = match error.downcast_cloned::() { - Ok(download) => { - return raw_download_response(download).ok_or_else(|| not_found().into()); - } - Err(error) => error, - }; - match error.downcast_ref::() { - Some(moved) => { - let mut response = Response::new(Body::empty()); - // Temporary and uncached: an old name can be taken by a new repo later, and a browser - // that cached a 301 would keep sending its visitors to the renamed repo. - *response.status_mut() = StatusCode::TEMPORARY_REDIRECT; - // Owner and repo names are plain ASCII and the query came from a valid URI, so this - // only fails on a corrupt location; a 404 is the safe answer then. - let Ok(location) = HeaderValue::from_str(&moved.location) else { - return Err(not_found().into()); - }; - response.headers_mut().insert(LOCATION, location); - response - .headers_mut() - .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); - Ok(response) - } - None => Err(error), - } -} - -/// The 200 response for a [`RawDownload`]. `None` when the file name is not a valid header value. -fn raw_download_response(download: RawDownload) -> Option { - let mut response = Response::new(Body::from(download.data)); - let headers = response.headers_mut(); - headers.insert( - http::header::CONTENT_TYPE, - HeaderValue::from_static(download.content_type), - ); - headers.insert( - http::header::CONTENT_DISPOSITION, - HeaderValue::from_str(&format!("inline; filename=\"{}\"", download.filename)).ok()?, - ); - headers.insert( - http::header::X_CONTENT_TYPE_OPTIONS, - HeaderValue::from_static("nosniff"), - ); - headers.insert( - http::header::CACHE_CONTROL, - HeaderValue::from_static("private, no-cache"), - ); - Some(response) -} diff --git a/crates/forge-web/src/pages/repo_settings_live.rs b/crates/forge-web/src/pages/repo_settings_live.rs index 00a3260..7e10a0d 100644 --- a/crates/forge-web/src/pages/repo_settings_live.rs +++ b/crates/forge-web/src/pages/repo_settings_live.rs @@ -17,12 +17,11 @@ use topcoat::Result; use topcoat::context::{Cx, context}; use topcoat::router::error::forbidden; -use topcoat::router::request::{method, uri}; use topcoat::router::response::Response; -use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route}; +use topcoat::router::{path_param, route}; use crate::auth::require_user; -use crate::live::{Topic, bump_settings, stream_wakes}; +use crate::live::{Topic, stream_wakes}; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; use crate::state::AppState; @@ -72,65 +71,3 @@ async fn security_live(cx: &Cx) -> Result { let state = context::(cx); stream_wakes(cx, &state.live, &[Topic::RepoSettings(ctx.repo.id.clone())]) } - -// The write layer - -/// Wraps every request. Only a POST under the settings or security paths does anything. Registered -/// on the public router in `boot.rs`, and on the test router, next to the other request layers. -pub struct RepoSettingsWriteLayer; - -impl Layer for RepoSettingsWriteLayer { - fn path(&self) -> Option<&Path> { - None - } - - fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { - Box::pin(bump_after_write(cx, body, next)) - } -} - -/// The `(owner, name)` of a POST under `/{o}/{r}/settings/...` or `/{o}/{r}/security/...`. -fn written(cx: &Cx) -> Option<(String, String)> { - if *method(cx) != Method::POST { - return None; - } - let path = uri(cx).path().to_owned(); - let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); - match parts.as_slice() { - [owner, name, "settings" | "security", ..] => { - Some(((*owner).to_owned(), (*name).to_owned())) - } - _ => None, - } -} - -/// Bumps the settings topic once the handler has run. The repo is looked up before the handler, -/// because a rename moves its name away. The handler's result passes through unchanged, so a -/// refused write bumps too: the page re-reads and agrees. -async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> Result { - let repo_id = match written(cx) { - Some((owner, name)) => { - let state = context::(cx); - match state.store.repo_by_owner_and_name(&owner, &name).await { - Ok(repo) => repo.map(|repo| repo.id), - Err(e) => { - tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed"); - None - } - } - } - None => None, - }; - let result = next.run(cx, body).await; - if let Some(repo_id) = repo_id { - let state = context::(cx); - bump_settings(&state.live, &repo_id); - // The repo header shows settings too (the mirror line, the archived notice, the tabs); its - // stream sends nothing when its fingerprint holds. - state.live.bump(&crate::live::Topic::Repo(repo_id.clone())); - // The merge gate of a pull page reads the branch protection rules, so every pull of the - // repo may show a different gate. A pull's stream sends nothing when its fingerprint holds. - crate::live::bump_repo_pulls(state, &repo_id).await; - } - result -} diff --git a/crates/forge-web/src/pages/review_requests.rs b/crates/forge-web/src/pages/review_requests.rs index 7565e4c..0c8a5a2 100644 --- a/crates/forge-web/src/pages/review_requests.rs +++ b/crates/forge-web/src/pages/review_requests.rs @@ -19,6 +19,7 @@ use crate::auth::{current_user, require_user}; use crate::i18n::authoring::{self as ga, K as AK}; use crate::i18n::issues::{self as ig, K as IK}; use crate::i18n::{self, Lang}; +use crate::layers::bump_review_requests; use crate::live::{Topic, stream_wakes}; use crate::notify; use crate::pages::issue_parts::{ItemKind, check_write, may_change, parse_number}; @@ -42,31 +43,6 @@ struct ReviewerForm { username: String, } -/// Wakes the review-request list of `user_id`: a request was added or withdrawn, or the user -/// submitted a review (which clears their own request). -pub fn bump_review_requests(state: &AppState, user_id: &str) { - state.live.bump(&Topic::ReviewRequests(user_id.to_owned())); -} - -/// Wakes the review-request lists of everyone with a pending request on the pull request. Call it -/// after the pull closed or merged, which drops it from those lists. -pub async fn bump_pending_reviewers(state: &AppState, issue_id: &str) { - let names = match state.store.requested_reviewers(issue_id).await { - Ok(names) => names, - Err(e) => { - tracing::error!(error = %e, issue_id, "live: listing reviewers to bump failed"); - return; - } - }; - for name in names { - match state.store.user_by_username(&name).await { - Ok(Some(user)) => bump_review_requests(state, &user.id), - Ok(None) => {} - Err(e) => tracing::error!(error = %e, name, "live: loading a reviewer to bump failed"), - } - } -} - /// The review-request list's stream. The viewer comes from the session only, so a user follows only /// their own list. Without a session: 401. #[route(GET "/review-requests/events")] diff --git a/crates/forge-web/src/pages/settings_live.rs b/crates/forge-web/src/pages/settings_live.rs index 486a085..731d116 100644 --- a/crates/forge-web/src/pages/settings_live.rs +++ b/crates/forge-web/src/pages/settings_live.rs @@ -29,12 +29,11 @@ use tokio::sync::watch; use topcoat::Result; use topcoat::context::{Cx, context, try_context}; use topcoat::router::content::sse::Event; -use topcoat::router::request::{method, uri}; use topcoat::router::response::Response; -use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode, route}; +use topcoat::router::{Body, StatusCode, route}; use crate::auth::current_user; -use crate::live::{LiveHub, Topic, bump_account, events_response, stream_wakes}; +use crate::live::{LiveHub, Topic, events_response, stream_wakes}; use crate::state::AppState; /// 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, Alive)> { } } -/// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router -/// in `boot.rs` and the test router. It sits on a path, so it runs inside the cookie layer (a -/// pathless layer would run outside it, where the session cannot be read). -pub struct AccountWriteLayer; - -impl Layer for AccountWriteLayer { - fn path(&self) -> Option<&Path> { - Some(Path::new("/settings")) - } - - fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { - Box::pin(bump_after_settings_write(cx, body, next)) - } -} - -/// Bumps the viewer's topic once the handler has run. The viewer is read before the handler, so a -/// write that ends the viewer's own session (a revoke of the current one) still wakes the tabs. -async fn bump_after_settings_write(cx: &Cx, body: Body, next: Next<'_>) -> Result { - if *method(cx) != Method::POST || !uri(cx).path().starts_with("/settings/") { - return next.run(cx, body).await; - } - let viewer = current_user(cx) - .await - .ok() - .flatten() - .map(|(user, _)| user.id); - let result = next.run(cx, body).await; - if let Some(user_id) = viewer { - bump_account(context::(cx), &user_id); - } - result -} - #[cfg(test)] mod tests { use std::collections::BTreeMap; diff --git a/crates/forge-web/src/test_support.rs b/crates/forge-web/src/test_support.rs index c0ca5de..cbe6583 100644 --- a/crates/forge-web/src/test_support.rs +++ b/crates/forge-web/src/test_support.rs @@ -17,7 +17,7 @@ use topcoat::cookie::CookieLayer; use topcoat::router::tower::TowerLayer; use topcoat::router::{Compression, Router, RouterBuilderDiscoverExt}; -use crate::pages::repo_ctx::RepoMovedLayer; +use crate::layers::RepoMovedLayer; use crate::state::AppState; use crate::throttle::Throttle; @@ -105,13 +105,13 @@ pub fn app_router(state: AppState) -> Router { Router::builder() .discover() .with(state) - .layer(crate::pages::settings_live::AccountWriteLayer) + .layer(crate::layers::AccountWriteLayer) .layer(CookieLayer::new()) .layer(RepoMovedLayer) - .layer(crate::pages::repo_settings_live::RepoSettingsWriteLayer) - .layer(crate::pages::pull_live::PullWriteLayer) - .layer(crate::pages::discussion_live::DiscussionWriteLayer) - .layer(crate::pages::org_live::OrgWriteLayer) + .layer(crate::layers::RepoSettingsWriteLayer) + .layer(crate::layers::PullWriteLayer) + .layer(crate::layers::DiscussionWriteLayer) + .layer(crate::layers::OrgWriteLayer) .layer(TowerLayer::new(crate::compression::ResponseCompression)) .with(Compression::disable()) .build()