diff --git a/crates/forge-web-base/src/i18n/mod.rs b/crates/forge-web-base/src/i18n/mod.rs index da811e3..495ddac 100644 --- a/crates/forge-web-base/src/i18n/mod.rs +++ b/crates/forge-web-base/src/i18n/mod.rs @@ -495,6 +495,14 @@ pub const ALL: &[Key] = &[ ]; /// The phrase a key names, in a user's language. +/// Picks the English or Turkish text. +pub fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str { + match lang { + Lang::En => en, + Lang::Tr => tr, + } +} + pub fn t(lang: Lang, key: Key) -> &'static str { use Key::*; use Lang::*; diff --git a/crates/forge-web/src/advisories/scan.rs b/crates/forge-web/src/advisories/scan.rs index cd5a1a7..f9fb993 100644 --- a/crates/forge-web/src/advisories/scan.rs +++ b/crates/forge-web/src/advisories/scan.rs @@ -10,7 +10,7 @@ use forge_core::store::advisories::ScanOutcome; use forge_core::{Error, Repo, Result}; use forge_git::browse::{EntryKind, default_branch_commit, read_text_blob, read_tree}; -use crate::pages::repo_settings_live::bump_settings; +use crate::live::bump_settings; use crate::state::AppState; /// Deepest directory searched for lockfiles. The root is depth 0. diff --git a/crates/forge-web/src/api/mod.rs b/crates/forge-web/src/api/mod.rs index 3de7b17..192591d 100644 --- a/crates/forge-web/src/api/mod.rs +++ b/crates/forge-web/src/api/mod.rs @@ -114,7 +114,7 @@ pub async fn authenticate( if let Err(e) = state.store.touch_token(&token_id).await { return Err(internal(e)); } - crate::pages::settings_live::bump_account(state, &user.id); + crate::live::bump_account(state, &user.id); Ok(Some(user)) } diff --git a/crates/forge-web/src/api/packages.rs b/crates/forge-web/src/api/packages.rs index 3a42179..d12328c 100644 --- a/crates/forge-web/src/api/packages.rs +++ b/crates/forge-web/src/api/packages.rs @@ -59,7 +59,7 @@ async fn caller(cx: &Cx, scope_required: bool) -> Result, Refusal> if let Err(e) = state.store.touch_token(&token_id).await { return Err(Box::new(failure(PackageError::Internal(e.to_string())))); } - crate::pages::settings_live::bump_account(state, &user.id); + crate::live::bump_account(state, &user.id); Ok(Some(user)) } diff --git a/crates/forge-web/src/auth.rs b/crates/forge-web/src/auth.rs index 13f4bf4..83dce1e 100644 --- a/crates/forge-web/src/auth.rs +++ b/crates/forge-web/src/auth.rs @@ -111,7 +111,7 @@ pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> { let state = context::(cx); state.store.delete_session(&session.id).await?; // The user's other tabs may show this session (a page that now leaves for the login page). - crate::pages::settings_live::bump_account(state, &session.user_id); + crate::live::bump_account(state, &session.user_id); session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); Ok(()) } diff --git a/crates/forge-web/src/automerge.rs b/crates/forge-web/src/automerge.rs index 5832127..9bac7d3 100644 --- a/crates/forge-web/src/automerge.rs +++ b/crates/forge-web/src/automerge.rs @@ -15,7 +15,7 @@ use crate::state::AppState; /// `sha`. Called after a commit status for `sha` was written. Failures are logged: the status /// that triggered this has already been stored. pub async fn on_status(state: &AppState, repo_id: &str, sha: &str) { - crate::pages::pull_live::bump_head(state, repo_id, sha).await; + crate::live::bump_head(state, repo_id, sha).await; let pulls = match state.store.auto_merge_pulls_for_head(repo_id, sha).await { Ok(pulls) => pulls, Err(e) => { @@ -55,7 +55,7 @@ async fn evaluate_logged(state: &AppState, repo: &Repo, pr: &PullRequest) { tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "auto-merge: evaluation failed"); } // The evaluation may have merged the pull or left it as it was; either way its page re-reads. - crate::pages::pull_live::bump_pull(state, &repo.id, &pr.issue.id); + crate::live::bump_pull(state, &repo.id, &pr.issue.id); } /// Merges `pr` when auto-merge is on and nothing blocks it any more. Returns whether it merged. diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index 3363393..1b67913 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -29,10 +29,9 @@ use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route}; use crate::api::{self, Refusal}; use crate::ci::{artifact_key, log_path}; -use crate::pages::admin_runners::bytes_text; -use crate::pages::repo::https_clone_url; use crate::self_update; use crate::state::AppState; +use crate::views::{bytes_text, https_clone_url}; path_param!(job_id); path_param!(artifact_name); diff --git a/crates/forge-web/src/git_auth.rs b/crates/forge-web/src/git_auth.rs index 15e5bbd..7347e0c 100644 --- a/crates/forge-web/src/git_auth.rs +++ b/crates/forge-web/src/git_auth.rs @@ -81,7 +81,7 @@ pub async fn user_from_basic( .touch_token(&access.id) .await .map_err(internal)?; - crate::pages::settings_live::bump_account(state, &user.id); + crate::live::bump_account(state, &user.id); Ok(Some(user)) } diff --git a/crates/forge-web/src/internal.rs b/crates/forge-web/src/internal.rs index 9104e6a..dffa2bc 100644 --- a/crates/forge-web/src/internal.rs +++ b/crates/forge-web/src/internal.rs @@ -170,7 +170,7 @@ async fn hook_endpoint( // A wiki push changes neither the code repo's refs nor its CI, pull requests or events. // It still goes to the standby. record_wiki_push(&state.store, &req).await; - crate::pages::wiki_live::bump_wiki(state, &req.repo_id); + crate::live::bump_wiki(state, &req.repo_id); crate::replication::enqueue_repo(state, &req.repo_id); HookResponse::allow() } diff --git a/crates/forge-web/src/live.rs b/crates/forge-web/src/live.rs index e61dfe8..9e39f0d 100644 --- a/crates/forge-web/src/live.rs +++ b/crates/forge-web/src/live.rs @@ -26,16 +26,18 @@ use std::collections::HashMap; use std::future::Future; use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; +use std::time::Duration; use futures_util::future::select_all; -use futures_util::{Stream, stream}; +use futures_util::{Stream, StreamExt, stream}; use tokio::sync::watch; use topcoat::Result; use topcoat::context::Cx; -use topcoat::router::content::sse::Event; -use topcoat::router::response::Response; +use topcoat::router::HeaderValue; +use topcoat::router::content::sse::{Event, KeepAlive, Sse}; +use topcoat::router::response::{IntoResponse, Response}; -use crate::pages::ci_runs::events_response; +use crate::state::AppState; /// What a live page follows. Add a variant when a page needs a new signal. #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -48,10 +50,10 @@ pub enum Topic { /// One issue: its body, comments, events, state, labels, reactions. Keyed by issue id. Issue(String), /// The pull request list of a repo: a pull opened, or any pull in the repo changed. Keyed by - /// repo id. Bumped by [`crate::pages::pull_live`]. + /// repo id. Bumped by the `pull_live` page. PullList(String), /// One pull request, its conversation, commits and files. Keyed by the pull's issue id. - /// Bumped by [`crate::pages::pull_live`]. + /// Bumped by the `pull_live` page. Pull(String), /// A repo's own state that its header shows: stars, watchers, forks, its name, description, /// archived flag and default branch, the tab switches, and the mirror's last sync. Keyed by repo @@ -67,7 +69,7 @@ pub enum Topic { /// A user's review requests: a pull request asked the user to review, a request was withdrawn, /// the user submitted a review, or a pull request with the user's request closed or merged. /// Keyed by the reviewer's user id. Streamed only to that user. Bumped by - /// [`crate::pages::review_requests`] and [`crate::pages::pull_live`]. + /// the `review_requests` page and the `pull_live` page. ReviewRequests(String), /// A user's import jobs: a job was queued, started, progressed or finished. Keyed by user id. /// Bumped by the importer when a job's state changes. Streamed only to that user. @@ -76,13 +78,13 @@ pub enum Topic { Explore, /// The discussions of a repo as a list: a discussion was opened, or any discussion of the repo /// changed (a comment, a reaction, an answer, a lock, a category). Keyed by repo id. Bumped by - /// [`crate::pages::discussion_live`]. + /// the `discussion_live` page. Discussions(String), /// One discussion: its body, comments, reactions, answer and lock state. Keyed by discussion - /// id. Bumped by [`crate::pages::discussion_live`]. + /// id. Bumped by the `discussion_live` page. Discussion(String), /// A repo's wiki: a page was saved, or a push changed the wiki's main branch. Keyed by repo id. - /// Bumped by [`crate::pages::wiki_live`] and by the wiki push hook. + /// Bumped by the `wiki_live` page and by the wiki push hook. Wiki(String), /// The snippet list: a snippet was created, changed or deleted. Global; each viewer's list is /// fingerprinted, so a bump that changes nothing the viewer sees sends nothing. @@ -90,7 +92,7 @@ pub enum Topic { /// One snippet: its files, title, visibility and revisions. Keyed by snippet id. Snippet(String), /// An organization's pages: its members, teams, team members and linked repos, and settings. - /// Keyed by the org's user id. Bumped by [`crate::pages::org_live`] after a POST under the org. + /// Keyed by the org's user id. Bumped by the `org_live` page after a POST under the org. Org(String), /// The account list of the admin area: an account was registered, edited, suspended, lifted, /// given or lost admin rights, or deleted. Global. Admin pages only, on [`admin`]. @@ -129,7 +131,7 @@ pub enum Topic { /// The server settings that pages render (every `Kind::Live` setting, such as the banner, the /// registration mode or the limits): one was saved or reset. Global. Every page holds /// `/-/alive`, anonymous viewers included, and follows it there (see - /// [`crate::pages::settings_live::alive_response`]). Bumped by the server settings after a save + /// `settings_live::alive_response`). Bumped by the server settings after a save /// or reset. ServerSettings, } @@ -212,7 +214,7 @@ struct Follow { } /// The `changed` event of a live page. The data is not read by the client. -fn changed_event() -> Result { +fn wake_event() -> Result { Ok(Event::new().event("changed").data("1")) } @@ -237,7 +239,7 @@ pub fn stream_wakes(cx: &Cx, hub: &LiveHub, topics: &[Topic]) -> Result { + for (issue_id, _) in refs { + state.live.bump(&Topic::Pull(issue_id)); + } + } + Err(e) => tracing::error!(error = %e, repo_id, "live: listing pulls to bump failed"), + } +} + +/// A commit status was written for `sha`: the pulls whose head is that commit, and the list. +pub async fn bump_head(state: &AppState, repo_id: &str, sha: &str) { + bump_list(state, repo_id); + match state.store.pulls_for_head_oid(repo_id, sha).await { + Ok(refs) => { + for (issue_id, _) in refs { + state.live.bump(&Topic::Pull(issue_id)); + } + } + Err(e) => { + tracing::error!(error = %e, repo_id, "live: listing pulls for a head to bump failed") + } + } +} + +/// How often an idle event stream sends a `: keepalive` comment, so a reverse proxy does not drop +/// the connection. This is not a poll: events follow the change signals. +const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30); + +/// A run's or job's status word and whether it is terminal. `None` when the row is gone. +pub(crate) type Status = Option<(String, bool)>; + +/// One `changed` event carrying the status word. +pub fn changed_event(status: String) -> Result { + Ok(Event::new().event("changed").data(status)) +} + +/// The events of a CI page, each named `name` (`changed` on a page's own stream). The first event +/// carries the status now. Each later one follows a wake of `wake`: with `only_on_status`, only when +/// the status differs from the last one sent. The stream ends after the terminal status is sent, +/// when the row is gone, or when the signal closes. Subscribe `wake` before the first read, so a +/// change in between is not lost. +pub fn changed_stream( + wake: watch::Receiver, + only_on_status: bool, + name: &'static str, + read: F, +) -> impl Stream> + Send + 'static +where + F: Fn() -> Fut + Send + 'static, + Fut: Future> + Send, +{ + struct Follow { + wake: watch::Receiver, + only_on_status: bool, + read: F, + /// The status last read, sent or not. + last: Option, + /// Set once a terminal status is read. Nothing follows it. + done: bool, + /// False until the first read. Every later read waits for a wake first. + primed: bool, + } + stream::unfold( + Follow { + wake, + only_on_status, + read, + last: None, + done: false, + primed: false, + }, + move |mut follow| async move { + loop { + if follow.done { + return None; + } + if follow.primed && follow.wake.changed().await.is_err() { + return None; + } + follow.primed = true; + let (status, terminal) = match (follow.read)().await { + Ok(Some(found)) => found, + Ok(None) => return None, + Err(e) => { + tracing::error!(error = %e, "ci: live stream could not read the status"); + return None; + } + }; + follow.done = terminal; + let changed = follow.last.as_deref() != Some(status.as_str()); + let send = changed || !follow.only_on_status; + follow.last = Some(status.clone()); + if send { + return Some((Ok(Event::new().event(name).data(status)), follow)); + } + } + }, + ) +} + +/// Open event streams one client address (IPv6 by /64) may hold. A page holds one or two, so this +/// is many tabs; past it a script that opens streams in a loop is refused. +const MAX_STREAMS_PER_CLIENT: usize = 64; +/// Open event streams server-wide. Each is a task and a socket that stay until the client leaves. +const MAX_STREAMS: usize = 4096; + +/// Open streams per client address, and their sum. +static OPEN_STREAMS: Mutex<(usize, Option>)> = + Mutex::new((0, None)); + +/// One open event stream, counted against its client's and the server's cap until dropped. +/// `ip` is `None` for an uncounted stream. +struct StreamSlot { + ip: Option, +} + +impl StreamSlot { + /// A slot for this request's client, or `None` when a cap is reached. Without the app state + /// (unit tests of a bare router) nothing is counted. + fn take(cx: &Cx) -> Option { + if topcoat::context::try_context::(cx).is_none() { + return Some(StreamSlot { ip: None }); + } + let ip = crate::client_ip::client_ip(cx); + let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner()); + let (total, per_client) = &mut *open; + let count = per_client + .get_or_insert_with(HashMap::new) + .entry(ip) + .or_insert(0); + if *total >= MAX_STREAMS || *count >= MAX_STREAMS_PER_CLIENT { + return None; + } + *count += 1; + *total += 1; + Some(StreamSlot { ip: Some(ip) }) + } +} + +impl Drop for StreamSlot { + fn drop(&mut self) { + let Some(ip) = self.ip else { + return; + }; + let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner()); + let (total, per_client) = &mut *open; + *total = total.saturating_sub(1); + if let Some(map) = per_client.as_mut() + && let Some(count) = map.get_mut(&ip) + { + *count = count.saturating_sub(1); + if *count == 0 { + map.remove(&ip); + } + } + } +} + +/// How long the browser waits before it reconnects a dropped event stream. The browser's default is +/// a few seconds; one second makes a page come back as soon as a server restart is done. +pub(crate) const STREAM_RETRY: Duration = Duration::from_secs(1); + +/// The response of an event stream: keep-alive comments while idle, no buffering by a reverse +/// proxy, and a `retry` field first so every stream reconnects after `STREAM_RETRY`. +pub fn events_response( + cx: &Cx, + events: impl Stream> + Send + 'static, +) -> Result { + // Past the cap the stream is refused: the page keeps working, only without live updates. + let Some(slot) = StreamSlot::take(cx) else { + let mut res = Response::new(topcoat::router::Body::from("too many open live streams")); + *res.status_mut() = http::StatusCode::TOO_MANY_REQUESTS; + return Ok(res); + }; + // The slot lives as long as the stream: it is given back when the client goes away. + let events = events.map(move |event| { + let _held = &slot; + event + }); + let retry = stream::once(std::future::ready(Ok(Event::new().retry(STREAM_RETRY)))); + let events = Sse::new(retry.chain(events)).keep_alive( + KeepAlive::new() + .interval(STREAM_KEEP_ALIVE) + .text("keepalive"), + ); + let mut res = events.into_response(cx)?; + res.headers_mut() + .insert("x-accel-buffering", HeaderValue::from_static("no")); + Ok(res) +} + #[cfg(test)] mod tests { - use std::time::Duration; - use super::*; #[tokio::test] diff --git a/crates/forge-web/src/merge_queue.rs b/crates/forge-web/src/merge_queue.rs index 57c9f47..2a40d96 100644 --- a/crates/forge-web/src/merge_queue.rs +++ b/crates/forge-web/src/merge_queue.rs @@ -420,7 +420,7 @@ async fn fail( .await { Ok(_) => { - crate::pages::pull_live::bump_pull(state, &repo.id, &pr.issue.id); + crate::live::bump_pull(state, &repo.id, &pr.issue.id); notify::dispatch( state, repo, @@ -441,5 +441,5 @@ async fn fail( /// Wakes the queue pages of `repo_id`, and the pull page and list of the entry's pull request. fn notify_entry(state: &AppState, repo: &Repo, entry: &QueueEntry) { state.ci_live.bump_queue(&repo.id); - crate::pages::pull_live::bump_pull(state, &repo.id, &entry.issue_id); + crate::live::bump_pull(state, &repo.id, &entry.issue_id); } diff --git a/crates/forge-web/src/mirrors/mod.rs b/crates/forge-web/src/mirrors/mod.rs index e636844..b450e60 100644 --- a/crates/forge-web/src/mirrors/mod.rs +++ b/crates/forge-web/src/mirrors/mod.rs @@ -23,7 +23,7 @@ use serde_json::json; use crate::audit::{self, Actor, Target}; use crate::live::Topic; -use crate::pages::repo_settings_live::bump_settings; +use crate::live::bump_settings; use crate::post_update::after_ref_update; use crate::state::AppState; use crate::webhooks::client::{WebhookPolicy, is_forbidden_ip, validate_url}; diff --git a/crates/forge-web/src/pages/account_tools_tests.rs b/crates/forge-web/src/pages/account_tools_tests.rs index 423f127..2c60b30 100644 --- a/crates/forge-web/src/pages/account_tools_tests.rs +++ b/crates/forge-web/src/pages/account_tools_tests.rs @@ -290,7 +290,7 @@ async fn banner_shows_on_pages_and_a_dismissal_hides_it() { assert!(body.contains("site-banner warning"), "{body}"); assert!(body.contains("Maintenance tonight")); } - let hash = crate::pages::banner::banner_hash("Maintenance tonight", "warning"); + let hash = crate::views::banner_hash("Maintenance tonight", "warning"); let req = Request::builder() .method("GET") .uri("/explore") diff --git a/crates/forge-web/src/pages/activity.rs b/crates/forge-web/src/pages/activity.rs index 62b1f8b..7634443 100644 --- a/crates/forge-web/src/pages/activity.rs +++ b/crates/forge-web/src/pages/activity.rs @@ -14,7 +14,8 @@ use topcoat::router::response::Response; use topcoat::router::{Body, HeaderValue, StatusCode, route}; use crate::auth::current_user; -use crate::pages::ci_runs::{changed_stream, events_response, run_href}; +use crate::live::{changed_stream, events_response}; +use crate::pages::ci_runs::run_href; use crate::state::AppState; use crate::views::repo_href; use futures_util::Stream; diff --git a/crates/forge-web/src/pages/admin_mail.rs b/crates/forge-web/src/pages/admin_mail.rs index 5bf3aec..cef6742 100644 --- a/crates/forge-web/src/pages/admin_mail.rs +++ b/crates/forge-web/src/pages/admin_mail.rs @@ -31,12 +31,12 @@ use crate::audit::{self, Actor, Target}; use crate::auth::check_csrf; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; +use crate::live::{changed_event, events_response}; use crate::mail::{enqueue, live, templates}; use crate::pages::admin_server::{ MAIL_KEYS, Row, refusal, save_topic, setting_lines, setting_rows, }; use crate::pages::admin_users::admin_only; -use crate::pages::ci_runs::{changed_event, events_response}; use crate::state::AppState; use crate::views::parts::{confirm_act, head, post_act}; use crate::views::{enc, rel_time, shell}; @@ -230,7 +230,7 @@ async fn mail_view(
-

