From 8bdec5c757eeb9c189d7a894f16367fd46473b88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Gruszczy=C5=84ski?= Date: Sun, 15 Nov 2026 20:54:59 +0100 Subject: [PATCH] v0.38.2 --- AGENTS.md | 2 +- CHANGELOG.md | 7 ++ Cargo.lock | 2 +- Cargo.toml | 2 +- docker-agent/model.go | 2 +- docs/CACHE.md | 46 ++++++++ docs/HEADLESS.md | 2 +- integrations/routeros-oci-build/README.md | 4 +- langs/en_US.json | 8 +- langs/pl_pl.json | 8 +- src/admin/logging_api.rs | 2 +- src/admin/openapi.json | 29 ++++- src/admin/web/app/settings.js | 4 +- src/admin/web/cache-panel.js | 3 +- src/admin/web/css/30-overview.css | 4 + src/admin/web/index.html | 5 + src/admin/web/management.js | 3 +- src/admin/web/vhosts/core.js | 4 +- src/admin/web/vhosts/editor.js | 6 +- src/cache/model/entry.rs | 30 ++++- src/cache/model/settings.rs | 2 + src/cache/stats.rs | 7 ++ src/config/model.rs | 2 + src/config/routing.rs | 2 + src/proxy/body/mod.rs | 11 +- src/proxy/cache_helpers.rs | 61 +++++++--- src/proxy/forward/cache_fast_path_tests.rs | 124 +++++++++++++++++++++ src/runtime/types.rs | 4 + src/vhost/model.rs | 12 ++ src/vhost/tests.rs | 28 +++++ src/vhost/validation.rs | 34 ++++++ tests/panel_refresh_contract.js | 2 +- 32 files changed, 418 insertions(+), 44 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 053652a..b59345f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # RustProxy source and documentation maintenance -Current source version: **0.38.1**. The Cargo package and binary are named `rust-proxy`. +Current source version: **0.38.2**. The Cargo package and binary are named `rust-proxy`. Before editing, read [README.md](README.md), the relevant [documentation guide](docs/README.md) and the actual code and tests. Historical release experiments are not current specifications. Use the bundled `src/admin/openapi.json` for API routes and payloads; the source implementation is authoritative for runtime behavior. diff --git a/CHANGELOG.md b/CHANGELOG.md index aea23f1..0604347 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ Release history focused on **features, settings, default behavior, compatibility and fixes**. Changes to internal code structure and preliminary performance experiments are intentionally omitted. Historical descriptions reflect their respective releases; consult the current documentation for the settings available in the latest release. +## 0.38.2 — Server-Timing, STALE and REVALIDATED + +- **Server-Timing is appended, not replaced:** on a MISS or BYPASS the origin's own `Server-Timing` metrics (`db;dur=…`, `app;dur=…`) now reach the client, with RustProxy's field after them; before, RustProxy removed them. Several RustProxy hops each append their own field. On a response served from the cache the stored origin metrics are removed, also when timing headers are off, because they described the request that filled the cache. +- **Metric names for a reverse proxy:** `proxy;dur`, `upstream;dur` and `proxy-cache;desc` (before: `proxy`, `origin`, `cache`). They no longer collide with a CDN in front of RustProxy (`origin` there means RustProxy) or with an application's own `cache` metric. The vhost option `timing_header_names` (panel: **Server-Timing metric names**) also offers `cdn` (`edge`, `origin`, `cdn-cache`, the Akamai mPulse names, for RustProxy as the outermost layer) and `legacy` (the previous names). +- **Timing-Allow-Origin:** new vhost option `timing_allow_origin` (origins or `*`) lets scripts on other origins, such as a RUM collector or an assets domain, read Server-Timing. +- **STALE and REVALIDATED:** responses served from cache past freshness (grace, stale-while-revalidate, max-stale, stale-if-error, collapse timeout) and cached objects confirmed by the origin with 304 are now told apart from plain hits. The Server-Timing cache metric and the access-log `cache` field (log filter, `rust-proxy logs`, `/api/logs?cache=`) report `STALE` / `REVALIDATED` instead of `HIT`. `X-Cache` does so with the new option **X-Cache shows STALE and REVALIDATED instead of HIT** (`cache.expose_detailed_status`, global and per vhost, off by default). The Cache dashboard counts them as HIT for the hit ratio and shows them on the request line; `/api/cache` has `stale` and `revalidated` per domain. See [Cache](docs/CACHE.md#detailed-cache-status-stale-and-revalidated). + ## 0.38.1 — built-in dashboard presets and matching fixes - **Path prefixes with a trailing slash:** a cache bypass prefix or forced-cache target written as `/api/` now also matches the paths below it (`/api/health`); before, it matched only the exact path `/api/`, so such responses were cached when their headers allowed it. `/api` (without the slash) already covered `/api` and `/api/…` and still does not match `/apix`. diff --git a/Cargo.lock b/Cargo.lock index 1b0ef3f..e5f6cbe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1943,7 +1943,7 @@ dependencies = [ [[package]] name = "rust-proxy" -version = "0.38.1" +version = "0.38.2" dependencies = [ "anyhow", "arc-swap", diff --git a/Cargo.toml b/Cargo.toml index a45de41..c15b5c0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-proxy" -version = "0.38.1" +version = "0.38.2" edition = "2021" rust-version = "1.99.1" description = "RustProxy - independent reverse proxy with local administration" diff --git a/docker-agent/model.go b/docker-agent/model.go index 9977bfa..fbd4c8b 100644 --- a/docker-agent/model.go +++ b/docker-agent/model.go @@ -1,6 +1,6 @@ package main -var version = "0.38.1" // overridden by the package builder using -ldflags -X main.version +var version = "0.38.2" // overridden by the package builder using -ldflags -X main.version type config struct { Listen string diff --git a/docs/CACHE.md b/docs/CACHE.md index a8b9d26..61d088f 100644 --- a/docs/CACHE.md +++ b/docs/CACHE.md @@ -141,6 +141,52 @@ done The initial request can show `RustProxy; fwd=miss`; an eligible repeat should show `RustProxy; hit; ttl=...`. If the origin sends no `Cache-Status`, there is no upstream member to display. If RustProxy diagnostic output is off, any visible `Cache-Status` is from upstream; absence of a RustProxy member is expected. The actual cache outcome should also be checked in server request logs. +## Detailed cache status: STALE and REVALIDATED + +Two kinds of responses come from the cache but are not plain hits: + +- **STALE** — served past its freshness: Varnish grace, `stale-while-revalidate`, `max-stale`, `stale-if-error` while the origin fails, or a request-collapse timeout. +- **REVALIDATED** — the stored object was confirmed by the origin with `304 Not Modified`. + +Where they show: + +| Place | Value | +|---|---| +| `Server-Timing` cache metric | always `STALE` / `REVALIDATED` | +| access log `cache` field, log filter and `rust-proxy logs` | always `STALE` / `REVALIDATED` (before 0.38.2: `HIT`); `cache_reason` gives the exact cause | +| `X-Cache` | `HIT` by default; `STALE` / `REVALIDATED` with **X-Cache shows STALE and REVALIDATED instead of HIT** (`cache.expose_detailed_status`, also per vhost) | +| Cache dashboard | counted as HIT for the hit ratio; the request line adds `· N STALE · N REVALIDATED` (also `stale` and `revalidated` per domain in `/api/cache`) | + +A growing STALE count while the origin is down means RustProxy is answering from cache instead of returning errors. `Only on HIT` treats STALE and REVALIDATED as hits. `X-Cache` stays `HIT` by default because monitoring scripts often match on it. + +## Server-Timing + +With **Expose Server-Timing diagnostics** (`timing_headers: true` on the vhost) RustProxy adds one `Server-Timing` field. Browsers show it in the developer tools (Network → Timing) and RUM tools read it through `PerformanceServerTiming`. + +```http +Server-Timing: app;dur=7 +Server-Timing: proxy;dur=2.31, upstream;dur=1.94, proxy-cache;desc="MISS" +``` + +| Metric | Meaning | +|---|---| +| `proxy;dur` | Total time in RustProxy until the response headers, in milliseconds. | +| `upstream;dur` | Time from sending the request to the backend until its response headers. Absent when the backend was not contacted. | +| `proxy-cache;desc` | `HIT`, `MISS`, `BYPASS`, `STALE` or `REVALIDATED` (see above). Absent when no cache decision was made. | + +**Metric names** (`timing_header_names`, panel: **Server-Timing metric names**): + +| Value | Names | When | +|---|---|---| +| `standard` (default) | `proxy`, `upstream`, `proxy-cache` | RustProxy as a reverse proxy or load balancer in front of the application. The names do not collide with a CDN in front of RustProxy (Cloudflare, Akamai, Fastly add their own `edge`, `origin`, `cdn-cache`, where *origin* means RustProxy) nor with an application's own `cache` metric. | +| `cdn` | `edge`, `origin`, `cdn-cache` | RustProxy is the outermost, CDN-like layer and a RUM tool expects the Akamai mPulse names. Do not use with a CDN in front of RustProxy. | +| `legacy` | `proxy`, `origin`, `cache` | Names used before 0.38.2, for existing dashboards. | + +- On a MISS or BYPASS the origin's own `Server-Timing` metrics are kept and RustProxy's field is appended after them. With several RustProxy hops (edge → front → application) every hop appends its own field, so the inner hop's cache result stays visible. +- On a response served from the cache (`HIT`, `STALE`, `REVALIDATED`) the stored `Server-Timing` of the origin is removed, because it describes the request that filled the cache, not this one. This also applies when `timing_headers` is off. +- Scripts on the same origin can always read `Server-Timing`. For scripts on another origin (a RUM collector, an assets domain) list those origins in **Timing-Allow-Origin** (`timing_allow_origin: ["https://app.example.com"]`, or `["*"]`); the header is only sent together with Server-Timing. +- Turn Server-Timing off on public production sites if response timings should not be exposed. + ## Advanced behavior - **Budget limits:** HOT RAM capacity, object count/size, transient fill memory and optional COLD byte/object limits. Configure based on real workload and monitor disk/RSS. diff --git a/docs/HEADLESS.md b/docs/HEADLESS.md index 5593e3d..5572a3c 100644 --- a/docs/HEADLESS.md +++ b/docs/HEADLESS.md @@ -196,7 +196,7 @@ In a container, mount the file read-only (RustProxy never writes it) and keep `/ `GET /healthz` on `--health-listen` answers `200` while every vhost with backends has at least one healthy backend and `503` otherwise: ```json -{"status":"ok","mode":"headless","version":"0.38.1","revision":4,"uptime_seconds":120, +{"status":"ok","mode":"headless","version":"0.38.2","revision":4,"uptime_seconds":120, "last_reload":{"ok":true,"at_unix":1794743660,"error":null}, "vhosts_without_healthy_backends":[], "pools":[{"vhost":"app","healthy":3,"backends":3}]} diff --git a/integrations/routeros-oci-build/README.md b/integrations/routeros-oci-build/README.md index 2f5f34e..24b7886 100644 --- a/integrations/routeros-oci-build/README.md +++ b/integrations/routeros-oci-build/README.md @@ -77,10 +77,10 @@ ENV_FILE=integrations/routeros-oci-build/.env \ bash integrations/routeros-oci-build/build-routeros-oci.sh push ``` -For example, with RustProxy version `0.38.1` and the defaults this publishes: +For example, with RustProxy version `0.38.2` and the defaults this publishes: ```text -oci.example.net/network/rustproxy:0.38.1 +oci.example.net/network/rustproxy:0.38.2 oci.example.net/network/rustproxy:latest oci.example.net/network/rustproxy:routeros ``` diff --git a/langs/en_US.json b/langs/en_US.json index 4c9a9e6..fbebe31 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -980,6 +980,11 @@ "vhHttp3Enabled": "Enable HTTP/3 for this vhost", "vhCloudflareClientIp": "Use verified Cloudflare client IP", "vhTimingHeaders": "Expose Server-Timing diagnostics", + "vhTimingHeaderNames": "Server-Timing metric names", + "vhTimingHeaderNamesStandard": "Reverse proxy (proxy, upstream, proxy-cache)", + "vhTimingHeaderNamesCdn": "CDN edge (edge, origin, cdn-cache)", + "vhTimingHeaderNamesLegacy": "Before 0.38.2 (proxy, origin, cache)", + "vhTimingAllowOrigin": "Timing-Allow-Origin (origins that may read the timings, or *)", "vhRateEnabled": "Enable per-client IP rate limit", "vhRateRequests": "Requests per window", "vhRateWindow": "Window (seconds)", @@ -1525,7 +1530,7 @@ "vhBackendDiagnostics": "Backend diagnostics", "vhBackendHeader": "Expose selected backend (X-RustProxy-Backend)", "vhBackendTimingHeader": "Expose backend response time (X-RustProxy-Backend-Time)", - "vhBackendDiagnosticsHelp": "Opt-in response headers. Backend time measures origin request-to-response-headers latency; responses served without contacting an origin do not report a backend.", + "vhBackendDiagnosticsHelp": "Opt-in response headers. Server-Timing is appended to the origin's own metrics; cached responses replace it. Backend time measures origin request-to-response-headers latency; responses served without contacting an origin do not report a backend.", "authModeHelp": "Select an identity provider and a supported integration method. Forward Auth checks sessions via the provider; OIDC uses central login with a callback on the protected application. Existing Vhost integrations remain supported.", "taAdvanced": "Advanced Tinyauth settings", "notfound": "404 hosts", @@ -2603,6 +2608,7 @@ "backendHealthOverride": "Custom health check for this backend", "backendHealthOverridesHelp": "When unchecked, inherit the vhost health policy. Disabling monitoring keeps the backend available for explicitly pinned locations, without active probes or passive ejection. Use a custom check for an individual backend.", "cacheOnlyHits": "Show RustProxy cache diagnostics only on HIT (retain origin headers)", + "cacheDetailedStatus": "X-Cache shows STALE and REVALIDATED instead of HIT", "phpHintEnabled": "Run configured PHP file extensions through an already-running PHP-FPM pool. RustProxy does not start PHP; non-PHP files remain static.", "phpHintPathInfo": "Split /static.php/skins/file.css into SCRIPT_FILENAME=static.php and PATH_INFO=/skins/file.css. Useful for Roundcube; usually unnecessary for WordPress. Off by default.", "phpHintPassAuthorization": "Pass the incoming Authorization header as HTTP_AUTHORIZATION to PHP (API/Bearer/Basic authentication). Disable if not needed.", diff --git a/langs/pl_pl.json b/langs/pl_pl.json index 4704603..9366f20 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -980,6 +980,11 @@ "vhHttp3Enabled": "Włącz HTTP/3 dla tego vhosta", "vhCloudflareClientIp": "Używaj zweryfikowanego IP klienta z Cloudflare", "vhTimingHeaders": "Udostępniaj diagnostykę Server-Timing", + "vhTimingHeaderNames": "Nazwy metryk Server-Timing", + "vhTimingHeaderNamesStandard": "Reverse proxy (proxy, upstream, proxy-cache)", + "vhTimingHeaderNamesCdn": "Brzeg CDN (edge, origin, cdn-cache)", + "vhTimingHeaderNamesLegacy": "Sprzed 0.38.2 (proxy, origin, cache)", + "vhTimingAllowOrigin": "Timing-Allow-Origin (originy, które mogą czytać czasy, albo *)", "vhRateEnabled": "Włącz limit żądań per IP klienta", "vhRateRequests": "Żądania na okno", "vhRateWindow": "Okno (sekundy)", @@ -1525,7 +1530,7 @@ "vhBackendDiagnostics": "Diagnostyka backendu", "vhBackendHeader": "Udostępniaj wybrany backend (X-RustProxy-Backend)", "vhBackendTimingHeader": "Udostępniaj czas odpowiedzi backendu (X-RustProxy-Backend-Time)", - "vhBackendDiagnosticsHelp": "Opcjonalne nagłówki odpowiedzi. Czas backendu oznacza czas od wysłania żądania do otrzymania nagłówków odpowiedzi; odpowiedzi obsłużone bez kontaktu z originem nie raportują backendu.", + "vhBackendDiagnosticsHelp": "Opcjonalne nagłówki odpowiedzi. Server-Timing jest dopisywany do metryk originu; odpowiedzi z cache zastępują zapisane metryki. Czas backendu oznacza czas od wysłania żądania do otrzymania nagłówków odpowiedzi; odpowiedzi obsłużone bez kontaktu z originem nie raportują backendu.", "authModeHelp": "Wybierz dostawcę tożsamości i obsługiwaną metodę integracji. Forward Auth sprawdza sesję u dostawcy, a OIDC zapewnia logowanie centralne z callbackiem na domenie chronionej aplikacji. Stare konfiguracje Vhostów pozostają obsługiwane.", "taAdvanced": "Zaawansowane ustawienia Tinyauth", "notfound": "Hosty 404", @@ -2603,6 +2608,7 @@ "backendHealthOverride": "Osobny health check dla tego backendu", "backendHealthOverridesHelp": "Bez nadpisania backend dziedziczy ustawienia vhosta. Wylaczenie monitorowania nie blokuje lokalizacji przypisanych do backendu, ale wylacza probe aktywna i pasywne wykluczanie.", "cacheOnlyHits": "Pokazuj naglowki RustProxy tylko dla HIT (zachowaj naglowki backendu)", + "cacheDetailedStatus": "X-Cache pokazuje STALE i REVALIDATED zamiast HIT", "phpHintEnabled": "Uruchamia pliki o wskazanych rozszerzeniach przez już działającą pulę PHP-FPM. RustProxy nie uruchamia PHP; inne pliki nadal są statyczne.", "phpHintPathInfo": "Rozdziela /static.php/skins/file.css na SCRIPT_FILENAME=static.php i PATH_INFO=/skins/file.css. Potrzebne np. w Roundcube; zwykle zbędne w WordPressie. Domyślnie wyłączone.", "phpHintPassAuthorization": "Przekazuje nagłówek Authorization do PHP jako HTTP_AUTHORIZATION (np. API/Bearer/Basic). Wyłącz, gdy aplikacja go nie używa.", diff --git a/src/admin/logging_api.rs b/src/admin/logging_api.rs index 049e41f..8d30788 100644 --- a/src/admin/logging_api.rs +++ b/src/admin/logging_api.rs @@ -27,7 +27,7 @@ async fn logs( || filter .cache .as_ref() - .is_some_and(|v| !matches!(v.as_str(), "HIT" | "MISS" | "BYPASS" | "-")) + .is_some_and(|v| !matches!(v.as_str(), "HIT" | "STALE" | "REVALIDATED" | "MISS" | "BYPASS" | "-")) { return Err(ApiError( StatusCode::BAD_REQUEST, diff --git a/src/admin/openapi.json b/src/admin/openapi.json index 349af5d..515484a 100644 --- a/src/admin/openapi.json +++ b/src/admin/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.0.3", "info": { "title": "RustProxy Administration API", - "version": "0.38.1", + "version": "0.38.2", "description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only." }, "servers": [ @@ -756,6 +756,12 @@ "default": null, "description": "If true, only emit cache diagnostic headers for actual HIT responses, never MISS/BYPASS. null inherits global expose_only_hits. Via is controlled independently." }, + "expose_detailed_status": { + "type": "boolean", + "nullable": true, + "default": null, + "description": "If true, X-Cache reports STALE or REVALIDATED instead of HIT for such responses. null inherits global expose_detailed_status." + }, "rules": { "type": "array", "maxItems": 128, @@ -852,7 +858,19 @@ "timing_headers": { "type": "boolean", "default": false, - "description": "Expose Server-Timing diagnostics for this vhost." + "description": "Append Server-Timing diagnostics for this vhost to the origin's own Server-Timing metrics. Responses served from the cache drop the stored origin metrics." + }, + "timing_header_names": { + "type": "string", + "enum": ["standard", "cdn", "legacy"], + "default": "standard", + "description": "Metric names in Server-Timing. standard (reverse proxy): proxy;dur, upstream;dur, proxy-cache;desc. cdn (RustProxy is the outermost CDN-like edge): edge;dur, origin;dur, cdn-cache;desc. legacy (before 0.38.2): proxy;dur, origin;dur, cache;desc. The cache value is HIT, MISS, BYPASS, STALE or REVALIDATED." + }, + "timing_allow_origin": { + "type": "array", + "items": { "type": "string" }, + "maxItems": 16, + "description": "Timing-Allow-Origin sent with Server-Timing: origins such as https://app.example.com that may read the timings from scripts, or a single \"*\". Empty sends no header (same-origin scripts can always read them)." }, "backend_header": { "type": "boolean", @@ -2461,6 +2479,11 @@ "default": false, "description": "Suppress RustProxy cache diagnostic headers on MISS/BYPASS. Cache HIT diagnostics remain governed by expose_* flags. The independently configured Via header is unaffected." }, + "expose_detailed_status": { + "type": "boolean", + "default": false, + "description": "X-Cache reports STALE (served past freshness: grace, stale-while-revalidate, stale-if-error, collapse timeout) or REVALIDATED (confirmed by the origin with 304) instead of HIT. These still count as HIT for expose_only_hits and the hit ratio." + }, "http_invalidation_allowed_cidrs": { "type": "array", "description": "Optional IP/CIDR allowlist for HTTP BAN and PURGE on matched public vhosts. Empty disables all HTTP invalidation. Max 32 entries; /0 networks forbidden. Trusted reverse proxies must provide an authenticated forwarding chain.", @@ -11361,6 +11384,8 @@ "type": "string", "enum": [ "HIT", + "STALE", + "REVALIDATED", "MISS", "BYPASS", "-" diff --git a/src/admin/web/app/settings.js b/src/admin/web/app/settings.js index 128e321..4d1c029 100644 --- a/src/admin/web/app/settings.js +++ b/src/admin/web/app/settings.js @@ -37,7 +37,7 @@ function renderSettings() { $("cache-query").checked = !!c.bypass_query; $("cache-prefixes").value = (c.bypass_prefixes || []).join("\n"); $("cache-http-invalidation-cidrs").value = (c.http_invalidation_allowed_cidrs || []).join("\n"); $("cache-static-cookie").checked = c.static_ignore_cookies !== false; $("cache-static-extensions").value = (c.static_extensions || []).join("\n"); - $("cache-status-header").checked = !!c.expose_status; $("cache-hits-header").checked = !!c.expose_hits; $("cache-rfc-header").checked = !!c.expose_cache_status; $("cache-resident-age-header").checked = !!c.expose_resident_age; $("cache-only-hits").checked = !!c.expose_only_hits; + $("cache-status-header").checked = !!c.expose_status; $("cache-hits-header").checked = !!c.expose_hits; $("cache-rfc-header").checked = !!c.expose_cache_status; $("cache-resident-age-header").checked = !!c.expose_resident_age; $("cache-only-hits").checked = !!c.expose_only_hits; $("cache-detailed-status").checked = !!c.expose_detailed_status; const viaHeader = c.via_header === undefined ? "RustProxy" : c.via_header; $("cache-via-enabled").checked = viaHeader !== null; $("cache-via-value").value = viaHeader || "RustProxy"; syncCacheVia(); setCacheMemoryPresetSelection(["conservative", "recommended", "performance"].includes(c.memory_preset) ? c.memory_preset : null); @@ -376,7 +376,7 @@ bindSettingsForm("response-form", next => { next.compression = { min_bytes: Number($("compress-min").value) }; for (const name of ["gzip", "br", "zstd", "deflate"]) next.compression[name] = $(`compress-${name}`).checked; }, "response", next => ({ server_header: next.server_header, diagnostic_headers: next.diagnostic_headers, compression: next.compression })); bindSettingsForm("cache-form", next => { - next.cache = { ...(next.cache || {}), enabled: $("cache-enabled").checked, varnish_compatible: $("cache-varnish-compatible").checked, varnish_grace_seconds: Number($("cache-varnish-grace").value), memory_preset: selectedCacheMemoryPreset, max_bytes: Math.round(Number($("cache-memory").value) * 1048576), transient_max_bytes: Math.round(Number($("cache-transient-memory").value) * 1048576), max_object_bytes: Number($("cache-object").value) * 1024, max_entries: Number($("cache-entries").value), hot_eviction_max_objects: Number($("cache-eviction-limit").value), hot_auto_trim_enabled: $("cache-auto-trim-enabled").checked, hot_auto_trim_after_seconds: Number($("cache-auto-trim-after").value), hot_auto_trim_target_percent: Number($("cache-auto-trim-target").value), cold_enabled: $("cache-cold-enabled").checked, cold_preset: selectedCacheColdPreset, cold_path: $("cache-cold-path").value.trim(), cold_max_bytes: Math.round(Number($("cache-cold-bytes").value) * 1048576), cold_max_entries: Number($("cache-cold-entries").value), cold_queue_max_bytes: Math.round(Number($("cache-cold-queue-bytes").value) * 1048576), cold_gc_interval_seconds: Number($("cache-cold-gc-interval").value), cold_gc_max_delete: Number($("cache-cold-gc-max-delete").value), cold_after_seconds: Number($("cache-cold-after").value), cold_max_hot_seconds: Number($("cache-cold-max-hot").value), cold_on_idle: $("cache-cold-on-idle").checked, cold_on_age: $("cache-cold-on-age").checked, cold_on_lru: $("cache-cold-on-lru").checked, cold_on_shutdown: $("cache-cold-on-shutdown").checked, max_ttl_seconds: Number($("cache-ttl").value), default_ttl_seconds: Number($("cache-default-ttl").value), collapse_enabled: $("cache-collapse-enabled").checked, collapse_wait_timeout_ms: Number($("cache-collapse-timeout").value), collapse_timeout_fallback: $("cache-collapse-fallback").value, stale_if_error_timeout: $("cache-sie-timeout").checked, stale_if_error_connection: $("cache-sie-connection").checked, stale_if_error_dns: $("cache-sie-dns").checked, stale_if_error_tls: $("cache-sie-tls").checked, stale_if_error_statuses: $("cache-sie-statuses").value.split(/[\s,]+/).filter(Boolean).map(Number), proactive_refresh_enabled: $("cache-proactive-enabled").checked, proactive_refresh_before_expiry_seconds: Number($("cache-proactive-before").value), proactive_refresh_percent: Number($("cache-proactive-percent").value), proactive_refresh_max_inflight: Number($("cache-proactive-inflight").value), bypass_query: $("cache-query").checked, bypass_prefixes: $("cache-prefixes").value.split(/\r?\n/).map(v => v.trim()).filter(Boolean), http_invalidation_allowed_cidrs: $("cache-http-invalidation-cidrs").value.split(/[\n,]+/).map(v => v.trim()).filter(Boolean), static_ignore_cookies: $("cache-static-cookie").checked, static_extensions: $("cache-static-extensions").value.split(/[\n,]+/).map(v => v.trim().replace(/^\./, "").toLowerCase()).filter(Boolean), expose_status: $("cache-status-header").checked, expose_hits: $("cache-hits-header").checked, expose_cache_status: $("cache-rfc-header").checked, expose_resident_age: $("cache-resident-age-header").checked, expose_only_hits: $("cache-only-hits").checked, via_header: $("cache-via-enabled").checked ? $("cache-via-value").value.trim() : null, rules: cacheRulesEditor ? cacheRulesEditor.read() : (next.cache?.rules || []) }; + next.cache = { ...(next.cache || {}), enabled: $("cache-enabled").checked, varnish_compatible: $("cache-varnish-compatible").checked, varnish_grace_seconds: Number($("cache-varnish-grace").value), memory_preset: selectedCacheMemoryPreset, max_bytes: Math.round(Number($("cache-memory").value) * 1048576), transient_max_bytes: Math.round(Number($("cache-transient-memory").value) * 1048576), max_object_bytes: Number($("cache-object").value) * 1024, max_entries: Number($("cache-entries").value), hot_eviction_max_objects: Number($("cache-eviction-limit").value), hot_auto_trim_enabled: $("cache-auto-trim-enabled").checked, hot_auto_trim_after_seconds: Number($("cache-auto-trim-after").value), hot_auto_trim_target_percent: Number($("cache-auto-trim-target").value), cold_enabled: $("cache-cold-enabled").checked, cold_preset: selectedCacheColdPreset, cold_path: $("cache-cold-path").value.trim(), cold_max_bytes: Math.round(Number($("cache-cold-bytes").value) * 1048576), cold_max_entries: Number($("cache-cold-entries").value), cold_queue_max_bytes: Math.round(Number($("cache-cold-queue-bytes").value) * 1048576), cold_gc_interval_seconds: Number($("cache-cold-gc-interval").value), cold_gc_max_delete: Number($("cache-cold-gc-max-delete").value), cold_after_seconds: Number($("cache-cold-after").value), cold_max_hot_seconds: Number($("cache-cold-max-hot").value), cold_on_idle: $("cache-cold-on-idle").checked, cold_on_age: $("cache-cold-on-age").checked, cold_on_lru: $("cache-cold-on-lru").checked, cold_on_shutdown: $("cache-cold-on-shutdown").checked, max_ttl_seconds: Number($("cache-ttl").value), default_ttl_seconds: Number($("cache-default-ttl").value), collapse_enabled: $("cache-collapse-enabled").checked, collapse_wait_timeout_ms: Number($("cache-collapse-timeout").value), collapse_timeout_fallback: $("cache-collapse-fallback").value, stale_if_error_timeout: $("cache-sie-timeout").checked, stale_if_error_connection: $("cache-sie-connection").checked, stale_if_error_dns: $("cache-sie-dns").checked, stale_if_error_tls: $("cache-sie-tls").checked, stale_if_error_statuses: $("cache-sie-statuses").value.split(/[\s,]+/).filter(Boolean).map(Number), proactive_refresh_enabled: $("cache-proactive-enabled").checked, proactive_refresh_before_expiry_seconds: Number($("cache-proactive-before").value), proactive_refresh_percent: Number($("cache-proactive-percent").value), proactive_refresh_max_inflight: Number($("cache-proactive-inflight").value), bypass_query: $("cache-query").checked, bypass_prefixes: $("cache-prefixes").value.split(/\r?\n/).map(v => v.trim()).filter(Boolean), http_invalidation_allowed_cidrs: $("cache-http-invalidation-cidrs").value.split(/[\n,]+/).map(v => v.trim()).filter(Boolean), static_ignore_cookies: $("cache-static-cookie").checked, static_extensions: $("cache-static-extensions").value.split(/[\n,]+/).map(v => v.trim().replace(/^\./, "").toLowerCase()).filter(Boolean), expose_status: $("cache-status-header").checked, expose_hits: $("cache-hits-header").checked, expose_cache_status: $("cache-rfc-header").checked, expose_resident_age: $("cache-resident-age-header").checked, expose_only_hits: $("cache-only-hits").checked, expose_detailed_status: $("cache-detailed-status").checked, via_header: $("cache-via-enabled").checked ? $("cache-via-value").value.trim() : null, rules: cacheRulesEditor ? cacheRulesEditor.read() : (next.cache?.rules || []) }; }, "cache"); bindSettingsForm("transform-form", next => { next.transform = { diff --git a/src/admin/web/cache-panel.js b/src/admin/web/cache-panel.js index 8bc2beb..f7d8f56 100644 --- a/src/admin/web/cache-panel.js +++ b/src/admin/web/cache-panel.js @@ -165,7 +165,8 @@ $("cp-cold-bytes").textContent = fmtBytes(coldBytes); $("cp-cold-disk-detail").textContent = `${t("cacheLimitShort")}: ${fmtBytes(coldLimit)} · ${coldPercent.toFixed(1)}%`; $("cp-ratio").textContent = `${fmt((all ? (m.hit_ratio || 0) : (hits + misses ? hits / (hits + misses) : 0)) * 100, 1)}%`; - $("cp-requests").textContent = `${number(all ? m.hits : hits)} HIT / ${number(all ? m.misses : misses)} MISS`; + const staleHits = total("stale"), revalidatedHits = total("revalidated"); + $("cp-requests").textContent = `${number(all ? m.hits : hits)} HIT / ${number(all ? m.misses : misses)} MISS${staleHits ? ` · ${number(staleHits)} STALE` : ""}${revalidatedHits ? ` · ${number(revalidatedHits)} REVALIDATED` : ""}`; const bypasses = all ? (Number(m.bypasses) || 0) : total("bypasses"); $("cp-bypass").textContent = number(bypasses); renderLiveChart({ hits: all ? (Number(m.hits) || 0) : hits, misses: all ? (Number(m.misses) || 0) : misses, bypasses }); diff --git a/src/admin/web/css/30-overview.css b/src/admin/web/css/30-overview.css index 3fed522..cd17fcf 100644 --- a/src/admin/web/css/30-overview.css +++ b/src/admin/web/css/30-overview.css @@ -49,6 +49,10 @@ html[data-theme=cream] :is(.card, .stat, dialog) { margin: 4px 0; } +.status-stale { + color: var(--accent); +} + .status-good, .stat:first-child small, .acl-policy-preview-head .is-allow, diff --git a/src/admin/web/index.html b/src/admin/web/index.html index e3e703a..8f9e00c 100644 --- a/src/admin/web/index.html +++ b/src/admin/web/index.html @@ -3008,6 +3008,9 @@ +
@@ -4394,6 +4397,8 @@ id="log-outcome"> + + diff --git a/src/admin/web/management.js b/src/admin/web/management.js index 3acfdbd..13a4067 100644 --- a/src/admin/web/management.js +++ b/src/admin/web/management.js @@ -181,7 +181,8 @@ if (!visibleColumns.has(column.id)) continue; const value = column.value(e), cell = el("td", String(value)); cell.title = String(value); if (column.id === "status") cell.className = e.status < 400 ? "status-good" : "status-error"; - if (column.id === "cache" && e.cache === "HIT") cell.className = "status-good"; + if (column.id === "cache" && ["HIT", "REVALIDATED"].includes(e.cache)) cell.className = "status-good"; + if (column.id === "cache" && e.cache === "STALE") cell.className = "status-stale"; row.append(cell); } return row; diff --git a/src/admin/web/vhosts/core.js b/src/admin/web/vhosts/core.js index fea114d..943fe75 100644 --- a/src/admin/web/vhosts/core.js +++ b/src/admin/web/vhosts/core.js @@ -51,7 +51,7 @@ const fillWebServices = (select, chosen = "") => { }; const allowDiscard = async () => { if (!dirty) return true; if (!(await appConfirm(t("vhUnsaved"), { danger: true, confirmLabel: t("discardAction") }))) return false; dirty = false; return true; }; const defaults = () => ({ - id: "", enabled: true, force_ssl: false, www_redirect: false, www_redirect_target: null, forward_client_ip: true, websockets: false, websocket_legacy_support: false, websocket_rfc8441: false, websocket_rfc9220: false, http2_enabled: true, http3_enabled: true, cloudflare_client_ip: false, timing_headers: false, backend_header: false, backend_timing_header: false, + id: "", enabled: true, force_ssl: false, www_redirect: false, www_redirect_target: null, forward_client_ip: true, websockets: false, websocket_legacy_support: false, websocket_rfc8441: false, websocket_rfc9220: false, http2_enabled: true, http3_enabled: true, cloudflare_client_ip: false, timing_headers: false, timing_header_names: "standard", timing_allow_origin: [], backend_header: false, backend_timing_header: false, frontend: { hosts: [], listener_ids: [] }, source: { type: "reverse_proxy" }, backends: [{ id: "origin-1", url: "", weight: 1, enabled: true, pool_eligible: true, allow_private: true, accept_local_listener_risk: false, preserve_host: true, protocol: "http1", tls_verify: false }], @@ -60,7 +60,7 @@ const defaults = () => ({ function activateTab(name) { document.querySelectorAll("#vhost-tabs button").forEach(b => { const active = b.dataset.tab === name; b.classList.toggle("active", active); b.setAttribute("aria-pressed", String(active)); b.setAttribute("aria-selected", String(active)); b.tabIndex = active ? 0 : -1; }); container.querySelectorAll(".vh-group").forEach(g => g.hidden = g.dataset.tab !== name); } function initTabs() { const tabs = $("vhost-tabs"); tabs.replaceChildren(); tabs.setAttribute("role", "tablist"); for (const [name, key] of [["details", "vhDetailsTab"], ["backends", "vhBackendPool"], ["health", "vhHealth"], ["locations", "vhLocations"], ["auth", "vhTabAuth"], ["ssl", "vhSsl"], ["cache", "vhCache"], ["compression", "vhCompression"], ["transform", "vhTransform"], ["security", "vhSecurity"], ["pages", "vhPages"], ["advanced", "advanced"]]) { const b = button(key, () => activateTab(name)); b.dataset.tab = name; b.setAttribute("role", "tab"); b.addEventListener("keydown", event => { const buttons = [...tabs.querySelectorAll("button")], index = buttons.indexOf(b); let next; if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % buttons.length; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + buttons.length - 1) % buttons.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = buttons.length - 1; else return; event.preventDefault(); activateTab(buttons[next].dataset.tab); buttons[next].focus(); }); tabs.append(b); } activateTab("details"); } -function collectCache() { const tri = name => str(name) === "" ? null : str(name) === "on", number = (name, mul = 1) => { if (str(name) === "") return null; const value = Number(str(name)) * mul; if (!Number.isSafeInteger(value)) throw new Error(t("vhJsonInvalid")); return value; }; return { enabled: tri("vh-cache-enabled"), max_ttl_seconds: number("vh-cache-ttl"), default_ttl_seconds: number("vh-cache-default"), max_object_bytes: number("vh-cache-object", 1024), bypass_query: tri("vh-cache-query"), static_ignore_cookies: tri("vh-cache-static-cookie"), static_extensions: yes("vh-cache-static-custom") ? lines(str("vh-cache-static-extensions")).map(v => v.replace(/^\./, "").toLowerCase()) : null, expose_status: tri("vh-cache-status"), expose_hits: tri("vh-cache-hits"), expose_cache_status: tri("vh-cache-rfc"), expose_resident_age: tri("vh-cache-resident-age"), expose_only_hits: tri("vh-cache-only-hits"), bypass_prefixes: yes("vh-cache-prefix-custom") ? lines(str("vh-cache-prefixes")) : null, unsafe_force: { enabled: yes("vh-cache-force-enabled"), targets: lines(str("vh-cache-force-targets")) }, rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.read() : [], ignore_global_rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.ignoreGlobal() : false }; } +function collectCache() { const tri = name => str(name) === "" ? null : str(name) === "on", number = (name, mul = 1) => { if (str(name) === "") return null; const value = Number(str(name)) * mul; if (!Number.isSafeInteger(value)) throw new Error(t("vhJsonInvalid")); return value; }; return { enabled: tri("vh-cache-enabled"), max_ttl_seconds: number("vh-cache-ttl"), default_ttl_seconds: number("vh-cache-default"), max_object_bytes: number("vh-cache-object", 1024), bypass_query: tri("vh-cache-query"), static_ignore_cookies: tri("vh-cache-static-cookie"), static_extensions: yes("vh-cache-static-custom") ? lines(str("vh-cache-static-extensions")).map(v => v.replace(/^\./, "").toLowerCase()) : null, expose_status: tri("vh-cache-status"), expose_hits: tri("vh-cache-hits"), expose_cache_status: tri("vh-cache-rfc"), expose_resident_age: tri("vh-cache-resident-age"), expose_only_hits: tri("vh-cache-only-hits"), expose_detailed_status: tri("vh-cache-detailed-status"), bypass_prefixes: yes("vh-cache-prefix-custom") ? lines(str("vh-cache-prefixes")) : null, unsafe_force: { enabled: yes("vh-cache-force-enabled"), targets: lines(str("vh-cache-force-targets")) }, rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.read() : [], ignore_global_rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.ignoreGlobal() : false }; } function collectCompression() { const tri = name => str(name) === "" ? null : str(name) === "on"; return { enabled: tri("vh-compression-enabled"), zstd: tri("vh-compression-zstd"), br: tri("vh-compression-br"), gzip: tri("vh-compression-gzip"), deflate: tri("vh-compression-deflate") }; } function collectTransform() { const tri = name => str(name) === "" ? null : str(name) === "on"; diff --git a/src/admin/web/vhosts/editor.js b/src/admin/web/vhosts/editor.js index 0863f0c..284e3d2 100644 --- a/src/admin/web/vhosts/editor.js +++ b/src/admin/web/vhosts/editor.js @@ -206,6 +206,8 @@ function load(value = defaults(), migrationIds = [], show = true) { (value.backends || []).forEach(m => memberRow(members, m)); g.append(button("vhAddBackend", () => { memberRow(members); changed(); })); g = group("vhBackendDiagnostics"); field(g, "timing-headers", "vhTimingHeaders", value.timing_headers === true, "checkbox"); + field(g, "timing-header-names", "vhTimingHeaderNames", value.timing_header_names || "standard", "select", { values: [["standard", "vhTimingHeaderNamesStandard"], ["cdn", "vhTimingHeaderNamesCdn"], ["legacy", "vhTimingHeaderNamesLegacy"]] }); + field(g, "timing-allow-origin", "vhTimingAllowOrigin", (value.timing_allow_origin || []).join(", "), "text", { maxLength: 2048 }).placeholder = "https://app.example.com"; field(g, "backend-header", "vhBackendHeader", value.backend_header === true, "checkbox"); field(g, "backend-timing-header", "vhBackendTimingHeader", value.backend_timing_header === true, "checkbox"); note(g, "vhBackendDiagnosticsHelp"); @@ -517,7 +519,7 @@ function load(value = defaults(), migrationIds = [], show = true) { const customStatic = field(staticExtensionFields, "vh-cache-static-custom", "vhCacheStaticCustom", cache.static_extensions != null, "checkbox"); const staticExtensions = field(staticExtensionFields, "vh-cache-static-extensions", "vhCacheStaticExtensions", (cache.static_extensions || envelope?.config.cache?.static_extensions || []).join("\n"), "textarea", { rows: 5, maxLength: 2048 }); const syncStatic = () => { staticExtensions.disabled = !customStatic.checked; }; customStatic.addEventListener("change", syncStatic); syncStatic(); note(staticExtensionFields, "vhCacheStaticHelp"); - tri(cacheOptions, "vh-cache-status", "cacheStatusHeader", cache.expose_status); tri(cacheOptions, "vh-cache-hits", "cacheHitsHeader", cache.expose_hits); tri(cacheOptions, "vh-cache-rfc", "cacheRfcHeader", cache.expose_cache_status); tri(cacheOptions, "vh-cache-resident-age", "cacheResidentAge", cache.expose_resident_age); tri(cacheOptions, "vh-cache-only-hits", "cacheOnlyHits", cache.expose_only_hits); + tri(cacheOptions, "vh-cache-status", "cacheStatusHeader", cache.expose_status); tri(cacheOptions, "vh-cache-hits", "cacheHitsHeader", cache.expose_hits); tri(cacheOptions, "vh-cache-rfc", "cacheRfcHeader", cache.expose_cache_status); tri(cacheOptions, "vh-cache-resident-age", "cacheResidentAge", cache.expose_resident_age); tri(cacheOptions, "vh-cache-only-hits", "cacheOnlyHits", cache.expose_only_hits); tri(cacheOptions, "vh-cache-detailed-status", "cacheDetailedStatus", cache.expose_detailed_status); const bypassFields = el("div", undefined, "vh-wide vh-override-fields"); cacheOptions.append(bypassFields); const customCachePrefixes = field(bypassFields, "vh-cache-prefix-custom", "vhCacheCustomPrefixes", cache.bypass_prefixes != null, "checkbox"); const bypassPrefixes = field(bypassFields, "vh-cache-prefixes", "cacheBypassPrefixes", (cache.bypass_prefixes || []).join("\n"), "textarea", { rows: 2, maxLength: 32768 }); @@ -617,7 +619,7 @@ function collect() { } if (yes("content-type-block-enabled") && !lines(str("content-type-block-list")).length) throw new Error(t("vhContentTypeRequired")); return { - id: str("id"), enabled: yes("enabled"), source: mainSourceType === "web_server" ? { type: "web_server", web_service_id: str("source-web-service") } : { type: "reverse_proxy" }, error_fallback: mainFallbackTarget ? { target: mainFallbackTarget, statuses: mainFallbackStatuses.length ? mainFallbackStatuses : [404] } : null, force_ssl: yes("force-ssl"), www_redirect: yes("www-redirect"), www_redirect_target: str("www-redirect-target") || null, forward_client_ip: yes("forward-client-ip"), websockets: yes("websockets"), websocket_legacy_support: yes("websockets") && yes("websocket-legacy-support"), websocket_rfc8441: yes("websockets") && ["h2", "h2h3"].includes(str("websocket-mode")), websocket_rfc9220: yes("websockets") && ["h3", "h2h3"].includes(str("websocket-mode")), http2_enabled: yes("http2-enabled"), http3_enabled: yes("http3-enabled"), cloudflare_client_ip: yes("cloudflare-client-ip"), timing_headers: yes("timing-headers"), backend_header: yes("backend-header"), backend_timing_header: yes("backend-timing-header"), basic_auth: basicEditor.read(), certificate_id: nullable("certificate-id"), allow_certificate_mismatch: yes("allow-certificate-mismatch"), tls_policy: yes("tls-policy-custom") ? { tls12: yes("tls-policy-12"), tls13: yes("tls-policy-13"), cipher_suites: lines(str("tls-policy-ciphers")), post_quantum: yes("tls-policy-pqc") } : null, cache: collectCache(), compression: collectCompression(), transform: collectTransform(), pages: pagesEditor.read(), frontend: { hosts: readHosts(), listener_ids: bindingSelection }, acl_profile_id: null, + id: str("id"), enabled: yes("enabled"), source: mainSourceType === "web_server" ? { type: "web_server", web_service_id: str("source-web-service") } : { type: "reverse_proxy" }, error_fallback: mainFallbackTarget ? { target: mainFallbackTarget, statuses: mainFallbackStatuses.length ? mainFallbackStatuses : [404] } : null, force_ssl: yes("force-ssl"), www_redirect: yes("www-redirect"), www_redirect_target: str("www-redirect-target") || null, forward_client_ip: yes("forward-client-ip"), websockets: yes("websockets"), websocket_legacy_support: yes("websockets") && yes("websocket-legacy-support"), websocket_rfc8441: yes("websockets") && ["h2", "h2h3"].includes(str("websocket-mode")), websocket_rfc9220: yes("websockets") && ["h3", "h2h3"].includes(str("websocket-mode")), http2_enabled: yes("http2-enabled"), http3_enabled: yes("http3-enabled"), cloudflare_client_ip: yes("cloudflare-client-ip"), timing_headers: yes("timing-headers"), timing_header_names: str("timing-header-names") || "standard", timing_allow_origin: str("timing-allow-origin").split(/[\s,]+/).filter(Boolean), backend_header: yes("backend-header"), backend_timing_header: yes("backend-timing-header"), basic_auth: basicEditor.read(), certificate_id: nullable("certificate-id"), allow_certificate_mismatch: yes("allow-certificate-mismatch"), tls_policy: yes("tls-policy-custom") ? { tls12: yes("tls-policy-12"), tls13: yes("tls-policy-13"), cipher_suites: lines(str("tls-policy-ciphers")), post_quantum: yes("tls-policy-pqc") } : null, cache: collectCache(), compression: collectCompression(), transform: collectTransform(), pages: pagesEditor.read(), frontend: { hosts: readHosts(), listener_ids: bindingSelection }, acl_profile_id: null, acl_profile_ids: window.rustProxyAclPicker.read(form.querySelector(".vh-acl-profile-choices")), proxy_timeouts: { connect_timeout_seconds: num("proxy-connect-timeout"), response_header_timeout_seconds: num("proxy-header-timeout"), read_timeout_seconds: num("proxy-read-timeout"), send_timeout_seconds: num("proxy-send-timeout") }, rate_limit: { enabled: yes("rate-enabled"), requests: num("rate-requests"), window_seconds: num("rate-window"), burst: num("rate-burst"), country_access: { mode: str("country-mode"), countries: lines(str("country-list")).map(value => value.toUpperCase()) }, country_limits: countryRatesReader(), user_agent_limits: uaRatesReader() }, diff --git a/src/cache/model/entry.rs b/src/cache/model/entry.rs index d5a3a57..928ad40 100644 --- a/src/cache/model/entry.rs +++ b/src/cache/model/entry.rs @@ -1,3 +1,21 @@ +pub const STALE_REASONS: [&str; 4] = [ + "cache_stale_if_error", + "cache_stale_while_revalidate", + "cache_max_stale", + "cache_collapse_timeout_stale", +]; +pub const REVALIDATED_REASONS: [&str; 2] = ["cache_revalidated", "cache_revalidated_uncached"]; +pub fn detailed_outcome(outcome: &'static str, reason: &str) -> &'static str { + if outcome != "HIT" { + outcome + } else if STALE_REASONS.contains(&reason) { + "STALE" + } else if REVALIDATED_REASONS.contains(&reason) { + "REVALIDATED" + } else { + "HIT" + } +} impl Settings { pub fn validate(&self) -> Result<()> { validate_rules(&self.rules, true)?; @@ -280,11 +298,15 @@ impl Settings { return; } if self.expose_status { + let shown = match reason { + Some(reason) if self.expose_detailed_status => detailed_outcome(outcome, reason), + _ => outcome, + }; insert_cache_diagnostic( headers, "x-cache", "x-upstream-cache", - HeaderValue::from_static(outcome), + HeaderValue::from_static(shown), ); if let Some(reason) = reason { insert_cache_diagnostic( @@ -441,6 +463,7 @@ pub struct Overrides { pub expose_cache_status: Option, pub expose_resident_age: Option, pub expose_only_hits: Option, + pub expose_detailed_status: Option, pub unsafe_force: UnsafeForce, #[serde(skip_serializing_if = "Vec::is_empty")] pub rules: Vec, @@ -496,6 +519,9 @@ impl Overrides { if let Some(value) = self.expose_only_hits { result.expose_only_hits = value; } + if let Some(value) = self.expose_detailed_status { + result.expose_detailed_status = value; + } result.validate()?; let compiled = CompiledRules::compile( vhost_id, @@ -600,6 +626,8 @@ pub struct DomainCounters { pub bypasses: u64, pub stored: u64, pub saved_body_bytes: u64, + pub stale: u64, + pub revalidated: u64, pub reasons: BTreeMap, } #[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq)] diff --git a/src/cache/model/settings.rs b/src/cache/model/settings.rs index acbf1a7..039f1ab 100644 --- a/src/cache/model/settings.rs +++ b/src/cache/model/settings.rs @@ -188,6 +188,7 @@ pub struct Settings { pub expose_cache_status: bool, pub expose_resident_age: bool, pub expose_only_hits: bool, + pub expose_detailed_status: bool, pub via_header: Option, #[serde(skip_serializing_if = "Vec::is_empty")] pub rules: Vec, @@ -256,6 +257,7 @@ impl Default for Settings { expose_cache_status: false, expose_resident_age: false, expose_only_hits: false, + expose_detailed_status: false, via_header: Some("RustProxy".into()), rules: Vec::new(), compiled_rules: None, diff --git a/src/cache/stats.rs b/src/cache/stats.rs index 2ff9c19..604bc52 100644 --- a/src/cache/stats.rs +++ b/src/cache/stats.rs @@ -95,7 +95,14 @@ impl DomainStats { for (label, counter) in self.reasons.load().iter() { reasons.insert((*label).to_owned(), load(counter)); } + let sum = |labels: &[&str]| -> u64 { + labels.iter().filter_map(|label| reasons.get(*label)).sum() + }; + let stale = sum(&STALE_REASONS); + let revalidated = sum(&REVALIDATED_REASONS); DomainCounters { + stale, + revalidated, hits: load(&self.hits), misses: load(&self.misses), bypasses: load(&self.bypasses), diff --git a/src/config/model.rs b/src/config/model.rs index 601d826..147aba0 100644 --- a/src/config/model.rs +++ b/src/config/model.rs @@ -287,6 +287,8 @@ pub struct CompiledFrontend { pub tls_http1: Option>, pub cloudflare_client_ip: bool, pub timing_headers: bool, + pub timing_header_names: crate::vhost::TimingHeaderNames, + pub timing_allow_origin: Option, pub backend_header: bool, pub backend_timing_header: bool, pub rate_limit: crate::rate_limit::Settings, diff --git a/src/config/routing.rs b/src/config/routing.rs index 8e53658..b7553b4 100644 --- a/src/config/routing.rs +++ b/src/config/routing.rs @@ -251,6 +251,8 @@ fn compile_routing( tls_http1: frontend_tls_http1, cloudflare_client_ip: host.cloudflare_client_ip, timing_headers: host.timing_headers, + timing_header_names: host.timing_header_names, + timing_allow_origin: crate::vhost::timing_allow_origin_value(&host.timing_allow_origin)?, backend_header: host.backend_header, backend_timing_header: host.backend_timing_header, rate_limit: host.rate_limit.clone(), diff --git a/src/proxy/body/mod.rs b/src/proxy/body/mod.rs index 298b53c..d50d006 100644 --- a/src/proxy/body/mod.rs +++ b/src/proxy/body/mod.rs @@ -206,6 +206,10 @@ impl Drop for Exchange { let request_bytes = self.request_bytes.load(Ordering::Relaxed); let response_bytes = self.response_bytes.load(Ordering::Relaxed); let duration_ms = duration.as_millis() as u64; + let cache_reason = *self + .cache_reason + .get_mut() + .unwrap_or_else(|e| e.into_inner()); let cache = match self.cache_status.load(Ordering::Relaxed) { 1 => "HIT", 2 => "MISS", @@ -251,10 +255,7 @@ impl Drop for Exchange { sni: None, authority: None, matched_by: None, - cache_reason: self - .cache_reason - .get_mut() - .unwrap_or_else(|e| e.into_inner()), + cache_reason, vhost: self.vhost.take(), route, cache_effective_enabled, @@ -292,7 +293,7 @@ impl Drop for Exchange { country, status, duration_ms, - cache, + cache: crate::cache::detailed_outcome(cache, cache_reason), request_bytes, response_bytes, outcome, diff --git a/src/proxy/cache_helpers.rs b/src/proxy/cache_helpers.rs index 12a8cd8..7c91ecb 100644 --- a/src/proxy/cache_helpers.rs +++ b/src/proxy/cache_helpers.rs @@ -293,31 +293,58 @@ fn finish_headers( !frontend.is_some_and(|frontend| !frontend.http3_enabled), ); } +fn server_timing_cache_desc(status: u16, reason: &str) -> Option<&'static str> { + match status { + 1 => Some(crate::cache::detailed_outcome("HIT", reason)), + 2 => Some("MISS"), + 3 => Some("BYPASS"), + _ => None, + } +} +fn server_timing_value( + names: crate::vhost::TimingHeaderNames, + total: Duration, + origin: Option, + cache: Option<&str>, +) -> String { + let (total_name, origin_name, cache_name) = match names { + crate::vhost::TimingHeaderNames::Standard => ("proxy", "upstream", "proxy-cache"), + crate::vhost::TimingHeaderNames::Cdn => ("edge", "origin", "cdn-cache"), + crate::vhost::TimingHeaderNames::Legacy => ("proxy", "origin", "cache"), + }; + let mut values = vec![format!("{total_name};dur={:.2}", total.as_secs_f64() * 1000.0)]; + if let Some(origin) = origin { + values.push(format!("{origin_name};dur={:.2}", origin.as_secs_f64() * 1000.0)); + } + if let Some(cache) = cache { + values.push(format!("{cache_name};desc=\"{cache}\"")); + } + values.join(", ") +} fn apply_timing_headers( response: &mut Response, frontend: Option<&crate::config::CompiledFrontend>, exchange: &Exchange, ) { - if !frontend.is_some_and(|frontend| frontend.timing_headers) { + let status = exchange.cache_status.load(Ordering::Relaxed); + if status == 1 { + response.headers_mut().remove("server-timing"); + } + let Some(frontend) = frontend.filter(|frontend| frontend.timing_headers) else { return; - } - let total_ms = exchange.started.elapsed().as_secs_f64() * 1000.0; - let mut values = vec![format!("proxy;dur={total_ms:.2}")]; - if let Some(origin) = response.extensions().get::() { - values.push(format!("origin;dur={:.2}", origin.0.as_secs_f64() * 1000.0)); - } - let cache = match exchange.cache_status.load(Ordering::Relaxed) { - 1 => Some("HIT"), - 2 => Some("MISS"), - 3 => Some("BYPASS"), - _ => None, }; - if let Some(cache) = cache { - values.push(format!("cache;desc=\"{cache}\"")); + let reason = *exchange.cache_reason.lock().unwrap_or_else(|e| e.into_inner()); + let value = server_timing_value( + frontend.timing_header_names, + exchange.started.elapsed(), + response.extensions().get::().map(|origin| origin.0), + server_timing_cache_desc(status, reason), + ); + if let Ok(value) = HeaderValue::from_str(&value) { + response.headers_mut().append("server-timing", value); } - response.headers_mut().remove("server-timing"); - if let Ok(value) = HeaderValue::from_str(&values.join(", ")) { - response.headers_mut().insert("server-timing", value); + if let Some(value) = &frontend.timing_allow_origin { + response.headers_mut().insert("timing-allow-origin", value.clone()); } } diff --git a/src/proxy/forward/cache_fast_path_tests.rs b/src/proxy/forward/cache_fast_path_tests.rs index 4486e52..612e4e9 100644 --- a/src/proxy/forward/cache_fast_path_tests.rs +++ b/src/proxy/forward/cache_fast_path_tests.rs @@ -526,6 +526,11 @@ mod cache_fast_path_tests { if parts.uri.path() == "/stale-no-validator" { response.headers_mut().remove("etag"); } + if matches!(parts.uri.path(), "/server-timing" | "/stale-then-503") { + response + .headers_mut() + .insert("server-timing", HeaderValue::from_static("app;dur=7")); + } if parts.uri.path() == "/stale-then-503" && request_number > 1 { *response.status_mut() = StatusCode::SERVICE_UNAVAILABLE; *response.body_mut() = Body::from("origin failed"); @@ -776,6 +781,125 @@ mod cache_fast_path_tests { fixture.stop().await; } + fn server_timing(headers: &HeaderMap) -> Vec { + headers + .get_all("server-timing") + .iter() + .map(|value| value.to_str().unwrap().to_owned()) + .collect() + } + + #[tokio::test] + async fn server_timing_appends_to_origin_metrics_and_replaces_them_on_hits() { + let origin = origin().await; + let mut config = config_for(origin.addr, true); + config.vhosts[0].timing_headers = true; + let fixture = Fixture::new(config).await; + let miss = server_timing(&fixture.get("/server-timing", &[]).await.headers); + assert_eq!(miss.len(), 2, "{miss:?}"); + assert_eq!(miss[0], "app;dur=7"); + assert!(miss[1].starts_with("proxy;dur="), "{miss:?}"); + assert!(miss[1].contains(", upstream;dur="), "{miss:?}"); + assert!(miss[1].ends_with(", proxy-cache;desc=\"MISS\""), "{miss:?}"); + let hit = server_timing(&fixture.get("/server-timing", &[]).await.headers); + assert_eq!(hit.len(), 1, "{hit:?}"); + assert!(hit[0].starts_with("proxy;dur="), "{hit:?}"); + assert!(!hit[0].contains("upstream;dur="), "{hit:?}"); + assert!(hit[0].ends_with(", proxy-cache;desc=\"HIT\""), "{hit:?}"); + fixture + .change(|config| { + config.vhosts[0].timing_header_names = crate::vhost::TimingHeaderNames::Cdn; + config.vhosts[0].timing_allow_origin = vec!["https://rum.example.com".into()]; + }) + .await; + let cdn = fixture.get("/server-timing", &[]).await.headers; + let cdn_timing = server_timing(&cdn); + assert!(cdn_timing[0].starts_with("edge;dur="), "{cdn_timing:?}"); + assert!(cdn_timing[0].ends_with(", cdn-cache;desc=\"HIT\""), "{cdn_timing:?}"); + assert_eq!(cdn["timing-allow-origin"], "https://rum.example.com"); + fixture + .change(|config| { + config.vhosts[0].timing_header_names = crate::vhost::TimingHeaderNames::Legacy + }) + .await; + let legacy = server_timing(&fixture.get("/server-timing", &[]).await.headers); + assert_eq!(legacy.len(), 1, "{legacy:?}"); + assert!(legacy[0].starts_with("proxy;dur="), "{legacy:?}"); + assert!(legacy[0].ends_with(", cache;desc=\"HIT\""), "{legacy:?}"); + fixture.stop().await; + } + + #[tokio::test] + async fn server_timing_reports_stale_and_drops_cached_metrics_without_timing_headers() { + let origin = origin().await; + let mut config = config_for(origin.addr, true); + config.vhosts[0].timing_headers = true; + let fixture = Fixture::new(config).await; + fixture.get("/stale-then-503", &[]).await; + let stale = server_timing(&fixture.get("/stale-then-503", &[]).await.headers); + assert_eq!(stale.len(), 1, "{stale:?}"); + assert!(stale[0].ends_with(", proxy-cache;desc=\"STALE\""), "{stale:?}"); + fixture.get("/cache-headers-revalidate", &[]).await; + let revalidated = + server_timing(&fixture.get("/cache-headers-revalidate", &[]).await.headers); + assert_eq!(revalidated.len(), 1, "{revalidated:?}"); + assert!(revalidated[0].contains(", upstream;dur="), "{revalidated:?}"); + assert!( + revalidated[0].ends_with(", proxy-cache;desc=\"REVALIDATED\""), + "{revalidated:?}" + ); + fixture.change(|config| config.vhosts[0].timing_headers = false).await; + let quiet = fixture.get("/server-timing", &[]).await; + assert_eq!(server_timing(&quiet.headers), vec!["app;dur=7".to_owned()]); + let cached = fixture.get("/server-timing", &[]).await; + assert_eq!(cached.headers["x-cache"], "HIT"); + assert!(server_timing(&cached.headers).is_empty()); + fixture.stop().await; + } + + #[tokio::test] + async fn detailed_cache_status_reaches_x_cache_logs_and_domain_counters() { + let origin = origin().await; + let mut config = config_for(origin.addr, true); + config.cache.expose_detailed_status = true; + let fixture = Fixture::new(config).await; + assert_eq!(fixture.get("/stale-then-503", &[]).await.headers["x-cache"], "MISS"); + assert_eq!(fixture.get("/stale-then-503", &[]).await.headers["x-cache"], "STALE"); + fixture.get("/cache-headers-revalidate", &[]).await; + let revalidated = fixture.get("/cache-headers-revalidate", &[]).await; + assert_eq!(revalidated.headers["x-cache"], "REVALIDATED"); + assert_eq!(fixture.get("/server-timing", &[]).await.headers["x-cache"], "MISS"); + assert_eq!(fixture.get("/server-timing", &[]).await.headers["x-cache"], "HIT"); + let mut logged = Vec::new(); + for _ in 0..50 { + logged = fixture + .app + .logs + .recent() + .into_iter() + .filter(|entry| entry.event == "request") + .map(|entry| entry.cache) + .collect(); + if logged.len() >= 6 { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert_eq!(logged, ["HIT", "MISS", "REVALIDATED", "MISS", "STALE", "MISS"]); + let dashboard = fixture.app.cache.dashboard(None, 0, 10); + let stale: u64 = dashboard.domains.iter().map(|row| row.counters.stale).sum(); + let revalidated: u64 = dashboard + .domains + .iter() + .map(|row| row.counters.revalidated) + .sum(); + let hits: u64 = dashboard.domains.iter().map(|row| row.counters.hits).sum(); + assert_eq!((stale, revalidated, hits), (1, 1, 3)); + fixture.change(|config| config.cache.expose_detailed_status = false).await; + assert_eq!(fixture.get("/stale-then-503", &[]).await.headers["x-cache"], "HIT"); + fixture.stop().await; + } + #[tokio::test] async fn rfc9211_stale_origin_200_is_fwd_stale_not_fwd_miss() { let origin = origin().await; diff --git a/src/runtime/types.rs b/src/runtime/types.rs index eb1ebbb..f5435a7 100644 --- a/src/runtime/types.rs +++ b/src/runtime/types.rs @@ -98,6 +98,7 @@ fn cache_revision(config: &config::Config) -> u64 { cache.expose_cache_status = false; cache.expose_resident_age = false; cache.expose_only_hits = false; + cache.expose_detailed_status = false; cache.via_header = None; let mut transform = config.transform.clone(); transform.preset = None; @@ -136,6 +137,8 @@ fn vhost_cache_revision(vhost: &crate::vhost::Vhost) -> u64 { view.www_redirect = false; view.www_redirect_target = None; view.timing_headers = false; + view.timing_header_names = Default::default(); + view.timing_allow_origin.clear(); view.backend_header = false; view.backend_timing_header = false; view.certificate_id = None; @@ -155,6 +158,7 @@ fn vhost_cache_revision(vhost: &crate::vhost::Vhost) -> u64 { view.proxy_timeouts = Default::default(); view.frontend.listener_ids.clear(); view.cache.expose_only_hits = None; + view.cache.expose_detailed_status = None; view.load_balancing = Default::default(); for member in &mut view.backends { member.weight = 1; diff --git a/src/vhost/model.rs b/src/vhost/model.rs index 6f57c07..4598ad5 100644 --- a/src/vhost/model.rs +++ b/src/vhost/model.rs @@ -40,6 +40,14 @@ impl Default for ProxyTimeouts { } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] #[serde(rename_all = "snake_case")] +pub enum TimingHeaderNames { + #[default] + Standard, + Cdn, + Legacy, +} +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(rename_all = "snake_case")] pub enum MethodPolicyMode { #[default] Off, @@ -316,6 +324,10 @@ pub struct Vhost { #[serde(default)] pub timing_headers: bool, #[serde(default)] + pub timing_header_names: TimingHeaderNames, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub timing_allow_origin: Vec, + #[serde(default)] pub backend_header: bool, #[serde(default)] pub backend_timing_header: bool, diff --git a/src/vhost/tests.rs b/src/vhost/tests.rs index eaf4bbc..1060b1d 100644 --- a/src/vhost/tests.rs +++ b/src/vhost/tests.rs @@ -299,3 +299,31 @@ mod websocket_protocol_flags_tests { assert!(r#"{"websocket_rfc9220":true}"#.contains("\"websocket_rfc9220\":true")); } } +mod timing_allow_origin_tests { + use super::*; + fn value(origins: &[&str]) -> Result> { + timing_allow_origin_value(&origins.iter().map(|v| v.to_string()).collect::>()) + } + #[test] + fn origins_and_wildcard_are_accepted() { + assert!(value(&[]).unwrap().is_none()); + assert_eq!(value(&["*"]).unwrap().unwrap(), "*"); + assert_eq!( + value(&["https://app.example.com", "http://localhost:3000"]).unwrap().unwrap(), + "https://app.example.com, http://localhost:3000" + ); + } + #[test] + fn paths_wildcard_mixes_and_other_schemes_are_rejected() { + for bad in [ + &["https://app.example.com/"][..], + &["https://app.example.com/path"], + &["https://user@app.example.com"], + &["ftp://app.example.com"], + &["app.example.com"], + &["*", "https://app.example.com"], + ] { + assert!(value(bad).is_err(), "{bad:?}"); + } + } +} diff --git a/src/vhost/validation.rs b/src/vhost/validation.rs index 7c15118..f9f2c82 100644 --- a/src/vhost/validation.rs +++ b/src/vhost/validation.rs @@ -251,6 +251,7 @@ impl Vhost { if let Some(server) = &self.server_header { server.validate()?; } + timing_allow_origin_value(&self.timing_allow_origin)?; self.basic_auth.compile()?; crate::auth_provider::Selection { choice: self.authentication, @@ -511,3 +512,36 @@ pub fn listener_plan(config: &Config, policy: &ValidationPolicy) -> Result Result> { + if origins.is_empty() { + return Ok(None); + } + ensure!( + origins.len() <= 16, + "Timing-Allow-Origin accepts at most 16 origins" + ); + if origins.iter().any(|origin| origin == "*") { + ensure!( + origins.len() == 1, + "Timing-Allow-Origin \"*\" cannot be combined with other origins" + ); + return Ok(Some(http::HeaderValue::from_static("*"))); + } + for origin in origins { + let parsed = url::Url::parse(origin) + .with_context(|| format!("invalid Timing-Allow-Origin origin {origin:?}"))?; + ensure!( + matches!(parsed.scheme(), "http" | "https") + && parsed.host_str().is_some() + && parsed.username().is_empty() + && parsed.password().is_none() + && parsed.path() == "/" + && parsed.query().is_none() + && parsed.fragment().is_none() + && !origin.ends_with('/'), + "Timing-Allow-Origin {origin:?} must be an origin such as https://app.example.com" + ); + } + Ok(Some(http::HeaderValue::from_str(&origins.join(", "))?)) +} diff --git a/tests/panel_refresh_contract.js b/tests/panel_refresh_contract.js index 8c83fd1..4b01730 100644 --- a/tests/panel_refresh_contract.js +++ b/tests/panel_refresh_contract.js @@ -51,5 +51,5 @@ const events = openapi.paths["/api/events"].get; const logsFlag = (events.parameters || []).find(parameter => parameter.name === "logs"); assert.equal(logsFlag?.schema?.type, "boolean"); assert.equal(logsFlag?.schema?.default, true); -assert.equal(openapi.info.version, "0.38.1"); +assert.equal(openapi.info.version, "0.38.2"); console.log("Panel refresh/API contract checks: OK");