From aa7d6b229ebb85c7ec4a8ae833d3b58b6ce3490d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 11 Sep 2026 06:25:09 +0300 Subject: [PATCH] in-web: cached family probes, per-page titles, avatar negative cache - health.rs: shared LazyLock reqwest client + 30s TTL probe cache (family_mark) - document_shell takes title; title_key_of maps path -> i18n key; soft-nav swap updates document.title; share pages get per-page titles - pages.rs: landing error uses lang(cx) Accept-Language fallback, not hard En - files.rs: Range header unwraps -> valid static fallbacks - avatar.rs: 404 misses get private max-age=300 negative cache - layout.rs: Profile menu deep-links {issuer}/people/{sub}; redundant SELF_KEY re-filter removed - i18n.rs: AllUsers duplicate key folded into AdminPanel; QuotaOf normalized to '/' in both languages --- crates/in-web/src/avatar.rs | 12 +++++- crates/in-web/src/files.rs | 8 ++-- crates/in-web/src/health.rs | 61 ++++++++++++++++++++++++++ crates/in-web/src/i18n.rs | 5 +-- crates/in-web/src/layout.rs | 85 +++++++++++++++++++++++-------------- crates/in-web/src/pages.rs | 17 +++++--- crates/in-web/src/share.rs | 16 ++++--- crates/in-web/tests/http.rs | 20 ++++----- 8 files changed, 160 insertions(+), 64 deletions(-) diff --git a/crates/in-web/src/avatar.rs b/crates/in-web/src/avatar.rs index 069af4d..af1799f 100644 --- a/crates/in-web/src/avatar.rs +++ b/crates/in-web/src/avatar.rs @@ -14,7 +14,10 @@ //! a request whose `?v=` already matches the row is stamped //! `private, max-age=31536000, immutable`, so a changed photo is a changed //! URL and no browser pins an old face behind a year of cache. Any other -//! spelling of the address revalidates with `private, no-cache`. +//! spelling of the address revalidates with `private, no-cache`. A miss — +//! an unknown id, im unreachable — is cached only briefly, so the browser +//! stops re-asking within a render but a face that comes back is not +//! held off for long. use topcoat::context::Cx; use topcoat::router::request::{headers as request_headers, uri}; @@ -24,7 +27,12 @@ use crate::server::{app, require_user}; path_param!(user_id); fn not_found() -> (StatusCode, HeaderMap, Vec) { - (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) + let mut headers = HeaderMap::new(); + headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static("private, max-age=300"), + ); + (StatusCode::NOT_FOUND, headers, Vec::new()) } /// The `?v=` the request carries, if it carries one. diff --git a/crates/in-web/src/files.rs b/crates/in-web/src/files.rs index b2acbe8..01eae7b 100644 --- a/crates/in-web/src/files.rs +++ b/crates/in-web/src/files.rs @@ -327,7 +327,8 @@ pub(crate) async fn bytes_response( Some(Err(())) => { headers.insert( header::CONTENT_RANGE, - HeaderValue::from_str(&format!("bytes */{total}")).unwrap(), + HeaderValue::from_str(&format!("bytes */{total}")) + .unwrap_or(HeaderValue::from_static("bytes */0")), ); return Some((StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty())); } @@ -338,12 +339,13 @@ pub(crate) async fn bytes_response( let end = start + span.len.saturating_sub(1); headers.insert( header::CONTENT_RANGE, - HeaderValue::from_str(&format!("bytes {start}-{end}/{total}")).unwrap(), + HeaderValue::from_str(&format!("bytes {start}-{end}/{total}")) + .unwrap_or(HeaderValue::from_static("bytes */0")), ); } headers.insert( header::CONTENT_LENGTH, - HeaderValue::from_str(&span.len.to_string()).unwrap(), + HeaderValue::from_str(&span.len.to_string()).unwrap_or(HeaderValue::from_static("0")), ); let frames = span.stream.map(|chunk| chunk.map(Frame::data)); Some((status, headers, Body::new(StreamBody::new(frames)))) diff --git a/crates/in-web/src/health.rs b/crates/in-web/src/health.rs index d7de382..5c58e8e 100644 --- a/crates/in-web/src/health.rs +++ b/crates/in-web/src/health.rs @@ -3,11 +3,21 @@ //! two seconds to answer — and the callers fan the probes out concurrently, //! so a family member that is down costs its two seconds, not two seconds //! each. +//! +//! A reading outlives its render: [`family_probes`] caches one round for +//! [`PROBE_TTL`] and reuses it for every page painted inside the window, so +//! a dark sibling stalls one render per window, not every render. The +//! client is shared too — one connection pool for the whole process, built +//! once — instead of a fresh one per render. + +use std::sync::{LazyLock, Mutex, PoisonError}; +use std::time::{Duration, Instant}; /// One `/healthz` reading. `Up` carries the body — the deploy contract's /// `ok ` — and the answer's latency; everything else, refused /// or wrong status or a body that does not begin ok or the two-second /// ceiling, is `Down`. +#[derive(Clone)] pub enum Probe { Up { body: String, ms: u128 }, Down, @@ -37,3 +47,54 @@ pub(crate) async fn probe_healthz(http: &reqwest::Client, url: &str) -> Probe { Probe::Down } } + +/// How long one round of probes stays true. Longer than a walk through the +/// pages, shorter than a sibling's outage outlasting notice. +const PROBE_TTL: Duration = Duration::from_secs(30); + +/// The one client every probe rides: `reqwest` pools connections per +/// client, so a fresh `Client::new()` per render would also mean a fresh +/// TLS handshake per render. Built once, shared. +static CLIENT: LazyLock = LazyLock::new(reqwest::Client::new); + +/// One cached round: when it was read, and what each sibling read — keyed +/// by the sibling's key and address together, so a moved service probes +/// again even inside the window. +type Round = (Instant, Vec<(String, String, Probe)>); + +static ROUND: LazyLock> = LazyLock::new(|| Mutex::new((Instant::now(), Vec::new()))); + +/// The family's health, one `Probe` per `(key, url)` pair, in order. A +/// round younger than [`PROBE_TTL`] over the same key-and-address set is +/// reused; anything else fans the probes out concurrently and files the +/// round. The two-second per-sibling ceiling lives in [`probe_healthz`]. +pub(crate) async fn family_probes(siblings: &[(&str, &str)]) -> Vec { + let lock = || ROUND.lock().unwrap_or_else(PoisonError::into_inner); + { + let round = lock(); + let same = round.0.elapsed() < PROBE_TTL + && round.1.len() == siblings.len() + && round + .1 + .iter() + .zip(siblings) + .all(|((key, url, _), (want_key, want_url))| key == want_key && url == want_url); + if same { + return round.1.iter().map(|(_, _, probe)| probe.clone()).collect(); + } + } + let mut handles = Vec::new(); + for (_, url) in siblings { + let http = CLIENT.clone(); + let url = format!("{}/healthz", url.trim_end_matches('/')); + handles.push(tokio::spawn(async move { probe_healthz(&http, &url).await })); + } + let mut round: Vec<(String, String, Probe)> = Vec::new(); + for ((key, url), handle) in siblings.iter().zip(handles) { + let probe = handle.await.unwrap_or(Probe::Down); + round.push(((*key).to_string(), (*url).to_string(), probe)); + } + let probes = round.iter().map(|(_, _, probe)| probe.clone()).collect(); + *lock() = (Instant::now(), round); + probes +} diff --git a/crates/in-web/src/i18n.rs b/crates/in-web/src/i18n.rs index 1342ec1..dc8a63c 100644 --- a/crates/in-web/src/i18n.rs +++ b/crates/in-web/src/i18n.rs @@ -180,7 +180,6 @@ pub enum Key { QuotaUsage, QuotaOf, AdminPanel, - AllUsers, SetQuota, QuotaBytes, DisableUser, @@ -371,9 +370,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { ConnectionLastPass => "Last full pass", Never => "never", QuotaUsage => "Storage used", - QuotaOf => "of", + QuotaOf => "/", AdminPanel => "Everyone", - AllUsers => "Everyone", SetQuota => "Set the quota", QuotaBytes => "Storage quota", DisableUser => "Disable", @@ -559,7 +557,6 @@ pub fn t(lang: Lang, key: Key) -> &'static str { ConnectionLastPass => "Son tam geçiş", Never => "hiç", AdminPanel => "Herkes", - AllUsers => "Herkes", SetQuota => "Kotayı ayarla", QuotaBytes => "Depolama kotası", DisableUser => "Devre dışı bırak", diff --git a/crates/in-web/src/layout.rs b/crates/in-web/src/layout.rs index 430efd2..cf09257 100644 --- a/crates/in-web/src/layout.rs +++ b/crates/in-web/src/layout.rs @@ -14,13 +14,14 @@ use topcoat::{ StatusCode, error::{NotFoundError, not_found}, layout, page, + request::uri, }, view::{Unescaped, View, ViewExt, error_boundary, view}, }; use in_core::store::User; -use crate::health::{Probe, probe_healthz}; +use crate::health::{family_probes, Probe}; use crate::i18n::{Key, Lang, t}; use crate::server::{app, current_user}; @@ -168,7 +169,7 @@ pub async fn user_menu<'a>(cx: &'a Cx, user: &'a User, lang: Lang) -> Result(t(lang, Key::AdminBadge)) } - (t(lang, Key::Profile)) + (t(lang, Key::Profile)) (t(lang, Key::NavSettings)) (t(lang, Key::SignOut)) @@ -265,25 +266,26 @@ async fn family_mark<'a>(cx: &'a Cx) -> Result { if siblings.is_empty() { return mark(cx).await.map(|v| v.boxed()); } - // Every probe at once: a family member that is down costs its two - // seconds, not two seconds each. - let http = reqwest::Client::new(); - let mut probes = Vec::new(); - for service in &siblings { - let http = http.clone(); - let url = format!("{}/healthz", service.url.trim_end_matches('/')); - probes.push(tokio::spawn(async move { probe_healthz(&http, &url).await })); - } - let mut rows = Vec::new(); - for (service, probe) in siblings.iter().zip(probes) { - let probe = probe.await.unwrap_or(Probe::Down); - rows.push(( - service.key.as_str(), - service.url.as_str(), - service.name.as_str(), - probe, - )); - } + // Every probe at once, one reading shared per window: a family member + // that is down costs its two seconds once per half minute, not on + // every page the reader opens. + let asked: Vec<(&str, &str)> = siblings + .iter() + .map(|service| (service.key.as_str(), service.url.as_str())) + .collect(); + let probes = family_probes(&asked).await; + let rows: Vec<_> = siblings + .iter() + .zip(probes) + .map(|(service, probe)| { + ( + service.key.as_str(), + service.url.as_str(), + service.name.as_str(), + probe, + ) + }) + .collect(); let marks = switcher_marks(rows); Ok(view! { cx => @@ -295,8 +297,8 @@ async fn family_mark<'a>(cx: &'a Cx) -> Result { .boxed()) } -/// The flyout's marks as final HTML, pure over resolved probes: in's own -/// row filtered out, every sibling a plain link carrying its probe's dot +/// The flyout's marks as final HTML, pure over resolved probes: every +/// sibling a plain link carrying its probe's dot /// — `health-on` while it answers `ok`, `health-off` while it does not — /// middots between. Dots only: the probe's body and latency never reach /// the chrome. Extracted from `family_mark` so the tests pin this exact @@ -305,7 +307,6 @@ pub fn switcher_marks<'a>( rows: impl IntoIterator, ) -> String { rows.into_iter() - .filter(|(key, _, _, _)| *key != SELF_KEY) .map(|(key, url, name, probe)| { let key = escape(key); let url = escape(url); @@ -595,6 +596,8 @@ pub async fn soft_nav_script<'a>(cx: &'a Cx) -> Result { else { document.documentElement.removeAttribute('data-theme'); } \ if (root.hasAttribute('data-ui')) { document.documentElement.setAttribute('data-ui', root.getAttribute('data-ui')); } \ else { document.documentElement.removeAttribute('data-ui'); } \ + var freshTitle = doc.querySelector('title'); \ + if (freshTitle && freshTitle.textContent) { document.title = freshTitle.textContent; } \ if (url) { history[push ? 'pushState' : 'replaceState'](null, '', url); } \ if (morphing) { \ morph(document.body, doc.body); \ @@ -1118,13 +1121,14 @@ const STYLE: Asset = asset!("assets/main.css"); /// layout pairing — the public share pages among them, whose query can ask /// for bytes a page-shaped answer cannot carry — so this is `pub(crate)`: /// they wrap their views in the same shell by calling it directly instead of -/// hand-copying the head. Signed-out visitors wear the provision defaults -/// and the session-gated live stream stays off (`asking` is false without a -/// session), so a stranger's page carries no user data and opens no -/// `/api/live` connection. +/// hand-copying the head, passing their own `title`. Signed-out visitors +/// wear the provision defaults and the session-gated live stream stays off +/// (`asking` is false without a session), so a stranger's page carries no +/// user data and opens no `/api/live` connection. pub(crate) async fn document_shell<'a>( cx: &'a Cx, slot: topcoat::view::Child<'a>, + title: &'a str, ) -> Result { // The per-user chrome knobs, read off the request's own user: the theme // into `data-theme`, the interface into `data-ui`, the language into @@ -1153,7 +1157,7 @@ pub(crate) async fn document_shell<'a>( rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=Newsreader:ital,wght@0,400;0,600;1,400;1,600&display=swap" > - "in" + (title) topcoat::runtime::script() @@ -1187,9 +1191,28 @@ pub(crate) async fn document_shell<'a>( }.boxed()) } +/// The tab title a page wears, read off its address: the shell is paired +/// around pages by path prefix, so a page cannot hand its name up — the +/// router's own address decides. The share pages, which wrap themselves in +/// the shell directly, pass their own instead. Anything unmatched — the +/// catch-all 404 among it — reads as the app's bare name. +fn title_key_of(path: &str) -> Option { + match path { + "/" => Some(Key::WelcomeTitle), + p if p.starts_with("/drive") => Some(Key::NavDrive), + p if p.starts_with("/shared") => Some(Key::NavShared), + p if p.starts_with("/trash") => Some(Key::NavTrash), + p if p.starts_with("/settings") => Some(Key::NavSettings), + p if p.starts_with("/view/") => Some(Key::FileDetails), + _ => None, + } +} + /// The router's own shell route: pairing is by path prefix, so every page -/// under `/` wears `document_shell` through here. +/// under `/` wears `document_shell` through here, titled off its address. #[layout("/")] async fn root_layout(cx: &Cx, slot: topcoat::view::Child<'_>) -> Result { - document_shell(cx, slot).await + let lang = crate::i18n::lang(cx).await; + let title = title_key_of(uri(cx).path()).map_or("in", |key| t(lang, key)); + document_shell(cx, slot, title).await } diff --git a/crates/in-web/src/pages.rs b/crates/in-web/src/pages.rs index c88fc79..064ccb1 100644 --- a/crates/in-web/src/pages.rs +++ b/crates/in-web/src/pages.rs @@ -14,7 +14,7 @@ use topcoat::context::Cx; use topcoat::router::{HeaderValue, StatusCode, header, page}; use topcoat::view::{View, ViewExt, view}; -use crate::i18n::{Key, Lang, lang, t}; +use crate::i18n::{Key, lang, t}; use crate::layout::wordmark; use crate::server::current_user; @@ -33,13 +33,16 @@ async fn landing(cx: &Cx) -> Result { .boxed()) } Ok(None) => Ok(sign_in_card(cx).await?.boxed()), - Err(_) => Ok(view! { - cx => -
-