(crate::pages::passkeys::s(lang, "Delivery", "Teslimat"))

+

(crate::i18n::s(lang, "Delivery", "Teslimat"))

setting_lines(lang: lang, rows: data.transport)
@@ -263,7 +263,7 @@ async fn mail_view(
-

(crate::pages::passkeys::s(lang, "Sending", "Gönderim"))

+

(crate::i18n::s(lang, "Sending", "Gönderim"))

diff --git a/crates/forge-web/src/pages/admin_replication.rs b/crates/forge-web/src/pages/admin_replication.rs index 5f9598d..e9d02e8 100644 --- a/crates/forge-web/src/pages/admin_replication.rs +++ b/crates/forge-web/src/pages/admin_replication.rs @@ -26,6 +26,7 @@ use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; use crate::auth::check_csrf; use crate::i18n::admin::{self as g, K}; +use crate::i18n::s; use crate::i18n::{self, Key, Lang}; use crate::live::{Topic, stream_changes}; use crate::pages::admin_backups::backups_rail; @@ -35,7 +36,6 @@ use crate::pages::admin_server::{ }; use crate::pages::admin_users::admin_only; use crate::pages::issues_list::list_href; -use crate::pages::passkeys::s; use crate::state::AppState; use crate::views::find::{Finder, finder_field}; use crate::views::parts::{head, post_act}; @@ -277,7 +277,7 @@ async fn replication_view(
if data.enabled {
-

(crate::pages::passkeys::s(lang, "Status", "Durum"))

+

(crate::i18n::s(lang, "Status", "Durum"))

(g::t(lang, K::Database)) (data.db_health) diff --git a/crates/forge-web/src/pages/admin_runners.rs b/crates/forge-web/src/pages/admin_runners.rs index 075aa33..c957b5f 100644 --- a/crates/forge-web/src/pages/admin_runners.rs +++ b/crates/forge-web/src/pages/admin_runners.rs @@ -32,15 +32,14 @@ use crate::ci::runner_log::Line; use crate::i18n::admin::{self as g, K}; use crate::i18n::releases_ci as rc; use crate::i18n::{self, Key, Lang}; +use crate::live::events_response; use crate::pages::admin_users::admin_only; -use crate::pages::ci_runs::{ - age_text, duration_text, events_response, job_href, run_href, state_text, -}; +use crate::pages::ci_runs::{age_text, duration_text, job_href, run_href, state_text}; use crate::pages::repo_mirrors::stamp_in_tz; use crate::state::AppState; use crate::views::parts::{SubPart, confirm_act, head, post_act, reveal}; use crate::views::repo_list::{PageLink, pager, pager_links}; -use crate::views::{alert, enc, now_unix, relative_time, shell}; +use crate::views::{alert, bytes_text, enc, now_unix, relative_time, shell}; path_param!(runner_id); path_param!(token_hash); @@ -1014,12 +1013,6 @@ fn identity_rows(lang: Lang, fields: &[FieldRow]) -> Vec<(&'static str, String)> .collect() } -/// A byte count in GiB with one decimal, such as `3.7 GiB`. -pub(crate) fn bytes_text(bytes: u64) -> String { - let gib = bytes as f64 / (1u64 << 30) as f64; - format!("{gib:.1} GiB") -} - fn or_dash(text: String) -> String { if text.is_empty() { "-".to_owned() @@ -1835,10 +1828,7 @@ async fn runners_events(cx: &Cx) -> Result { let wake = state.ci_live.subscribe_runners(); let events = futures_util::stream::unfold(wake, |mut wake| async move { wake.changed().await.ok()?; - Some(( - crate::pages::ci_runs::changed_event("runners".to_owned()), - wake, - )) + Some((crate::live::changed_event("runners".to_owned()), wake)) }); events_response(cx, events) } diff --git a/crates/forge-web/src/pages/admin_server.rs b/crates/forge-web/src/pages/admin_server.rs index cb000c7..8db9b21 100644 --- a/crates/forge-web/src/pages/admin_server.rs +++ b/crates/forge-web/src/pages/admin_server.rs @@ -31,11 +31,11 @@ use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; use crate::auth::check_csrf; use crate::i18n::admin::{self as g, K}; +use crate::i18n::s; use crate::i18n::{self, Key, Lang}; use crate::live::Topic; +use crate::live::{changed_event, events_response}; use crate::pages::admin_users::admin_only; -use crate::pages::ci_runs::{changed_event, events_response}; -use crate::pages::passkeys::s; use crate::self_update; use crate::state::AppState; use crate::views::find::{Finder, finder_field}; diff --git a/crates/forge-web/src/pages/admin_user_detail.rs b/crates/forge-web/src/pages/admin_user_detail.rs index 4a05483..2eba8a7 100644 --- a/crates/forge-web/src/pages/admin_user_detail.rs +++ b/crates/forge-web/src/pages/admin_user_detail.rs @@ -22,10 +22,10 @@ use crate::auth::{check_csrf, two_factor_enabled}; use crate::i18n::accounts::{A, t as at}; use crate::i18n::admin::{self as g, K}; use crate::i18n::orgs::{self as og, K as OG}; +use crate::i18n::s; use crate::i18n::{self, Key, Lang}; use crate::live::{Topic, stream_changes}; use crate::pages::admin_users::admin_only; -use crate::pages::passkeys::s; use crate::state::AppState; use crate::views::parts::{SubPart, confirm_act, head, post_act}; use crate::views::{alert, enc, rel_time, rel_time_or_never, shell, user_facing_message}; @@ -662,10 +662,7 @@ async fn perform(cx: &Cx, form: &ActionForm, action: Action) -> Result<(Outcome, { Ok(()) => { // A suspension ends the user's sessions: their open tabs must see it. - crate::pages::settings_live::bump_account( - context::(cx), - &target.id, - ); + crate::live::bump_account(context::(cx), &target.id); audit( AuditAction::UserSuspended, serde_json::json!({ "reason": form.reason.trim() }), diff --git a/crates/forge-web/src/pages/admin_users.rs b/crates/forge-web/src/pages/admin_users.rs index 1614bac..a465057 100644 --- a/crates/forge-web/src/pages/admin_users.rs +++ b/crates/forge-web/src/pages/admin_users.rs @@ -18,10 +18,10 @@ use crate::audit::{self, Actor, Target}; use crate::auth::{check_csrf, current_user, hash_password_async}; use crate::i18n::admin::{self as g, K}; use crate::i18n::orgs::{self as og, K as OG}; +use crate::i18n::s; use crate::i18n::{self, Key, Lang}; use crate::live::{Topic, stream_changes}; use crate::pages::issues_list::list_href; -use crate::pages::passkeys::s; use crate::state::AppState; use crate::views::find::{Finder, finder_field}; use crate::views::parts::{RailItem, head, rail, reveal}; @@ -657,7 +657,7 @@ async fn user_delete(cx: &Cx, Form(form): Form) -> Result match store.delete_user(&target.id, &ghost.id).await { Ok(_) => { // Their sessions and keys are gone: any open tab of theirs must leave. - crate::pages::settings_live::bump_account(context::(cx), &target.id); + crate::live::bump_account(context::(cx), &target.id); audit::record( store, Some(cx), diff --git a/crates/forge-web/src/pages/assets.rs b/crates/forge-web/src/pages/assets.rs index 70d6eaa..fe77d85 100644 --- a/crates/forge-web/src/pages/assets.rs +++ b/crates/forge-web/src/pages/assets.rs @@ -2,8 +2,6 @@ //! highlighting classes at `/assets/highlight.css`, and the colours of the hue choices at //! `/theme/custom.css`. -use std::sync::OnceLock; - use topcoat::Result; use topcoat::context::Cx; use topcoat::router::request::uri; @@ -12,7 +10,6 @@ use topcoat::router::{HeaderMap, StatusCode, header, route}; use crate::accent; use crate::custom_colour; -use crate::render::highlight::highlight_css; use crate::views::{NAV_SCRIPT_HREF, STYLESHEET_HREF, highlight_href}; /// Immutable only when the request names the current version (`href` is the URL the pages link). @@ -31,14 +28,6 @@ fn cache_for(cx: &Cx, href: &str) -> topcoat::router::HeaderValue { const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); -/// Highlight classes, built once on first use. -static HIGHLIGHT_CSS: OnceLock = OnceLock::new(); - -/// The highlight classes, shared by the route and the page links (which hash them). -pub fn highlight_css_text() -> &'static str { - HIGHLIGHT_CSS.get_or_init(highlight_css).as_str() -} - /// Immutable when the URL carries the current content hash, so a changed file gets a new URL. #[route(GET "/assets/main.css")] async fn main_css(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> { @@ -82,7 +71,7 @@ async fn highlight_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static .expect("static header value"), ); headers.insert(header::CACHE_CONTROL, cache_for(cx, highlight_href())); - Ok((StatusCode::OK, headers, highlight_css_text())) + Ok((StatusCode::OK, headers, crate::views::highlight_css_text())) } /// The colours of the hue choices on one page. The query names the four choices: `al` and `ad` for diff --git a/crates/forge-web/src/pages/audit_log.rs b/crates/forge-web/src/pages/audit_log.rs index 3372f10..2379c32 100644 --- a/crates/forge-web/src/pages/audit_log.rs +++ b/crates/forge-web/src/pages/audit_log.rs @@ -14,11 +14,11 @@ use topcoat::view::{View, component, view}; use crate::auth::require_user; use crate::i18n::admin::{self as g, K}; +use crate::i18n::s; use crate::i18n::{self, Lang, audit_names}; use crate::live::{Topic, stream_changes}; use crate::pages::admin_users::admin_only; use crate::pages::issues_list::list_href; -use crate::pages::passkeys::s; use crate::pages::settings_security::security_rail_for; use crate::state::AppState; use crate::views::find::{Finder, finder_field}; diff --git a/crates/forge-web/src/pages/avatars.rs b/crates/forge-web/src/pages/avatars.rs index 7c7a383..851137e 100644 --- a/crates/forge-web/src/pages/avatars.rs +++ b/crates/forge-web/src/pages/avatars.rs @@ -13,13 +13,7 @@ use topcoat::router::request::headers; use topcoat::router::{path_param_segment, query_params, route}; use crate::state::AppState; - -/// Background colors for the generated default avatar, picked by the user id hash. Muted sage, -/// olive and teal tones, so the default avatars sit with the sage accent. Each keeps white text -/// readable (4.5:1 or better). -const PALETTE: [&str; 8] = [ - "#5E7D63", "#4A6750", "#3F5F46", "#4E6E68", "#3E6B63", "#5B6B4E", "#56705F", "#4F6A55", -]; +use crate::views::default_svg; const CACHE_IMMUTABLE: &str = "public, max-age=31536000, immutable"; /// Without a matching `?v=`, the browser revalidates: the ETag gives a cheap 304. @@ -34,52 +28,6 @@ struct AvatarQuery { v: Option, } -/// The generated default avatar: the first letter of the username on a palette color picked by -/// the username, so a page can draw it inline without asking the server. -pub fn default_svg(username: &str) -> String { - let digest = Sha256::digest(username.as_bytes()); - let color = PALETTE[usize::from(digest[0]) % PALETTE.len()]; - let letter = username - .chars() - .next() - .map_or_else(|| "?".to_owned(), |c| c.to_uppercase().collect()); - let letter = xml_escape(&letter); - format!( - r##"{letter}"## - ) -} - -/// The generated default avatar as a `data:` URL, for an `` of an account known to have no -/// photo: the page shows it at once, with no request. -pub fn default_data_url(username: &str) -> String { - let svg = default_svg(username); - let mut out = String::with_capacity(svg.len() + 40); - out.push_str("data:image/svg+xml,"); - for byte in svg.bytes() { - if byte.is_ascii_alphanumeric() || b" -_.~/=:;,'()".contains(&byte) { - out.push(char::from(byte)); - } else { - out.push_str(&format!("%{byte:02X}")); - } - } - out -} - -fn xml_escape(text: &str) -> String { - let mut out = String::with_capacity(text.len()); - for c in text.chars() { - match c { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - other => out.push(other), - } - } - out -} - /// True when an `If-None-Match` header lists `etag` (quoted), `*`, or its weak form. fn etag_matches(if_none_match: &str, etag: &str) -> bool { if_none_match @@ -150,16 +98,16 @@ mod tests { #[test] fn default_svg_escapes_the_letter_and_is_stable() { - let svg = super::default_svg("<"); + let svg = crate::views::default_svg("<"); assert!(svg.contains("><"), "{svg}"); - assert_eq!(svg, super::default_svg("<")); - let url = super::default_data_url("<"); + assert_eq!(svg, crate::views::default_svg("<")); + let url = crate::views::default_data_url("<"); assert!(url.starts_with("data:image/svg+xml,%3Csvg"), "{url}"); assert!( !url.contains('<') && !url.contains('#') && !url.contains('"'), "{url}" ); - assert!(super::PALETTE.iter().any(|c| svg.contains(c))); + assert!(crate::views::PALETTE.iter().any(|c| svg.contains(c))); } #[test] diff --git a/crates/forge-web/src/pages/banner.rs b/crates/forge-web/src/pages/banner.rs index 9f2eb38..252b47f 100644 --- a/crates/forge-web/src/pages/banner.rs +++ b/crates/forge-web/src/pages/banner.rs @@ -4,14 +4,11 @@ //! in the `forge_banner` cookie for a signed-out visitor, and as the `banner_dismissed` account //! preference for a signed-in user. -use std::collections::HashMap; use std::time::Duration; -use forge_core::config::BannerConfig; -use forge_core::token::hash_token; use serde::Deserialize; use topcoat::Result; -use topcoat::context::{Cx, context, try_context}; +use topcoat::context::{Cx, context}; use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; use topcoat::router::content::Form; use topcoat::router::error::{SeeOther, see_other}; @@ -20,64 +17,10 @@ use topcoat::router::route; use crate::auth::current_user; use crate::pages::theme_cookie::safe_back; use crate::state::AppState; - -/// Name of the dismissal cookie. -pub const BANNER_COOKIE: &str = "forge_banner"; - -/// Account preference key holding the dismissed hash of a signed-in user. -pub const BANNER_PREF: &str = "banner_dismissed"; +use crate::views::{BANNER_COOKIE, BANNER_PREF}; const BANNER_COOKIE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60); -/// What the shell draws. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct BannerView { - pub message: String, - pub warning: bool, - pub hash: String, - /// Unix seconds when the banner expires, or `None` for never. The page drops it at that time. - pub expires: Option, -} - -/// Short stable id of a message and level. -pub fn banner_hash(message: &str, level: &str) -> String { - hash_token(&format!("{level}\n{message}"))[..16].to_owned() -} - -/// The banner to show at `now`, or `None` when it is off, expired or dismissed (`dismissed` is the -/// stored hash). -pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Option { - if !config.active_at(now) { - return None; - } - let message = config.message.trim().to_owned(); - let hash = banner_hash(&message, &config.level); - if dismissed == Some(hash.as_str()) { - return None; - } - Some(BannerView { - message, - warning: config.level == "warning", - hash, - expires: config.expires_unix(), - }) -} - -/// The banner for this request, read from the live settings. `prefs` is a signed-in viewer's -/// account preferences; without them the dismissal comes from the cookie. -pub fn current(cx: &Cx, prefs: Option<&HashMap>) -> Option { - let state = try_context::(cx)?; - let live = state.live(); - if live.banner.message.trim().is_empty() { - return None; - } - let dismissed = match prefs { - Some(prefs) => prefs.get(BANNER_PREF).cloned(), - None => cookies(cx).get(BANNER_COOKIE).map(|c| c.value().to_owned()), - }; - view_for(&live.banner, crate::views::now_unix(), dismissed.as_deref()) -} - #[derive(Deserialize)] struct DismissForm { #[serde(default)] @@ -112,7 +55,8 @@ async fn dismiss(cx: &Cx, Form(form): Form) -> Result { #[cfg(test)] mod tests { - use super::*; + use crate::views::view_for; + use forge_core::config::BannerConfig; fn config(message: &str, level: &str, expires: &str) -> BannerConfig { BannerConfig { diff --git a/crates/forge-web/src/pages/blame.rs b/crates/forge-web/src/pages/blame.rs index 0aa2308..0068364 100644 --- a/crates/forge-web/src/pages/blame.rs +++ b/crates/forge-web/src/pages/blame.rs @@ -14,9 +14,9 @@ use topcoat::view::{Unescaped, View, component, view}; use crate::i18n::browse as b; use crate::i18n::code::{self as g, K}; +use crate::i18n::s; use crate::i18n::{self, Lang}; use crate::pages::blob::{Line, text_lines}; -use crate::pages::passkeys::s; use crate::pages::ref_live; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; @@ -240,7 +240,7 @@ async fn blame_page(cx: &Cx) -> Result {
(file_name) (size) - }) } @@ -186,7 +186,7 @@ async fn source_tabs(cx: &Cx, lang: Lang, base: &str, active: Source) -> Result< let forgejo = format!("{base}?source=forgejo"); Ok(view! {
- (crate::pages::passkeys::s(lang, "Source", "Kaynak")) + (crate::i18n::s(lang, "Source", "Kaynak"))