use std::fmt; use topcoat::context::Cx; use topcoat::router::Method; use topcoat::router::request::{method, uri}; use crate::live::Topic; use crate::state::AppState; pub use live_seq::LiveSeqLayer; 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; #[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 {} #[derive(Debug, Clone)] pub struct RawDownload { pub content_type: &'static str, 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 {} pub fn bump_review_requests(state: &AppState, user_id: &str) { state.live.bump(&Topic::ReviewRequests(user_id.to_owned())); } 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"), } } } fn post_segments(cx: &Cx) -> Option> { if *method(cx) != Method::POST { return None; } Some(uri(cx).path().trim_start_matches('/').split('/').collect()) } 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; 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)) } } 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}; 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)) } } 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()); *response.status_mut() = StatusCode::TEMPORARY_REDIRECT; 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), } } 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::response::Response; use topcoat::router::{Body, Layer, LayerFuture, Next, Path}; use super::{bump_pending_reviewers, post_segments}; use crate::live::{bump_list, bump_pull, bump_repo_pulls}; use crate::state::AppState; enum Written { Pull { owner: String, repo: String, number: i64, }, New { owner: String, repo: String, }, Repo { owner: String, repo: String, }, } fn written(cx: &Cx) -> Option { let parts = post_segments(cx)?; 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, } } 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)) } } 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); 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 org_write { use topcoat::context::{Cx, context}; use topcoat::router::response::Response; use topcoat::router::{Body, Layer, LayerFuture, Next, Path}; use super::post_segments; use crate::live::Topic; use crate::state::AppState; fn written_org(cx: &Cx) -> Option { let parts = post_segments(cx)?; let ["org", name, kind, ..] = parts.as_slice() else { return None; }; matches!(*kind, "members" | "teams" | "settings").then(|| (*name).to_owned()) } 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)) } } 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::response::Response; use topcoat::router::{Body, Layer, LayerFuture, Next, Path}; use super::post_segments; use crate::live::{Topic, bump_repo_pulls, bump_settings}; use crate::state::AppState; 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)) } } fn written(cx: &Cx) -> Option<(String, String)> { let parts = post_segments(cx)?; match parts.as_slice() { [owner, name, "settings", ..] => Some(((*owner).to_owned(), (*name).to_owned())), _ => None, } } 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); state.live.bump(&Topic::Repo(repo_id.clone())); bump_repo_pulls(state, &repo_id).await; } result } } mod live_seq { use topcoat::Result; use topcoat::context::Cx; use topcoat::router::response::Response; use topcoat::router::{Body, Layer, LayerFuture, Next, Path}; use crate::live::{LiveSeq, live_seq}; pub struct LiveSeqLayer; impl Layer for LiveSeqLayer { fn path(&self) -> Option<&Path> { None } fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { Box::pin(record_seq(cx, body, next)) } } async fn record_seq(cx: &Cx, body: Body, next: Next<'_>) -> Result { let cx = cx.with(LiveSeq(live_seq())); next.run(&cx, body).await } } 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; 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 { 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()) } const FORBIDDEN_PATH: &str = "/-/forbidden"; const PATH: &str = "/-/not-found"; }