v0.41.3_hotfix1

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-24 23:16:54 +01:00
1 parent dd9ecc48f1
commit 0d0100acbc
35 files changed
+981 -391

No files matched your search

+2
View File
@@ -4,6 +4,8 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.41.3 — Practical dashboard presets and stored-log domains ## 0.41.3 — Practical dashboard presets and stored-log domains
- **Hotfix:** cache outcome charts and domain counters count each client request once at its final response, including collapsed fills, stale fallback and revalidation; background refresh does not count as a client HIT. Cache operations retain their own counters. Error share uses completed exchanges, protocol shares use protocol totals, and HTTP/1.0 is included in H1. Additive status/Cache API and Prometheus metrics; no configuration or storage migration. Source-level hotfix; rebuild and run Rust regression tests before deployment.
- **Dashboard presets:** six additional built-in layouts: Daily operations (compact), Latency and incident triage, Memory pressure and limits, Delivery efficiency, Docker two-host comparison and Phone quick diagnostics. Compact layouts combine traffic, memory breakdown, cache, backend health and diagnostics; selected charts have a larger minimum height. All 12 previous presets, the factory layout and existing administrator presets remain unchanged. Docker agent selections remain independent of the layout. - **Dashboard presets:** six additional built-in layouts: Daily operations (compact), Latency and incident triage, Memory pressure and limits, Delivery efficiency, Docker two-host comparison and Phone quick diagnostics. Compact layouts combine traffic, memory breakdown, cache, backend health and diagnostics; selected charts have a larger minimum height. All 12 previous presets, the factory layout and existing administrator presets remain unchanged. Docker agent selections remain independent of the layout.
- **Stored Logs:** per-site source names and the Source column show configured domains and aliases in parentheses, including manually configured Docker assignments, currently discovered label publications, redirect hosts and local 404 hosts. Rotations share the same domain metadata; shared, unmatched and historical sources without a current mapping keep their existing names. The inventory and query API add `domains` without changing source IDs or filesystem scan rules. - **Stored Logs:** per-site source names and the Source column show configured domains and aliases in parentheses, including manually configured Docker assignments, currently discovered label publications, redirect hosts and local 404 hosts. Rotations share the same domain metadata; shared, unmatched and historical sources without a current mapping keep their existing names. The inventory and query API add `domains` without changing source IDs or filesystem scan rules.
+36 -35
View File
@@ -2,14 +2,14 @@
4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example 4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example
e76e688874828e3743d03693b1d2872b9633b4db09909673786caf30f7cfe489 .gitignore e76e688874828e3743d03693b1d2872b9633b4db09909673786caf30f7cfe489 .gitignore
45bf3959f2bd53a08db232fd518f390d455a45501f98bd3c97e71e22dad90bd6 AGENTS.md 45bf3959f2bd53a08db232fd518f390d455a45501f98bd3c97e71e22dad90bd6 AGENTS.md
694c212be5cd9f696f09c3cf583814f5f6938d1e6231a80c3c12f4609374596e CHANGELOG.md aaf6b1a760d968721aca28d7d719cef2e80ef5df2d80bad4001383185ba9030f CHANGELOG.md
3396712e5842af47d4fa8a428fac5fff2f73110380f172c2a33ef7149c2f10ff Cargo.lock 3396712e5842af47d4fa8a428fac5fff2f73110380f172c2a33ef7149c2f10ff Cargo.lock
f2f82427377eb5264b8a6150797e3543858c781d49044404bbf46021885ddb02 Cargo.toml f2f82427377eb5264b8a6150797e3543858c781d49044404bbf46021885ddb02 Cargo.toml
788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile 788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile
0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 LICENSE 0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 LICENSE
82d1dee2fc68158f0ea73259151461e64c8b18d807cd1fecfb1ed99dc30cf5f4 README.md 82d1dee2fc68158f0ea73259151461e64c8b18d807cd1fecfb1ed99dc30cf5f4 README.md
da8311e3db945290666324a2f24bf4521b365272d7ac3f862ded1be993eea646 UPDATE_CHECK.toml da8311e3db945290666324a2f24bf4521b365272d7ac3f862ded1be993eea646 UPDATE_CHECK.toml
60bb6386160863f7dba1d100d88f6d603b55b7373fd4ab94b7b5f442455ad380 build.rs 120609370b79e192c9a2a72c1706225aa5da06c5806efa26a010b733e120322b build.rs
95ececaba550a4bcfd6754073877ba0633373b1e1451521b9ac905a51e8ca6eb deploy/README.md 95ececaba550a4bcfd6754073877ba0633373b1e1451521b9ac905a51e8ca6eb deploy/README.md
13d514de5042a230cacf8c10abe1ef183c94ac799a89b8e2c111152ac7c69b48 deploy/rustproxy.service 13d514de5042a230cacf8c10abe1ef183c94ac799a89b8e2c111152ac7c69b48 deploy/rustproxy.service
c111f5b20484707b80efb7dd9176acbaa27b63ac78db497261ac234821e1fade dev.sh c111f5b20484707b80efb7dd9176acbaa27b63ac78db497261ac234821e1fade dev.sh
@@ -39,22 +39,22 @@ f30c895df3d7f289f3b7c9a73969009ecf91110f59cb247daa242f68e78aa014 docker-agent/s
20313df0c14a1696d099ed881b159fe854e92538a60548a1729f92babaead881 docker-agent/system.go 20313df0c14a1696d099ed881b159fe854e92538a60548a1729f92babaead881 docker-agent/system.go
188b74ec4f58da1b46d86925a67b6a590c92fb4fd7516e8d03d43871bc3b4542 docker-agent/system_test.go 188b74ec4f58da1b46d86925a67b6a590c92fb4fd7516e8d03d43871bc3b4542 docker-agent/system_test.go
c0940a4b323d71931cf2ad4ad24d58b6d6bfd49af90c6e3fc91fcbe2b4cf312f docs/ACCESS.md c0940a4b323d71931cf2ad4ad24d58b6d6bfd49af90c6e3fc91fcbe2b4cf312f docs/ACCESS.md
92b12de43c020be79a759676ccedb1f6bbd9630d0cdb79fddea33403fdd0ed4e docs/API.md 0379e53a640364263a46a160be8b720df8c4a74fd220ae7310f72ae3e45dbe72 docs/API.md
728b15b9825f547f34c4121219784798dd046fbbdd72ece8906d0cd77e8efc64 docs/BACKUP.md 728b15b9825f547f34c4121219784798dd046fbbdd72ece8906d0cd77e8efc64 docs/BACKUP.md
68d38960a2ce461da54d2e4179a3b2c7f1f24ea630f2e51739b0796f811fe6cd docs/CACHE.md 96c01362bad3a6218c0b8795f2e76aac220cc5526e257208e14817bc532752e4 docs/CACHE.md
51d34823d139ff3b0b8e1cf1a31850746be5ed7da847a2cca51be36fd5f7733a docs/CACHE_TEMPLATE_LIBRARY.md 51d34823d139ff3b0b8e1cf1a31850746be5ed7da847a2cca51be36fd5f7733a docs/CACHE_TEMPLATE_LIBRARY.md
31285f000cf725d018a926023fe608fec983b959053f7a55e0954b962a8bc20c docs/CERTIFICATES.md 31285f000cf725d018a926023fe608fec983b959053f7a55e0954b962a8bc20c docs/CERTIFICATES.md
6aa83366ad45227d10ebe121ed2c4f690ebcb826939ec2b2eafb40bfd714ac69 docs/CONFIGURATION.md 6aa83366ad45227d10ebe121ed2c4f690ebcb826939ec2b2eafb40bfd714ac69 docs/CONFIGURATION.md
08fd05b08c7b0a749ebf2337e4243f6aba6f654eaee5398a3f478c720df4e4dd docs/CUSTOM_LOCATIONS.md 08fd05b08c7b0a749ebf2337e4243f6aba6f654eaee5398a3f478c720df4e4dd docs/CUSTOM_LOCATIONS.md
6e695211374eb39aff05dbfc0886854a30db85de8c4d9fc0480552c8d155d2a2 docs/DASHBOARD.md 3c11b55f4a43f66e1a6e105492ef442e39025de0d07e4d93db97dcc2544d08eb docs/DASHBOARD.md
81bd7a901619092e2a5a5fb7e4edd2157f2b5ce7e0483c24581ec290080446c0 docs/DOCKER_DISCOVERY.md 81bd7a901619092e2a5a5fb7e4edd2157f2b5ce7e0483c24581ec290080446c0 docs/DOCKER_DISCOVERY.md
01404657b1e79efbcb9d78da5ebf7de9b995c7820360624de1e5f82a6fea37f9 docs/FEATURES.md d97c448de8f0c6d8a8a426d76e535e58a41f332adcc475fbc1ba4a4d58a76e62 docs/FEATURES.md
5e12c541648ca382366f999e93b8ae434603e5c750f6fad3bd6a8df81e3724a1 docs/HEADLESS.md 5e12c541648ca382366f999e93b8ae434603e5c750f6fad3bd6a8df81e3724a1 docs/HEADLESS.md
4282602f0b814841f71282040003bec91c24611e5152b33407b76e62357f8d3a docs/INSTALL.md 4282602f0b814841f71282040003bec91c24611e5152b33407b76e62357f8d3a docs/INSTALL.md
3268808766ad66263e465f251dce18cff2e7ede355638dc2b0975870b1a5eead docs/LOAD_BALANCING.md 3268808766ad66263e465f251dce18cff2e7ede355638dc2b0975870b1a5eead docs/LOAD_BALANCING.md
425f1ca32172d987b6fabbd08076bbd091101193e103e9fe5452e0709159a2bd docs/LOGS.md 425f1ca32172d987b6fabbd08076bbd091101193e103e9fe5452e0709159a2bd docs/LOGS.md
0e9ae9509a78d00951d2c7c3f13eaf518d1f3448a29b048f5933e1f5f8440275 docs/MIGRATION.md 0e9ae9509a78d00951d2c7c3f13eaf518d1f3448a29b048f5933e1f5f8440275 docs/MIGRATION.md
a7717c4ab03417914805527e573ea1dfd5d35295bf7b347d0c098bda6d469850 docs/MONITORING.md 48105c4303401aa99ffff00d3ebaf3024535a492a4a7b883c6803e4732b37434 docs/MONITORING.md
6d3937088eeb67a9f690d44ebe0b6e660b68116dbf69091ac7816bdc52cec2b6 docs/PERFORMANCE.md 6d3937088eeb67a9f690d44ebe0b6e660b68116dbf69091ac7816bdc52cec2b6 docs/PERFORMANCE.md
d5894c07c68ec4230987767198434abee13b0e525842fea21bcbe752fa82742b docs/PHP_FPM.md d5894c07c68ec4230987767198434abee13b0e525842fea21bcbe752fa82742b docs/PHP_FPM.md
1282e8d3e2ee044316e5536acaecc041eb7e1098965b4a657b0f1b00fe4a688f docs/README.md 1282e8d3e2ee044316e5536acaecc041eb7e1098965b4a657b0f1b00fe4a688f docs/README.md
@@ -116,7 +116,7 @@ b009b3749233f844acacb9f48663e67d919baed4863bc89d38c1ab9677ef8237 examples/vcl/p
d242de9614fbb52933b4accd32f4715ca94107abe4a3b1d7e088362b07a6ba60 examples/vhosts-balanced.json d242de9614fbb52933b4accd32f4715ca94107abe4a3b1d7e088362b07a6ba60 examples/vhosts-balanced.json
af2bdb1343a8141069e94ccd2c7f92574ad848437e2f9fdb5c7576a9a18ef4a5 examples/vhosts-private.json af2bdb1343a8141069e94ccd2c7f92574ad848437e2f9fdb5c7576a9a18ef4a5 examples/vhosts-private.json
716dd2ba150e3813116d2a8c568865b1e315f2fd29c6e636dcd72709dd444837 grafana/README.md 716dd2ba150e3813116d2a8c568865b1e315f2fd29c6e636dcd72709dd444837 grafana/README.md
c720a4426d7b4dc52048077157dd05aefa427ae78ca811afc3b7b9cbbe875cae grafana/rustproxy-overview.json 0354f8b8e78e81dd8d240e0170fee14202e94686831f1a008fdc2a58da528de4 grafana/rustproxy-overview.json
1a041c505669625a7f0f8011484cf5b6d2ec69a7de859801312e4fcf4c8d3555 install-debian13.sh 1a041c505669625a7f0f8011484cf5b6d2ec69a7de859801312e4fcf4c8d3555 install-debian13.sh
909e9ab94617ace74a425f15084bf85f3086cc52ba5b28f2b441ff800abc6ef9 install.sh 909e9ab94617ace74a425f15084bf85f3086cc52ba5b28f2b441ff800abc6ef9 install.sh
42f9f1d18c021fc7734b5bd020844bf678725a0e539e2fcbe05ec676f6239eae integrations/README.md 42f9f1d18c021fc7734b5bd020844bf678725a0e539e2fcbe05ec676f6239eae integrations/README.md
@@ -132,8 +132,8 @@ e9cbb0224c4a3d23a6019ba557e0cd568c1ad5e1582ff1e335fb7d99b7a1055d integrations/r
3f092a9ab80221eddd67be4d1a776acbc6e04c1eb6011b588280c28e83b2582f integrations/routeros-oci-build/build-routeros-oci.sh 3f092a9ab80221eddd67be4d1a776acbc6e04c1eb6011b588280c28e83b2582f integrations/routeros-oci-build/build-routeros-oci.sh
3f267cafa16006e5456ade78ee2d5fae02cc7ce747839523068ffd8d7c98798a integrations/routeros-oci-build/docker-entrypoint.sh 3f267cafa16006e5456ade78ee2d5fae02cc7ce747839523068ffd8d7c98798a integrations/routeros-oci-build/docker-entrypoint.sh
ae2ee2887fcba096d0de25edcc18faa1ffec35759274518db1bf6d6982f7176c langs/README.md ae2ee2887fcba096d0de25edcc18faa1ffec35759274518db1bf6d6982f7176c langs/README.md
df4d901d7c6567ba467627ba0bdf84a259fe42422caafa169a174022ee0b43b9 langs/en_US.json de011f823f6a9a8be25c11293a3d2e2fa82678f5fabe951dc074c560a43c0bdb langs/en_US.json
1022ca7ca94a03b0bd6b68aa1b901fae61282c93061154d1c68284bca7e4d2fa langs/pl_pl.json 888171b50ff58d55935def6813dc8c1feb21b4bc43d131f8205b14f1102124af langs/pl_pl.json
8ed80f14633970899d56f4ea72684a8d4b1f2843c1c78bfacc4cbb5f7ce9ef4b make_zip.py 8ed80f14633970899d56f4ea72684a8d4b1f2843c1c78bfacc4cbb5f7ce9ef4b make_zip.py
e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql
20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql 20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql
@@ -204,9 +204,9 @@ b9c2952e3fcfca540d0ad64f2d3acc5c1f5240e707f4f23ef4d452f46fcb520f src/admin/docu
2805c7d1c08fed6a54711b8b5d51078ba8c2daecae431b6c7c39fe0345b6cecc src/admin/file_logs.rs 2805c7d1c08fed6a54711b8b5d51078ba8c2daecae431b6c7c39fe0345b6cecc src/admin/file_logs.rs
737876e72c315987515d259de84d46c22780e89f19ed3102fc5c4f55d0e2951b src/admin/file_logs_io.rs 737876e72c315987515d259de84d46c22780e89f19ed3102fc5c4f55d0e2951b src/admin/file_logs_io.rs
e2253599b5e39510946729920d240711403a3889cc495eb49824296228f1d080 src/admin/file_logs_query.rs e2253599b5e39510946729920d240711403a3889cc495eb49824296228f1d080 src/admin/file_logs_query.rs
e287399bfef114028b8831cb854db2323c0e1b61e3503ef409ebb2c5cdbc2a8c src/admin/logging_api.rs ab0a933e7175f8135476316919fb60c4fdacd8d9feff10692f697b609637b198 src/admin/logging_api.rs
51228956c33358278ebed62941da273e1e87d0b5c5d1c40cc0d2c91aec9d7362 src/admin/mod.rs 51228956c33358278ebed62941da273e1e87d0b5c5d1c40cc0d2c91aec9d7362 src/admin/mod.rs
4d347c3df70fa6a4533d2884968274addc28afbc5ca0eec19f13510b810fddaa src/admin/openapi.json 9c45eff3550e15a706ff10ead33dbcef766f01ba3da238026bafa9d7981373d3 src/admin/openapi.json
9f8842cdec27d703d1795dd6eb37d9420e9f5a2e56a0df93278c92bace5d1f4c src/admin/operations.rs 9f8842cdec27d703d1795dd6eb37d9420e9f5a2e56a0df93278c92bace5d1f4c src/admin/operations.rs
257d93a29d0bda96462bcf695aba8d0ec0f9412c379e066ec46ae8ee034e3a53 src/admin/panel_assets.rs 257d93a29d0bda96462bcf695aba8d0ec0f9412c379e066ec46ae8ee034e3a53 src/admin/panel_assets.rs
f5127855c2994d052678865df36d703b74f4a0afc633daf7718b10da18d26e37 src/admin/panel_content.rs f5127855c2994d052678865df36d703b74f4a0afc633daf7718b10da18d26e37 src/admin/panel_content.rs
@@ -222,7 +222,7 @@ fba52102e77ca8871a42f97c91be8f10a9aa4f997868652d550fff3fbd41b66e src/admin/sess
9b5bc1a439c5e5611c47732fe86097877b50b09b10a0838d9813314ea6232d0c src/admin/status_live.rs 9b5bc1a439c5e5611c47732fe86097877b50b09b10a0838d9813314ea6232d0c src/admin/status_live.rs
c20f214e2ec2a14d8a88d07a63a27d9396a7a6bf9446f6ee31dbd77b12e4b585 src/admin/status_system.rs c20f214e2ec2a14d8a88d07a63a27d9396a7a6bf9446f6ee31dbd77b12e4b585 src/admin/status_system.rs
ea1d0b8ff69157215f9358f0de35b91462ab2bf1fb97f9ce9b37846d0432c56b src/admin/tail.rs ea1d0b8ff69157215f9358f0de35b91462ab2bf1fb97f9ce9b37846d0432c56b src/admin/tail.rs
9deb2985b0a0e4308df888b7987213739002a5d9aa2f42f53ee13051397cc218 src/admin/tests.rs c26309a124bc72119f6e4177200f735eecd0aceb0b167a220d333fa6cd3a8602 src/admin/tests.rs
d6c7ef48325c8f4f7ae7504827c0255c263b41c838f61960381907ca78eb9b95 src/admin/web/acl-picker.js d6c7ef48325c8f4f7ae7504827c0255c263b41c838f61960381907ca78eb9b95 src/admin/web/acl-picker.js
1e46ac359a11a85374d93936fb849864bea43021c20770fff5076acd846e8859 src/admin/web/acme.js 1e46ac359a11a85374d93936fb849864bea43021c20770fff5076acd846e8859 src/admin/web/acme.js
30a71c399e9a2cd9a4c1830568e4767f219ce09bca35f6d5fd22424f1a6617ac src/admin/web/admin_origin_rejected.html 30a71c399e9a2cd9a4c1830568e4767f219ce09bca35f6d5fd22424f1a6617ac src/admin/web/admin_origin_rejected.html
@@ -240,22 +240,22 @@ fce1fe268749b28ab68ac41519ced05252c1193f11bc9a3851de45dae4c419ad src/admin/web/
f01c5fe8eb9c8249b1d07563f42bb63c397de0b602eb178c131b8a9e50d3b1c4 src/admin/web/app/icons.js f01c5fe8eb9c8249b1d07563f42bb63c397de0b602eb178c131b8a9e50d3b1c4 src/admin/web/app/icons.js
9fc3165febd83a6661b2827aacd612fbc0f834e99ef1585ec54e03e97fe54a72 src/admin/web/app/logo-animation.js 9fc3165febd83a6661b2827aacd612fbc0f834e99ef1585ec54e03e97fe54a72 src/admin/web/app/logo-animation.js
92ed982c3ac4bc4218a24a200d2a33f30fc6705b77b260db2be31b0ce91a7df9 src/admin/web/app/memory-breakdown.js 92ed982c3ac4bc4218a24a200d2a33f30fc6705b77b260db2be31b0ce91a7df9 src/admin/web/app/memory-breakdown.js
32aa11f041eafdf16e66adef6f5847a67413785224da2c19ecbf825996622aff src/admin/web/app/overview-extra-metrics.js e165db3dd12be8dbff2dfffe3bb9608ce9125924cb97558c26826e9f3d070699 src/admin/web/app/overview-extra-metrics.js
3049a308881f98ab19ffd95b4bb88976702c61f2fc82792b4402f0212fcd7403 src/admin/web/app/overview-masonry.js 3049a308881f98ab19ffd95b4bb88976702c61f2fc82792b4402f0212fcd7403 src/admin/web/app/overview-masonry.js
776306b8db51db952de352aa066ea1775b12e71b7cd956bb25084860cef650e4 src/admin/web/app/overview-rows.js 776306b8db51db952de352aa066ea1775b12e71b7cd956bb25084860cef650e4 src/admin/web/app/overview-rows.js
6f10f3239aea505aa01796620981eed873930c129ed5a2fd7eb439e0e0d24558 src/admin/web/app/overview-samples.js 6f10f3239aea505aa01796620981eed873930c129ed5a2fd7eb439e0e0d24558 src/admin/web/app/overview-samples.js
db9012546cae8c58fc2bcbee71c9a95956a13a6db9e6d126c6a3770d45a4e4d2 src/admin/web/app/overview-wide-metrics.js 3b5c68e6258946b79b7f5042384ad2d39407807a40984ef2f58c4b0edb9d65fa src/admin/web/app/overview-wide-metrics.js
e799e0406c7ff54cbf71faf704a20265bdf5180a8ed2f26388d0775231365410 src/admin/web/app/path-permissions.js e799e0406c7ff54cbf71faf704a20265bdf5180a8ed2f26388d0775231365410 src/admin/web/app/path-permissions.js
b0930110e4eb7de6826e27b5b46c47e46556449fed6dc505d42da4f5e9c20366 src/admin/web/app/preferences.js b0930110e4eb7de6826e27b5b46c47e46556449fed6dc505d42da4f5e9c20366 src/admin/web/app/preferences.js
30ec0a7027215eae63946689af2c042de0cf468a6b1054535694da4dd4214cdb src/admin/web/app/rate-sampling.js 30ec0a7027215eae63946689af2c042de0cf468a6b1054535694da4dd4214cdb src/admin/web/app/rate-sampling.js
3b8e566d81a5b94ef21c73e7805ae128454f085554de9358040de266bcbdb0e0 src/admin/web/app/refresh.js 3b8e566d81a5b94ef21c73e7805ae128454f085554de9358040de266bcbdb0e0 src/admin/web/app/refresh.js
14176caf91a5eaea548fca298b316c85aff614a5ef7de9ccac820ba1c018ef3f src/admin/web/app/runtime.js a90bf72f6a7df7b3aa27a648862ac9852db381b9bf4cc35a72d9b57fc1335b2f src/admin/web/app/runtime.js
31201586925e6f4792071d7d03fb05dcc4a69a03c02a4e85eb0746f45af68074 src/admin/web/app/session-resume.js 31201586925e6f4792071d7d03fb05dcc4a69a03c02a4e85eb0746f45af68074 src/admin/web/app/session-resume.js
65e46879e94f13e8271d4105246f29d820903fe68b9efe2dbe4a4ff661ca9dfc src/admin/web/app/settings.js 65e46879e94f13e8271d4105246f29d820903fe68b9efe2dbe4a4ff661ca9dfc src/admin/web/app/settings.js
2281f06990f86acd3ff12fa368e1b73e4c83601e20245f24abbce389dfccb77f src/admin/web/app/sidebar.js 2281f06990f86acd3ff12fa368e1b73e4c83601e20245f24abbce389dfccb77f src/admin/web/app/sidebar.js
b7ead49224a4ec67181d3f24f9d9634bd6d76756f826a4d5d993300637d1d8f3 src/admin/web/app/stream-dashboard.js b7ead49224a4ec67181d3f24f9d9634bd6d76756f826a4d5d993300637d1d8f3 src/admin/web/app/stream-dashboard.js
7de070cc8cdde45d7e0932259299e341e25b32c9ffbd87e4fcce934d0f090de4 src/admin/web/app/web-overview.js 7de070cc8cdde45d7e0932259299e341e25b32c9ffbd87e4fcce934d0f090de4 src/admin/web/app/web-overview.js
857a3c49d003a4c3beed98acf404fcffa1b7b127f34579a916196e007e8a2963 src/admin/web/cache-panel.js ba22ff211f408052aee0aa75a5a52734b1c257247e7112972aff75a9646faf22 src/admin/web/cache-panel.js
fe7982223b9b3ba70a18c28a09659884cd7277f8d152c851f4db1d482ab5ea04 src/admin/web/cache-rules.js fe7982223b9b3ba70a18c28a09659884cd7277f8d152c851f4db1d482ab5ea04 src/admin/web/cache-rules.js
6288b0a8228d828ac2e2535ace2d1aefd1c04011e789eb97f7279129874ac35c src/admin/web/certificate-api.js 6288b0a8228d828ac2e2535ace2d1aefd1c04011e789eb97f7279129874ac35c src/admin/web/certificate-api.js
f554ca7179fe4d97ae24aa004d4bc9ada5f84fc78257891933a7fed728006ef8 src/admin/web/css/00-tokens.css f554ca7179fe4d97ae24aa004d4bc9ada5f84fc78257891933a7fed728006ef8 src/admin/web/css/00-tokens.css
@@ -300,7 +300,7 @@ ac9f667273918e18406df06cb2613c923f50a88897693a03a18f500e22dc6ec2 src/admin/web/
c2e5f554810b8e34fb47361fb90a01073a2e332ee26d82e030956fad3ec1f83e src/admin/web/login.js c2e5f554810b8e34fb47361fb90a01073a2e332ee26d82e030956fad3ec1f83e src/admin/web/login.js
6185182b81273372dbd506fa57281ee81d3cd1233ac328640a7f33794f754e1b src/admin/web/management.js 6185182b81273372dbd506fa57281ee81d3cd1233ac328640a7f33794f754e1b src/admin/web/management.js
1f3d10e389c9c20e6eb019509fa6e82b50c6b43bbf988c1210a4d42bb73985d0 src/admin/web/partials/overview-charts.html 1f3d10e389c9c20e6eb019509fa6e82b50c6b43bbf988c1210a4d42bb73985d0 src/admin/web/partials/overview-charts.html
1fcbe9017bd6f32cdbdcf65fcc6f4342daf9632a5e1a97c7a3a56d76cbe87095 src/admin/web/partials/overview-metrics.html bd94e61e051a6bebe0afbda0a21aa36349c2067516b974986765555ed47455cc src/admin/web/partials/overview-metrics.html
80d6eb03f204a90f7b140c5b053d0fd8facb350b1c96b74fa1402e2a35d4fb10 src/admin/web/prometheus-token.js 80d6eb03f204a90f7b140c5b053d0fd8facb350b1c96b74fa1402e2a35d4fb10 src/admin/web/prometheus-token.js
b2d4b67fb65c55003e516e23dd783de55b0f00278035f16589f156a4659b7a54 src/admin/web/redirects.js b2d4b67fb65c55003e516e23dd783de55b0f00278035f16589f156a4659b7a54 src/admin/web/redirects.js
f8c3424d17bb94f80f00a7f8f4fac7ac3c8718141e975ccf5b42cc8686a00082 src/admin/web/settings.js f8c3424d17bb94f80f00a7f8f4fac7ac3c8718141e975ccf5b42cc8686a00082 src/admin/web/settings.js
@@ -352,7 +352,7 @@ d789bf40cf9433e2fd16409d112210fe93154588b1ac9bddc9c7f78e1db14426 src/balance/po
a361c341932ffd186c0b21356c91ab1fe8043f5020d40798266d15ae896a114e src/balance/tests.rs a361c341932ffd186c0b21356c91ab1fe8043f5020d40798266d15ae896a114e src/balance/tests.rs
ae06d238b1451328c751a511476ef39c012f3a397393f939ca02f96ecd0119a6 src/basic_auth/mod.rs ae06d238b1451328c751a511476ef39c012f3a397393f939ca02f96ecd0119a6 src/basic_auth/mod.rs
9a8858b7ff461a4d961ba701ca3ed6eaec15c3f7f05eef8e0e30edc63617605a src/basic_auth/tests.rs 9a8858b7ff461a4d961ba701ca3ed6eaec15c3f7f05eef8e0e30edc63617605a src/basic_auth/tests.rs
3ea2e11fa1f3af55f8937dae17ff5a50c5ec841a42420163c20d32fb2ff85ec9 src/cache/cache_regression_tests.rs 6df8d743e007baf9262a5936a533af30c880a63356c92b04188a6a2b77635a88 src/cache/cache_regression_tests.rs
7def03ace07dc38a4806277d75b6ce673d33ddaaf1c4855fa0a3372be1cf9489 src/cache/cold.rs 7def03ace07dc38a4806277d75b6ce673d33ddaaf1c4855fa0a3372be1cf9489 src/cache/cold.rs
b75ff512a1c6344483e00d2c67578ceea6b5472c279da0246f3622daa68d7e16 src/cache/cold/cleanup.rs b75ff512a1c6344483e00d2c67578ceea6b5472c279da0246f3622daa68d7e16 src/cache/cold/cleanup.rs
640a0f11bf3c77e44f276ba300bdb645465621b2015a32e215e416faaaf65b18 src/cache/cold/cold_tier_tests.rs 640a0f11bf3c77e44f276ba300bdb645465621b2015a32e215e416faaaf65b18 src/cache/cold/cold_tier_tests.rs
@@ -372,7 +372,7 @@ bd831807ca4720b3a41a6ea1d9a6c0ed2d935225e2dacbd9313be064f2e4a20e src/cache/look
dd2d3132d4a8d2f453021d27bd8c804159edd86d286d4c3ddf6b47aadca80a09 src/cache/lookup/hot.rs dd2d3132d4a8d2f453021d27bd8c804159edd86d286d4c3ddf6b47aadca80a09 src/cache/lookup/hot.rs
4148106b9baf70e41eeba24233b1edbe8dd6f927c11f2c7647e89fbbfb60555e src/cache/lookup/hot_hit_034_tests.rs 4148106b9baf70e41eeba24233b1edbe8dd6f927c11f2c7647e89fbbfb60555e src/cache/lookup/hot_hit_034_tests.rs
e9c6ab0c2be9f96573f826e6a1b9e4c2b8b526f779e72e95a6463ae07e45ab55 src/cache/lookup/insert.rs e9c6ab0c2be9f96573f826e6a1b9e4c2b8b526f779e72e95a6463ae07e45ab55 src/cache/lookup/insert.rs
891461e5f23264a71c6f220c3a3e872488d2894a4409defda1672d085ab8ead9 src/cache/lookup/tiered.rs eac60232821c18a6f5def8a5c310202917151be11119ee887828dc882e197245 src/cache/lookup/tiered.rs
46564e91dde4a3232a62ae56008ae9c6b45fe7c5520b19add5735c7a5a4c2d9d src/cache/mod.rs 46564e91dde4a3232a62ae56008ae9c6b45fe7c5520b19add5735c7a5a4c2d9d src/cache/mod.rs
0c8b0d550e94d4474dcdf991aa0340228dc5f2f904f39350e6e666a16f16fe87 src/cache/model.rs 0c8b0d550e94d4474dcdf991aa0340228dc5f2f904f39350e6e666a16f16fe87 src/cache/model.rs
b96e30ef2b12ad7647915457f087a4d11b6141847bc5e971a75c2739c88c3d8c src/cache/model/cache.rs b96e30ef2b12ad7647915457f087a4d11b6141847bc5e971a75c2739c88c3d8c src/cache/model/cache.rs
@@ -460,7 +460,7 @@ e8399753a6ff49b7de19edb0a268bf871c9979a518354160cf07b4669051fcbb src/logging.rs
0a6578a0f4023b9f8d73043bf942dc5e096ef9afb8c0d2f131c14f65d08ac01d src/main/shutdown/tests.rs 0a6578a0f4023b9f8d73043bf942dc5e096ef9afb8c0d2f131c14f65d08ac01d src/main/shutdown/tests.rs
ff491043180085800b786b77e6bd3c400b60051012482918440cd5dc6493d1e7 src/main/tasks.rs ff491043180085800b786b77e6bd3c400b60051012482918440cd5dc6493d1e7 src/main/tasks.rs
a719c51aebcba0f16f8810c37618201954e79d6806da085ee6c5e4697a05b521 src/metrics.rs a719c51aebcba0f16f8810c37618201954e79d6806da085ee6c5e4697a05b521 src/metrics.rs
9c7ed78345abc33d260f8d5cd52339bf8de748c08b53eaa2bdea8a32a0ea2a20 src/metrics/global.rs 314c8f825727ad20abcbe51c7e5ac6bc714f136a8b3b64e105a3cb67079c2086 src/metrics/global.rs
31154052757c2bb975b8ce8cad67f3fad7b5132b615a73d5b0d7bf1b5311722b src/metrics/rate_sampling.rs 31154052757c2bb975b8ce8cad67f3fad7b5132b615a73d5b0d7bf1b5311722b src/metrics/rate_sampling.rs
4e71dcbd92d8afe5808eaee693243725e8b6515377de9837fce4623af98b383a src/metrics/vhost/mod.rs 4e71dcbd92d8afe5808eaee693243725e8b6515377de9837fce4623af98b383a src/metrics/vhost/mod.rs
bb8507a5329ba320e4af02757f5f37da61db39fec147fcc2a3b76e3fcfd47434 src/metrics/vhost/tests.rs bb8507a5329ba320e4af02757f5f37da61db39fec147fcc2a3b76e3fcfd47434 src/metrics/vhost/tests.rs
@@ -474,31 +474,31 @@ d09dc18863b0508a5e8d54a5305904170f3e8f12857b7a0d5393a11849541e50 src/pages/test
5650a3f70162abd97021e0a51a92cac2c4dd39004426ef99dff36cbb0741aeac src/prometheus.rs 5650a3f70162abd97021e0a51a92cac2c4dd39004426ef99dff36cbb0741aeac src/prometheus.rs
b9d71633703469d1d14e89c4d8a7698f4d354e5111cfe6ed3b2587566d0e2333 src/prometheus/core.rs b9d71633703469d1d14e89c4d8a7698f4d354e5111cfe6ed3b2587566d0e2333 src/prometheus/core.rs
8595f0a7d1b075ec825a4a4b55b71dabda3d7be450718e9d7e7f554b3ef1c695 src/prometheus/docker_misc.rs 8595f0a7d1b075ec825a4a4b55b71dabda3d7be450718e9d7e7f554b3ef1c695 src/prometheus/docker_misc.rs
cc909edf740a091f9057912f555dd888b644fa1cb49647fe0e2e1f5dba8ff5af src/prometheus/json.rs 2474ce2f6db14bd38aad500c8bfc1e71c62b39d03fbd7bc5b80daaf084ef332a src/prometheus/json.rs
f9aab3297fcf647295849f77cbf99197f4dd27efd6817e54c03451e04972430c src/prometheus/model.rs f9aab3297fcf647295849f77cbf99197f4dd27efd6817e54c03451e04972430c src/prometheus/model.rs
f8a9541b568ade946dfc0b3353548a773a0126f705b537815ce0523439b07ef4 src/prometheus/tests.rs f8a9541b568ade946dfc0b3353548a773a0126f705b537815ce0523439b07ef4 src/prometheus/tests.rs
028e1dd9f2ec2afaf699a6b21c2d4b0d96e76f11f5e4ed009c233dadf0f3be51 src/prometheus/traffic.rs 028e1dd9f2ec2afaf699a6b21c2d4b0d96e76f11f5e4ed009c233dadf0f3be51 src/prometheus/traffic.rs
12cf2b67072b10bcb163eeef76efc298dae1d9598ea6bb8a441f735339c1c467 src/prometheus/vhosts_backends.rs 12cf2b67072b10bcb163eeef76efc298dae1d9598ea6bb8a441f735339c1c467 src/prometheus/vhosts_backends.rs
f1b0254f53b1a4336bd8170ad441ba072b49a114e497b985cb20699b4e375044 src/prometheus/web_php.rs f1b0254f53b1a4336bd8170ad441ba072b49a114e497b985cb20699b4e375044 src/prometheus/web_php.rs
a3871c3ad7ab2ec20e4947b3ed139953ebd732de751738c5fbb251208a2afbe1 src/proxy/body/mod.rs 813c9a86cabecf5dbca9c8c1299ffe28d60435f600e8a84030e82ac818243899 src/proxy/body/mod.rs
d1957f51f655eb8fa88a5691a71b1bff6c876655f9b71d996f0f9a72382a3283 src/proxy/body/tests.rs 3b6043ef037b3f2f7ee60845f9aaef8f2fcce14e3b2c3c9f0a0a16513669070f src/proxy/body/tests.rs
4dc32268ee8b84714443e70bc9e18ffa5b5c33fd4d69ce75a05cb8a33a78dc25 src/proxy/cache_helpers.rs dd9299fd76ceaa4677acc21868c3fef56c7ad111ab47313383cf90003021d252 src/proxy/cache_helpers.rs
2d39552aa01ce3d048560944975243d0a58ae762d838e547f5fa65007d871dc4 src/proxy/cache_http_invalidation.rs 2d39552aa01ce3d048560944975243d0a58ae762d838e547f5fa65007d871dc4 src/proxy/cache_http_invalidation.rs
a86b10ce0707b51e925e11ea14f7f40fa108a196166f62cf40007a97f9e17203 src/proxy/cache_http_invalidation_tests.rs a86b10ce0707b51e925e11ea14f7f40fa108a196166f62cf40007a97f9e17203 src/proxy/cache_http_invalidation_tests.rs
b2c4e168f63767008bda51eac4bd070be853e4de232af78588a61d5b182d9b51 src/proxy/cache_plan/mod.rs b2c4e168f63767008bda51eac4bd070be853e4de232af78588a61d5b182d9b51 src/proxy/cache_plan/mod.rs
811a00b55b24638b4bf8a6bea9ed7c0ffe2a758f76bfe63a95e1d31bce1c2c9c src/proxy/cache_plan/tests.rs 811a00b55b24638b4bf8a6bea9ed7c0ffe2a758f76bfe63a95e1d31bce1c2c9c src/proxy/cache_plan/tests.rs
d6bd4aafab7b1371c31b3d22ddf949a08ea942489649ca12c7615b3b2d5a109a src/proxy/error_fallback.rs 1f6077e2c2755a12f70f60f94fcf364d0a1b2c69e28d9b9b97f87f3e491eb233 src/proxy/error_fallback.rs
79ec6b6e378ecfe478ed779ba53e69030c4d5f06ebd6ae0092f335751db0667f src/proxy/forward/cache_fast_path_tests.rs eb0f287457164267c3798d37974a3dba16a4eb6bb402af16a11ac607e9a8f4c5 src/proxy/forward/cache_fast_path_tests.rs
016bb2719511df1fc5c70256fd7d917b95e9b4ee6044c205537472737b1f6089 src/proxy/forward/cache_lookup.rs 41d0201c52e5eb1f56bdd70659c359c6d8f5190b9d53ece95769009ebdbe0b1b src/proxy/forward/cache_lookup.rs
287012c81144d8f15af4a148ce3ca911d431bc59adff44e697567561aa372bb3 src/proxy/forward/h3_navigation_tests.rs 287012c81144d8f15af4a148ce3ca911d431bc59adff44e697567561aa372bb3 src/proxy/forward/h3_navigation_tests.rs
a2a097852d126851fc7191c2fda65764dc842745ad657b970399c1f906caf114 src/proxy/forward/response.rs a2a097852d126851fc7191c2fda65764dc842745ad657b970399c1f906caf114 src/proxy/forward/response.rs
62b282d625e2e7312ce08024236cfd77f288820e012711f19eca45edb6cecc0f src/proxy/forward/route_cache.rs 06f3809ff7423182b5f61ec576b6be520741cf8153ae9d66f6bade12443f1781 src/proxy/forward/route_cache.rs
ccecf3077cebe96320f1cef9b8df17253a9dde314d57b2f9a62a6af754406105 src/proxy/forward/static_cookie_policy_tests.rs ccecf3077cebe96320f1cef9b8df17253a9dde314d57b2f9a62a6af754406105 src/proxy/forward/static_cookie_policy_tests.rs
1cb08b2edc6773ee1ba4c1c4944c85553c048e87fe01d4140440eac1139f1069 src/proxy/forward/success_finish.rs 2846bb55d082f5792b10f3aa82304d6071040906efb211493f12a44300ccd943 src/proxy/forward/success_finish.rs
a2ec6be0292084dcb02b254c4555c570f927db017a4ed278e90bbe2d1b5cd485 src/proxy/forward/success_prepare.rs f38156f48c3164de63b7bc9794fa53eb25001d98b72c6b4c3168c8379bdd69d2 src/proxy/forward/success_prepare.rs
45bd21104a1555a7d5e404263a395f22643c9c404520ffa6f14c5741b60f0cbb src/proxy/forward/upstream.rs 45bd21104a1555a7d5e404263a395f22643c9c404520ffa6f14c5741b60f0cbb src/proxy/forward/upstream.rs
9cc1b71a86d98fbc24ce7abeb5c2a8353510267947963be74ad83312a5f7f297 src/proxy/forward/web_source.rs 226ab8d3bc9d523e51bbb0715c47da6efbf116762ce1f519eebfe70d9e06235f src/proxy/forward/web_source.rs
aba2d86576079a9e98c4b9ec3177434d488d81d9566c44c9826eb064bbb0639e src/proxy/forward_entry.rs af965de8621680ff871a0e1d264a17e00dc7ffaf22fcb49503d10fd0b25cb257 src/proxy/forward_entry.rs
9b25f5e3ea4443a63ee6f45d12e1957dd316fe8e85325fc00ea416faaab1025a src/proxy/h2_graceful.rs 9b25f5e3ea4443a63ee6f45d12e1957dd316fe8e85325fc00ea416faaab1025a src/proxy/h2_graceful.rs
fc61c3f81d0bd8d91dab2a72267d497404e45e10e5cfc6000af16a254f888148 src/proxy/headers/authority_tests.rs fc61c3f81d0bd8d91dab2a72267d497404e45e10e5cfc6000af16a254f888148 src/proxy/headers/authority_tests.rs
e87437ccf80e50e0159d204dfdd1f8dc0739b6e375be192fce0af749810258cf src/proxy/headers/mod.rs e87437ccf80e50e0159d204dfdd1f8dc0739b6e375be192fce0af749810258cf src/proxy/headers/mod.rs
@@ -508,8 +508,8 @@ af9b044761a56e8a6dc57f9d760b289ff4a6bf37db11dbfcd3ec4da5b8f426b6 src/proxy/head
92806ce1802da9b6771ece474d91a3458eba3f6ed19b0817b897e828a02e7e32 src/proxy/redirect_helpers.rs 92806ce1802da9b6771ece474d91a3458eba3f6ed19b0817b897e828a02e7e32 src/proxy/redirect_helpers.rs
b83b9c30022e8c8fc97654a7d83ee44702c78bc92d2089bd397054e0023c3b7c src/proxy/request_id/mod.rs b83b9c30022e8c8fc97654a7d83ee44702c78bc92d2089bd397054e0023c3b7c src/proxy/request_id/mod.rs
a57ea795430bf52d550083fef759c739f3821217aac465c0024aa1565b0727d1 src/proxy/request_id/tests.rs a57ea795430bf52d550083fef759c739f3821217aac465c0024aa1565b0727d1 src/proxy/request_id/tests.rs
7c676831d20f1f16a95d972b67a76261ee0e6fa839261511d0c796b86471082b src/proxy/types.rs 39ee3095e334220bc0e56dc856004ff1ea295dc3b536b465bb6fe2b18776bd25 src/proxy/types.rs
228d75dbe0c35a1e5a331c9f30bc7223a1a8387630c3e7068cb1aa68594b5a22 src/proxy/upstream_helpers.rs ba8e3304ba62dd087ee199f1eeb91962ee78597e095720a717692690453ab28a src/proxy/upstream_helpers.rs
96d18a85beb9d9492f4d0690eefd9afad9c1c4eabc36f41b447b81861a92ed2a src/proxy/web_cache_revalidation/mod.rs 96d18a85beb9d9492f4d0690eefd9afad9c1c4eabc36f41b447b81861a92ed2a src/proxy/web_cache_revalidation/mod.rs
5522456cc85948228250feac92308d53b130c4a7af98d24f669aca4dfe6999b6 src/proxy/web_cache_revalidation/tests.rs 5522456cc85948228250feac92308d53b130c4a7af98d24f669aca4dfe6999b6 src/proxy/web_cache_revalidation/tests.rs
3d591201595a3b1e928ded20a8736477a47e5acc3bcbde158f7c17547ce155ba src/proxy/websocket.rs 3d591201595a3b1e928ded20a8736477a47e5acc3bcbde158f7c17547ce155ba src/proxy/websocket.rs
@@ -642,6 +642,7 @@ f51b881c441fe8cab388c744911671ff925694b650e5ae7a5072cfdceb9ddaa4 third_party/sw
7c30c280d0b0a8bf855eeffab583ca34dc161255f7ef6124148aa979c17c26d3 tools/dev/memory_load.py 7c30c280d0b0a8bf855eeffab583ca34dc161255f7ef6124148aa979c17c26d3 tools/dev/memory_load.py
d1418f8e574a7390fd45a2aa879bdf5720b773162d65e295ab0350506aa5220a tools/dev/mock_auth.py d1418f8e574a7390fd45a2aa879bdf5720b773162d65e295ab0350506aa5220a tools/dev/mock_auth.py
2d3ff92300b09ce9cecbbaaa9309b4d33160fa4b2291c9952b784e8cfb599ab5 tools/dev/mock_server.py 2d3ff92300b09ce9cecbbaaa9309b4d33160fa4b2291c9952b784e8cfb599ab5 tools/dev/mock_server.py
5f898b953a3f0a34f9675a3469d4863635d9f95dd157f4752195a8046d784e6c tools/dev/test_dashboard_metrics.js
c711154a9df425a56607bd88f03815ffb408213a31a2b66ed1c1c9a6301a2fc6 tools/legacy/backup.py c711154a9df425a56607bd88f03815ffb408213a31a2b66ed1c1c9a6301a2fc6 tools/legacy/backup.py
5421082e24f3794356331157e30b428f3221a0d74c0b5d060bd4d3989e0bcf3a update.sh 5421082e24f3794356331157e30b428f3221a0d74c0b5d060bd4d3989e0bcf3a update.sh
56c702111022e1ca2c8f6b72c635c749b05936ffe6387bdb0a202691614cbc96 upgrade.sh 56c702111022e1ca2c8f6b72c635c749b05936ffe6387bdb0a202691614cbc96 upgrade.sh
+5 -3
View File
@@ -7,7 +7,7 @@ RustProxy exposes an authenticated administration API on the **separate administ
The current bundled `src/admin/openapi.json` declares these operations (among others): The current bundled `src/admin/openapi.json` declares these operations (among others):
| Method and path | Purpose | | Method and path | Purpose |
|---|---| | --- | --- |
| `GET /healthz` | Minimal health response, without privileged state. | | `GET /healthz` | Minimal health response, without privileged state. |
| `GET /api/auth/status` | Whether first-time administrator setup is required. | | `GET /api/auth/status` | Whether first-time administrator setup is required. |
| `POST /api/auth/login` · `POST /api/auth/logout` | Start/end a browser admin session. | | `POST /api/auth/login` · `POST /api/auth/logout` | Start/end a browser admin session. |
@@ -37,6 +37,8 @@ The current bundled `src/admin/openapi.json` declares these operations (among ot
Some paths have additional DELETE/PATCH operations, job-status resources, query parameters or restricted actions. Use OpenAPI for the **actual fields/methods**, not guesses based on a table. `GET /metrics` here is not a replacement for the separate Prometheus exporter. Some paths have additional DELETE/PATCH operations, job-status resources, query parameters or restricted actions. Use OpenAPI for the **actual fields/methods**, not guesses based on a table. `GET /metrics` here is not a replacement for the separate Prometheus exporter.
The full and live status responses include `metrics.cache_request_outcomes` (`hits`, `misses`, `bypasses`, `other`) and `metrics.completed_success`. Full and live `GET /api/cache` include `request_outcomes`, using the same process counters. These are final client-request classifications; existing `cache` / Cache `metrics` fields remain technical operation counters. Domain outcomes count final requests, while diagnostic reasons can include separate refresh and collapse events.
For browser polling, `GET /api/cache?view=live`, `GET /api/transform?view=live` and `GET /api/traffic?view=live` omit static response members that do not need to be retransmitted on every interval. Their `revision` identifies the active configuration; Cache and Traffic additionally return `catalog_version` (a fingerprint of the effective Vhost list, including Docker publications). If either revision or this fingerprint changes, clients should fetch the corresponding endpoint without `view=live` and refresh their cached static fields. Requests without `view=live` remain the complete compatibility form. Cache live responses contain metrics/dashboard/bans, Transform live responses contain resources/metrics, and Traffic live responses retain current settings/GeoIP/analytics while omitting the static Vhost list. Full Cache and Traffic responses provide readable `vhosts[].label` and `vhosts[].docker` together with the stable `id`; Docker-generated IDs are valid cache purge/invalidation and analytics scopes. Unknown `view` values are rejected. For browser polling, `GET /api/cache?view=live`, `GET /api/transform?view=live` and `GET /api/traffic?view=live` omit static response members that do not need to be retransmitted on every interval. Their `revision` identifies the active configuration; Cache and Traffic additionally return `catalog_version` (a fingerprint of the effective Vhost list, including Docker publications). If either revision or this fingerprint changes, clients should fetch the corresponding endpoint without `view=live` and refresh their cached static fields. Requests without `view=live` remain the complete compatibility form. Cache live responses contain metrics/dashboard/bans, Transform live responses contain resources/metrics, and Traffic live responses retain current settings/GeoIP/analytics while omitting the static Vhost list. Full Cache and Traffic responses provide readable `vhosts[].label` and `vhosts[].docker` together with the stable `id`; Docker-generated IDs are valid cache purge/invalidation and analytics scopes. Unknown `view` values are rejected.
Certificate inspection accepts `{ "cert_file": "filename.pem" }` for a managed file or an absolute external path and returns `{ "cert_file": "...", "covered_hosts": ["example.com"] }`. It applies the existing certificate-file trust and size checks and reads no private key. It makes no configuration or permission changes. This POST requires the signed-in administrator's normal Origin, request-marker and CSRF checks; general RO/RW API tokens and certificate-only credentials cannot call it. Certificate inspection accepts `{ "cert_file": "filename.pem" }` for a managed file or an absolute external path and returns `{ "cert_file": "...", "covered_hosts": ["example.com"] }`. It applies the existing certificate-file trust and size checks and reads no private key. It makes no configuration or permission changes. This POST requires the signed-in administrator's normal Origin, request-marker and CSRF checks; general RO/RW API tokens and certificate-only credentials cannot call it.
@@ -46,7 +48,7 @@ Certificate inspection accepts `{ "cert_file": "filename.pem" }` for a managed f
The administration listener is HTTP on loopback (`127.0.0.1:9090`) by default and is separate from the public Vhost listeners. No administrator password is bundled: complete first-time setup with the local CLI (`admin setup-token` or `admin init`). For remote access prefer an SSH tunnel; for direct access enable administration HTTPS with a trusted certificate and restrict the network before binding outside loopback. The administration listener is HTTP on loopback (`127.0.0.1:9090`) by default and is separate from the public Vhost listeners. No administrator password is bundled: complete first-time setup with the local CLI (`admin setup-token` or `admin init`). For remote access prefer an SSH tunnel; for direct access enable administration HTTPS with a trusted certificate and restrict the network before binding outside loopback.
| Credential | Scope | | Credential | Scope |
|---|---| | --- | --- |
| Browser session | Full administration. HttpOnly, SameSite=Strict cookie (Secure on HTTPS), absolute lifetime 7–30 days. Writes require matching Origin, `X-CSRF-Token` and `X-RustProxy-Request: 1`. | | Browser session | Full administration. HttpOnly, SameSite=Strict cookie (Secure on HTTPS), absolute lifetime 7–30 days. Writes require matching Origin, `X-CSRF-Token` and `X-RustProxy-Request: 1`. |
| General API token (`ro` / `rw`) | Created in **Settings → Security → API tokens** (see [API tokens in the panel](#api-tokens-in-the-panel)). Displayed once, stored as a hash, bound to a mandatory IP/CIDR allowlist. Sent as `Authorization: Bearer <token>`. `ro` reads resources and sections; `rw` also writes configuration sections and selected operations. Cannot manage authentication, backups, tokens or certificate credentials. | | General API token (`ro` / `rw`) | Created in **Settings → Security → API tokens** (see [API tokens in the panel](#api-tokens-in-the-panel)). Displayed once, stored as a hash, bound to a mandatory IP/CIDR allowlist. Sent as `Authorization: Bearer <token>`. `ro` reads resources and sections; `rw` also writes configuration sections and selected operations. Cannot manage authentication, backups, tokens or certificate credentials. |
| Certificate API key | Key ID + Bearer token limited to specific certificate IDs and actions (reload by default, deploy opt-in). | | Certificate API key | Key ID + Bearer token limited to specific certificate IDs and actions (reload by default, deploy opt-in). |
@@ -83,7 +85,7 @@ This is a special-risk topology. Configure a fixed HTTPS public origin, an allow
The section name in the URL and its corresponding JSON member in a full configuration are: The section name in the URL and its corresponding JSON member in a full configuration are:
| Section path (`/api/config/…`) | JSON member(s) in `config` | | Section path (`/api/config/…`) | JSON member(s) in `config` |
|---|---| | --- | --- |
| `listeners` | `listeners` | | `listeners` | `listeners` |
| `docker-agents` | `docker_agents` | | `docker-agents` | `docker_agents` |
| `http2` | `http2` | | `http2` | `http2` |
+2
View File
@@ -301,6 +301,8 @@ Where they show:
| `X-Cache` | `HIT` by default; `STALE` / `REVALIDATED` with **X-Cache shows STALE and REVALIDATED instead of HIT** (`cache.expose_detailed_status`, also per vhost) | | `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`) | | 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`) |
Panel HIT/MISS/BYPASS counts are final request outcomes, recorded once at response headers. STALE and REVALIDATED are HIT subcategories; collapsed requests served from the newly filled cache are HIT, even if their first lookup missed. Background refresh reasons remain visible as maintenance events without incrementing client HIT. Technical lookup counters remain separate and may record several operations per request. Domain counters reset when a cache representation change clears their catalog; global request counters reset only on service restart.
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. 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 ## Server-Timing
+3 -2
View File
@@ -140,8 +140,9 @@ Under **Settings → Appearance → Charts**, **Show values on hover** is **off
## Interpreting charts ## Interpreting charts
- The **Cache hit ratio** donut shows cumulative `HIT / (HIT + MISS)`: BYPASS and requests outside cache are deliberately excluded from its denominator. - The **Cache hit ratio** donut and recent cache activity charts use final HTTP request outcomes, not internal cache lookups. The cumulative ratio is `HIT / (HIT + MISS)`; BYPASS and OTHER are excluded. A request that waits for a fill and then hits, serves stale on error or receives a validated cached response is one HIT.
- The **Cache outcomes** compact horizontal 100% bar is **hidden by default**; enable it in **Settings → Appearance → Dashboard layout** or the Overview layout editor. It summarizes **cumulative request counters since the current service process started**, not recent polling intervals. The upper-right number shows the total HTTP requests since service start (full description in its tooltip and accessible label); the legend shows counts and percentages for HIT, MISS, BYPASS and OTHER. The percentages use all HTTP requests as the denominator. BYPASS includes requests where the cache path was considered but disabled/skipped (including globally disabled cache); OTHER covers requests without a cache decision, e.g. early rejected or redirect paths. These are request counts, not bytes; service restarts reset them. Values appear immediately with the first HTTP request; refreshing or pausing the browser does not reset totals. If independently counted cache outcomes exceed the request counter (e.g. while snapshots are inconsistent or a request incurs multiple cache events), the summary shows unavailable rather than fabricating OTHER or a normalized 100% breakdown. The separate recent cache trend chart remains unchanged. - The **Cache outcomes** compact horizontal 100% bar is **hidden by default**; enable it in **Settings → Appearance → Dashboard layout** or the Overview layout editor. It summarizes cumulative mutually exclusive final HTTP request outcomes since service start. The upper-right number and percentages use the sum of HIT, MISS, BYPASS and OTHER from the same snapshot. Requests are classified when response headers are ready; rejected requests and cancellations before headers without a final response are OTHER. Requests still awaiting a response are not counted yet. BYPASS includes requests where caching was considered but disabled or skipped; OTHER includes redirects, local responses and early rejects without a cache decision. Background refreshes and repeated lookups cannot add client request outcomes. Reloading the browser or changing cache settings does not reset these process counters; a service restart does. No data is shown before the first classified request.
- **Error share** uses completed exchanges with an error divided by all completed admitted exchanges in the same sampling interval (not new requests); a period with no completions has no ratio. The HTTP protocol shares use the sum of incoming H1, H2 and H3 counters; H1 includes HTTP/1.0 and HTTP/1.1.
- Live views are process/sampling-based and can show no-data when an integration has not reported yet. - Live views are process/sampling-based and can show no-data when an integration has not reported yet.
+1 -1
View File
@@ -80,7 +80,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se
## Monitoring and logs ## Monitoring and logs
- Overview dashboard with requests per second, bandwidth, status codes, error share, cache hit ratio, protocol mix, system load, backend health, requests rejected by limits and nearest certificate expiry. - Overview dashboard with requests per second, bandwidth, status codes, completed-exchange error share, final-request cache hit ratio and outcomes, protocol mix, system load, backend health, requests rejected by limits and nearest certificate expiry.
- Optional **Memory breakdown** card: process RSS split into cache data, cache bookkeeping, cache buffers, allocator-held free memory, mapped files and the rest of the process, with glibc heap statistics and an "outside cache" trend for spotting leaks. - Optional **Memory breakdown** card: process RSS split into cache data, cache bookkeeping, cache buffers, allocator-held free memory, mapped files and the rest of the process, with glibc heap statistics and an "outside cache" trend for spotting leaks.
- Customizable dashboard layouts (drag-and-drop with a live drop placeholder, keyboard moves, per-block width, explicit gap filling), 18 built-in layouts and up to 16 saved presets per administrator. - Customizable dashboard layouts (drag-and-drop with a live drop placeholder, keyboard moves, per-block width, explicit gap filling), 18 built-in layouts and up to 16 saved presets per administrator.
- Per-Vhost, per-backend, per-Web-Service and per-Stream statistics. - Per-Vhost, per-backend, per-Web-Service and per-Stream statistics.
+1 -1
View File
@@ -138,7 +138,7 @@ curl -fsS -H "Authorization: Bearer $RUSTPROXY_API_TOKEN" \
guaranteed exact one-second rolling averages; poll every **2–5 seconds**. guaranteed exact one-second rolling averages; poll every **2–5 seconds**.
`requests_per_second_average` is a separate **uptime average**. `requests_per_second_average` is a separate **uptime average**.
- `traffic.error_percent` is lifetime errors divided by completed requests; - `traffic.error_percent` is lifetime errors divided by completed requests;
`cache.hit_percent` is lifetime HOT/COLD hit ratio from cache metrics. `cache.hit_percent` is the lifetime technical HOT/COLD hit ratio from cache metrics. The panel and Grafana request-outcome charts use separate final HTTP request counters: `rust_proxy_cache_request_hits_total`, `rust_proxy_cache_request_misses_total`, `rust_proxy_cache_request_bypasses_total`, and `rust_proxy_cache_request_other_total`. A request is classified once at response headers (or OTHER on pre-header cancellation/rejection); ongoing requests are excluded. Internal lookups and repeated fill attempts remain in the existing technical counters. Background 304 refreshes are maintenance and no longer increment HIT. `rust_proxy_requests_completed_success_total` complements `rust_proxy_errors_total` for the error share of completed admitted exchanges. HTTP/1.x counters include both 1.0 and 1.1.
Zero-denominator percentages are `null` unless a cache ratio has a defined Zero-denominator percentages are `null` unless a cache ratio has a defined
default. The `traffic.network_rx_bytes_per_second` and default. The `traffic.network_rx_bytes_per_second` and
`network_tx_bytes_per_second` fields are **host** interface rates, not `network_tx_bytes_per_second` fields are **host** interface rates, not
+4 -4
View File
@@ -2899,19 +2899,19 @@
"targets": [ "targets": [
{ {
"refId": "A", "refId": "A",
"expr": "rate(rust_proxy_cache_hits_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "expr": "rate(rust_proxy_cache_request_hits_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])",
"legendFormat": "HIT/s", "legendFormat": "HIT/s",
"range": true "range": true
}, },
{ {
"refId": "B", "refId": "B",
"expr": "rate(rust_proxy_cache_misses_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "expr": "rate(rust_proxy_cache_request_misses_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])",
"legendFormat": "MISS/s", "legendFormat": "MISS/s",
"range": true "range": true
}, },
{ {
"refId": "C", "refId": "C",
"expr": "rate(rust_proxy_cache_bypasses_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "expr": "rate(rust_proxy_cache_request_bypasses_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])",
"legendFormat": "BYPASS/s", "legendFormat": "BYPASS/s",
"range": true "range": true
}, },
@@ -7168,7 +7168,7 @@
"targets": [ "targets": [
{ {
"refId": "A", "refId": "A",
"expr": "sum(rate(rust_proxy_cache_hits_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "expr": "sum(rate(rust_proxy_cache_request_hits_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))",
"legendFormat": "Cache HIT/s", "legendFormat": "Cache HIT/s",
"range": true "range": true
}, },
+9 -9
View File
@@ -2849,7 +2849,7 @@
"overviewExtraRequestErrorRate": "Request errors/s", "overviewExtraRequestErrorRate": "Request errors/s",
"overviewExtraRequestErrorRateDescription": "Rate based on request error counter deltas.", "overviewExtraRequestErrorRateDescription": "Rate based on request error counter deltas.",
"overviewExtraCacheHitRate": "Cache hits share (recent)", "overviewExtraCacheHitRate": "Cache hits share (recent)",
"overviewExtraCacheHitRateDescription": "Share of HIT among new HIT and MISS events; skips BYPASS.", "overviewExtraCacheHitRateDescription": "Share of HIT among newly classified HIT and MISS requests; skips BYPASS.",
"overviewExtraCacheMemory": "Cache hot RAM utilization", "overviewExtraCacheMemory": "Cache hot RAM utilization",
"overviewExtraCacheMemoryDescription": "Cache resident bytes as a share of configured hot RAM budget, if available.", "overviewExtraCacheMemoryDescription": "Cache resident bytes as a share of configured hot RAM budget, if available.",
"overviewExtraH2Share": "HTTP/2 request share", "overviewExtraH2Share": "HTTP/2 request share",
@@ -2884,12 +2884,12 @@
"overviewExtraTotalRpsDetail": "Total HTTP request rate calculated from counters.", "overviewExtraTotalRpsDetail": "Total HTTP request rate calculated from counters.",
"overviewExtraActiveExchanges": "Active HTTP exchanges", "overviewExtraActiveExchanges": "Active HTTP exchanges",
"overviewExtraActiveExchangesDetail": "Requests currently being processed.", "overviewExtraActiveExchangesDetail": "Requests currently being processed.",
"overviewExtraH1Share": "HTTP/1.1 share", "overviewExtraH1Share": "HTTP/1.x share",
"overviewExtraH1ShareDetail": "Share of new HTTP requests using H1.", "overviewExtraH1ShareDetail": "Share of new HTTP requests using HTTP/1.0 or HTTP/1.1.",
"overviewExtraH3Share": "HTTP/3 share", "overviewExtraH3Share": "HTTP/3 share",
"overviewExtraH3ShareDetail": "Share of new HTTP requests using H3.", "overviewExtraH3ShareDetail": "Share of new HTTP requests using H3.",
"overviewExtraCacheMissRate": "Cache misses / s", "overviewExtraCacheMissRate": "Cache misses / s",
"overviewExtraCacheMissRateDetail": "Rate of cache misses.", "overviewExtraCacheMissRateDetail": "Rate of requests classified as cache MISS.",
"overviewExtraBackendActive": "In-flight backend requests", "overviewExtraBackendActive": "In-flight backend requests",
"overviewExtraBackendActiveDetail": "Current HTTP upstream requests across backends.", "overviewExtraBackendActiveDetail": "Current HTTP upstream requests across backends.",
"overviewExtraBackendsHealthy": "Healthy backends", "overviewExtraBackendsHealthy": "Healthy backends",
@@ -2899,7 +2899,7 @@
"overviewExtraBackendsAllUp": "All monitored backends are up", "overviewExtraBackendsAllUp": "All monitored backends are up",
"overviewExtraErrorShare": "Error share", "overviewExtraErrorShare": "Error share",
"overviewExtraErrorShareDescription": "Share of HTTP requests that ended with an error in the last sampling interval.", "overviewExtraErrorShareDescription": "Share of HTTP requests that ended with an error in the last sampling interval.",
"overviewExtraErrorShareDetail": "Errors / requests", "overviewExtraErrorShareDetail": "Errors / completed exchanges",
"overviewExtraRejectedRate": "Rejected by limits / s", "overviewExtraRejectedRate": "Rejected by limits / s",
"overviewExtraRejectedRateDescription": "Requests and connections rejected by concurrency limits. Sustained values suggest raising max-connections or max-inflight.", "overviewExtraRejectedRateDescription": "Requests and connections rejected by concurrency limits. Sustained values suggest raising max-connections or max-inflight.",
"overviewExtraRejectedDetail": "Total requests / connections", "overviewExtraRejectedDetail": "Total requests / connections",
@@ -3083,12 +3083,12 @@
"h3_udp_send_buffer_mib": "UDP send buffer (MiB; 0 = system default)", "h3_udp_send_buffer_mib": "UDP send buffer (MiB; 0 = system default)",
"http3ApplyPolicy": "LIVE / RESTART", "http3ApplyPolicy": "LIVE / RESTART",
"cacheMixTitle": "Cache outcomes", "cacheMixTitle": "Cache outcomes",
"cacheMixHelp": "Cumulative HIT/MISS/BYPASS and OTHER HTTP request mix since service start; OTHER means no cache decision. Each category shows count and share.", "cacheMixHelp": "Cumulative final cache outcomes since service start; OTHER means no final cache decision. Requests still awaiting a response are excluded.",
"cacheMixOther": "OTHER", "cacheMixOther": "OTHER",
"cacheMixSample": "Since service start · {count} HTTP requests", "cacheMixSample": "Since service start · {count} classified HTTP requests",
"cacheMixWaiting": "No HTTP requests since service start", "cacheMixWaiting": "No classified HTTP requests since service start",
"cacheMixAria": "Since service start: {hit} HIT, {miss} MISS, {bypass} BYPASS, {other} OTHER", "cacheMixAria": "Since service start: {hit} HIT, {miss} MISS, {bypass} BYPASS, {other} OTHER",
"cacheMixInvalid": "Totals unavailable: request and cache counters disagree", "cacheMixInvalid": "Cache request outcomes unavailable",
"pathPermissionsTitle": "Permission commands", "pathPermissionsTitle": "Permission commands",
"pathPermissionsWebDescription": "Commands to grant the RustProxy service user read access to website files (r) and read/traverse access to directories (r+x). They do not grant write (w) or file execution permissions.", "pathPermissionsWebDescription": "Commands to grant the RustProxy service user read access to website files (r) and read/traverse access to directories (r+x). They do not grant write (w) or file execution permissions.",
"pathPermissionsCertificateDescription": "Commands to grant the RustProxy service user read access to the certificate and private key (r) and traversal of parent directories (x). They do not grant write (w) permissions.", "pathPermissionsCertificateDescription": "Commands to grant the RustProxy service user read access to the certificate and private key (r) and traversal of parent directories (x). They do not grant write (w) permissions.",
+9 -9
View File
@@ -2849,7 +2849,7 @@
"overviewExtraRequestErrorRate": "Błędy żądań/s", "overviewExtraRequestErrorRate": "Błędy żądań/s",
"overviewExtraRequestErrorRateDescription": "Tempo wyliczone z przyrostu licznika błędów żądań.", "overviewExtraRequestErrorRateDescription": "Tempo wyliczone z przyrostu licznika błędów żądań.",
"overviewExtraCacheHitRate": "Udział trafień cache (ostatnie próbki)", "overviewExtraCacheHitRate": "Udział trafień cache (ostatnie próbki)",
"overviewExtraCacheHitRateDescription": "Udział HIT w nowych trafieniach i chybieniach; bez BYPASS.", "overviewExtraCacheHitRateDescription": "Udział HIT w nowych sklasyfikowanych żądaniach HIT i MISS; bez BYPASS.",
"overviewExtraCacheMemory": "Wykorzystanie pamięci HOT cache", "overviewExtraCacheMemory": "Wykorzystanie pamięci HOT cache",
"overviewExtraCacheMemoryDescription": "Pamięć rezydentna cache względem limitu HOT RAM, gdy jest dostępny.", "overviewExtraCacheMemoryDescription": "Pamięć rezydentna cache względem limitu HOT RAM, gdy jest dostępny.",
"overviewExtraH2Share": "Udział żądań HTTP/2", "overviewExtraH2Share": "Udział żądań HTTP/2",
@@ -2884,12 +2884,12 @@
"overviewExtraTotalRpsDetail": "Tempo wszystkich żądań HTTP, liczone z liczników.", "overviewExtraTotalRpsDetail": "Tempo wszystkich żądań HTTP, liczone z liczników.",
"overviewExtraActiveExchanges": "Aktywne wymiany HTTP", "overviewExtraActiveExchanges": "Aktywne wymiany HTTP",
"overviewExtraActiveExchangesDetail": "Żądania aktualnie obsługiwane.", "overviewExtraActiveExchangesDetail": "Żądania aktualnie obsługiwane.",
"overviewExtraH1Share": "Udział HTTP/1.1", "overviewExtraH1Share": "Udział HTTP/1.x",
"overviewExtraH1ShareDetail": "Udział H1 w nowych żądaniach HTTP.", "overviewExtraH1ShareDetail": "Udział nowych żądań HTTP/1.0 i HTTP/1.1.",
"overviewExtraH3Share": "Udział HTTP/3", "overviewExtraH3Share": "Udział HTTP/3",
"overviewExtraH3ShareDetail": "Udział H3 w nowych żądaniach HTTP.", "overviewExtraH3ShareDetail": "Udział H3 w nowych żądaniach HTTP.",
"overviewExtraCacheMissRate": "Cache MISS / s", "overviewExtraCacheMissRate": "Cache MISS / s",
"overviewExtraCacheMissRateDetail": "Tempo nietrafień w cache.", "overviewExtraCacheMissRateDetail": "Tempo żądań sklasyfikowanych jako cache MISS.",
"overviewExtraBackendActive": "Żądania do backendów", "overviewExtraBackendActive": "Żądania do backendów",
"overviewExtraBackendActiveDetail": "Suma aktualnych żądań do backendów HTTP.", "overviewExtraBackendActiveDetail": "Suma aktualnych żądań do backendów HTTP.",
"overviewExtraBackendsHealthy": "Sprawne backendy", "overviewExtraBackendsHealthy": "Sprawne backendy",
@@ -2899,7 +2899,7 @@
"overviewExtraBackendsAllUp": "Wszystkie monitorowane backendy działają", "overviewExtraBackendsAllUp": "Wszystkie monitorowane backendy działają",
"overviewExtraErrorShare": "Udział błędów", "overviewExtraErrorShare": "Udział błędów",
"overviewExtraErrorShareDescription": "Odsetek żądań HTTP zakończonych błędem w ostatnim interwale próbkowania.", "overviewExtraErrorShareDescription": "Odsetek żądań HTTP zakończonych błędem w ostatnim interwale próbkowania.",
"overviewExtraErrorShareDetail": "Błędy / żądania", "overviewExtraErrorShareDetail": "Błędy / zakończone wymiany",
"overviewExtraRejectedRate": "Odrzucone przez limity / s", "overviewExtraRejectedRate": "Odrzucone przez limity / s",
"overviewExtraRejectedRateDescription": "Żądania i połączenia odrzucone przez limity współbieżności. Stałe wartości oznaczają, że warto podnieść max-connections lub max-inflight.", "overviewExtraRejectedRateDescription": "Żądania i połączenia odrzucone przez limity współbieżności. Stałe wartości oznaczają, że warto podnieść max-connections lub max-inflight.",
"overviewExtraRejectedDetail": "Łącznie żądania / połączenia", "overviewExtraRejectedDetail": "Łącznie żądania / połączenia",
@@ -3083,12 +3083,12 @@
"h3_udp_send_buffer_mib": "Bufor nadawczy UDP (MiB; 0 = domyślny systemowy)", "h3_udp_send_buffer_mib": "Bufor nadawczy UDP (MiB; 0 = domyślny systemowy)",
"http3ApplyPolicy": "NA ŻYWO / RESTART", "http3ApplyPolicy": "NA ŻYWO / RESTART",
"cacheMixTitle": "Wyniki cache", "cacheMixTitle": "Wyniki cache",
"cacheMixHelp": "Udział HIT/MISS/BYPASS i INNE we wszystkich żądaniach HTTP od startu usługi. INNE oznacza brak decyzji cache. Każda kategoria pokazuje liczbę i procent.", "cacheMixHelp": "Końcowe wyniki cache od startu usługi; OTHER oznacza brak końcowej decyzji cache. Żądania nadal oczekujące na odpowiedź nie są wliczane.",
"cacheMixOther": "INNE", "cacheMixOther": "INNE",
"cacheMixSample": "Od startu usługi · {count} żądań HTTP", "cacheMixSample": "Od startu usługi · {count} sklasyfikowanych żądań HTTP",
"cacheMixWaiting": "Brak żądań HTTP od startu usługi", "cacheMixWaiting": "Brak sklasyfikowanych żądań HTTP od startu usługi",
"cacheMixAria": "Od startu usługi: {hit} HIT, {miss} MISS, {bypass} BYPASS, {other} INNE", "cacheMixAria": "Od startu usługi: {hit} HIT, {miss} MISS, {bypass} BYPASS, {other} INNE",
"cacheMixInvalid": "Suma niedostępna: niespójne liczniki żądań i cache", "cacheMixInvalid": "Wyniki cache dla żądań są niedostępne",
"pathPermissionsTitle": "Polecenia nadania uprawnień", "pathPermissionsTitle": "Polecenia nadania uprawnień",
"pathPermissionsWebDescription": "Polecenia do nadania użytkownikowi usługi RustProxy uprawnień do odczytu plików WWW (r) oraz odczytu i przechodzenia przez katalogi (r+x). Nie nadają prawa zapisu (w) ani wykonywania plików.", "pathPermissionsWebDescription": "Polecenia do nadania użytkownikowi usługi RustProxy uprawnień do odczytu plików WWW (r) oraz odczytu i przechodzenia przez katalogi (r+x). Nie nadają prawa zapisu (w) ani wykonywania plików.",
"pathPermissionsCertificateDescription": "Polecenia do nadania użytkownikowi usługi RustProxy uprawnień do odczytu certyfikatu i klucza prywatnego (r) oraz przechodzenia przez katalogi (x). Nie nadają prawa zapisu (w).", "pathPermissionsCertificateDescription": "Polecenia do nadania użytkownikowi usługi RustProxy uprawnień do odczytu certyfikatu i klucza prywatnego (r) oraz przechodzenia przez katalogi (x). Nie nadają prawa zapisu (w).",
+73 -26
View File
@@ -24,10 +24,12 @@ async fn logs(
.vhost .vhost
.as_ref() .as_ref()
.is_some_and(|v| !crate::config::valid_id(v)) .is_some_and(|v| !crate::config::valid_id(v))
|| filter || filter.cache.as_ref().is_some_and(|v| {
.cache !matches!(
.as_ref() v.as_str(),
.is_some_and(|v| !matches!(v.as_str(), "HIT" | "STALE" | "REVALIDATED" | "MISS" | "BYPASS" | "-")) "HIT" | "STALE" | "REVALIDATED" | "MISS" | "BYPASS" | "-"
)
})
{ {
return Err(ApiError( return Err(ApiError(
StatusCode::BAD_REQUEST, StatusCode::BAD_REQUEST,
@@ -249,25 +251,49 @@ fn monitored_vhost_catalog(state: &Arc<App>) -> (Vec<crate::vhost::Vhost>, Vec<V
let (publications, _) = crate::docker::label_publications(desired, &observed); let (publications, _) = crate::docker::label_publications(desired, &observed);
let mut docker_labels = std::collections::HashMap::new(); let mut docker_labels = std::collections::HashMap::new();
for agent in &desired.docker_agents.agents { for agent in &desired.docker_agents.agents {
let inventory = observed.get(&agent.id).and_then(|item| item.inventory.as_ref()); let inventory = observed
let assignments = agent.assignments.iter().filter(|assignment| assignment.enabled) .get(&agent.id)
.chain(publications.iter().filter(|entry| entry.agent_id == agent.id) .and_then(|item| item.inventory.as_ref());
.map(|entry| &entry.assignment)); let assignments = agent
.assignments
.iter()
.filter(|assignment| assignment.enabled)
.chain(
publications
.iter()
.filter(|entry| entry.agent_id == agent.id)
.map(|entry| &entry.assignment),
);
for assignment in assignments { for assignment in assignments {
let service = inventory.and_then(|inventory| inventory.services.iter() let service = inventory.and_then(|inventory| {
.find(|service| service.key == assignment.service_key)); inventory
let name = service.map(|service| service.container_name.as_str()) .services
.iter()
.find(|service| service.key == assignment.service_key)
});
let name = service
.map(|service| service.container_name.as_str())
.filter(|name| !name.is_empty()) .filter(|name| !name.is_empty())
.unwrap_or(assignment.hostname.as_str()); .unwrap_or(assignment.hostname.as_str());
docker_labels.insert(crate::docker::generated_id(&agent.id, &assignment.service_key), docker_labels.insert(
(name.to_owned(), agent.name.clone())); crate::docker::generated_id(&agent.id, &assignment.service_key),
(name.to_owned(), agent.name.clone()),
);
} }
} }
let vhosts: Vec<_> = cache_rule_vhosts(state).into_iter() let vhosts: Vec<_> = cache_rule_vhosts(state)
.into_iter()
.filter(|vhost| snapshot.vhost_metrics.contains_key(&vhost.id)) .filter(|vhost| snapshot.vhost_metrics.contains_key(&vhost.id))
.collect(); .collect();
let options: Vec<Value> = vhosts.iter().map(|vhost| { let options: Vec<Value> = vhosts
let host = vhost.frontend.hosts.first().map(String::as_str).unwrap_or(&vhost.id); .iter()
.map(|vhost| {
let host = vhost
.frontend
.hosts
.first()
.map(String::as_str)
.unwrap_or(&vhost.id);
let docker = docker_labels.get(&vhost.id); let docker = docker_labels.get(&vhost.id);
let label = match docker { let label = match docker {
Some((name, agent)) => format!("{name} - {host} (Docker: {agent})"), Some((name, agent)) => format!("{name} - {host} (Docker: {agent})"),
@@ -275,10 +301,14 @@ fn monitored_vhost_catalog(state: &Arc<App>) -> (Vec<crate::vhost::Vhost>, Vec<V
}; };
json!({"id": vhost.id, "hosts": vhost.frontend.hosts, json!({"id": vhost.id, "hosts": vhost.frontend.hosts,
"docker": docker.is_some(), "label": label}) "docker": docker.is_some(), "label": label})
}).collect(); })
.collect();
let bytes = serde_json::to_vec(&options).unwrap_or_default(); let bytes = serde_json::to_vec(&options).unwrap_or_default();
let digest = <sha2::Sha256 as sha2::Digest>::digest(&bytes); let digest = <sha2::Sha256 as sha2::Digest>::digest(&bytes);
let catalog_version: String = digest[..12].iter().map(|byte| format!("{byte:02x}")).collect(); let catalog_version: String = digest[..12]
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
(vhosts, options, catalog_version) (vhosts, options, catalog_version)
} }
@@ -304,10 +334,15 @@ async fn traffic_status(
}; };
let snapshot = state.config.load_full(); let snapshot = state.config.load_full();
let (vhosts, options, catalog_version) = monitored_vhost_catalog(&state); let (vhosts, options, catalog_version) = monitored_vhost_catalog(&state);
if query.vhost.as_ref().is_some_and(|id| { if query
id != "*" && !vhosts.iter().any(|vhost| &vhost.id == id) .vhost
}) { .as_ref()
return Err(ApiError(StatusCode::NOT_FOUND, "unknown vhost traffic scope".into())); .is_some_and(|id| id != "*" && !vhosts.iter().any(|vhost| &vhost.id == id))
{
return Err(ApiError(
StatusCode::NOT_FOUND,
"unknown vhost traffic scope".into(),
));
} }
let scope = query.vhost.as_deref().unwrap_or("*"); let scope = query.vhost.as_deref().unwrap_or("*");
let mut payload = json!({ let mut payload = json!({
@@ -353,8 +388,15 @@ async fn cache_status(
}; };
let snapshot = state.config.load_full(); let snapshot = state.config.load_full();
let (vhosts, options, catalog_version) = monitored_vhost_catalog(&state); let (vhosts, options, catalog_version) = monitored_vhost_catalog(&state);
if query.vhost.as_ref().is_some_and(|id| !vhosts.iter().any(|vhost| &vhost.id == id)) { if query
return Err(ApiError(StatusCode::NOT_FOUND, "unknown vhost cache scope".into())); .vhost
.as_ref()
.is_some_and(|id| !vhosts.iter().any(|vhost| &vhost.id == id))
{
return Err(ApiError(
StatusCode::NOT_FOUND,
"unknown vhost cache scope".into(),
));
} }
let dashboard = state.cache.dashboard( let dashboard = state.cache.dashboard(
query.vhost.as_deref(), query.vhost.as_deref(),
@@ -365,6 +407,7 @@ async fn cache_status(
"revision": snapshot.envelope.revision, "revision": snapshot.envelope.revision,
"catalog_version": catalog_version, "catalog_version": catalog_version,
"metrics": state.cache.view(), "metrics": state.cache.view(),
"request_outcomes": state.metrics.cache_request_outcomes(),
"dashboard": dashboard, "dashboard": dashboard,
"bans": state.cache.bans() "bans": state.cache.bans()
}); });
@@ -372,11 +415,15 @@ async fn cache_status(
return Ok(Json(payload)); return Ok(Json(payload));
} }
payload["settings"] = json!(snapshot.envelope.config.cache); payload["settings"] = json!(snapshot.envelope.config.cache);
payload["vhosts"] = json!(vhosts.iter().zip(options.iter()).map(|(vhost, option)| { payload["vhosts"] = json!(vhosts
.iter()
.zip(options.iter())
.map(|(vhost, option)| {
let mut item = option.clone(); let mut item = option.clone();
item["metrics"] = json!(state.cache.scope_view(&vhost.id)); item["metrics"] = json!(state.cache.scope_view(&vhost.id));
item["settings"] = json!(vhost.cache.resolve(&snapshot.envelope.config.cache).ok()); item["settings"] = json!(vhost.cache.resolve(&snapshot.envelope.config.cache).ok());
item item
}).collect::<Vec<_>>()); })
.collect::<Vec<_>>());
Ok(Json(payload)) Ok(Json(payload))
} }
+25 -1
View File
@@ -1594,7 +1594,16 @@
}, },
"metrics": { "metrics": {
"type": "object", "type": "object",
"properties": {}, "properties": {
"cache_request_outcomes": {
"$ref": "#/components/schemas/CacheRequestOutcomes"
},
"completed_success": {
"type": "integer",
"minimum": 0,
"description": "Admitted exchanges completed without a recorded error."
}
},
"additionalProperties": true "additionalProperties": true
}, },
"transform_metrics": { "transform_metrics": {
@@ -1973,6 +1982,18 @@
}, },
"additionalProperties": false "additionalProperties": false
}, },
"CacheRequestOutcomes": {
"type": "object",
"description": "Mutually exclusive final public HTTP request outcomes since process start. Requests awaiting response headers are not counted yet; early rejects and cancellations without a final response are OTHER.",
"additionalProperties": false,
"required": ["hits", "misses", "bypasses", "other"],
"properties": {
"hits": {"type": "integer", "minimum": 0},
"misses": {"type": "integer", "minimum": 0},
"bypasses": {"type": "integer", "minimum": 0},
"other": {"type": "integer", "minimum": 0}
}
},
"Cache": { "Cache": {
"type": "object", "type": "object",
"properties": { "properties": {
@@ -1991,6 +2012,9 @@
"properties": {}, "properties": {},
"additionalProperties": true "additionalProperties": true
}, },
"request_outcomes": {
"$ref": "#/components/schemas/CacheRequestOutcomes"
},
"vhosts": { "vhosts": {
"type": "array", "type": "array",
"items": { "items": {
+198 -49
View File
@@ -3025,14 +3025,21 @@ mod tests {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut config = config::demo_config("127.0.0.1:9000".parse().unwrap()); let mut config = config::demo_config("127.0.0.1:9000".parse().unwrap());
config.vhosts[0].id = "app".into(); config.vhosts[0].id = "app".into();
config.vhosts[0].frontend.hosts = vec!["app.example.test".into(), "*.app.example.test".into()]; config.vhosts[0].frontend.hosts =
vec!["app.example.test".into(), "*.app.example.test".into()];
config.vhosts[0].enabled = false; config.vhosts[0].enabled = false;
config.redirects.push(serde_json::from_value(json!({ config.redirects.push(
serde_json::from_value(json!({
"id": "app", "frontend": {"hosts": ["old.example.test"], "listener_ids": ["http"]} "id": "app", "frontend": {"hosts": ["old.example.test"], "listener_ids": ["http"]}
})).unwrap()); }))
config.not_found_hosts.push(serde_json::from_value(json!({ .unwrap(),
);
config.not_found_hosts.push(
serde_json::from_value(json!({
"id": "app", "frontend": {"hosts": ["park.example.test"], "listener_ids": ["http"]} "id": "app", "frontend": {"hosts": ["park.example.test"], "listener_ids": ["http"]}
})).unwrap()); }))
.unwrap(),
);
config.docker_agents.agents.push(crate::docker::Agent { config.docker_agents.agents.push(crate::docker::Agent {
id: "node1".into(), id: "node1".into(),
domains: vec!["example.test".into()], domains: vec!["example.test".into()],
@@ -3057,41 +3064,86 @@ mod tests {
"labels": {"rustproxy.enable": "true", "rustproxy.host": "label", "rustproxy.aliases": "label-alias"} "labels": {"rustproxy.enable": "true", "rustproxy.host": "label", "rustproxy.aliases": "label-alias"}
}] }]
})).unwrap(); })).unwrap();
let observed = std::collections::BTreeMap::from([("node1".into(), crate::docker::Observation { let observed = std::collections::BTreeMap::from([(
agent_id: "node1".into(), ok: true, checked_at_unix_ms: 1, "node1".into(),
last_ok_unix_ms: Some(1), error: None, inventory: Some(inventory), crate::docker::Observation {
})]); agent_id: "node1".into(),
ok: true,
checked_at_unix_ms: 1,
last_ok_unix_ms: Some(1),
error: None,
inventory: Some(inventory),
},
)]);
config.logging.file.per_vhost = true; config.logging.file.per_vhost = true;
config.logging.file.directory = dir.path().to_string_lossy().into_owned(); config.logging.file.directory = dir.path().to_string_lossy().into_owned();
config.error_log.path = dir.path().join("error.log").to_string_lossy().into_owned(); config.error_log.path = dir.path().join("error.log").to_string_lossy().into_owned();
for name in ["app.jsonl", "app.jsonl.1", "app.redirect.jsonl", "app.host404.jsonl", for name in [
"deleted.jsonl", "_unmatched.jsonl", &format!("{manual}.jsonl"), &format!("{labelled}.jsonl")] { "app.jsonl",
"app.jsonl.1",
"app.redirect.jsonl",
"app.host404.jsonl",
"deleted.jsonl",
"_unmatched.jsonl",
&format!("{manual}.jsonl"),
&format!("{labelled}.jsonl"),
] {
std::fs::write(dir.path().join(name), records(1, 2).join("\n")).unwrap(); std::fs::write(dir.path().join(name), records(1, 2).join("\n")).unwrap();
} }
write_gz(&dir.path().join("app.jsonl.2.gz"), &records(1, 2)); write_gz(&dir.path().join("app.jsonl.2.gz"), &records(1, 2));
let sources = configured_file_log_sources(&config, &observed); let sources = configured_file_log_sources(&config, &observed);
let domains = |id: &str| sources.iter().find(|s| s.id == id).unwrap().domains.clone(); let domains = |id: &str| sources.iter().find(|s| s.id == id).unwrap().domains.clone();
let app_domains = vec!["app.example.test".to_owned(), "*.app.example.test".to_owned()]; let app_domains = vec![
"app.example.test".to_owned(),
"*.app.example.test".to_owned(),
];
assert_eq!(domains("vhost:app"), app_domains); assert_eq!(domains("vhost:app"), app_domains);
assert_eq!(domains("vhost-file:app.jsonl.1"), app_domains); assert_eq!(domains("vhost-file:app.jsonl.1"), app_domains);
assert_eq!(domains("vhost-gz:app.jsonl.2.gz"), app_domains); assert_eq!(domains("vhost-gz:app.jsonl.2.gz"), app_domains);
assert_eq!(domains("vhost:app.redirect"), vec!["old.example.test"]); assert_eq!(domains("vhost:app.redirect"), vec!["old.example.test"]);
assert_eq!(domains("vhost:app.host404"), vec!["park.example.test"]); assert_eq!(domains("vhost:app.host404"), vec!["park.example.test"]);
assert_eq!(domains(&format!("vhost:{manual}")), vec!["manual.example.test", "manual-alias.example.test"]); assert_eq!(
assert_eq!(domains(&format!("vhost:{labelled}")), vec!["label.example.test", "label-alias.example.test"]); domains(&format!("vhost:{manual}")),
vec!["manual.example.test", "manual-alias.example.test"]
);
assert_eq!(
domains(&format!("vhost:{labelled}")),
vec!["label.example.test", "label-alias.example.test"]
);
for id in ["vhost:deleted", "vhost:_unmatched", "error"] { for id in ["vhost:deleted", "vhost:_unmatched", "error"] {
assert!(domains(id).is_empty(), "{id}"); assert!(domains(id).is_empty(), "{id}");
} }
let inventory = file_log_sources_json(&sources); let inventory = file_log_sources_json(&sources);
let source = inventory.as_array().unwrap().iter().find(|s| s["id"] == "vhost:app").unwrap(); let source = inventory
.as_array()
.unwrap()
.iter()
.find(|s| s["id"] == "vhost:app")
.unwrap();
assert_eq!(source["domains"], json!(app_domains)); assert_eq!(source["domains"], json!(app_domains));
let query = FileLogQuery { source: Some("vhost:app".into()), consolidate_vhosts: Some(true), ..Default::default() }; let query = FileLogQuery {
let result = file_log_query_blocking(&config, &observed, &query, &[]).unwrap().0; source: Some("vhost:app".into()),
consolidate_vhosts: Some(true),
..Default::default()
};
let result = file_log_query_blocking(&config, &observed, &query, &[])
.unwrap()
.0;
assert_eq!(result["sources"].as_array().unwrap().len(), 3); assert_eq!(result["sources"].as_array().unwrap().len(), 3);
assert!(result["sources"].as_array().unwrap().iter().all(|s| s["domains"] == json!(app_domains))); assert!(result["sources"]
.as_array()
.unwrap()
.iter()
.all(|s| s["domains"] == json!(app_domains)));
config.logging.file.per_vhost = false; config.logging.file.per_vhost = false;
config.logging.file.path = dir.path().join("access.jsonl").to_string_lossy().into_owned(); config.logging.file.path = dir
assert!(configured_file_log_sources(&config, &observed).iter().all(|s| s.domains.is_empty())); .path()
.join("access.jsonl")
.to_string_lossy()
.into_owned();
assert!(configured_file_log_sources(&config, &observed)
.iter()
.all(|s| s.domains.is_empty()));
} }
#[test] #[test]
@@ -3304,16 +3356,25 @@ mod tests {
} }
fn records(from: u64, to: u64) -> Vec<String> { fn records(from: u64, to: u64) -> Vec<String> {
(from..to) (from..to)
.map(|time| format!(r#"{{"event":"request","time_ms":{time},"status":200,"path":"/p{time}"}}"#)) .map(|time| {
format!(r#"{{"event":"request","time_ms":{time},"status":200,"path":"/p{time}"}}"#)
})
.collect() .collect()
} }
#[test] #[test]
fn stored_log_rotations_are_read_newest_first_regardless_of_mtime() { fn stored_log_rotations_are_read_newest_first_regardless_of_mtime() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
// logrotate numbering: .jsonl newest, .1 (delaycompress, plain), .2.gz, .10.gz oldest. std::fs::write(
std::fs::write(dir.path().join("mail.jsonl"), records(400, 410).join("\n") + "\n").unwrap(); dir.path().join("mail.jsonl"),
std::fs::write(dir.path().join("mail.jsonl.1"), records(300, 310).join("\n") + "\n").unwrap(); records(400, 410).join("\n") + "\n",
)
.unwrap();
std::fs::write(
dir.path().join("mail.jsonl.1"),
records(300, 310).join("\n") + "\n",
)
.unwrap();
write_gz(&dir.path().join("mail.jsonl.2.gz"), &records(200, 210)); write_gz(&dir.path().join("mail.jsonl.2.gz"), &records(200, 210));
write_gz(&dir.path().join("mail.jsonl.10.gz"), &records(100, 110)); write_gz(&dir.path().join("mail.jsonl.10.gz"), &records(100, 110));
// The oldest rotation has the newest mtime (copied or touched files). // The oldest rotation has the newest mtime (copied or touched files).
@@ -3323,19 +3384,40 @@ mod tests {
.unwrap() .unwrap()
.set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(3600)) .set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(3600))
.unwrap(); .unwrap();
std::fs::write(dir.path().join("old.redirect.jsonl"), records(1, 2).join("\n")).unwrap(); std::fs::write(
std::fs::write(dir.path().join("park.host404.jsonl"), records(1, 2).join("\n")).unwrap(); dir.path().join("old.redirect.jsonl"),
std::fs::write(dir.path().join("_unmatched.jsonl"), records(1, 2).join("\n")).unwrap(); records(1, 2).join("\n"),
)
.unwrap();
std::fs::write(
dir.path().join("park.host404.jsonl"),
records(1, 2).join("\n"),
)
.unwrap();
std::fs::write(
dir.path().join("_unmatched.jsonl"),
records(1, 2).join("\n"),
)
.unwrap();
std::fs::write(dir.path().join("mail.jsonl-20261113.gz"), b"ignored").unwrap(); std::fs::write(dir.path().join("mail.jsonl-20261113.gz"), b"ignored").unwrap();
let mut config = Config::default(); let mut config = Config::default();
config.logging.file.per_vhost = true; config.logging.file.per_vhost = true;
config.logging.file.directory = dir.path().to_string_lossy().into_owned(); config.logging.file.directory = dir.path().to_string_lossy().into_owned();
config.error_log.path = dir.path().join("none/error.log").to_string_lossy().into_owned(); config.error_log.path = dir
.path()
.join("none/error.log")
.to_string_lossy()
.into_owned();
let sources = configured_file_log_sources(&config, &Default::default()); let sources = configured_file_log_sources(&config, &Default::default());
let mail: Vec<_> = sources.iter().filter(|s| s.group_id == "vhost:mail").collect(); let mail: Vec<_> = sources
.iter()
.filter(|s| s.group_id == "vhost:mail")
.collect();
assert_eq!( assert_eq!(
mail.iter().map(|s| (s.id.as_str(), s.rotation)).collect::<Vec<_>>(), mail.iter()
.map(|s| (s.id.as_str(), s.rotation))
.collect::<Vec<_>>(),
vec![ vec![
("vhost:mail", 0), ("vhost:mail", 0),
("vhost-file:mail.jsonl.1", 1), ("vhost-file:mail.jsonl.1", 1),
@@ -3343,10 +3425,24 @@ mod tests {
("vhost-gz:mail.jsonl.10.gz", 10) ("vhost-gz:mail.jsonl.10.gz", 10)
] ]
); );
let scope = |id: &str| sources.iter().find(|s| s.id == id).map(|s| (s.scope, s.site.clone())); let scope = |id: &str| {
assert_eq!(scope("vhost:old.redirect"), Some(("redirect", "old".into()))); sources
assert_eq!(scope("vhost:park.host404"), Some(("host404", "park".into()))); .iter()
assert_eq!(scope("vhost:_unmatched"), Some(("unmatched", String::new()))); .find(|s| s.id == id)
.map(|s| (s.scope, s.site.clone()))
};
assert_eq!(
scope("vhost:old.redirect"),
Some(("redirect", "old".into()))
);
assert_eq!(
scope("vhost:park.host404"),
Some(("host404", "park".into()))
);
assert_eq!(
scope("vhost:_unmatched"),
Some(("unmatched", String::new()))
);
assert_eq!(scope("vhost:mail"), Some(("vhost", "mail".into()))); assert_eq!(scope("vhost:mail"), Some(("vhost", "mail".into())));
let query = |extra: FileLogQuery| { let query = |extra: FileLogQuery| {
@@ -3356,7 +3452,9 @@ mod tests {
limit: Some(5), limit: Some(5),
..extra ..extra
}; };
file_log_query_blocking(&config, &Default::default(), &query, &[]).unwrap().0 file_log_query_blocking(&config, &Default::default(), &query, &[])
.unwrap()
.0
}; };
let value = query(FileLogQuery::default()); let value = query(FileLogQuery::default());
let times: Vec<u64> = value["entries"] let times: Vec<u64> = value["entries"]
@@ -3369,21 +3467,23 @@ mod tests {
assert_eq!(value["total"], 40); assert_eq!(value["total"], 40);
assert_eq!(value["newest_ms"], 409); assert_eq!(value["newest_ms"], 409);
assert_eq!(value["oldest_ms"], 100); assert_eq!(value["oldest_ms"], 100);
let files: Vec<_> = value["files"].as_array().unwrap().iter().map(|f| f["rotation"].as_u64().unwrap()).collect(); let files: Vec<_> = value["files"]
.as_array()
.unwrap()
.iter()
.map(|f| f["rotation"].as_u64().unwrap())
.collect();
assert_eq!(files, vec![0, 1, 2, 10]); assert_eq!(files, vec![0, 1, 2, 10]);
// A period stops before older rotations.
let value = query(FileLogQuery { let value = query(FileLogQuery {
since_ms: Some(305), since_ms: Some(305),
..FileLogQuery::default() ..FileLogQuery::default()
}); });
assert_eq!(value["total"], 15); assert_eq!(value["total"], 15);
assert_eq!(value["oldest_ms"], 305); assert_eq!(value["oldest_ms"], 305);
// .2.gz is read to learn that it is entirely older; .10.gz is skipped.
assert_eq!(value["files"].as_array().unwrap().len(), 3); assert_eq!(value["files"].as_array().unwrap().len(), 3);
assert_eq!(value["files_skipped"], 1); assert_eq!(value["files_skipped"], 1);
// A single rotated file is its own source.
let value = file_log_query_blocking( let value = file_log_query_blocking(
&config, &config,
&Default::default(), &Default::default(),
@@ -3404,7 +3504,11 @@ mod tests {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let active = dir.path().join("access.jsonl"); let active = dir.path().join("access.jsonl");
std::fs::write(&active, records(30, 31).join("\n")).unwrap(); std::fs::write(&active, records(30, 31).join("\n")).unwrap();
std::fs::write(dir.path().join("access.jsonl.1"), records(20, 21).join("\n")).unwrap(); std::fs::write(
dir.path().join("access.jsonl.1"),
records(20, 21).join("\n"),
)
.unwrap();
write_gz(&dir.path().join("access.jsonl.2.gz"), &records(10, 11)); write_gz(&dir.path().join("access.jsonl.2.gz"), &records(10, 11));
let mut config = Config::default(); let mut config = Config::default();
config.logging.file.per_vhost = false; config.logging.file.per_vhost = false;
@@ -3820,7 +3924,13 @@ mod tests {
( (
"/api/cache?view=live", "/api/cache?view=live",
&["settings", "vhosts"][..], &["settings", "vhosts"][..],
&["revision", "metrics", "dashboard", "bans"][..], &[
"revision",
"metrics",
"request_outcomes",
"dashboard",
"bans",
][..],
), ),
( (
"/api/transform?view=live", "/api/transform?view=live",
@@ -3857,7 +3967,10 @@ mod tests {
} }
for (path, required) in [ for (path, required) in [
("/api/cache", &["settings", "vhosts"][..]), (
"/api/cache",
&["settings", "vhosts", "request_outcomes"][..],
),
("/api/transform", &["settings", "vhosts"][..]), ("/api/transform", &["settings", "vhosts"][..]),
("/api/traffic", &["vhosts"][..]), ("/api/traffic", &["vhosts"][..]),
] { ] {
@@ -4612,27 +4725,63 @@ mod tests {
}; };
let read = |response: axum::response::Response| async move { let read = |response: axum::response::Response| async move {
assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.status(), StatusCode::OK);
let body = axum::body::to_bytes(response.into_body(), 1 << 20).await.unwrap(); let body = axum::body::to_bytes(response.into_body(), 1 << 20)
.await
.unwrap();
serde_json::from_slice::<serde_json::Value>(&body).unwrap() serde_json::from_slice::<serde_json::Value>(&body).unwrap()
}; };
let public = serde_json::json!([["Cache-Control", "public, max-age=600"], ["Content-Type", "text/css"]]); let public = serde_json::json!([
let data = read(router.clone().oneshot(run("https://localhost/assets/app.css?v=2", public.clone())).await.unwrap()).await; ["Cache-Control", "public, max-age=600"],
["Content-Type", "text/css"]
]);
let data = read(
router
.clone()
.oneshot(run("https://localhost/assets/app.css?v=2", public.clone()))
.await
.unwrap(),
)
.await;
assert_eq!(data["request"]["cacheable"], true, "{data}"); assert_eq!(data["request"]["cacheable"], true, "{data}");
assert_eq!(data["request"]["static_cookie_relaxed"], true); assert_eq!(data["request"]["static_cookie_relaxed"], true);
assert_eq!(data["request"]["shared_static_check"], true); assert_eq!(data["request"]["shared_static_check"], true);
assert_eq!(data["response"]["stored"], true); assert_eq!(data["response"]["stored"], true);
let html = serde_json::json!([["Cache-Control", "public, max-age=600"], ["Content-Type", "text/html"]]); let html = serde_json::json!([
let data = read(router.clone().oneshot(run("https://localhost/", html)).await.unwrap()).await; ["Cache-Control", "public, max-age=600"],
["Content-Type", "text/html"]
]);
let data = read(
router
.clone()
.oneshot(run("https://localhost/", html))
.await
.unwrap(),
)
.await;
assert_eq!(data["request"]["reason"], "cache_rule_cookie"); assert_eq!(data["request"]["reason"], "cache_rule_cookie");
assert_eq!(data["request"]["reason_class"], "vcl_cookie_guard"); assert_eq!(data["request"]["reason_class"], "vcl_cookie_guard");
let data = read(router.clone().oneshot(run("https://localhost/user/a.png", public)).await.unwrap()).await; let data = read(
router
.clone()
.oneshot(run("https://localhost/user/a.png", public))
.await
.unwrap(),
)
.await;
assert_eq!(data["request"]["reason"], "cache_rule"); assert_eq!(data["request"]["reason"], "cache_rule");
assert_eq!(data["request"]["reason_class"], "vcl_rule"); assert_eq!(data["request"]["reason_class"], "vcl_rule");
let private = serde_json::json!([["Cache-Control", "private, max-age=600"]]); let private = serde_json::json!([["Cache-Control", "private, max-age=600"]]);
let data = read(router.clone().oneshot(run("https://localhost/assets/app.css", private)).await.unwrap()).await; let data = read(
router
.clone()
.oneshot(run("https://localhost/assets/app.css", private))
.await
.unwrap(),
)
.await;
assert_eq!(data["response"]["stored"], false); assert_eq!(data["response"]["stored"], false);
assert_eq!(data["response"]["reason"], "response_cache_control"); assert_eq!(data["response"]["reason"], "response_cache_control");
assert_eq!(data["response"]["reason_class"], "response"); assert_eq!(data["response"]["reason_class"], "response");
+13 -12
View File
@@ -36,10 +36,11 @@ window.rustProxyExtraOverview = (() => {
const hit = positive(hits), miss = positive(misses); const hit = positive(hits), miss = positive(misses);
const total = hit !== null && miss !== null ? hit + miss : 0; const total = hit !== null && miss !== null ? hit + miss : 0;
const share = total > 0 ? hit / total * 100 : 0; const share = total > 0 ? hit / total * 100 : 0;
const missShare = total > 0 ? 100 - share : 0;
const hitArc = $(`${prefix}-hit-arc`), missArc = $(`${prefix}-miss-arc`); const hitArc = $(`${prefix}-hit-arc`), missArc = $(`${prefix}-miss-arc`);
if (hitArc) hitArc.setAttribute("stroke-dasharray", `${share} ${100 - share}`); if (hitArc) hitArc.setAttribute("stroke-dasharray", `${share} ${100 - share}`);
if (missArc) { if (missArc) {
missArc.setAttribute("stroke-dasharray", `${100 - share} ${share}`); missArc.setAttribute("stroke-dasharray", `${missShare} ${100 - missShare}`);
missArc.setAttribute("stroke-dashoffset", String(-share)); missArc.setAttribute("stroke-dashoffset", String(-share));
} }
const hitCount = $(`${prefix}-hit-count`), missCount = $(`${prefix}-miss-count`); const hitCount = $(`${prefix}-hit-count`), missCount = $(`${prefix}-miss-count`);
@@ -134,13 +135,13 @@ window.rustProxyExtraOverview = (() => {
const fields = ({ const fields = ({
extra_tls_error_rate: [m.tls_handshake_errors], extra_tls_error_rate: [m.tls_handshake_errors],
extra_request_error_rate: [m.errors], extra_request_error_rate: [m.errors],
extra_cache_hit_rate: [c.hits, c.misses], extra_cache_hit_rate: [m.cache_request_outcomes?.hits, m.cache_request_outcomes?.misses],
extra_h2_share: [m.http2_requests, m.requests], extra_h2_share: [m.http2_requests, m.http1_requests, m.http3_requests],
extra_h1_share: [m.http1_requests, m.requests], extra_h1_share: [m.http1_requests, m.http2_requests, m.http3_requests],
extra_h3_share: [m.http3_requests, m.requests], extra_h3_share: [m.http3_requests, m.http1_requests, m.http2_requests],
extra_total_rps: [m.requests], extra_total_rps: [m.requests],
extra_cache_miss_rate: [c.misses], extra_cache_miss_rate: [m.cache_request_outcomes?.misses],
extra_error_share: [m.errors, m.requests], extra_error_share: [m.errors, m.completed_success],
extra_rejected_rate: [m.rejected_requests, m.rejected_connections], extra_rejected_rate: [m.rejected_requests, m.rejected_connections],
})[id].map(positive); })[id].map(positive);
const unit = ["extra_cache_hit_rate", "extra_h2_share", "extra_h1_share", "extra_h3_share", "extra_error_share"].includes(id) const unit = ["extra_cache_hit_rate", "extra_h2_share", "extra_h1_share", "extra_h3_share", "extra_error_share"].includes(id)
@@ -156,13 +157,13 @@ window.rustProxyExtraOverview = (() => {
if (id === "extra_rejected_rate") return { if (id === "extra_rejected_rate") return {
value: (deltas[0] + deltas[1]) / seconds, unit, detail: `${t("overviewExtraRejectedDetail")}: ${fmt(fields[0])} / ${fmt(fields[1])}` value: (deltas[0] + deltas[1]) / seconds, unit, detail: `${t("overviewExtraRejectedDetail")}: ${fmt(fields[0])} / ${fmt(fields[1])}`
}; };
if (id === "extra_error_share") return {
value: deltas[1] > 0 ? Math.min(100, deltas[0] / deltas[1] * 100) : 0, unit, detail: `${t("overviewExtraErrorShareDetail")}: ${fmt(deltas[0])} / ${fmt(deltas[1])}`
};
if (unit === "rate") return { value: deltas[0] / seconds, unit, detail: "" }; if (unit === "rate") return { value: deltas[0] / seconds, unit, detail: "" };
const sum = id === "extra_cache_hit_rate" ? deltas[0] + deltas[1] : deltas[1]; // Percentages use the sum of mutually exclusive categories, sampled
// at the same lifecycle stage. No false 0% or clamped 100% on skew.
const sum = deltas.reduce((total, value) => total + value, 0);
return { return {
value: sum > 0 ? Math.min(100, deltas[0] / sum * 100) : null, unit, detail: "", value: sum > 0 ? deltas[0] / sum * 100 : null, unit,
detail: id === "extra_error_share" ? `${t("overviewExtraErrorShareDetail")}: ${fmt(deltas[0])} / ${fmt(sum)}` : "",
slices: id === "extra_cache_hit_rate" ? [deltas[0], deltas[1]] : null slices: id === "extra_cache_hit_rate" ? [deltas[0], deltas[1]] : null
}; };
} }
+1 -1
View File
@@ -15,7 +15,7 @@ window.rustProxyWideOverview = (() => {
}, },
wide_cache_activity: { wide_cache_activity: {
unit: "rate", names: ["hits", "misses"], counters: s => unit: "rate", names: ["hits", "misses"], counters: s =>
[s.cache?.hits, s.cache?.misses] [s.metrics?.cache_request_outcomes?.hits, s.metrics?.cache_request_outcomes?.misses]
}, },
wide_connections: { wide_connections: {
unit: "count", names: ["open", "websockets"], values: s => unit: "count", names: ["open", "websockets"], values: s =>
+11 -12
View File
@@ -460,14 +460,12 @@ function renderNetworkInterfaceCharts(interfaces, appendSample) {
} }
} }
function cacheOutcomeMix(totals) { function cacheOutcomeMix(outcomes) {
if (!Array.isArray(totals) || totals.length !== 4 || const counts = [outcomes?.hits, outcomes?.misses, outcomes?.bypasses, outcomes?.other];
totals.some(value => !Number.isSafeInteger(value) || value < 0)) return null; if (counts.some(value => !Number.isSafeInteger(value) || value < 0)) return null;
const [requests, hits, misses, bypasses] = totals; const requests = counts.reduce((sum, value) => sum + value, 0);
const cacheTotal = hits + misses + bypasses; if (!Number.isSafeInteger(requests)) return null;
if (requests === 0 || !Number.isSafeInteger(cacheTotal) || cacheTotal > requests) return null; return { counts, percentages: counts.map(value => requests ? value / requests * 100 : 0), requests };
const counts = [hits, misses, bypasses, requests - cacheTotal];
return { counts, percentages: counts.map(value => value / requests * 100), requests };
} }
function fitCacheMixLabels() { function fitCacheMixLabels() {
const bar = $("cache-mix-bar"); const bar = $("cache-mix-bar");
@@ -515,12 +513,13 @@ function renderDiagnostics(status, appendSample = true, systemSample = appendSam
const d = status.system || {}, live = status.live_system || d, c = status.cache || {}, m = status.metrics || {}; const d = status.system || {}, live = status.live_system || d, c = status.cache || {}, m = status.metrics || {};
$("metric-h3").textContent = fmt(m.http3_requests); $("metric-h3").textContent = fmt(m.http3_requests);
$("metric-h3-active").textContent = fmt(m.http3_active_connections || 0); $("metric-h3-active").textContent = fmt(m.http3_active_connections || 0);
const cacheHits = c.hits == null ? null : Number(c.hits), cacheMisses = c.misses == null ? null : Number(c.misses); const outcomes = m.cache_request_outcomes;
const cacheHits = outcomes?.hits ?? null, cacheMisses = outcomes?.misses ?? null;
const cacheEvents = cacheHits !== null && cacheMisses !== null ? cacheHits + cacheMisses : 0; const cacheEvents = cacheHits !== null && cacheMisses !== null ? cacheHits + cacheMisses : 0;
$("metric-cache-ratio").textContent = cacheEvents > 0 ? `${fmt(cacheHits / cacheEvents * 100, 1)}%` : "-"; $("metric-cache-ratio").textContent = cacheEvents > 0 ? `${fmt(cacheHits / cacheEvents * 100, 1)}%` : "-";
window.rustProxyExtraOverview?.donut?.("cache-ratio", cacheHits, cacheMisses); window.rustProxyExtraOverview?.donut?.("cache-ratio", cacheHits, cacheMisses);
const counters = [m.requests, c.hits, c.misses, c.bypasses].map(value => value == null ? NaN : Number(value)); const mix = cacheOutcomeMix(outcomes);
renderCacheMix(cacheOutcomeMix(counters), counters[0]); renderCacheMix(mix?.requests ? mix : null, mix?.requests ?? null);
if (systemSample) { if (systemSample) {
if (d.process_rss_bytes != null) $("metric-rss").textContent = fmtBytes(d.process_rss_bytes); if (d.process_rss_bytes != null) $("metric-rss").textContent = fmtBytes(d.process_rss_bytes);
$("process-summary").hidden = d.process_threads == null; $("process-summary").hidden = d.process_threads == null;
@@ -555,7 +554,7 @@ function renderDiagnostics(status, appendSample = true, systemSample = appendSam
window.rustProxyChartScale.axes("system-chart", 100, "percent", systemSamples.length, window.rustProxyChartScale.axes("system-chart", 100, "percent", systemSamples.length,
{ top: 5 / 100, bottom: 95 / 100 }); { top: 5 / 100, bottom: 95 / 100 });
$("cache-state").textContent = t(envelope?.config.cache?.enabled ? "enabled" : "notEnabled"); $("cache-state").textContent = t(envelope?.config.cache?.enabled ? "enabled" : "notEnabled");
$("cache-counters").textContent = [c.hits, c.misses, c.bypasses].map(n => fmt(n)).join(" / "); $("cache-counters").textContent = [outcomes?.hits, outcomes?.misses, outcomes?.bypasses].map(n => n == null ? "-" : fmt(n)).join(" / ");
$("cache-objects").textContent = `${fmt(c.entries)} / ${fmtBytes(c.resident_bytes)}`; $("cache-objects").textContent = `${fmt(c.entries)} / ${fmtBytes(c.resident_bytes)}`;
$("cache-memory-breakdown").textContent = `${fmtBytes(c.resident_bytes)} / ${fmtBytes(c.transient_bytes)}`; $("cache-memory-breakdown").textContent = `${fmtBytes(c.resident_bytes)} / ${fmtBytes(c.transient_bytes)}`;
$("cache-transient-breakdown").textContent = `${fmtBytes(c.fill_bytes_active)} / ${fmtBytes(c.cold_queue_bytes)} / ${fmtBytes((Number(c.cold_write_bytes_active) || 0) + (Number(c.cold_read_bytes_active) || 0))}`; $("cache-transient-breakdown").textContent = `${fmtBytes(c.fill_bytes_active)} / ${fmtBytes(c.cold_queue_bytes)} / ${fmtBytes((Number(c.cold_write_bytes_active) || 0) + (Number(c.cold_read_bytes_active) || 0))}`;
+11 -7
View File
@@ -122,7 +122,8 @@
const previous = liveChartPrevious && liveChartPreviousAt != null const previous = liveChartPrevious && liveChartPreviousAt != null
? { values: keys.map(key => liveChartPrevious[key]), at: liveChartPreviousAt, generation: liveChartGeneration } : null; ? { values: keys.map(key => liveChartPrevious[key]), at: liveChartPreviousAt, generation: liveChartGeneration } : null;
const sample = rustProxyRateSampling.difference(previous, keys.map(key => current[key]), now, rustProxyRateSampling.cadence("cache_seconds")); const sample = rustProxyRateSampling.difference(previous, keys.map(key => current[key]), now, rustProxyRateSampling.cadence("cache_seconds"));
liveChartPrevious = current; liveChartPreviousAt = now; liveChartGeneration = sample.next.generation; liveChartPrevious = Object.fromEntries(keys.map((key, i) => [key, sample.next.values[i]]));
liveChartPreviousAt = sample.next.at; liveChartGeneration = sample.next.generation;
if (sample.deltas) { if (sample.deltas) {
keys.forEach((key, i) => { liveChartSamples[key].push(sample.deltas[i] / sample.seconds); liveChartSamples[key] = liveChartSamples[key].slice(-liveChartLimit); }); keys.forEach((key, i) => { liveChartSamples[key].push(sample.deltas[i] / sample.seconds); liveChartSamples[key] = liveChartSamples[key].slice(-liveChartLimit); });
} }
@@ -141,7 +142,10 @@
function render(data) { function render(data) {
const m = data.metrics || {}, d = data.dashboard || { domains: [], objects: [], matching_objects: 0 }, groups = d.domains || [], shownGroups = visibleDomains(data, groups); const m = data.metrics || {}, d = data.dashboard || { domains: [], objects: [], matching_objects: 0 }, groups = d.domains || [], shownGroups = visibleDomains(data, groups);
const total = field => groups.reduce((n, row) => n + (row[field] || 0), 0), all = scope() === "*"; const total = field => groups.reduce((n, row) => n + (row[field] || 0), 0), all = scope() === "*";
const hits = total("hits"), misses = total("misses"); const hits = all ? data.request_outcomes?.hits : total("hits");
const misses = all ? data.request_outcomes?.misses : total("misses");
const bypasses = all ? data.request_outcomes?.bypasses : total("bypasses");
const validOutcomes = [hits, misses, bypasses].every(n => Number.isSafeInteger(n) && n >= 0);
const hotEntries = all ? (m.entries || 0) : total("hot_entries"), coldEntries = all ? (m.cold_entries || 0) : total("cold_entries"); const hotEntries = all ? (m.entries || 0) : total("hot_entries"), coldEntries = all ? (m.cold_entries || 0) : total("cold_entries");
const hotEntryLimit = Number(data.settings?.max_entries) || 0; const hotEntryLimit = Number(data.settings?.max_entries) || 0;
const hotEntryPercent = setMeter("cp-hot-entries-meter", hotEntries, hotEntryLimit); const hotEntryPercent = setMeter("cp-hot-entries-meter", hotEntries, hotEntryLimit);
@@ -164,12 +168,12 @@
const coldPercent = setMeter("cp-cold-disk", coldBytes, coldLimit); const coldPercent = setMeter("cp-cold-disk", coldBytes, coldLimit);
$("cp-cold-bytes").textContent = fmtBytes(coldBytes); $("cp-cold-bytes").textContent = fmtBytes(coldBytes);
$("cp-cold-disk-detail").textContent = `${t("cacheLimitShort")}: ${fmtBytes(coldLimit)} · ${coldPercent.toFixed(1)}%`; $("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-ratio").textContent = validOutcomes && hits + misses > 0 ? `${fmt(hits / (hits + misses) * 100, 1)}%` : "-";
const staleHits = total("stale"), revalidatedHits = total("revalidated"); 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` : ""}`; $("cp-requests").textContent = validOutcomes ? `${number(hits)} HIT / ${number(misses)} MISS${staleHits ? ` · ${number(staleHits)} STALE` : ""}${revalidatedHits ? ` · ${number(revalidatedHits)} REVALIDATED` : ""}` : "-";
const bypasses = all ? (Number(m.bypasses) || 0) : total("bypasses"); $("cp-bypass").textContent = validOutcomes ? number(bypasses) : "-";
$("cp-bypass").textContent = number(bypasses); if (validOutcomes) renderLiveChart({ hits, misses, bypasses });
renderLiveChart({ hits: all ? (Number(m.hits) || 0) : hits, misses: all ? (Number(m.misses) || 0) : misses, bypasses }); else resetLiveChart();
$("cp-fills").textContent = `${t("cacheFills")}: ${number(m.fills_active)} · ${t("cacheCollapseWaiters")}: ${number(m.collapse_waiters)} · ${t("cacheCollapsed")}: ${number(m.collapsed_fills)}`; $("cp-fills").textContent = `${t("cacheFills")}: ${number(m.fills_active)} · ${t("cacheCollapseWaiters")}: ${number(m.collapse_waiters)} · ${t("cacheCollapsed")}: ${number(m.collapsed_fills)}`;
$("cp-saved").textContent = fmtBytes(total("saved_body_bytes")); $("cp-saved").textContent = fmtBytes(total("saved_body_bytes"));
$("cp-tier-moves").textContent = `${number(m.hot_demotions)} ↓ / ${number(m.cold_promotions)} ↑`; $("cp-tier-moves").textContent = `${number(m.hot_demotions)} ↓ / ${number(m.cold_promotions)} ↑`;
+2 -2
View File
@@ -34,8 +34,8 @@
<article class="stat stat-cache-outcomes" data-dashboard-widget="cache_outcomes"> <article class="stat stat-cache-outcomes" data-dashboard-widget="cache_outcomes">
<div class="cache-mix-header"> <div class="cache-mix-header">
<span data-i18n="cacheMixTitle">Cache outcomes</span> <span data-i18n="cacheMixTitle">Cache outcomes</span>
<small class="cache-mix-caption" id="cache-mix-caption" aria-label="HTTP requests since service start" <small class="cache-mix-caption" id="cache-mix-caption" aria-label="Classified HTTP requests since service start"
title="HTTP requests since service start">-</small> title="Classified HTTP requests since service start">-</small>
</div> </div>
<strong id="cache-mix-headline">-</strong> <strong id="cache-mix-headline">-</strong>
<div class="cache-mix-bar" id="cache-mix-bar" role="img" <div class="cache-mix-bar" id="cache-mix-bar" role="img"
+100 -24
View File
@@ -964,10 +964,7 @@ mod tests {
let mut request = HeaderMap::new(); let mut request = HeaderMap::new();
let header_name = http::HeaderName::from_bytes(name.as_bytes()).unwrap(); let header_name = http::HeaderName::from_bytes(name.as_bytes()).unwrap();
for field in fields { for field in fields {
request.append( request.append(header_name.clone(), HeaderValue::from_str(field).unwrap());
header_name.clone(),
HeaderValue::from_str(field).unwrap(),
);
} }
variant_key(&[0x52; 32], &[name.to_owned()], &request) variant_key(&[0x52; 32], &[name.to_owned()], &request)
} }
@@ -992,7 +989,10 @@ mod tests {
); );
assert_eq!( assert_eq!(
keyed("accept", &["text/plain;profile=\"a,b\", application/json"]), keyed("accept", &["text/plain;profile=\"a,b\", application/json"]),
keyed("accept", &["text/plain;profile=\"a,b\"", "application/json"]) keyed(
"accept",
&["text/plain;profile=\"a,b\"", "application/json"]
)
); );
assert_eq!( assert_eq!(
keyed("if-none-match", &["\"tag,a\", W/\"tag-b\""]), keyed("if-none-match", &["\"tag,a\", W/\"tag-b\""]),
@@ -1021,12 +1021,18 @@ mod tests {
keyed("x-custom", &["foo, bar"]), keyed("x-custom", &["foo, bar"]),
keyed("x-custom", &["foo,bar"]) keyed("x-custom", &["foo,bar"])
); );
assert_eq!(keyed("x-custom", &[" token "]), keyed("x-custom", &["token"])); assert_eq!(
keyed("x-custom", &[" token "]),
keyed("x-custom", &["token"])
);
assert_ne!( assert_ne!(
keyed("x-custom", &["foo", "bar"]), keyed("x-custom", &["foo", "bar"]),
keyed("x-custom", &["foo,bar"]) keyed("x-custom", &["foo,bar"])
); );
assert_ne!(keyed("user-agent", &["Agent"]), keyed("user-agent", &["agent"])); assert_ne!(
keyed("user-agent", &["Agent"]),
keyed("user-agent", &["agent"])
);
assert_ne!( assert_ne!(
keyed("cookie", &["session=one; theme=dark"]), keyed("cookie", &["session=one; theme=dark"]),
keyed("cookie", &["session=two; theme=dark"]) keyed("cookie", &["session=two; theme=dark"])
@@ -1082,7 +1088,9 @@ mod tests {
equivalent.insert("user-agent", HeaderValue::from_static("AgentOne")); equivalent.insert("user-agent", HeaderValue::from_static("AgentOne"));
let equivalent_ticket = ticket(&cache, &equivalent); let equivalent_ticket = ticket(&cache, &equivalent);
assert_eq!(original_ticket.key, equivalent_ticket.key); assert_eq!(original_ticket.key, equivalent_ticket.key);
let hit = cache.get(&equivalent_ticket).expect("semantically equivalent Vary HIT"); let hit = cache
.get(&equivalent_ticket)
.expect("semantically equivalent Vary HIT");
assert_eq!( assert_eq!(
hit.response.into_body().collect().await.unwrap().to_bytes(), hit.response.into_body().collect().await.unwrap().to_bytes(),
Bytes::from_static(b"public-variant") Bytes::from_static(b"public-variant")
@@ -1296,6 +1304,21 @@ mod tests {
let mut validation = HeaderMap::new(); let mut validation = HeaderMap::new();
validation.insert("cache-control", HeaderValue::from_static("no-cache")); validation.insert("cache-control", HeaderValue::from_static("no-cache"));
validation.insert("etag", HeaderValue::from_static("\"origin\"")); validation.insert("etag", HeaderValue::from_static("\"origin\""));
let hits_before = cache.view().hits;
assert!(cache.publish_background_revalidated(
t.clone(),
&candidate,
candidate.merge_validation_headers(&validation),
&validation,
&s,
Duration::ZERO,
));
assert_eq!(
cache.view().hits,
hits_before,
"background 304 is not a client hit"
);
let candidate = cache.revalidation(&t).expect("background-validated body");
let merged = candidate.merge_validation_headers(&validation); let merged = candidate.merge_validation_headers(&validation);
let hit = cache let hit = cache
.publish_revalidated( .publish_revalidated(
@@ -1307,6 +1330,7 @@ mod tests {
Duration::ZERO, Duration::ZERO,
) )
.expect("validated body can be delivered"); .expect("validated body can be delivered");
assert_eq!(cache.view().hits, hits_before + 1);
assert_eq!( assert_eq!(
hit.response.into_body().collect().await.unwrap().to_bytes(), hit.response.into_body().collect().await.unwrap().to_bytes(),
Bytes::from_static(b"payload") Bytes::from_static(b"payload")
@@ -1448,16 +1472,26 @@ mod tests {
h.append("vary", HeaderValue::from_static("Cookie, Accept-Language")); h.append("vary", HeaderValue::from_static("Cookie, Accept-Language"));
h.append("vary", HeaderValue::from_static("X-Theme, cookie")); h.append("vary", HeaderValue::from_static("X-Theme, cookie"));
assert!(normalize_static_cookie_vary( assert!(normalize_static_cookie_vary(
StatusCode::OK, &mut h, &settings, Duration::ZERO, true, StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE, &ResponseOverrides::NONE,
)); ));
assert_eq!(h["vary"], "Accept-Language, X-Theme"); assert_eq!(h["vary"], "Accept-Language, X-Theme");
assert_eq!( assert_eq!(
plan(StatusCode::OK, &h, &settings, Duration::ZERO).unwrap().vary, plan(StatusCode::OK, &h, &settings, Duration::ZERO)
.unwrap()
.vary,
vec!["accept-language".to_owned(), "x-theme".to_owned()] vec!["accept-language".to_owned(), "x-theme".to_owned()]
); );
assert!(!normalize_static_cookie_vary( assert!(!normalize_static_cookie_vary(
StatusCode::OK, &mut h, &settings, Duration::ZERO, true, StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE, &ResponseOverrides::NONE,
)); ));
} }
@@ -1477,12 +1511,21 @@ mod tests {
let settings = Settings::default(); let settings = Settings::default();
let mut h = headers(policy); let mut h = headers(policy);
h.insert("vary", vary.parse().unwrap()); h.insert("vary", vary.parse().unwrap());
if has_cookie { h.insert("set-cookie", HeaderValue::from_static("session=secret")); } if has_cookie {
h.insert("set-cookie", HeaderValue::from_static("session=secret"));
}
let original = h.clone(); let original = h.clone();
assert!(!normalize_static_cookie_vary( assert!(
StatusCode::OK, &mut h, &settings, Duration::ZERO, true, !normalize_static_cookie_vary(
StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE, &ResponseOverrides::NONE,
), "{policy}, {vary}"); ),
"{policy}, {vary}"
);
assert_eq!(h, original, "{policy}, {vary}"); assert_eq!(h, original, "{policy}, {vary}");
} }
let mut settings = Settings::default(); let mut settings = Settings::default();
@@ -1490,16 +1533,28 @@ mod tests {
h.insert("vary", HeaderValue::from_static("Cookie")); h.insert("vary", HeaderValue::from_static("Cookie"));
settings.static_ignore_vary_cookie = false; settings.static_ignore_vary_cookie = false;
assert!(!normalize_static_cookie_vary( assert!(!normalize_static_cookie_vary(
StatusCode::OK, &mut h, &settings, Duration::ZERO, true, StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE, &ResponseOverrides::NONE,
)); ));
settings.static_ignore_vary_cookie = true; settings.static_ignore_vary_cookie = true;
assert!(!normalize_static_cookie_vary( assert!(!normalize_static_cookie_vary(
StatusCode::OK, &mut h, &settings, Duration::ZERO, false, StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
false,
&ResponseOverrides::NONE, &ResponseOverrides::NONE,
)); ));
assert!(!normalize_static_cookie_vary( assert!(!normalize_static_cookie_vary(
StatusCode::NOT_MODIFIED, &mut h, &settings, Duration::ZERO, true, StatusCode::NOT_MODIFIED,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE, &ResponseOverrides::NONE,
)); ));
assert_eq!(h["vary"], "Cookie"); assert_eq!(h["vary"], "Cookie");
@@ -1521,10 +1576,17 @@ mod tests {
h.insert("etag", HeaderValue::from_static("\"asset\"")); h.insert("etag", HeaderValue::from_static("\"asset\""));
} }
let original = h.clone(); let original = h.clone();
assert!(!normalize_static_cookie_vary( assert!(
StatusCode::OK, &mut h, &settings, Duration::ZERO, true, !normalize_static_cookie_vary(
StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE, &ResponseOverrides::NONE,
), "{policy}"); ),
"{policy}"
);
assert_eq!(h, original, "{policy}"); assert_eq!(h, original, "{policy}");
} }
@@ -1535,7 +1597,11 @@ mod tests {
let mut h = headers("public"); let mut h = headers("public");
h.insert("vary", HeaderValue::from_static("Cookie")); h.insert("vary", HeaderValue::from_static("Cookie"));
assert!(normalize_static_cookie_vary( assert!(normalize_static_cookie_vary(
StatusCode::OK, &mut h, &settings, Duration::ZERO, true, StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE, &ResponseOverrides::NONE,
)); ));
assert!(!h.contains_key("vary")); assert!(!h.contains_key("vary"));
@@ -1545,9 +1611,19 @@ mod tests {
fn static_vary_cookie_vhost_override_inherits_and_can_disable() { fn static_vary_cookie_vhost_override_inherits_and_can_disable() {
let global = Settings::default(); let global = Settings::default();
let mut overrides = Overrides::default(); let mut overrides = Overrides::default();
assert!(overrides.resolve(&global).unwrap().static_ignore_vary_cookie); assert!(
overrides
.resolve(&global)
.unwrap()
.static_ignore_vary_cookie
);
overrides.static_ignore_vary_cookie = Some(false); overrides.static_ignore_vary_cookie = Some(false);
assert!(!overrides.resolve(&global).unwrap().static_ignore_vary_cookie); assert!(
!overrides
.resolve(&global)
.unwrap()
.static_ignore_vary_cookie
);
} }
#[test] #[test]
+50 -7
View File
@@ -10,6 +10,48 @@ impl Cache {
None None
} }
pub fn publish_revalidated( pub fn publish_revalidated(
&self,
ticket: Ticket,
cached: &Revalidation,
headers: HeaderMap,
validation_headers: &HeaderMap,
settings: &Settings,
response_delay: Duration,
) -> Option<Hit> {
self.publish_validated(
ticket,
cached,
headers,
validation_headers,
settings,
response_delay,
true,
)
}
pub(crate) fn publish_background_revalidated(
&self,
ticket: Ticket,
cached: &Revalidation,
headers: HeaderMap,
validation_headers: &HeaderMap,
settings: &Settings,
response_delay: Duration,
) -> bool {
self.publish_validated(
ticket,
cached,
headers,
validation_headers,
settings,
response_delay,
false,
)
.is_some()
}
#[allow(clippy::too_many_arguments)]
fn publish_validated(
&self, &self,
ticket: Ticket, ticket: Ticket,
cached: &Revalidation, cached: &Revalidation,
@@ -17,6 +59,7 @@ impl Cache {
validation_headers: &HeaderMap, validation_headers: &HeaderMap,
settings: &Settings, settings: &Settings,
response_delay: Duration, response_delay: Duration,
client_hit: bool,
) -> Option<Hit> { ) -> Option<Hit> {
let plan = plan(StatusCode::OK, &headers, settings, response_delay)?; let plan = plan(StatusCode::OK, &headers, settings, response_delay)?;
if cached.body.len() > settings.max_object_bytes { if cached.body.len() > settings.max_object_bytes {
@@ -28,7 +71,7 @@ impl Cache {
} }
} }
headers.remove("x-request-id"); headers.remove("x-request-id");
let hits = cached.hits.saturating_add(1); let hits = cached.hits.saturating_add(if client_hit { 1 } else { 0 });
let age = plan.initial_age.as_secs(); let age = plan.initial_age.as_secs();
let remaining_ttl = plan.ttl.saturating_sub(age); let remaining_ttl = plan.ttl.saturating_sub(age);
let vary = plan.vary.clone(); let vary = plan.vary.clone();
@@ -96,11 +139,13 @@ impl Cache {
if cached.storage_key != storage_key { if cached.storage_key != storage_key {
self.discard_storage_key(&cached.storage_key); self.discard_storage_key(&cached.storage_key);
} }
if client_hit {
self.counters.hits.fetch_add(1, Ordering::Relaxed); self.counters.hits.fetch_add(1, Ordering::Relaxed);
}
let mut response = cached.response(headers); let mut response = cached.response(headers);
response.headers_mut().insert(::http::header::AGE, response
HeaderValue::from(age), .headers_mut()
); .insert(::http::header::AGE, HeaderValue::from(age));
Some(Hit { Some(Hit {
response, response,
body: cached.body.clone(), body: cached.body.clone(),
@@ -205,9 +250,7 @@ impl Cache {
candidate.finish(); candidate.finish();
return Response::from_parts(parts, body); return Response::from_parts(parts, body);
} }
// A HEAD miss is fetched upstream as GET. The proxy must still consume
// the GET body to publish this candidate before stripping the body for
// the HEAD client. Mark *only* responses with a live fill candidate.
let mut response = Response::from_parts( let mut response = Response::from_parts(
parts, parts,
Body::new(FillBody { Body::new(FillBody {
+40 -1
View File
@@ -38,6 +38,8 @@ pub struct Metrics {
pub websocket_duration_us: AtomicU64, pub websocket_duration_us: AtomicU64,
pub requests: AtomicU64, pub requests: AtomicU64,
pub completed: AtomicU64, pub completed: AtomicU64,
pub completed_success: AtomicU64,
cache_request_outcomes: [AtomicU64; 4],
pub active: AtomicU64, pub active: AtomicU64,
pub errors: AtomicU64, pub errors: AtomicU64,
pub rejected_requests: AtomicU64, pub rejected_requests: AtomicU64,
@@ -52,6 +54,13 @@ pub struct Metrics {
pub status_4xx: AtomicU64, pub status_4xx: AtomicU64,
pub status_5xx: AtomicU64, pub status_5xx: AtomicU64,
} }
#[derive(Debug, Default, PartialEq, Eq, Serialize)]
pub struct CacheRequestOutcomes {
pub hits: u64,
pub misses: u64,
pub bypasses: u64,
pub other: u64,
}
#[derive(Serialize)] #[derive(Serialize)]
pub struct View { pub struct View {
pub http1_requests: u64, pub http1_requests: u64,
@@ -83,6 +92,8 @@ pub struct View {
pub websocket_bytes_out: u64, pub websocket_bytes_out: u64,
pub requests: u64, pub requests: u64,
pub completed: u64, pub completed: u64,
pub completed_success: u64,
pub cache_request_outcomes: CacheRequestOutcomes,
pub active: u64, pub active: u64,
pub errors: u64, pub errors: u64,
pub rejected_requests: u64, pub rejected_requests: u64,
@@ -97,6 +108,26 @@ fn n(value: &AtomicU64) -> u64 {
value.load(Ordering::Relaxed) value.load(Ordering::Relaxed)
} }
impl Metrics { impl Metrics {
pub(crate) fn record_cache_request_outcome(&self, status: u16) {
let index = match status {
1 => 0,
2 => 1,
3 => 2,
_ => 3,
};
self.cache_request_outcomes[index].fetch_add(1, Ordering::Relaxed);
}
pub fn cache_request_outcomes(&self) -> CacheRequestOutcomes {
let [hits, misses, bypasses, other] = self.cache_request_outcomes.each_ref().map(n);
CacheRequestOutcomes {
hits,
misses,
bypasses,
other,
}
}
pub fn record_compression(&self, encoding: crate::compression::AppliedEncoding) { pub fn record_compression(&self, encoding: crate::compression::AppliedEncoding) {
let counter = match encoding { let counter = match encoding {
crate::compression::AppliedEncoding::Gzip => &self.compression_gzip, crate::compression::AppliedEncoding::Gzip => &self.compression_gzip,
@@ -139,6 +170,8 @@ impl Metrics {
websocket_bytes_out: n(&self.websocket_bytes_out), websocket_bytes_out: n(&self.websocket_bytes_out),
requests: n(&self.requests), requests: n(&self.requests),
completed, completed,
completed_success: n(&self.completed_success),
cache_request_outcomes: self.cache_request_outcomes(),
active: n(&self.active), active: n(&self.active),
errors: n(&self.errors), errors: n(&self.errors),
rejected_requests: n(&self.rejected_requests), rejected_requests: n(&self.rejected_requests),
@@ -156,11 +189,17 @@ impl Metrics {
} }
pub fn prometheus(&self, logs_dropped: u64, revision: u64) -> String { pub fn prometheus(&self, logs_dropped: u64, revision: u64) -> String {
let mut out = String::new(); let mut out = String::new();
let cache = self.cache_request_outcomes();
let entries = [ let entries = [
("cache_request_hits_total", "counter", "Public requests classified as cache HIT.", cache.hits),
("cache_request_misses_total", "counter", "Public requests classified as cache MISS.", cache.misses),
("cache_request_bypasses_total", "counter", "Public requests classified as cache BYPASS.", cache.bypasses),
("cache_request_other_total", "counter", "Public requests without a final cache decision.", cache.other),
("requests_completed_success_total", "counter", "Admitted exchanges completed without a recorded error.", n(&self.completed_success)),
( (
"http1_requests_total", "http1_requests_total",
"counter", "counter",
"Public requests received using HTTP/1.1.", "Public requests received using HTTP/1.0 or HTTP/1.1.",
n(&self.http1_requests), n(&self.http1_requests),
), ),
( (
+8 -4
View File
@@ -214,10 +214,12 @@ fn summary_from_snapshot(detail: &Value, rates: crate::metrics::SummaryRates) ->
.as_u64() .as_u64()
.zip(system["memory_total_bytes"].as_u64()) .zip(system["memory_total_bytes"].as_u64())
.and_then(|(used, total)| percentage(used, total)); .and_then(|(used, total)| percentage(used, total));
let request_error_percent = percentage( let errors = number(&requests["errors_total"]);
number(&requests["errors_total"]), let completed_for_ratio = requests["completed_success_total"]
number(&requests["completed_total"]), .as_u64()
); .map(|success| success.saturating_add(errors))
.unwrap_or_else(|| number(&requests["completed_total"]));
let request_error_percent = percentage(errors, completed_for_ratio);
let web_requests = detail["web_server"]["services"] let web_requests = detail["web_server"]["services"]
.as_array() .as_array()
.map_or(0u64, |items| { .map_or(0u64, |items| {
@@ -481,6 +483,8 @@ fn snapshot(app: &App) -> Value {
let requests = json!({ let requests = json!({
"total": metrics.requests, "completed_total": metrics.completed, "total": metrics.requests, "completed_total": metrics.completed,
"completed_success_total": metrics.completed_success,
"cache_request_outcomes": metrics.cache_request_outcomes,
"active": metrics.active, "errors_total": metrics.errors, "active": metrics.active, "errors_total": metrics.errors,
"rejected_total": metrics.rejected_requests, "rejected_total": metrics.rejected_requests,
"status": { "status": {
+47
View File
@@ -90,6 +90,8 @@ pub struct Exchange {
pub status: AtomicU16, pub status: AtomicU16,
pub cache_status: AtomicU16, pub cache_status: AtomicU16,
pub cache_reason: Mutex<&'static str>, pub cache_reason: Mutex<&'static str>,
pub cache_scope: Mutex<Option<(String, String)>>,
pub cache_outcome_recorded: AtomicBool,
pub failed: AtomicBool, pub failed: AtomicBool,
pub aborted: AtomicBool, pub aborted: AtomicBool,
pub request_bytes: AtomicU64, pub request_bytes: AtomicU64,
@@ -100,6 +102,43 @@ pub struct Exchange {
pub _permit: OwnedSemaphorePermit, pub _permit: OwnedSemaphorePermit,
} }
impl Exchange { impl Exchange {
pub fn set_cache_outcome(&self, scope: &str, host: &str, status: u16, reason: &'static str) {
self.cache_status.store(status, Ordering::Relaxed);
*self.cache_reason.lock().unwrap_or_else(|e| e.into_inner()) = reason;
let mut target = self.cache_scope.lock().unwrap_or_else(|e| e.into_inner());
if !target
.as_ref()
.is_some_and(|(s, h)| s == scope && h == host)
{
*target = Some((scope.to_owned(), host.to_owned()));
}
}
pub fn reset_cache_outcome(&self) {
self.cache_status.store(0, Ordering::Relaxed);
*self.cache_reason.lock().unwrap_or_else(|e| e.into_inner()) = "not_proxy_response";
*self.cache_scope.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
pub fn finish_cache_outcome(&self, cache: &crate::cache::Cache) {
if self.cache_outcome_recorded.swap(true, Ordering::Relaxed) {
return;
}
let status = self.cache_status.load(Ordering::Relaxed);
self.metrics.record_cache_request_outcome(status);
let outcome = match status {
1 => "HIT",
2 => "MISS",
3 => "BYPASS",
_ => return,
};
let reason = *self.cache_reason.lock().unwrap_or_else(|e| e.into_inner());
let target = self.cache_scope.lock().unwrap_or_else(|e| e.into_inner());
if let Some((scope, host)) = target.as_ref() {
cache.record(scope, host, outcome, reason);
}
}
pub fn set_source(&self, source: ExchangeSource) { pub fn set_source(&self, source: ExchangeSource) {
self.source.store(source as u8, Ordering::Relaxed); self.source.store(source as u8, Ordering::Relaxed);
} }
@@ -157,6 +196,10 @@ impl Exchange {
} }
impl Drop for Exchange { impl Drop for Exchange {
fn drop(&mut self) { fn drop(&mut self) {
if !self.cache_outcome_recorded.swap(true, Ordering::Relaxed) {
self.reset_cache_outcome();
self.metrics.record_cache_request_outcome(0);
}
let status = self.status.load(Ordering::Relaxed); let status = self.status.load(Ordering::Relaxed);
let failed = self.failed.load(Ordering::Relaxed); let failed = self.failed.load(Ordering::Relaxed);
let aborted = self.aborted.load(Ordering::Relaxed); let aborted = self.aborted.load(Ordering::Relaxed);
@@ -177,6 +220,10 @@ impl Drop for Exchange {
.fetch_add(duration.as_micros() as u64, Ordering::Relaxed); .fetch_add(duration.as_micros() as u64, Ordering::Relaxed);
if failed || aborted || status >= 500 { if failed || aborted || status >= 500 {
self.metrics.errors.fetch_add(1, Ordering::Relaxed); self.metrics.errors.fetch_add(1, Ordering::Relaxed);
} else {
self.metrics
.completed_success
.fetch_add(1, Ordering::Relaxed);
} }
match status / 100 { match status / 100 {
1 => &self.metrics.status_1xx, 1 => &self.metrics.status_1xx,
+46
View File
@@ -38,6 +38,8 @@ mod tests {
status: AtomicU16::new(200), status: AtomicU16::new(200),
cache_status: AtomicU16::new(0), cache_status: AtomicU16::new(0),
cache_reason: Mutex::new("not_proxy_response"), cache_reason: Mutex::new("not_proxy_response"),
cache_scope: Mutex::new(None),
cache_outcome_recorded: AtomicBool::new(false),
failed: AtomicBool::new(false), failed: AtomicBool::new(false),
aborted: AtomicBool::new(false), aborted: AtomicBool::new(false),
request_bytes: AtomicU64::new(0), request_bytes: AtomicU64::new(0),
@@ -49,6 +51,50 @@ mod tests {
}); });
(exchange, slots) (exchange, slots)
} }
#[tokio::test]
async fn cache_outcome_is_final_and_idempotent() {
let (exchange, _) = observation().await;
let metrics = exchange.metrics.clone();
let cache = crate::cache::Cache::new(1);
exchange.set_cache_outcome("site", "localhost", 2, "cache_miss");
exchange.set_cache_outcome("site", "localhost", 1, "cache_hit");
exchange.finish_cache_outcome(&cache);
exchange.finish_cache_outcome(&cache);
drop(exchange);
let outcomes = metrics.cache_request_outcomes();
assert_eq!(
(
outcomes.hits,
outcomes.misses,
outcomes.bypasses,
outcomes.other
),
(1, 0, 0, 0)
);
let totals = cache.scope_totals();
assert_eq!(totals["site"].hits, 1);
assert_eq!(totals["site"].misses, 0);
assert_eq!(metrics.completed_success.load(Ordering::Relaxed), 1);
}
#[tokio::test]
async fn pre_header_cancellation_discards_provisional_cache_outcome() {
let (exchange, _) = observation().await;
let metrics = exchange.metrics.clone();
exchange.set_cache_outcome("site", "localhost", 2, "cache_miss");
drop(exchange);
let outcomes = metrics.cache_request_outcomes();
assert_eq!(
(
outcomes.hits,
outcomes.misses,
outcomes.bypasses,
outcomes.other
),
(0, 0, 0, 1)
);
}
#[tokio::test] #[tokio::test]
async fn optimized_empty_request_keeps_exchange_until_response() { async fn optimized_empty_request_keeps_exchange_until_response() {
let (exchange, slots) = observation().await; let (exchange, slots) = observation().await;
+56 -28
View File
@@ -55,10 +55,9 @@ fn schedule_proactive_refresh(
if !refreshed { if !refreshed {
return; return;
} }
context.state.cache.record( context.state.cache.record_reason(
&context.scope, &context.scope,
&context.host, &context.host,
"HIT",
"cache_proactive_refreshed", "cache_proactive_refreshed",
); );
let Some(next) = context.state.cache.revalidation_tiered(&ticket).await else { let Some(next) = context.state.cache.revalidation_tiered(&ticket).await else {
@@ -95,9 +94,10 @@ fn enforce_local_page_no_cache(response: &mut Response) {
] { ] {
response.headers_mut().remove(name); response.headers_mut().remove(name);
} }
response response.headers_mut().insert(
.headers_mut() ::http::header::CACHE_CONTROL,
.insert(::http::header::CACHE_CONTROL, HeaderValue::from_static("no-store")); HeaderValue::from_static("no-store"),
);
} }
fn error(status: StatusCode, detail: &'static str) -> Response { fn error(status: StatusCode, detail: &'static str) -> Response {
@@ -108,10 +108,12 @@ fn error(status: StatusCode, detail: &'static str) -> Response {
); );
let mut response = if let Some(html) = crate::pages::builtin_gateway_error(status) { let mut response = if let Some(html) = crate::pages::builtin_gateway_error(status) {
let mut response = (status, html).into_response(); let mut response = (status, html).into_response();
response.headers_mut().insert(::http::header::CONTENT_TYPE, response.headers_mut().insert(
::http::header::CONTENT_TYPE,
HeaderValue::from_static("text/html; charset=utf-8"), HeaderValue::from_static("text/html; charset=utf-8"),
); );
response.headers_mut().insert(::http::header::X_CONTENT_TYPE_OPTIONS, response.headers_mut().insert(
::http::header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"), HeaderValue::from_static("nosniff"),
); );
response response
@@ -123,10 +125,12 @@ fn error(status: StatusCode, detail: &'static str) -> Response {
); );
(status, body).into_response() (status, body).into_response()
}; };
response response.headers_mut().insert(
.headers_mut() ::http::header::CACHE_CONTROL,
.insert(::http::header::CACHE_CONTROL, HeaderValue::from_static("no-store")); HeaderValue::from_static("no-store"),
response.headers_mut().insert(::http::header::X_CONTENT_TYPE_OPTIONS, );
response.headers_mut().insert(
::http::header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"), HeaderValue::from_static("nosniff"),
); );
response.extensions_mut().insert(LocalGeneratedResponse); response.extensions_mut().insert(LocalGeneratedResponse);
@@ -159,7 +163,9 @@ fn local_location_response(spec: &crate::vhost::LocationResponse, method: &Metho
}) })
.unwrap_or_else(|_| (StatusCode::INTERNAL_SERVER_ERROR, Body::empty()).into_response()); .unwrap_or_else(|_| (StatusCode::INTERNAL_SERVER_ERROR, Body::empty()).into_response());
if let Ok(value) = HeaderValue::from_str(&spec.content_type) { if let Ok(value) = HeaderValue::from_str(&spec.content_type) {
response.headers_mut().insert(::http::header::CONTENT_TYPE, value); response
.headers_mut()
.insert(::http::header::CONTENT_TYPE, value);
} }
response response
} }
@@ -296,7 +302,8 @@ fn finish_headers(
.unwrap_or(&snapshot.envelope.config.diagnostic_headers) .unwrap_or(&snapshot.envelope.config.diagnostic_headers)
.apply(response.headers_mut(), request_id); .apply(response.headers_mut(), request_id);
if frontend.is_some_and(|f| f.auth_provider.is_some() || f.basic_auth.is_some()) { if frontend.is_some_and(|f| f.auth_provider.is_some() || f.basic_auth.is_some()) {
response.headers_mut().insert(::http::header::CACHE_CONTROL, response.headers_mut().insert(
::http::header::CACHE_CONTROL,
HeaderValue::from_static("private, no-store"), HeaderValue::from_static("private, no-store"),
); );
} }
@@ -328,9 +335,15 @@ fn server_timing_value(
crate::vhost::TimingHeaderNames::Cdn => ("edge", "origin", "cdn-cache"), crate::vhost::TimingHeaderNames::Cdn => ("edge", "origin", "cdn-cache"),
crate::vhost::TimingHeaderNames::Legacy => ("proxy", "origin", "cache"), crate::vhost::TimingHeaderNames::Legacy => ("proxy", "origin", "cache"),
}; };
let mut values = vec![format!("{total_name};dur={:.2}", total.as_secs_f64() * 1000.0)]; let mut values = vec![format!(
"{total_name};dur={:.2}",
total.as_secs_f64() * 1000.0
)];
if let Some(origin) = origin { if let Some(origin) = origin {
values.push(format!("{origin_name};dur={:.2}", origin.as_secs_f64() * 1000.0)); values.push(format!(
"{origin_name};dur={:.2}",
origin.as_secs_f64() * 1000.0
));
} }
if let Some(cache) = cache { if let Some(cache) = cache {
values.push(format!("{cache_name};desc=\"{cache}\"")); values.push(format!("{cache_name};desc=\"{cache}\""));
@@ -349,33 +362,39 @@ fn apply_timing_headers(
let Some(frontend) = frontend.filter(|frontend| frontend.timing_headers) else { let Some(frontend) = frontend.filter(|frontend| frontend.timing_headers) else {
return; return;
}; };
let reason = *exchange.cache_reason.lock().unwrap_or_else(|e| e.into_inner()); let reason = *exchange
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner());
let value = server_timing_value( let value = server_timing_value(
frontend.timing_header_names, frontend.timing_header_names,
exchange.started.elapsed(), exchange.started.elapsed(),
response.extensions().get::<OriginTiming>().map(|origin| origin.0), response
.extensions()
.get::<OriginTiming>()
.map(|origin| origin.0),
server_timing_cache_desc(status, reason), server_timing_cache_desc(status, reason),
); );
if let Ok(value) = HeaderValue::from_str(&value) { if let Ok(value) = HeaderValue::from_str(&value) {
response.headers_mut().append("server-timing", value); response.headers_mut().append("server-timing", value);
} }
if let Some(value) = &frontend.timing_allow_origin { if let Some(value) = &frontend.timing_allow_origin {
response.headers_mut().insert("timing-allow-origin", value.clone()); response
.headers_mut()
.insert("timing-allow-origin", value.clone());
} }
} }
// Docker publications use "docker-<agent>-<service hash>/docker" internally.
// Keep those stable internal IDs for routing, logs, and metrics, but avoid
// repeating the Docker marker in the opt-in response diagnostic header.
fn backend_diagnostic_label(id: &str) -> std::borrow::Cow<'_, str> { fn backend_diagnostic_label(id: &str) -> std::borrow::Cow<'_, str> {
let Some(name) = id.strip_prefix("docker-").and_then(|id| id.strip_suffix("/docker")) else { let Some(name) = id
.strip_prefix("docker-")
.and_then(|id| id.strip_suffix("/docker"))
else {
return std::borrow::Cow::Borrowed(id); return std::borrow::Cow::Borrowed(id);
}; };
let Some((agent, hash)) = name.rsplit_once('-') else { let Some((agent, hash)) = name.rsplit_once('-') else {
return std::borrow::Cow::Borrowed(id); return std::borrow::Cow::Borrowed(id);
}; };
// The generated Docker vhost ID ends in a 12-character SHA-256 prefix.
// Do not rewrite ordinary or malformed backend identifiers.
if agent.is_empty() || hash.len() != 12 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) { if agent.is_empty() || hash.len() != 12 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
return std::borrow::Cow::Borrowed(id); return std::borrow::Cow::Borrowed(id);
} }
@@ -388,12 +407,19 @@ fn apply_backend_diagnostic_values(
backend_timing_header: bool, backend_timing_header: bool,
) { ) {
const BACKEND: ::http::HeaderName = ::http::HeaderName::from_static("x-rustproxy-backend"); const BACKEND: ::http::HeaderName = ::http::HeaderName::from_static("x-rustproxy-backend");
const LEGACY_BACKEND: ::http::HeaderName = ::http::HeaderName::from_static("x-rust-proxy-backend"); const LEGACY_BACKEND: ::http::HeaderName =
::http::HeaderName::from_static("x-rust-proxy-backend");
const LEGACY_BACKEND_TIME: ::http::HeaderName = const LEGACY_BACKEND_TIME: ::http::HeaderName =
::http::HeaderName::from_static("x-rust-proxy-backend-time"); ::http::HeaderName::from_static("x-rust-proxy-backend-time");
const BACKEND_TIME: ::http::HeaderName = ::http::HeaderName::from_static("x-rustproxy-backend-time"); const BACKEND_TIME: ::http::HeaderName =
::http::HeaderName::from_static("x-rustproxy-backend-time");
let headers = response.headers_mut(); let headers = response.headers_mut();
for name in [&BACKEND, &LEGACY_BACKEND, &LEGACY_BACKEND_TIME, &BACKEND_TIME] { for name in [
&BACKEND,
&LEGACY_BACKEND,
&LEGACY_BACKEND_TIME,
&BACKEND_TIME,
] {
if headers.contains_key(name) { if headers.contains_key(name) {
headers.remove(name); headers.remove(name);
} }
@@ -478,7 +504,9 @@ async fn normalize_h3_h1_unknown_body(
if request.version() != Version::HTTP_3 if request.version() != Version::HTTP_3
|| upstream_version != Version::HTTP_11 || upstream_version != Version::HTTP_11
|| method == Method::CONNECT || method == Method::CONNECT
|| request.headers().contains_key(::http::header::CONTENT_LENGTH) || request
.headers()
.contains_key(::http::header::CONTENT_LENGTH)
|| request.body().size_hint().exact().is_some() || request.body().size_hint().exact().is_some()
{ {
return Ok(()); return Ok(());
+3
View File
@@ -165,6 +165,9 @@ async fn execute_error_fallback(
tracing::warn!(vhost = %frontend.id, route = %route.id, target = %fallback.target, "error fallback request body is not replayable"); tracing::warn!(vhost = %frontend.id, route = %route.id, target = %fallback.target, "error fallback request body is not replayable");
return None; return None;
}; };
if let Some(exchange) = &template.exchange {
exchange.reset_cache_outcome();
}
let request = template.rebuild( let request = template.rebuild(
body.clone(), body.clone(),
peer, peer,
+120 -22
View File
@@ -89,6 +89,23 @@ mod cache_fast_path_tests {
} }
} }
fn assert_cache_outcomes(fixture: &Fixture, hits: u64, misses: u64, bypasses: u64, other: u64) {
let outcomes = fixture.app.metrics.cache_request_outcomes();
assert_eq!(
(
outcomes.hits,
outcomes.misses,
outcomes.bypasses,
outcomes.other
),
(hits, misses, bypasses, other)
);
let totals = fixture.app.cache.scope_totals();
assert_eq!(totals.values().map(|v| v.hits).sum::<u64>(), hits);
assert_eq!(totals.values().map(|v| v.misses).sum::<u64>(), misses);
assert_eq!(totals.values().map(|v| v.bypasses).sum::<u64>(), bypasses);
}
async fn send( async fn send(
app: Arc<App>, app: Arc<App>,
method: Method, method: Method,
@@ -244,6 +261,7 @@ mod cache_fast_path_tests {
.await; .await;
assert_eq!(allowed.status, StatusCode::OK); assert_eq!(allowed.status, StatusCode::OK);
assert_eq!(origin.requests.load(Ordering::Relaxed), 1); assert_eq!(origin.requests.load(Ordering::Relaxed), 1);
assert_cache_outcomes(&fixture, 0, 0, 1, 1);
fixture.stop().await; fixture.stop().await;
} }
@@ -482,15 +500,18 @@ mod cache_fast_path_tests {
_ => "public, max-age=600", _ => "public, max-age=600",
}), }),
); );
response response.headers_mut().insert(
.headers_mut() "vary",
.insert("vary", HeaderValue::from_static(if parts.uri.path().starts_with("/vary-cookie") { HeaderValue::from_static(if parts.uri.path().starts_with("/vary-cookie") {
"Cookie, X-Variant" "Cookie, X-Variant"
} else { } else {
"X-Variant" "X-Variant"
})); }),
);
if parts.uri.path() == "/vary-cookie-set.css" { if parts.uri.path() == "/vary-cookie-set.css" {
response.headers_mut().insert("set-cookie", HeaderValue::from_static("session=private")); response
.headers_mut()
.insert("set-cookie", HeaderValue::from_static("session=private"));
} }
response response
.headers_mut() .headers_mut()
@@ -772,6 +793,7 @@ mod cache_fast_path_tests {
cache_chain(&posted.headers).last().copied(), cache_chain(&posted.headers).last().copied(),
Some("RustProxy; fwd=method; detail=\"request_method\""), Some("RustProxy; fwd=method; detail=\"request_method\""),
); );
assert_cache_outcomes(&fixture, 1, 1, 1, 0);
fixture.stop().await; fixture.stop().await;
} }
@@ -790,6 +812,7 @@ mod cache_fast_path_tests {
Some("RustProxy; fwd=stale; fwd-status=503; detail=\"cache_stale_if_error\""), Some("RustProxy; fwd=stale; fwd-status=503; detail=\"cache_stale_if_error\""),
); );
assert_eq!(origin.requests.load(Ordering::Relaxed), 2); assert_eq!(origin.requests.load(Ordering::Relaxed), 2);
assert_cache_outcomes(&fixture, 1, 1, 0, 0);
fixture.stop().await; fixture.stop().await;
} }
@@ -827,7 +850,10 @@ mod cache_fast_path_tests {
let cdn = fixture.get("/server-timing", &[]).await.headers; let cdn = fixture.get("/server-timing", &[]).await.headers;
let cdn_timing = server_timing(&cdn); let cdn_timing = server_timing(&cdn);
assert!(cdn_timing[0].starts_with("edge;dur="), "{cdn_timing:?}"); assert!(cdn_timing[0].starts_with("edge;dur="), "{cdn_timing:?}");
assert!(cdn_timing[0].ends_with(", cdn-cache;desc=\"HIT\""), "{cdn_timing:?}"); assert!(
cdn_timing[0].ends_with(", cdn-cache;desc=\"HIT\""),
"{cdn_timing:?}"
);
assert_eq!(cdn["timing-allow-origin"], "https://rum.example.com"); assert_eq!(cdn["timing-allow-origin"], "https://rum.example.com");
fixture fixture
.change(|config| { .change(|config| {
@@ -850,17 +876,25 @@ mod cache_fast_path_tests {
fixture.get("/stale-then-503", &[]).await; fixture.get("/stale-then-503", &[]).await;
let stale = server_timing(&fixture.get("/stale-then-503", &[]).await.headers); let stale = server_timing(&fixture.get("/stale-then-503", &[]).await.headers);
assert_eq!(stale.len(), 1, "{stale:?}"); assert_eq!(stale.len(), 1, "{stale:?}");
assert!(stale[0].ends_with(", proxy-cache;desc=\"STALE\""), "{stale:?}"); assert!(
stale[0].ends_with(", proxy-cache;desc=\"STALE\""),
"{stale:?}"
);
fixture.get("/cache-headers-revalidate", &[]).await; fixture.get("/cache-headers-revalidate", &[]).await;
let revalidated = let revalidated =
server_timing(&fixture.get("/cache-headers-revalidate", &[]).await.headers); server_timing(&fixture.get("/cache-headers-revalidate", &[]).await.headers);
assert_eq!(revalidated.len(), 1, "{revalidated:?}"); assert_eq!(revalidated.len(), 1, "{revalidated:?}");
assert!(revalidated[0].contains(", upstream;dur="), "{revalidated:?}"); assert!(
revalidated[0].contains(", upstream;dur="),
"{revalidated:?}"
);
assert!( assert!(
revalidated[0].ends_with(", proxy-cache;desc=\"REVALIDATED\""), revalidated[0].ends_with(", proxy-cache;desc=\"REVALIDATED\""),
"{revalidated:?}" "{revalidated:?}"
); );
fixture.change(|config| config.vhosts[0].timing_headers = false).await; fixture
.change(|config| config.vhosts[0].timing_headers = false)
.await;
let quiet = fixture.get("/server-timing", &[]).await; let quiet = fixture.get("/server-timing", &[]).await;
assert_eq!(server_timing(&quiet.headers), vec!["app;dur=7".to_owned()]); assert_eq!(server_timing(&quiet.headers), vec!["app;dur=7".to_owned()]);
let cached = fixture.get("/server-timing", &[]).await; let cached = fixture.get("/server-timing", &[]).await;
@@ -875,13 +909,25 @@ mod cache_fast_path_tests {
let mut config = config_for(origin.addr, true); let mut config = config_for(origin.addr, true);
config.cache.expose_detailed_status = true; config.cache.expose_detailed_status = true;
let fixture = Fixture::new(config).await; let fixture = Fixture::new(config).await;
assert_eq!(fixture.get("/stale-then-503", &[]).await.headers["x-cache"], "MISS"); assert_eq!(
assert_eq!(fixture.get("/stale-then-503", &[]).await.headers["x-cache"], "STALE"); 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; fixture.get("/cache-headers-revalidate", &[]).await;
let revalidated = fixture.get("/cache-headers-revalidate", &[]).await; let revalidated = fixture.get("/cache-headers-revalidate", &[]).await;
assert_eq!(revalidated.headers["x-cache"], "REVALIDATED"); assert_eq!(revalidated.headers["x-cache"], "REVALIDATED");
assert_eq!(fixture.get("/server-timing", &[]).await.headers["x-cache"], "MISS"); assert_eq!(
assert_eq!(fixture.get("/server-timing", &[]).await.headers["x-cache"], "HIT"); 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(); let mut logged = Vec::new();
for _ in 0..50 { for _ in 0..50 {
logged = fixture logged = fixture
@@ -897,7 +943,10 @@ mod cache_fast_path_tests {
} }
tokio::time::sleep(Duration::from_millis(20)).await; tokio::time::sleep(Duration::from_millis(20)).await;
} }
assert_eq!(logged, ["HIT", "MISS", "REVALIDATED", "MISS", "STALE", "MISS"]); assert_eq!(
logged,
["HIT", "MISS", "REVALIDATED", "MISS", "STALE", "MISS"]
);
let dashboard = fixture.app.cache.dashboard(None, 0, 10); let dashboard = fixture.app.cache.dashboard(None, 0, 10);
let stale: u64 = dashboard.domains.iter().map(|row| row.counters.stale).sum(); let stale: u64 = dashboard.domains.iter().map(|row| row.counters.stale).sum();
let revalidated: u64 = dashboard let revalidated: u64 = dashboard
@@ -907,8 +956,13 @@ mod cache_fast_path_tests {
.sum(); .sum();
let hits: u64 = dashboard.domains.iter().map(|row| row.counters.hits).sum(); let hits: u64 = dashboard.domains.iter().map(|row| row.counters.hits).sum();
assert_eq!((stale, revalidated, hits), (1, 1, 3)); assert_eq!((stale, revalidated, hits), (1, 1, 3));
fixture.change(|config| config.cache.expose_detailed_status = false).await; fixture
assert_eq!(fixture.get("/stale-then-503", &[]).await.headers["x-cache"], "HIT"); .change(|config| config.cache.expose_detailed_status = false)
.await;
assert_eq!(
fixture.get("/stale-then-503", &[]).await.headers["x-cache"],
"HIT"
);
fixture.stop().await; fixture.stop().await;
} }
@@ -939,15 +993,30 @@ mod cache_fast_path_tests {
config.cache.static_ignore_cookies = true; config.cache.static_ignore_cookies = true;
config.cache.static_ignore_vary_cookie = true; config.cache.static_ignore_vary_cookie = true;
let fixture = Fixture::new(config).await; let fixture = Fixture::new(config).await;
let first = fixture.get("/vary-cookie.css", &[("cookie", "session=alpha"), ("x-variant", "a")]).await; let first = fixture
.get(
"/vary-cookie.css",
&[("cookie", "session=alpha"), ("x-variant", "a")],
)
.await;
assert_eq!(first.headers["x-cache"], "MISS"); assert_eq!(first.headers["x-cache"], "MISS");
assert_eq!(first.headers["vary"], "X-Variant"); assert_eq!(first.headers["vary"], "X-Variant");
assert_eq!(first.body, "origin-a"); assert_eq!(first.body, "origin-a");
let second = fixture.get("/vary-cookie.css", &[("cookie", "session=beta"), ("x-variant", "a")]).await; let second = fixture
.get(
"/vary-cookie.css",
&[("cookie", "session=beta"), ("x-variant", "a")],
)
.await;
assert_eq!(second.headers["x-cache"], "HIT"); assert_eq!(second.headers["x-cache"], "HIT");
assert_eq!(second.headers["vary"], "X-Variant"); assert_eq!(second.headers["vary"], "X-Variant");
assert_eq!(second.body, "origin-a"); assert_eq!(second.body, "origin-a");
let other = fixture.get("/vary-cookie.css", &[("cookie", "session=gamma"), ("x-variant", "b")]).await; let other = fixture
.get(
"/vary-cookie.css",
&[("cookie", "session=gamma"), ("x-variant", "b")],
)
.await;
assert_eq!(other.headers["x-cache"], "MISS"); assert_eq!(other.headers["x-cache"], "MISS");
assert_eq!(other.body, "origin-b"); assert_eq!(other.body, "origin-b");
assert_eq!(origin.requests.load(Ordering::Relaxed), 2); assert_eq!(origin.requests.load(Ordering::Relaxed), 2);
@@ -962,13 +1031,21 @@ mod cache_fast_path_tests {
config.cache.static_ignore_vary_cookie = true; config.cache.static_ignore_vary_cookie = true;
config.vhosts[0].cache.static_ignore_vary_cookie = Some(false); config.vhosts[0].cache.static_ignore_vary_cookie = Some(false);
let fixture = Fixture::new(config).await; let fixture = Fixture::new(config).await;
let first = fixture.get("/vary-cookie.css", &[("cookie", "session=alpha")]).await; let first = fixture
.get("/vary-cookie.css", &[("cookie", "session=alpha")])
.await;
assert_eq!(first.headers["x-cache-reason"], "response_vary_cookie"); assert_eq!(first.headers["x-cache-reason"], "response_vary_cookie");
assert_eq!(first.headers["vary"], "Cookie, X-Variant"); assert_eq!(first.headers["vary"], "Cookie, X-Variant");
let second = fixture.get("/vary-cookie.css", &[("cookie", "session=beta")]).await; let second = fixture
.get("/vary-cookie.css", &[("cookie", "session=beta")])
.await;
assert_eq!(second.headers["x-cache"], "MISS"); assert_eq!(second.headers["x-cache"], "MISS");
assert_eq!(origin.requests.load(Ordering::Relaxed), 2); assert_eq!(origin.requests.load(Ordering::Relaxed), 2);
fixture.change(|config| { config.vhosts[0].cache.static_ignore_vary_cookie = None; }).await; fixture
.change(|config| {
config.vhosts[0].cache.static_ignore_vary_cookie = None;
})
.await;
let private = fixture.get("/vary-cookie-private.css", &[]).await; let private = fixture.get("/vary-cookie-private.css", &[]).await;
assert_eq!(private.headers["vary"], "Cookie, X-Variant"); assert_eq!(private.headers["vary"], "Cookie, X-Variant");
assert_eq!(private.headers["x-cache"], "MISS"); assert_eq!(private.headers["x-cache"], "MISS");
@@ -1204,6 +1281,27 @@ mod cache_fast_path_tests {
assert_eq!(origin.requests.load(Ordering::Relaxed), 1); assert_eq!(origin.requests.load(Ordering::Relaxed), 1);
assert_eq!(fixture.app.metrics.completed.load(Ordering::Relaxed), 12); assert_eq!(fixture.app.metrics.completed.load(Ordering::Relaxed), 12);
assert_eq!(fixture.app.metrics.active.load(Ordering::Relaxed), 0); assert_eq!(fixture.app.metrics.active.load(Ordering::Relaxed), 0);
assert_cache_outcomes(&fixture, 11, 1, 0, 0);
fixture.stop().await;
}
#[tokio::test]
async fn cache_outcomes_include_capacity_rejections_once() {
let origin = origin().await;
let fixture = Fixture::new(config_for(origin.addr, true)).await;
let slots = fixture.app.inflight.clone();
let permit = slots
.clone()
.acquire_many_owned(slots.available_permits() as u32)
.await
.unwrap();
assert_eq!(
fixture.get("/", &[]).await.status,
StatusCode::SERVICE_UNAVAILABLE
);
assert_cache_outcomes(&fixture, 0, 0, 0, 1);
drop(permit);
assert_eq!(fixture.get("/", &[]).await.status, StatusCode::OK);
assert_cache_outcomes(&fixture, 0, 1, 0, 1);
fixture.stop().await; fixture.stop().await;
} }
} }
+9 -43
View File
@@ -1,5 +1,9 @@
{ {
if let Some(ticket) = &cache_ticket { if let Some(ticket) = &cache_ticket {
if let Some(exchange) = &exchange {
exchange.set_cache_outcome(scope, &host, 2, revalidation_reason.or(freshness_revalidation_reason).unwrap_or("cache_miss"));
}
if revalidation_reason.is_none() { if revalidation_reason.is_none() {
if let Some(mut hit) = state.cache.get_tiered(ticket, cache_settings).await { if let Some(mut hit) = state.cache.get_tiered(ticket, cache_settings).await {
let conditional = crate::cache::conditional_not_modified( let conditional = crate::cache::conditional_not_modified(
@@ -57,10 +61,9 @@ if let Some(ticket) = &cache_ticket {
tokio::spawn(async move { tokio::spawn(async move {
let _guard = guard; let _guard = guard;
if refresh_cache_once(&refresh_context, refresh_ticket, cached).await { if refresh_cache_once(&refresh_context, refresh_ticket, cached).await {
refresh_context.state.cache.record( refresh_context.state.cache.record_reason(
&refresh_context.scope, &refresh_context.scope,
&refresh_context.host, &refresh_context.host,
"HIT",
"cache_stale_while_revalidate_refreshed", "cache_stale_while_revalidate_refreshed",
); );
} }
@@ -100,14 +103,7 @@ if let Some(ticket) = &cache_ticket {
hit.response = crate::cache::make_not_modified(hit.response); hit.response = crate::cache::make_not_modified(hit.response);
} }
if let Some(exchange) = &exchange { if let Some(exchange) = &exchange {
exchange.cache_status.store(1, Ordering::Relaxed); exchange.set_cache_outcome(scope, &host, 1, reason);
}
state.cache.record(scope, &host, "HIT", reason);
if let Some(exchange) = &exchange {
*exchange
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner()) = reason;
} }
cache_settings.annotate_reason_transformed_freshness( cache_settings.annotate_reason_transformed_freshness(
hit.response.headers_mut(), hit.response.headers_mut(),
@@ -127,37 +123,14 @@ if let Some(ticket) = &cache_ticket {
hit.response.extensions_mut().insert(ResponseRulesApplied); hit.response.extensions_mut().insert(ResponseRulesApplied);
return intercept_route_origin_error(hit.response, route, &snapshot); return intercept_route_origin_error(hit.response, route, &snapshot);
} }
state.cache.record(scope, &host, "MISS", "cache_miss");
miss_recorded = true;
if let Some(exchange) = &exchange {
exchange.cache_status.store(2, Ordering::Relaxed);
*exchange
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner()) = "cache_miss";
}
} else if cached_revalidation.is_none() { } else if cached_revalidation.is_none() {
let _ = state.cache.get_tiered(ticket, cache_settings).await; let _ = state.cache.get_tiered(ticket, cache_settings).await;
state.cache.record(scope, &host, "MISS", "cache_miss");
miss_recorded = true;
if let Some(exchange) = &exchange {
exchange.cache_status.store(2, Ordering::Relaxed);
*exchange
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner()) = "cache_miss";
}
} }
} else { } else {
state.cache.bypass(); state.cache.bypass();
let reason = effective_reason.unwrap_or("configuration_changed"); let reason = effective_reason.unwrap_or("configuration_changed");
state.cache.record(scope, &host, "BYPASS", reason);
if let Some(exchange) = &exchange { if let Some(exchange) = &exchange {
exchange.cache_status.store(3, Ordering::Relaxed); exchange.set_cache_outcome(scope, &host, 3, reason);
*exchange
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner()) = reason;
} }
} }
let serve_stale = |reason: &'static str, elapsed: Duration, origin_backend: &str, let serve_stale = |reason: &'static str, elapsed: Duration, origin_backend: &str,
@@ -196,10 +169,8 @@ let serve_stale = |reason: &'static str, elapsed: Duration, origin_backend: &str
hit.response hit.response
.extensions_mut() .extensions_mut()
.insert(OriginBackend(origin_backend.to_owned())); .insert(OriginBackend(origin_backend.to_owned()));
state.cache.record(scope, &host, "HIT", reason);
if let Some(exchange) = &exchange { if let Some(exchange) = &exchange {
exchange.cache_status.store(1, Ordering::Relaxed); exchange.set_cache_outcome(scope, &host, 1, reason);
*exchange.cache_reason.lock().unwrap_or_else(|e| e.into_inner()) = reason;
} }
Some(intercept_route_origin_error(hit.response, route, &snapshot)) Some(intercept_route_origin_error(hit.response, route, &snapshot))
}; };
@@ -283,13 +254,8 @@ if handshake.is_none()
hit.resident_age_seconds, hit.resident_age_seconds,
); );
hit.response.extensions_mut().insert(ResponseRulesApplied); hit.response.extensions_mut().insert(ResponseRulesApplied);
state.cache.record(scope, &host, "HIT", reason);
if let Some(exchange) = &exchange { if let Some(exchange) = &exchange {
exchange.cache_status.store(1, Ordering::Relaxed); exchange.set_cache_outcome(scope, &host, 1, reason);
*exchange
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner()) = reason;
} }
return intercept_route_origin_error(hit.response, route, &snapshot); return intercept_route_origin_error(hit.response, route, &snapshot);
} }
+1 -2
View File
@@ -451,7 +451,6 @@ let pending_revalidation = revalidation_reason.is_some()
|| cached_revalidation || cached_revalidation
.as_ref() .as_ref()
.is_some_and(|cached| !cached.reusable_for_request(&freshness_headers)); .is_some_and(|cached| !cached.reusable_for_request(&freshness_headers));
let miss_recorded = false;
( (
backend, backend_lease, affinity_cookie, admin_control_plane, cache_settings, backend, backend_lease, affinity_cookie, admin_control_plane, cache_settings,
transform_settings, scope, ignore_static_cookie, force_cache, force_vary_cookie, transform_settings, scope, ignore_static_cookie, force_cache, force_vary_cookie,
@@ -459,7 +458,7 @@ let miss_recorded = false;
origin_suffix, uri, exchange, lease, stop, downstream, h2_downstream, origin_suffix, uri, exchange, lease, stop, downstream, h2_downstream,
range_selection, if_range, range_requested, effective_reason, revalidation_reason, range_selection, if_range, range_requested, effective_reason, revalidation_reason,
cache_ticket, client_conditionals, cached_revalidation, freshness_revalidation_reason, cache_ticket, client_conditionals, cached_revalidation, freshness_revalidation_reason,
pending_revalidation, miss_recorded, cache_rule_context, pending_revalidation, cache_rule_context,
static_cookie_relaxed, shared_static_cookie_fill, static_cookie_relaxed, shared_static_cookie_fill,
) )
} }
+3 -20
View File
@@ -85,13 +85,8 @@ if response.status() == StatusCode::NOT_MODIFIED && revalidation_sent {
.extensions_mut() .extensions_mut()
.insert(OriginBackend(active_backend.id.clone())); .insert(OriginBackend(active_backend.id.clone()));
if let Some(exchange) = &exchange { if let Some(exchange) = &exchange {
exchange.cache_status.store(1, Ordering::Relaxed); exchange.set_cache_outcome(scope, &host, 1, "cache_revalidated");
*exchange
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner()) = "cache_revalidated";
} }
state.cache.record(scope, &host, "HIT", "cache_revalidated");
return intercept_route_origin_error(revalidated, route, &snapshot); return intercept_route_origin_error(revalidated, route, &snapshot);
} }
} }
@@ -133,19 +128,8 @@ let reason = effective_reason
"configuration_changed" "configuration_changed"
} }
}); });
if outcome == "MISS" && !miss_recorded {
state.cache.record(scope, &host, "MISS", reason);
if let Some(exchange) = &exchange {
exchange.cache_status.store(2, Ordering::Relaxed);
}
} else if outcome == "MISS" && reason != "cache_miss" {
state.cache.record_reason(scope, &host, reason);
}
if let Some(exchange) = &exchange { if let Some(exchange) = &exchange {
*exchange exchange.set_cache_outcome(scope, &host, if outcome == "MISS" { 2 } else { 3 }, reason);
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner()) = reason;
} }
if fill_leader.is_some() && (origin_plan.is_none() || transformed_plan.is_none()) { if fill_leader.is_some() && (origin_plan.is_none() || transformed_plan.is_none()) {
if let Some(ticket) = cache_ticket.as_ref() { if let Some(ticket) = cache_ticket.as_ref() {
@@ -174,8 +158,7 @@ if let (Some(ticket), Some(plan), Some(transformed)) =
cache_settings, cache_settings,
fill_leader.take(), fill_leader.take(),
); );
// Avoid refreshing a cookie/credential-keyed entry without its original
// VCL variation context: proactive refresh must never collapse users.
if cache_settings.proactive_refresh_enabled && proactive_remaining_ttl > 0 if cache_settings.proactive_refresh_enabled && proactive_remaining_ttl > 0
&& !force_vary_cookie && !force_vary_authorization && !force_vary_cookie && !force_vary_authorization
{ {
+1 -3
View File
@@ -112,8 +112,7 @@ if handshake.as_ref().is_some_and(|handshake| {
"RustProxy: HTTP/1.1 WebSocket upstream returned 2xx without switching protocols\n", "RustProxy: HTTP/1.1 WebSocket upstream returned 2xx without switching protocols\n",
); );
} }
// Shared-static guard runs on the *original* backend headers, before VCL
// response edits such as strip_set_cookie or ignore_cache_control.
let shared_static_reason = if shared_static_cookie_fill && cache_ticket.is_some() { let shared_static_reason = if shared_static_cookie_fill && cache_ticket.is_some() {
crate::cache::shared_static_response_reason( crate::cache::shared_static_response_reason(
response.status(), response.headers(), cache_settings, response.status(), response.headers(), cache_settings,
@@ -417,7 +416,6 @@ if !range_requested && handshake.is_none() {
state state
.transform_metrics .transform_metrics
.record_error(scope, transform_started.elapsed()); .record_error(scope, transform_started.elapsed());
state.cache.record_reason(scope, &host, "transform_error");
if let Some(exchange) = &exchange { if let Some(exchange) = &exchange {
*exchange *exchange
.cache_reason .cache_reason
+11 -9
View File
@@ -84,6 +84,14 @@
(needs_validation, (needs_validation,
policy.revalidation_reason().is_some() || freshness_revalidation_requested) policy.revalidation_reason().is_some() || freshness_revalidation_requested)
}; };
if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
let reason = if !enabled { "cache_disabled" }
else if let Some(reason) = policy.bypass_reason() { reason }
else if needs_validation { "request_revalidated" }
else if cache_ticket.is_some() { "cache_miss" }
else { "cache_unavailable" };
exchange.set_cache_outcome(scope, &host, if cache_ticket.is_some() { 2 } else { 3 }, reason);
}
if let Some(ticket) = &cache_ticket { if let Some(ticket) = &cache_ticket {
if !needs_validation { if !needs_validation {
if let Some(mut hit) = state.cache.get_tiered(ticket, cache_settings).await { if let Some(mut hit) = state.cache.get_tiered(ticket, cache_settings).await {
@@ -105,11 +113,9 @@
cache_settings.annotate_reason_transformed_freshness(response.headers_mut(), "HIT", hit.hits, cache_settings.annotate_reason_transformed_freshness(response.headers_mut(), "HIT", hit.hits,
hit.cache_status_ttl, "cache_hit", hit.transformed); hit.cache_status_ttl, "cache_hit", hit.transformed);
cache_settings.annotate_resident_age(response.headers_mut(), hit.resident_age_seconds); cache_settings.annotate_resident_age(response.headers_mut(), hit.resident_age_seconds);
state.cache.record(scope, &host, "HIT", "cache_hit");
if hit.transformed { state.transform_metrics.record_cache_hit(scope); } if hit.transformed { state.transform_metrics.record_cache_hit(scope); }
if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() { if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
exchange.cache_status.store(1, Ordering::Relaxed); exchange.set_cache_outcome(scope, &host, 1, "cache_hit");
*exchange.cache_reason.lock().unwrap_or_else(|e| e.into_inner()) = "cache_hit";
} }
response.extensions_mut().insert(ResponseRulesApplied); response.extensions_mut().insert(ResponseRulesApplied);
response.extensions_mut().insert(StaticSourceResponse); response.extensions_mut().insert(StaticSourceResponse);
@@ -158,11 +164,9 @@
route.frontend.as_deref(), Some(route), false), route.frontend.as_deref(), Some(route), false),
); );
if let Some(mut hit) = revalidated { if let Some(mut hit) = revalidated {
state.cache.record(scope, &host, "HIT", hit.reason);
if hit.transformed { state.transform_metrics.record_cache_hit(scope); } if hit.transformed { state.transform_metrics.record_cache_hit(scope); }
if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() { if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
exchange.cache_status.store(1, Ordering::Relaxed); exchange.set_cache_outcome(scope, &host, 1, hit.reason);
*exchange.cache_reason.lock().unwrap_or_else(|e| e.into_inner()) = hit.reason;
} }
hit.response.extensions_mut().insert(ResponseRulesApplied); hit.response.extensions_mut().insert(ResponseRulesApplied);
hit.response.extensions_mut().insert(StaticSourceResponse); hit.response.extensions_mut().insert(StaticSourceResponse);
@@ -263,10 +267,8 @@
} }
} }
if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() { if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
exchange.cache_status.store(if outcome == "MISS" { 2 } else { 3 }, Ordering::Relaxed); exchange.set_cache_outcome(scope, &host, if outcome == "MISS" { 2 } else { 3 }, reason);
*exchange.cache_reason.lock().unwrap_or_else(|e| e.into_inner()) = reason;
} }
state.cache.record(scope, &host, outcome, reason);
let transformed = response.extensions().get::<crate::transform::Applied>().is_some(); let transformed = response.extensions().get::<crate::transform::Applied>().is_some();
if let Some(cached) = &cached_revalidation { if let Some(cached) = &cached_revalidation {
cache_settings.annotate_reason_transformed_forwarded( cache_settings.annotate_reason_transformed_forwarded(
+17 -13
View File
@@ -145,15 +145,20 @@ async fn forward_request(
let frontend_rank = frontend.and_then(|_| snapshot.frontend_rank(&host, local.0, tls)); let frontend_rank = frontend.and_then(|_| snapshot.frontend_rank(&host, local.0, tls));
let redirect = snapshot let redirect = snapshot
.redirect_on(&host, &path, local.0, tls) .redirect_on(&host, &path, local.0, tls)
.filter(|_| match (frontend_rank, snapshot.redirect_rank(&host, &path, local.0, tls)) { .filter(|_| {
match (
frontend_rank,
snapshot.redirect_rank(&host, &path, local.0, tls),
) {
(Some(vhost), Some(redirect)) => redirect >= vhost, (Some(vhost), Some(redirect)) => redirect >= vhost,
_ => true, _ => true,
}
}); });
let local_host = snapshot let local_host = snapshot.not_found_host_on(&host, local.0, tls).filter(|_| {
.not_found_host_on(&host, local.0, tls) match (frontend_rank, snapshot.not_found_rank(&host, local.0, tls)) {
.filter(|_| match (frontend_rank, snapshot.not_found_rank(&host, local.0, tls)) {
(Some(vhost), Some(local_host)) => local_host >= vhost, (Some(vhost), Some(local_host)) => local_host >= vhost,
_ => true, _ => true,
}
}); });
// Requests answered by a redirect or local 404 host are logged under that host. // Requests answered by a redirect or local 404 host are logged under that host.
if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() { if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
@@ -311,7 +316,9 @@ async fn forward_request(
"RustProxy: global request rate limit exceeded\n", "RustProxy: global request rate limit exceeded\n",
); );
if let Ok(value) = HeaderValue::from_str(&limited.retry_after_seconds.to_string()) { if let Ok(value) = HeaderValue::from_str(&limited.retry_after_seconds.to_string()) {
response.headers_mut().insert(::http::header::RETRY_AFTER, value); response
.headers_mut()
.insert(::http::header::RETRY_AFTER, value);
} }
return response; return response;
} }
@@ -368,7 +375,9 @@ async fn forward_request(
"RustProxy: request rate limit exceeded\n", "RustProxy: request rate limit exceeded\n",
); );
if let Ok(value) = HeaderValue::from_str(&limited.retry_after_seconds.to_string()) { if let Ok(value) = HeaderValue::from_str(&limited.retry_after_seconds.to_string()) {
response.headers_mut().insert(::http::header::RETRY_AFTER, value); response
.headers_mut()
.insert(::http::header::RETRY_AFTER, value);
} }
return response; return response;
} }
@@ -468,10 +477,7 @@ async fn forward_request(
.as_ref() .as_ref()
.and_then(|selection| selection.route.as_ref()); .and_then(|selection| selection.route.as_ref());
if precomputed.is_none_or(|route| !Arc::ptr_eq(route, chosen)) { if precomputed.is_none_or(|route| !Arc::ptr_eq(route, chosen)) {
*exchange *exchange.routed.lock().unwrap_or_else(|e| e.into_inner()) = Some(chosen.clone());
.routed
.lock()
.unwrap_or_else(|e| e.into_inner()) = Some(chosen.clone());
} }
} }
chosen.map(Arc::as_ref) chosen.map(Arc::as_ref)
@@ -597,8 +603,7 @@ async fn forward_request(
) )
}); });
}; };
// Client URI as received (before location rewrites and cache-rule query changes),
// kept only for pools that hash the path, URI, host or a query parameter.
let balance_uri = route let balance_uri = route
.pool .pool
.as_ref() .as_ref()
@@ -640,7 +645,6 @@ async fn forward_request(
cached_revalidation, cached_revalidation,
freshness_revalidation_reason, freshness_revalidation_reason,
pending_revalidation, pending_revalidation,
mut miss_recorded,
cache_rule_context, cache_rule_context,
static_cookie_relaxed, static_cookie_relaxed,
shared_static_cookie_fill, shared_static_cookie_fill,
+7 -7
View File
@@ -62,7 +62,11 @@ async fn dispatch(state: Arc<App>, request: Request) -> Response {
let peer = request.extensions().get::<PeerAddr>().copied(); let peer = request.extensions().get::<PeerAddr>().copied();
let local = request.extensions().get::<LocalAddr>().copied(); let local = request.extensions().get::<LocalAddr>().copied();
let (Some(peer), Some(local)) = (peer, local) else { let (Some(peer), Some(local)) = (peer, local) else {
return (StatusCode::INTERNAL_SERVER_ERROR, "Missing request extension").into_response(); return (
StatusCode::INTERNAL_SERVER_ERROR,
"Missing request extension",
)
.into_response();
}; };
forward(state, peer, local, request).await forward(state, peer, local, request).await
} }
@@ -364,18 +368,14 @@ async fn refresh_cache_once(
pool.strip_affinity_response(&mut validation_headers); pool.strip_affinity_response(&mut validation_headers);
} }
let merged = cached.merge_validation_headers(&validation_headers); let merged = cached.merge_validation_headers(&validation_headers);
return context return context.state.cache.publish_background_revalidated(
.state
.cache
.publish_revalidated(
ticket, ticket,
&cached, &cached,
merged, merged,
&origin_validation_headers, &origin_validation_headers,
&context.cache_settings, &context.cache_settings,
started.elapsed(), started.elapsed(),
) );
.is_some();
} }
if origin.status() != StatusCode::OK { if origin.status() != StatusCode::OK {
return false; return false;
+56 -34
View File
@@ -41,13 +41,10 @@ fn should_replace_error_page(response: &Response, minimal_welcome: bool) -> bool
.is_none() .is_none()
} }
// A cacheable HEAD miss is sent to the origin as GET. The resulting body
// must be read to EOF for FillBody to publish the entry; dropping it here
// would turn every cold HEAD into another MISS. Only drain bodies explicitly
// marked by the cache layer. Enforce byte and wall-clock limits so a broken
// origin cannot leave unbounded detached work after the HEAD response.
fn strip_head_response_body(response: &mut Response) { fn strip_head_response_body(response: &mut Response) {
let fill = response.extensions_mut().remove::<crate::cache::PendingFill>(); let fill = response
.extensions_mut()
.remove::<crate::cache::PendingFill>();
let body = std::mem::replace(response.body_mut(), Body::empty()); let body = std::mem::replace(response.body_mut(), Body::empty());
if let Some(fill) = fill { if let Some(fill) = fill {
tokio::spawn(async move { tokio::spawn(async move {
@@ -106,7 +103,7 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
&& request.method() == Method::CONNECT && request.method() == Method::CONNECT
&& websocket::h3_protocol(&request) == Some("websocket")); && websocket::h3_protocol(&request) == Some("websocket"));
match request.version() { match request.version() {
Version::HTTP_11 => { Version::HTTP_10 | Version::HTTP_11 => {
state.metrics.http1_requests.fetch_add(1, Ordering::Relaxed); state.metrics.http1_requests.fetch_add(1, Ordering::Relaxed);
} }
Version::HTTP_2 => { Version::HTTP_2 => {
@@ -123,6 +120,7 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
frontend.metrics.requests.fetch_add(1, Ordering::Relaxed); frontend.metrics.requests.fetch_add(1, Ordering::Relaxed);
} }
let Ok(permit) = state.inflight.clone().try_acquire_owned() else { let Ok(permit) = state.inflight.clone().try_acquire_owned() else {
state.metrics.record_cache_request_outcome(0);
state state
.metrics .metrics
.rejected_requests .rejected_requests
@@ -242,6 +240,8 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
status: AtomicU16::new(500), status: AtomicU16::new(500),
cache_status: AtomicU16::new(0), cache_status: AtomicU16::new(0),
cache_reason: Mutex::new("not_proxy_response"), cache_reason: Mutex::new("not_proxy_response"),
cache_scope: Mutex::new(None),
cache_outcome_recorded: AtomicBool::new(false),
failed: AtomicBool::new(false), failed: AtomicBool::new(false),
aborted: AtomicBool::new(false), aborted: AtomicBool::new(false),
request_bytes: AtomicU64::new(0), request_bytes: AtomicU64::new(0),
@@ -320,9 +320,10 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
] { ] {
response.headers_mut().remove(name); response.headers_mut().remove(name);
} }
response response.headers_mut().insert(
.headers_mut() ::http::header::CACHE_CONTROL,
.insert(::http::header::CACHE_CONTROL, HeaderValue::from_static("no-store")); HeaderValue::from_static("no-store"),
);
} else { } else {
if response if response
.extensions() .extensions()
@@ -475,8 +476,10 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
.lock() .lock()
.unwrap_or_else(|e| e.into_inner()) .unwrap_or_else(|e| e.into_inner())
.clone(); .clone();
// Stale-if-error copies name the backend that failed; a plain cache hit has none. let origin = response
let origin = response.extensions().get::<OriginBackend>().map(|o| o.0.clone()); .extensions()
.get::<OriginBackend>()
.map(|o| o.0.clone());
let srv_id = lease let srv_id = lease
.as_ref() .as_ref()
.map(|lease| lease.member.definition.id.clone()) .map(|lease| lease.member.definition.id.clone())
@@ -485,7 +488,9 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
.as_deref() .as_deref()
.map(|id| id.rsplit('/').next().unwrap_or(id).to_owned()) .map(|id| id.rsplit('/').next().unwrap_or(id).to_owned())
}); });
let srv_url = lease.as_ref().map(|lease| lease.member.definition.url.clone()); let srv_url = lease
.as_ref()
.map(|lease| lease.member.definition.url.clone());
let backend_time = response let backend_time = response
.extensions() .extensions()
.get::<OriginTiming>() .get::<OriginTiming>()
@@ -507,7 +512,9 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
.as_ref() .as_ref()
.and_then(|v| v.vhost.as_deref()) .and_then(|v| v.vhost.as_deref())
.or(frontend_context.as_ref().map(|f| f.id.as_str())), .or(frontend_context.as_ref().map(|f| f.id.as_str())),
lb_algorithm: request_vars.as_ref().and_then(|v| v.lb_algorithm.as_deref()), lb_algorithm: request_vars
.as_ref()
.and_then(|v| v.lb_algorithm.as_deref()),
hash_key: request_vars.as_ref().and_then(|v| v.hash_key.as_deref()), hash_key: request_vars.as_ref().and_then(|v| v.hash_key.as_deref()),
client_ip: request_vars.as_ref().and_then(|v| v.client_ip.as_deref()), client_ip: request_vars.as_ref().and_then(|v| v.client_ip.as_deref()),
country: request_vars.as_ref().and_then(|v| v.country.as_deref()), country: request_vars.as_ref().and_then(|v| v.country.as_deref()),
@@ -570,6 +577,7 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
exchange exchange
.status .status
.store(response.status().as_u16(), Ordering::Relaxed); .store(response.status().as_u16(), Ordering::Relaxed);
exchange.finish_cache_outcome(&state.cache);
let ws_success = response.status() == StatusCode::SWITCHING_PROTOCOLS let ws_success = response.status() == StatusCode::SWITCHING_PROTOCOLS
|| response.extensions().get::<websocket::H3Tunnel>().is_some(); || response.extensions().get::<websocket::H3Tunnel>().is_some();
if ws_attempt && !ws_success { if ws_attempt && !ws_success {
@@ -632,7 +640,14 @@ mod head_cache_fill_tests {
..Default::default() ..Default::default()
}; };
let ticket = cache let ticket = cache
.ticket(1, "https", "example.test", "app", "/head", &HeaderMap::new()) .ticket(
1,
"https",
"example.test",
"app",
"/head",
&HeaderMap::new(),
)
.expect("valid cache ticket"); .expect("valid cache ticket");
let mut origin = Response::new(Body::from("cached from HEAD")); let mut origin = Response::new(Body::from("cached from HEAD"));
origin.headers_mut().insert( origin.headers_mut().insert(
@@ -643,22 +658,24 @@ mod head_cache_fill_tests {
::http::header::CONTENT_LENGTH, ::http::header::CONTENT_LENGTH,
HeaderValue::from_static("16"), HeaderValue::from_static("16"),
); );
let plan = crate::cache::plan( let plan = crate::cache::plan(StatusCode::OK, origin.headers(), &settings, Duration::ZERO)
StatusCode::OK,
origin.headers(),
&settings,
Duration::ZERO,
)
.expect("cacheable GET representation"); .expect("cacheable GET representation");
let mut head = cache.wrap(origin, ticket.clone(), plan, &settings); let mut head = cache.wrap(origin, ticket.clone(), plan, &settings);
assert!(head.extensions().get::<crate::cache::PendingFill>().is_some()); assert!(head
.extensions()
.get::<crate::cache::PendingFill>()
.is_some());
strip_head_response_body(&mut head); strip_head_response_body(&mut head);
assert_eq!(head.headers()[::http::header::CONTENT_LENGTH], "16"); assert_eq!(head.headers()[::http::header::CONTENT_LENGTH], "16");
assert!(head.body().is_end_stream(), "HEAD must have no response body"); assert!(
assert!(head.extensions().get::<crate::cache::PendingFill>().is_none()); head.body().is_end_stream(),
"HEAD must have no response body"
);
assert!(head
.extensions()
.get::<crate::cache::PendingFill>()
.is_none());
// The cache fill is detached from the HEAD response. It must finish
// independently, allowing a later GET or HEAD to reuse this object.
let hit = tokio::time::timeout(Duration::from_secs(2), async { let hit = tokio::time::timeout(Duration::from_secs(2), async {
loop { loop {
if let Some(hit) = cache.get(&ticket) { if let Some(hit) = cache.get(&ticket) {
@@ -685,25 +702,30 @@ mod head_cache_fill_tests {
..Default::default() ..Default::default()
}; };
let ticket = cache let ticket = cache
.ticket(1, "https", "example.test", "app", "/too-big", &HeaderMap::new()) .ticket(
1,
"https",
"example.test",
"app",
"/too-big",
&HeaderMap::new(),
)
.expect("valid cache ticket"); .expect("valid cache ticket");
let mut origin = Response::new(Body::from(Bytes::from(vec![b'x'; 1025]))); let mut origin = Response::new(Body::from(Bytes::from(vec![b'x'; 1025])));
origin.headers_mut().insert( origin.headers_mut().insert(
::http::header::CACHE_CONTROL, ::http::header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=60"), HeaderValue::from_static("public, max-age=60"),
); );
let plan = crate::cache::plan( let plan = crate::cache::plan(StatusCode::OK, origin.headers(), &settings, Duration::ZERO)
StatusCode::OK,
origin.headers(),
&settings,
Duration::ZERO,
)
.expect("cacheable headers, unknown body length"); .expect("cacheable headers, unknown body length");
let mut head = cache.wrap(origin, ticket.clone(), plan, &settings); let mut head = cache.wrap(origin, ticket.clone(), plan, &settings);
strip_head_response_body(&mut head); strip_head_response_body(&mut head);
assert!(head.body().is_end_stream()); assert!(head.body().is_end_stream());
tokio::time::sleep(Duration::from_millis(20)).await; tokio::time::sleep(Duration::from_millis(20)).await;
assert!(cache.get(&ticket).is_none(), "oversized HEAD must not be cached"); assert!(
cache.get(&ticket).is_none(),
"oversized HEAD must not be cached"
);
} }
#[tokio::test] #[tokio::test]