(t(Lang::En, Key::SomethingWentWrong))

-
+ Err(_) => { + let language = lang(cx).await; + Ok(view! { + cx => +
+

(t(language, Key::SomethingWentWrong))

+
+ } + .boxed()) } - .boxed()), } } diff --git a/crates/in-web/src/share.rs b/crates/in-web/src/share.rs index 138614d..99b2478 100644 --- a/crates/in-web/src/share.rs +++ b/crates/in-web/src/share.rs @@ -680,8 +680,12 @@ fn has_flag(query: &str, key: &str) -> bool { /// `/s` surface stays a `#[route]` and wraps its views itself — in /// `document_shell`, the same shell every `#[page]` under `/` wears, never /// a hand-copied head. -async fn public_page(cx: &Cx, page: impl View) -> Result { - document_shell(cx, topcoat::view::Child::new(page)) +async fn public_page( + cx: &Cx, + title: &str, + page: impl View, +) -> Result { + document_shell(cx, topcoat::view::Child::new(page), title) .await? .first() .await? @@ -701,7 +705,7 @@ async fn dead_link(cx: &Cx) -> topcoat::Result(t(language, Key::BackToDrive))

}; - public_page(cx, page).await + public_page(cx, t(language, Key::NothingAtThisAddress), page).await } /// The public viewer. No auth: the token in the path is the whole /// credential. A file target renders its card (and its bytes on `?dl=1` @@ -890,7 +894,7 @@ async fn password_gate(cx: &Cx) -> topcoat::Result }; - public_page(cx, page).await + public_page(cx, t(language, Key::PasswordProtected), page).await } #[derive(Deserialize)] @@ -1170,7 +1174,7 @@ async fn file_card( (topcoat::view::Child::new(media_player_script(cx).await?)) }; - public_page(cx, page).await + public_page(cx, &file.name, page).await } /// One file's chip on the public card: the link's own thumbnail where one @@ -1272,7 +1276,7 @@ async fn folder_card( }; - public_page(cx, page).await + public_page(cx, &root.name, page).await } /// The request's own path, without its query: the download links the public diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index d824722..47a9c30 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -3342,11 +3342,12 @@ async fn the_family_flyout_marks_siblings_with_health_dots() { } /// The CI gate for the flyout markup: `switcher_marks` is the exact HTML -/// the flyout renders, so the probe-to-dot mapping and in's omission are -/// pinned without a router or an asset bundle — which is where the -/// renders above get skipped. Up reads `health-on`, Down `health-off`, -/// the keys stay links with their titles, and the probe's body and -/// latency never reach the chrome. +/// the flyout renders, so the probe-to-dot mapping is pinned without a +/// router or an asset bundle — which is where the renders above get +/// skipped. Up reads `health-on`, Down `health-off`, the keys stay links +/// with their titles, and the probe's body and latency never reach the +/// chrome. (The omission of in's own row is `family_mark`'s doing; the +/// router renders above pin it.) #[test] fn the_family_flyout_marks_pure_html() { use in_web::health::Probe; @@ -3354,8 +3355,6 @@ fn the_family_flyout_marks_pure_html() { let marks = in_web::layout::switcher_marks([ ("iz", "http://127.0.0.1:9001", "Board", Probe::Up { body: "ok dev".into(), ms: 12 }), ("im", "http://127.0.0.1:9002", "Account", Probe::Down), - // in's own row goes in; it must not come back out. - ("in", "http://127.0.0.1:7655", "Files", Probe::Up { body: "ok dev".into(), ms: 1 }), ]); assert!( marks.contains( @@ -3373,7 +3372,6 @@ fn the_family_flyout_marks_pure_html() { "the dark sibling reads off: {marks}" ); assert!(marks.contains(">im"), "the dark sibling renders: {marks}"); - assert!(!marks.contains(">in"), "in's own row stays out: {marks}"); assert!(!marks.contains("ok dev"), "the flyout carries dots only: {marks}"); assert!(!marks.contains(" ms"), "the flyout carries no latency: {marks}"); assert!( @@ -5094,10 +5092,10 @@ async fn settings_lives_in_the_user_menu_not_the_topbar() { let menu_start = body.find("user-menu-panel").expect("no user menu"); let menu = &body[menu_start..]; assert!(menu.contains("href=\"/settings\""), "{menu}"); - let issuer = format!("href=\"{}/\"", app.config.oidc.issuer); + let profile = format!("href=\"{}/people/{}\"", app.config.oidc.issuer, "sub-menu"); assert!( - menu.contains(&issuer), - "no profile link to the issuer: {menu}" + menu.contains(&profile), + "no profile deep link to im's people page: {menu}" ); }