From c097a7cbfa306379c152582f8acb4a64794355d4 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] im-web: cached family probes, refusal i18n, soft-nav // guard, escape fixes - health.rs: shared LazyLock reqwest client + 30s TTL probe cache; no more per-render Client::new + inline 2s sibling stalls on every page - pages.rs/i18n.rs: 'unavailable' error arm (En+Tr) for photo store failures - layout.rs: soft-nav rejects protocol-relative // hrefs (foreign-HTML swap hole) - escape(): map ' -> '; drop redundant manual escape at view! text sinks (pages.rs:837,1110; admin.rs:209) that double-escaped - directory/oidc/photo: handler unwraps mapped to error paths - people.rs: single avatar fetch; admin placeholders via t(); sessions created_at formatted like seen --- crates/im-web/src/admin.rs | 38 +++++++++++-------- crates/im-web/src/directory.rs | 22 ++++++++--- crates/im-web/src/health.rs | 68 ++++++++++++++++++++++++++++++++++ crates/im-web/src/i18n.rs | 13 +++++++ crates/im-web/src/layout.rs | 33 +++++++++-------- crates/im-web/src/oidc.rs | 6 ++- crates/im-web/src/pages.rs | 6 ++- crates/im-web/src/people.rs | 7 ++-- crates/im-web/src/photo.rs | 14 +++---- 9 files changed, 155 insertions(+), 52 deletions(-) diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index b5b81b1..29b0f87 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -15,7 +15,7 @@ use topcoat::router::response::{IntoResponse, Response}; use topcoat::router::{HeaderValue, StatusCode, header, route}; use topcoat::view::{Child, ViewExt, view}; -use crate::health::{Probe, probe_healthz}; +use crate::health::{Probe, probe_family}; use crate::i18n::{self, Key, lang_of, t}; use crate::layout::shell; use crate::mailer; @@ -48,6 +48,7 @@ fn escape(raw: &str) -> String { .replace('<', "<") .replace('>', ">") .replace('"', """) + .replace('\'', "'") } /// One row action as a two-step disclosure — iz's `confirm-details` idiom: @@ -205,7 +206,7 @@ async fn admin_page(cx: &Cx) -> Result { _ => None, }; - let my_email = escape(&me.email); + let my_email = me.email.clone(); let stage = view! { cx =>
@@ -256,6 +257,12 @@ fn sessions_row( "[year]-[month]-[day] [hour]:[minute]" )) .unwrap_or_else(|_| seen_at.date().to_string()); + let created = session + .created_at + .format(&time::macros::format_description!( + "[year]-[month]-[day] [hour]:[minute]" + )) + .unwrap_or_else(|_| session.created_at.date().to_string()); rows.push_str(&format!( concat!( r#"{}"#, @@ -283,7 +290,7 @@ fn sessions_row( .as_deref() .map(escape) .unwrap_or_else(|| "—".to_string()), - session.created_at.date(), + created, seen, escape(&session.token_hash), t(lang, Key::RevokeButton), @@ -640,13 +647,13 @@ async fn services_section(
- +
{client_add_label}
- +
"#, @@ -654,8 +661,10 @@ async fn services_section( key_label = t(lang, Key::ServiceKeyLabel), name_label = t(lang, Key::NameCol), url_label = t(lang, Key::AddressLabel), + url_placeholder = t(lang, Key::ServiceUrlPlaceholder), id_label = t(lang, Key::ClientIdLabel), uris_label = t(lang, Key::RedirectUrisLabel), + uris_placeholder = t(lang, Key::RedirectUrisPlaceholder), registered_label = t(lang, Key::RegisteredCol), service_add_label = t(lang, Key::ServiceAdd), add = t(lang, Key::ServiceAdd), @@ -1443,22 +1452,21 @@ async fn logs_section(cx: &Cx, lang: i18n::Lang) -> Result Result { let services = im_core::services::list(&app(cx).store).await?; - // 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 &services { - let http = http.clone(); - let url = format!("{}/healthz", service.url.trim_end_matches('/')); - probes.push(tokio::spawn(async move { probe_healthz(&http, &url).await })); - } + // One shared reading: this table and the chrome's flyout share the + // cached probe round, so a family member that is down costs its two + // seconds once per window, not once per page view. + let urls = services + .iter() + .map(|service| format!("{}/healthz", service.url.trim_end_matches('/'))) + .collect::>(); + let probes = probe_family(&urls).await; let mut rows = String::new(); for (service, probe) in services.iter().zip(probes) { let key = escape(&service.key); let name = escape(&service.name); let url = escape(&service.url); - let state = match probe.await.unwrap_or(Probe::Down) { + let state = match probe { Probe::Up { body, ms } => format!( r#"{} · {ms} ms"#, escape(&body) diff --git a/crates/im-web/src/directory.rs b/crates/im-web/src/directory.rs index ce8257b..10196f2 100644 --- a/crates/im-web/src/directory.rs +++ b/crates/im-web/src/directory.rs @@ -68,7 +68,8 @@ async fn directory(cx: &Cx) -> topcoat::Result topcoat::Result member, }; + // A member that will not serialize cannot happen — plain + // fields all the way down — but a stream cannot panic on + // the impossible: ending is the honest answer, and the + // client heals the gap the way it heals any disconnect. + let Ok(json) = serde_json::to_string(&member) else { + return None; + }; return Some(( - Ok(Event::new() - .event("profile") - .data(serde_json::to_string(&member).expect("member JSON"))), + Ok(Event::new().event("profile").data(json)), (rx, deadline, stopping, first), )); } @@ -177,7 +183,8 @@ async fn family(cx: &Cx) -> topcoat::Result } let store = server::app(cx).store.clone(); let services = im_core::services::list(&store).await?; - Json(serde_json::to_value(services).unwrap()).into_response(cx) + let services = serde_json::to_value(services)?; + Json(services).into_response(cx) } /// The body a sibling posts to keep its own row: its wordmark key, the @@ -216,7 +223,10 @@ async fn family_register( ) .await { - Ok(service) => Json(serde_json::to_value(service).unwrap()).into_response(cx), + Ok(service) => { + let service = serde_json::to_value(&service)?; + Json(service).into_response(cx) + } Err(im_core::store::StoreError::Conflict(_)) => ( StatusCode::CONFLICT, Json(serde_json::json!({ "error": "owned" })), diff --git a/crates/im-web/src/health.rs b/crates/im-web/src/health.rs index 41885e1..3520b93 100644 --- a/crates/im-web/src/health.rs +++ b/crates/im-web/src/health.rs @@ -3,11 +3,19 @@ //! `GET {url}/healthz` where it stands — no credentials, 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. +//! [`probe_family`] sits over that with the two things a per-render probe +//! used to pay again and again: one shared client, and a short-lived +//! cache so a burst of renders reuses the last reading instead of +//! re-stalling on a down sibling. + +use std::sync::{LazyLock, Mutex}; +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(crate) enum Probe { Up { body: String, ms: u128 }, Down, @@ -37,3 +45,63 @@ pub(crate) async fn probe_healthz(http: &reqwest::Client, url: &str) -> Probe { Probe::Down } } + +/// How long one family reading stands in for fresh probes. Long enough +/// that paging the panel does not re-stall on a dark sibling, short +/// enough that a service coming back is noticed within half a minute. +const CACHE_TTL: Duration = Duration::from_secs(30); + +/// The probe client every reader shares: one connection pool built once +/// per process, not a fresh client — and fresh sockets — per render. +static HTTP: LazyLock = LazyLock::new(reqwest::Client::new); + +/// The last family reading: when it was taken, and what each probed +/// `/healthz` answered, keyed by URL. +static CACHE: LazyLock)>> = + LazyLock::new(|| Mutex::new((Instant::now(), Vec::new()))); + +/// One reading per URL, in order. A reading younger than [`CACHE_TTL`] +/// that already covers every URL asked is reused whole — the chrome and +/// the panel can share a render without doubling the probes, and a down +/// sibling's two-second ceiling is paid once per window, not once per +/// page view. Otherwise every URL is probed at once and the reading is +/// remembered. A family that gained or lost a row reads fresh; a lost +/// probe task reads `Down`, and the next window re-probes. +pub(crate) async fn probe_family(urls: &[String]) -> Vec { + if let Some(cached) = fresh(urls) { + return cached; + } + let probes: Vec<_> = urls + .iter() + .map(|url| { + let url = url.clone(); + tokio::spawn(async move { probe_healthz(&HTTP, &url).await }) + }) + .collect(); + let mut readings: Vec<(String, Probe)> = Vec::with_capacity(urls.len()); + for (url, probe) in urls.iter().zip(probes) { + readings.push((url.clone(), probe.await.unwrap_or(Probe::Down))); + } + if let Ok(mut slot) = CACHE.lock() { + *slot = (Instant::now(), readings.clone()); + } + readings.into_iter().map(|(_, probe)| probe).collect() +} + +/// The cached reading, when it is young enough to stand and covers every +/// URL asked. A poisoned cache is a miss — the next round re-probes. +fn fresh(urls: &[String]) -> Option> { + let cache = CACHE.lock().ok()?; + let (at, readings) = &*cache; + if at.elapsed() >= CACHE_TTL { + return None; + } + urls.iter() + .map(|url| { + readings + .iter() + .find(|(seen, _)| seen == url) + .map(|(_, probe)| probe.clone()) + }) + .collect() +} diff --git a/crates/im-web/src/i18n.rs b/crates/im-web/src/i18n.rs index de1adbf..e468493 100644 --- a/crates/im-web/src/i18n.rs +++ b/crates/im-web/src/i18n.rs @@ -63,6 +63,7 @@ pub enum Key { ErrPhotoTooBig, ErrNotAnImage, ErrNoFile, + ErrUnavailable, ErrResetInvalid, ErrSessionUnknown, ErrBadTheme, @@ -144,6 +145,7 @@ pub enum Key { ServicesTitle, ServiceKeyLabel, ServiceAdd, + ServiceUrlPlaceholder, ServiceKept, ServiceMoveUp, ServiceMoveDown, @@ -251,6 +253,7 @@ pub enum Key { RedirectUrisLabel, RegisteredCol, ClientAdd, + RedirectUrisPlaceholder, RotateWord, RevokeWord, ConfirmRotate, @@ -377,6 +380,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (ErrNotAnImage, Tr) => "Bu dosya bir görsel değil.", (ErrNoFile, En) => "Choose an image first.", (ErrNoFile, Tr) => "Önce bir görsel seç.", + (ErrUnavailable, En) => "That could not be saved right now — try again.", + (ErrUnavailable, Tr) => "Bu şu anda kaydedilemedi — yeniden dene.", (ErrResetInvalid, En) => "This reset link is not valid — ask for a fresh one.", (ErrResetInvalid, Tr) => "Bu sıfırlama bağlantısı geçerli değil — yenisini iste.", (ErrSessionUnknown, En) => "That session is already gone.", @@ -524,6 +529,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (ServiceKeyLabel, Tr) => "Anahtar", (ServiceAdd, En) => "Add service", (ServiceAdd, Tr) => "Hizmet ekle", + (ServiceUrlPlaceholder, En) => "https://in.dizey.sh", + (ServiceUrlPlaceholder, Tr) => "https://in.dizey.sh", (ServiceKept, En) => "kept by the app", (ServiceKept, Tr) => "uygulaması koruyor", (ServiceMoveUp, En) => "Move up", @@ -749,6 +756,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (RegisteredCol, Tr) => "Kayıt", (ClientAdd, En) => "Register client", (ClientAdd, Tr) => "İstemci kaydet", + (RedirectUrisPlaceholder, En) => { + "http://127.0.0.1:9000/callback https://drive.dizey.sh/callback" + } + (RedirectUrisPlaceholder, Tr) => { + "http://127.0.0.1:9000/callback https://drive.dizey.sh/callback" + } (RotateWord, En) => "Rotate", (RotateWord, Tr) => "Yenile", (RevokeWord, En) => "Revoke", diff --git a/crates/im-web/src/layout.rs b/crates/im-web/src/layout.rs index 4dd4742..4fba4fd 100644 --- a/crates/im-web/src/layout.rs +++ b/crates/im-web/src/layout.rs @@ -7,7 +7,7 @@ use topcoat::asset::{Asset, asset}; use topcoat::context::Cx; use topcoat::view::{BoxView, Child, View, ViewExt, view}; -use crate::health::{Probe, probe_healthz}; +use crate::health::{Probe, probe_family}; use crate::i18n::{Key, Lang, lang_of, t}; use crate::server; @@ -44,20 +44,19 @@ pub async fn family_wordmark(cx: &Cx) -> Result> { if siblings.is_empty() { return wordmark(cx).await.map(ViewExt::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(), probe)); - } + // One shared reading: a render inside the cache window reuses the + // last probe round, so a family member that is down costs its two + // seconds once per window, not once per page view. + let urls = siblings + .iter() + .map(|service| format!("{}/healthz", service.url.trim_end_matches('/'))) + .collect::>(); + let probes = probe_family(&urls).await; + let rows = siblings + .iter() + .zip(probes) + .map(|(service, probe)| (service.key.as_str(), service.url.as_str(), probe)) + .collect::>(); let marks = trio_marks(rows); Ok(view! { cx => @@ -366,7 +365,9 @@ pub async fn soft_nav_script(cx: &Cx) -> Result { var a = e.target.closest ? e.target.closest('a') : null; if (!a || a.target || a.hasAttribute('download') || a.hasAttribute('data-hard')) { return; } var href = a.getAttribute('href') || ''; - if (href.indexOf('/') !== 0) { return; } + // Same-app paths only: `//host` is protocol-relative — another origin — + // and goes the browser's own way. + if (href.indexOf('/') !== 0 || href.indexOf('//') === 0) { return; } e.preventDefault(); go(href, true, true); }, true); diff --git a/crates/im-web/src/oidc.rs b/crates/im-web/src/oidc.rs index 8253334..369a4e6 100644 --- a/crates/im-web/src/oidc.rs +++ b/crates/im-web/src/oidc.rs @@ -150,9 +150,10 @@ async fn authorize(cx: &Cx) -> Result { let Some(user) = user else { let back = format!("/authorize?{query}"); let location = format!("/login?back={}", urlencode(&back)); + let location = HeaderValue::from_str(&location)?; return ( StatusCode::SEE_OTHER, - [(header::LOCATION, HeaderValue::from_str(&location).unwrap())], + [(header::LOCATION, location)], ) .into_response(cx); }; @@ -172,9 +173,10 @@ async fn authorize(cx: &Cx) -> Result { if let Some(state) = state { location.push_str(&format!("&state={state}")); } + let location = HeaderValue::from_str(&location)?; ( StatusCode::SEE_OTHER, - [(header::LOCATION, HeaderValue::from_str(&location).unwrap())], + [(header::LOCATION, location)], ) .into_response(cx) } diff --git a/crates/im-web/src/pages.rs b/crates/im-web/src/pages.rs index aa5e742..961d43e 100644 --- a/crates/im-web/src/pages.rs +++ b/crates/im-web/src/pages.rs @@ -40,6 +40,7 @@ pub fn error_text(code: &str, lang: Lang) -> &'static str { "photo_too_big" => t(lang, Key::ErrPhotoTooBig), "not_an_image" => t(lang, Key::ErrNotAnImage), "no_file" => t(lang, Key::ErrNoFile), + "unavailable" => t(lang, Key::ErrUnavailable), "session_unknown" => t(lang, Key::ErrSessionUnknown), "bad_theme" => t(lang, Key::ErrBadTheme), "bad_ui" => t(lang, Key::ErrBadUi), @@ -485,6 +486,7 @@ pub(crate) fn escape(raw: &str) -> String { .replace('<', "<") .replace('>', ">") .replace('"', """) + .replace('\'', "'") } /// What the agent string means to a person — "Chrome on Linux", not the raw @@ -832,7 +834,7 @@ async fn signed_in<'a>(cx: &'a Cx, user: im_core::model::User) -> Result(t(lang, Key::EmailCardTitle)) if let Some(pending) = pending_email.as_deref() {
- (crate::i18n::email_pending_line(lang, &escape(pending))) + (crate::i18n::email_pending_line(lang, pending))
} if let Some(links) = query_value(&query, "links") { @@ -1105,7 +1107,7 @@ async fn email_change_page(cx: &Cx) -> Result {
(t(lang, Key::EmailConfirmTitle))
- (crate::i18n::email_confirm_sub(lang, &escape(&new_email))) + (crate::i18n::email_confirm_sub(lang, &new_email))
diff --git a/crates/im-web/src/people.rs b/crates/im-web/src/people.rs index 3d7876e..26c9408 100644 --- a/crates/im-web/src/people.rs +++ b/crates/im-web/src/people.rs @@ -38,8 +38,7 @@ async fn people_page(cx: &Cx) -> Result { // The stage template moves every value it mentions, so the account's // template data is staged here as owned values first; the markup below // never names `person` itself. - let face_button = avatar(cx, &person).await?.first().await?; - let face_plain = avatar(cx, &person).await?.first().await?; + let face = avatar(cx, &person).await?.first().await?; let display_name = person.name.clone(); let email_shown = person.email.clone(); let has_photo = person.has_photo; @@ -57,10 +56,10 @@ async fn people_page(cx: &Cx) -> Result { // The face opens the viewer here too — same as // the landing, same as iz's person page. } else { - (face_plain) + (face) }
(display_name)
diff --git a/crates/im-web/src/photo.rs b/crates/im-web/src/photo.rs index 937ff33..b5b61ee 100644 --- a/crates/im-web/src/photo.rs +++ b/crates/im-web/src/photo.rs @@ -115,23 +115,23 @@ fn bytes_response( content_type: &str, cache: &'static str, version: u64, -) -> (StatusCode, HeaderMap, Vec) { +) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { let etag = format!("\"p{version}\""); let mut headers = HeaderMap::new(); - headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap()); + headers.insert(header::ETAG, HeaderValue::from_str(&etag)?); headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); let if_none_match = request_headers(cx) .get(header::IF_NONE_MATCH) .and_then(|v| v.to_str().ok()); if if_none_match == Some(etag.as_str()) { - return (StatusCode::NOT_MODIFIED, headers, Vec::new()); + return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new())); } headers.insert( header::CONTENT_TYPE, HeaderValue::from_str(content_type) .unwrap_or(HeaderValue::from_static("application/octet-stream")), ); - (StatusCode::OK, headers, bytes) + Ok((StatusCode::OK, headers, bytes)) } /// The default face, as an image: the name's first letter on a quiet tile — @@ -203,7 +203,7 @@ async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { } else { "private, no-cache" }; - return Ok(bytes_response(cx, bytes, &mime, cache, version)); + return bytes_response(cx, bytes, &mime, cache, version); } let initial = user .as_ref() @@ -211,13 +211,13 @@ async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { .unwrap_or('?') .to_uppercase() .to_string(); - Ok(bytes_response( + bytes_response( cx, default_avatar(&initial), "image/svg+xml", "private, no-cache", version, - )) + ) } #[cfg(test)]