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
+1007 -417

No files matched your search

+83 -36
View File
@@ -24,10 +24,12 @@ async fn logs(
.vhost
.as_ref()
.is_some_and(|v| !crate::config::valid_id(v))
|| filter
.cache
.as_ref()
.is_some_and(|v| !matches!(v.as_str(), "HIT" | "STALE" | "REVALIDATED" | "MISS" | "BYPASS" | "-"))
|| filter.cache.as_ref().is_some_and(|v| {
!matches!(
v.as_str(),
"HIT" | "STALE" | "REVALIDATED" | "MISS" | "BYPASS" | "-"
)
})
{
return Err(ApiError(
StatusCode::BAD_REQUEST,
@@ -249,36 +251,64 @@ fn monitored_vhost_catalog(state: &Arc<App>) -> (Vec<crate::vhost::Vhost>, Vec<V
let (publications, _) = crate::docker::label_publications(desired, &observed);
let mut docker_labels = std::collections::HashMap::new();
for agent in &desired.docker_agents.agents {
let inventory = observed.get(&agent.id).and_then(|item| item.inventory.as_ref());
let assignments = agent.assignments.iter().filter(|assignment| assignment.enabled)
.chain(publications.iter().filter(|entry| entry.agent_id == agent.id)
.map(|entry| &entry.assignment));
let inventory = observed
.get(&agent.id)
.and_then(|item| item.inventory.as_ref());
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 {
let service = inventory.and_then(|inventory| inventory.services.iter()
.find(|service| service.key == assignment.service_key));
let name = service.map(|service| service.container_name.as_str())
let service = inventory.and_then(|inventory| {
inventory
.services
.iter()
.find(|service| service.key == assignment.service_key)
});
let name = service
.map(|service| service.container_name.as_str())
.filter(|name| !name.is_empty())
.unwrap_or(assignment.hostname.as_str());
docker_labels.insert(crate::docker::generated_id(&agent.id, &assignment.service_key),
(name.to_owned(), agent.name.clone()));
docker_labels.insert(
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))
.collect();
let options: Vec<Value> = vhosts.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 label = match docker {
Some((name, agent)) => format!("{name} - {host} (Docker: {agent})"),
None => format!("{} / {}", vhost.id, vhost.frontend.hosts.join(", ")),
};
json!({"id": vhost.id, "hosts": vhost.frontend.hosts,
let options: Vec<Value> = vhosts
.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 label = match docker {
Some((name, agent)) => format!("{name} - {host} (Docker: {agent})"),
None => format!("{} / {}", vhost.id, vhost.frontend.hosts.join(", ")),
};
json!({"id": vhost.id, "hosts": vhost.frontend.hosts,
"docker": docker.is_some(), "label": label})
}).collect();
})
.collect();
let bytes = serde_json::to_vec(&options).unwrap_or_default();
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)
}
@@ -304,10 +334,15 @@ async fn traffic_status(
};
let snapshot = state.config.load_full();
let (vhosts, options, catalog_version) = monitored_vhost_catalog(&state);
if query.vhost.as_ref().is_some_and(|id| {
id != "*" && !vhosts.iter().any(|vhost| &vhost.id == id)
}) {
return Err(ApiError(StatusCode::NOT_FOUND, "unknown vhost traffic scope".into()));
if query
.vhost
.as_ref()
.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 mut payload = json!({
@@ -353,8 +388,15 @@ async fn cache_status(
};
let snapshot = state.config.load_full();
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)) {
return Err(ApiError(StatusCode::NOT_FOUND, "unknown vhost cache scope".into()));
if query
.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(
query.vhost.as_deref(),
@@ -365,6 +407,7 @@ async fn cache_status(
"revision": snapshot.envelope.revision,
"catalog_version": catalog_version,
"metrics": state.cache.view(),
"request_outcomes": state.metrics.cache_request_outcomes(),
"dashboard": dashboard,
"bans": state.cache.bans()
});
@@ -372,11 +415,15 @@ async fn cache_status(
return Ok(Json(payload));
}
payload["settings"] = json!(snapshot.envelope.config.cache);
payload["vhosts"] = json!(vhosts.iter().zip(options.iter()).map(|(vhost, option)| {
let mut item = option.clone();
item["metrics"] = json!(state.cache.scope_view(&vhost.id));
item["settings"] = json!(vhost.cache.resolve(&snapshot.envelope.config.cache).ok());
item
}).collect::<Vec<_>>());
payload["vhosts"] = json!(vhosts
.iter()
.zip(options.iter())
.map(|(vhost, option)| {
let mut item = option.clone();
item["metrics"] = json!(state.cache.scope_view(&vhost.id));
item["settings"] = json!(vhost.cache.resolve(&snapshot.envelope.config.cache).ok());
item
})
.collect::<Vec<_>>());
Ok(Json(payload))
}
+25 -1
View File
@@ -1594,7 +1594,16 @@
},
"metrics": {
"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
},
"transform_metrics": {
@@ -1973,6 +1982,18 @@
},
"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": {
"type": "object",
"properties": {
@@ -1991,6 +2012,9 @@
"properties": {},
"additionalProperties": true
},
"request_outcomes": {
"$ref": "#/components/schemas/CacheRequestOutcomes"
},
"vhosts": {
"type": "array",
"items": {
+200 -51
View File
@@ -3025,14 +3025,21 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let mut config = config::demo_config("127.0.0.1:9000".parse().unwrap());
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.redirects.push(serde_json::from_value(json!({
"id": "app", "frontend": {"hosts": ["old.example.test"], "listener_ids": ["http"]}
})).unwrap());
config.not_found_hosts.push(serde_json::from_value(json!({
"id": "app", "frontend": {"hosts": ["park.example.test"], "listener_ids": ["http"]}
})).unwrap());
config.redirects.push(
serde_json::from_value(json!({
"id": "app", "frontend": {"hosts": ["old.example.test"], "listener_ids": ["http"]}
}))
.unwrap(),
);
config.not_found_hosts.push(
serde_json::from_value(json!({
"id": "app", "frontend": {"hosts": ["park.example.test"], "listener_ids": ["http"]}
}))
.unwrap(),
);
config.docker_agents.agents.push(crate::docker::Agent {
id: "node1".into(),
domains: vec!["example.test".into()],
@@ -3057,41 +3064,86 @@ mod tests {
"labels": {"rustproxy.enable": "true", "rustproxy.host": "label", "rustproxy.aliases": "label-alias"}
}]
})).unwrap();
let observed = std::collections::BTreeMap::from([("node1".into(), 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),
})]);
let observed = std::collections::BTreeMap::from([(
"node1".into(),
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.directory = dir.path().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",
"deleted.jsonl", "_unmatched.jsonl", &format!("{manual}.jsonl"), &format!("{labelled}.jsonl")] {
for name in [
"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();
}
write_gz(&dir.path().join("app.jsonl.2.gz"), &records(1, 2));
let sources = configured_file_log_sources(&config, &observed);
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-file:app.jsonl.1"), 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.host404"), vec!["park.example.test"]);
assert_eq!(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"]);
assert_eq!(
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"] {
assert!(domains(id).is_empty(), "{id}");
}
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));
let query = FileLogQuery { source: Some("vhost:app".into()), consolidate_vhosts: Some(true), ..Default::default() };
let result = file_log_query_blocking(&config, &observed, &query, &[]).unwrap().0;
let query = FileLogQuery {
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!(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.path = dir.path().join("access.jsonl").to_string_lossy().into_owned();
assert!(configured_file_log_sources(&config, &observed).iter().all(|s| s.domains.is_empty()));
config.logging.file.path = dir
.path()
.join("access.jsonl")
.to_string_lossy()
.into_owned();
assert!(configured_file_log_sources(&config, &observed)
.iter()
.all(|s| s.domains.is_empty()));
}
#[test]
@@ -3304,16 +3356,25 @@ mod tests {
}
fn records(from: u64, to: u64) -> Vec<String> {
(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()
}
#[test]
fn stored_log_rotations_are_read_newest_first_regardless_of_mtime() {
let dir = tempfile::tempdir().unwrap();
// logrotate numbering: .jsonl newest, .1 (delaycompress, plain), .2.gz, .10.gz oldest.
std::fs::write(dir.path().join("mail.jsonl"), records(400, 410).join("\n") + "\n").unwrap();
std::fs::write(dir.path().join("mail.jsonl.1"), records(300, 310).join("\n") + "\n").unwrap();
std::fs::write(
dir.path().join("mail.jsonl"),
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.10.gz"), &records(100, 110));
// The oldest rotation has the newest mtime (copied or touched files).
@@ -3323,19 +3384,40 @@ mod tests {
.unwrap()
.set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(3600))
.unwrap();
std::fs::write(dir.path().join("old.redirect.jsonl"), 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("old.redirect.jsonl"),
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();
let mut config = Config::default();
config.logging.file.per_vhost = true;
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 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!(
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![
("vhost:mail", 0),
("vhost-file:mail.jsonl.1", 1),
@@ -3343,10 +3425,24 @@ mod tests {
("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()));
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())));
let scope = |id: &str| {
sources
.iter()
.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())));
let query = |extra: FileLogQuery| {
@@ -3356,7 +3452,9 @@ mod tests {
limit: Some(5),
..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 times: Vec<u64> = value["entries"]
@@ -3369,21 +3467,23 @@ mod tests {
assert_eq!(value["total"], 40);
assert_eq!(value["newest_ms"], 409);
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]);
// A period stops before older rotations.
let value = query(FileLogQuery {
since_ms: Some(305),
..FileLogQuery::default()
});
assert_eq!(value["total"], 15);
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_skipped"], 1);
// A single rotated file is its own source.
let value = file_log_query_blocking(
&config,
&Default::default(),
@@ -3404,7 +3504,11 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let active = dir.path().join("access.jsonl");
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));
let mut config = Config::default();
config.logging.file.per_vhost = false;
@@ -3820,7 +3924,13 @@ mod tests {
(
"/api/cache?view=live",
&["settings", "vhosts"][..],
&["revision", "metrics", "dashboard", "bans"][..],
&[
"revision",
"metrics",
"request_outcomes",
"dashboard",
"bans",
][..],
),
(
"/api/transform?view=live",
@@ -3857,7 +3967,10 @@ mod tests {
}
for (path, required) in [
("/api/cache", &["settings", "vhosts"][..]),
(
"/api/cache",
&["settings", "vhosts", "request_outcomes"][..],
),
("/api/transform", &["settings", "vhosts"][..]),
("/api/traffic", &["vhosts"][..]),
] {
@@ -4612,27 +4725,63 @@ mod tests {
};
let read = |response: axum::response::Response| async move {
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()
};
let public = serde_json::json!([["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;
let public = serde_json::json!([
["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"]["static_cookie_relaxed"], true);
assert_eq!(data["request"]["shared_static_check"], true);
assert_eq!(data["response"]["stored"], true);
let html = serde_json::json!([["Cache-Control", "public, max-age=600"], ["Content-Type", "text/html"]]);
let data = read(router.clone().oneshot(run("https://localhost/", html)).await.unwrap()).await;
let html = serde_json::json!([
["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_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_class"], "vcl_rule");
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"]["reason"], "response_cache_control");
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 total = hit !== null && miss !== null ? hit + miss : 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`);
if (hitArc) hitArc.setAttribute("stroke-dasharray", `${share} ${100 - share}`);
if (missArc) {
missArc.setAttribute("stroke-dasharray", `${100 - share} ${share}`);
missArc.setAttribute("stroke-dasharray", `${missShare} ${100 - missShare}`);
missArc.setAttribute("stroke-dashoffset", String(-share));
}
const hitCount = $(`${prefix}-hit-count`), missCount = $(`${prefix}-miss-count`);
@@ -134,13 +135,13 @@ window.rustProxyExtraOverview = (() => {
const fields = ({
extra_tls_error_rate: [m.tls_handshake_errors],
extra_request_error_rate: [m.errors],
extra_cache_hit_rate: [c.hits, c.misses],
extra_h2_share: [m.http2_requests, m.requests],
extra_h1_share: [m.http1_requests, m.requests],
extra_h3_share: [m.http3_requests, m.requests],
extra_cache_hit_rate: [m.cache_request_outcomes?.hits, m.cache_request_outcomes?.misses],
extra_h2_share: [m.http2_requests, m.http1_requests, m.http3_requests],
extra_h1_share: [m.http1_requests, m.http2_requests, m.http3_requests],
extra_h3_share: [m.http3_requests, m.http1_requests, m.http2_requests],
extra_total_rps: [m.requests],
extra_cache_miss_rate: [c.misses],
extra_error_share: [m.errors, m.requests],
extra_cache_miss_rate: [m.cache_request_outcomes?.misses],
extra_error_share: [m.errors, m.completed_success],
extra_rejected_rate: [m.rejected_requests, m.rejected_connections],
})[id].map(positive);
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 {
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: "" };
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 {
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
};
}
+1 -1
View File
@@ -15,7 +15,7 @@ window.rustProxyWideOverview = (() => {
},
wide_cache_activity: {
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: {
unit: "count", names: ["open", "websockets"], values: s =>
+11 -12
View File
@@ -460,14 +460,12 @@ function renderNetworkInterfaceCharts(interfaces, appendSample) {
}
}
function cacheOutcomeMix(totals) {
if (!Array.isArray(totals) || totals.length !== 4 ||
totals.some(value => !Number.isSafeInteger(value) || value < 0)) return null;
const [requests, hits, misses, bypasses] = totals;
const cacheTotal = hits + misses + bypasses;
if (requests === 0 || !Number.isSafeInteger(cacheTotal) || cacheTotal > requests) return null;
const counts = [hits, misses, bypasses, requests - cacheTotal];
return { counts, percentages: counts.map(value => value / requests * 100), requests };
function cacheOutcomeMix(outcomes) {
const counts = [outcomes?.hits, outcomes?.misses, outcomes?.bypasses, outcomes?.other];
if (counts.some(value => !Number.isSafeInteger(value) || value < 0)) return null;
const requests = counts.reduce((sum, value) => sum + value, 0);
if (!Number.isSafeInteger(requests)) return null;
return { counts, percentages: counts.map(value => requests ? value / requests * 100 : 0), requests };
}
function fitCacheMixLabels() {
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 || {};
$("metric-h3").textContent = fmt(m.http3_requests);
$("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;
$("metric-cache-ratio").textContent = cacheEvents > 0 ? `${fmt(cacheHits / cacheEvents * 100, 1)}%` : "-";
window.rustProxyExtraOverview?.donut?.("cache-ratio", cacheHits, cacheMisses);
const counters = [m.requests, c.hits, c.misses, c.bypasses].map(value => value == null ? NaN : Number(value));
renderCacheMix(cacheOutcomeMix(counters), counters[0]);
const mix = cacheOutcomeMix(outcomes);
renderCacheMix(mix?.requests ? mix : null, mix?.requests ?? null);
if (systemSample) {
if (d.process_rss_bytes != null) $("metric-rss").textContent = fmtBytes(d.process_rss_bytes);
$("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,
{ top: 5 / 100, bottom: 95 / 100 });
$("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-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))}`;
+11 -7
View File
@@ -122,7 +122,8 @@
const previous = liveChartPrevious && liveChartPreviousAt != 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"));
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) {
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) {
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 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 hotEntryLimit = Number(data.settings?.max_entries) || 0;
const hotEntryPercent = setMeter("cp-hot-entries-meter", hotEntries, hotEntryLimit);
@@ -164,12 +168,12 @@
const coldPercent = setMeter("cp-cold-disk", coldBytes, coldLimit);
$("cp-cold-bytes").textContent = fmtBytes(coldBytes);
$("cp-cold-disk-detail").textContent = `${t("cacheLimitShort")}: ${fmtBytes(coldLimit)} · ${coldPercent.toFixed(1)}%`;
$("cp-ratio").textContent = `${fmt((all ? (m.hit_ratio || 0) : (hits + misses ? hits / (hits + misses) : 0)) * 100, 1)}%`;
$("cp-ratio").textContent = validOutcomes && hits + misses > 0 ? `${fmt(hits / (hits + misses) * 100, 1)}%` : "-";
const staleHits = total("stale"), revalidatedHits = total("revalidated");
$("cp-requests").textContent = `${number(all ? m.hits : hits)} HIT / ${number(all ? m.misses : misses)} MISS${staleHits ? ` · ${number(staleHits)} STALE` : ""}${revalidatedHits ? ` · ${number(revalidatedHits)} REVALIDATED` : ""}`;
const bypasses = all ? (Number(m.bypasses) || 0) : total("bypasses");
$("cp-bypass").textContent = number(bypasses);
renderLiveChart({ hits: all ? (Number(m.hits) || 0) : hits, misses: all ? (Number(m.misses) || 0) : misses, bypasses });
$("cp-requests").textContent = validOutcomes ? `${number(hits)} HIT / ${number(misses)} MISS${staleHits ? ` · ${number(staleHits)} STALE` : ""}${revalidatedHits ? ` · ${number(revalidatedHits)} REVALIDATED` : ""}` : "-";
$("cp-bypass").textContent = validOutcomes ? number(bypasses) : "-";
if (validOutcomes) renderLiveChart({ hits, 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-saved").textContent = fmtBytes(total("saved_body_bytes"));
$("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">
<div class="cache-mix-header">
<span data-i18n="cacheMixTitle">Cache outcomes</span>
<small class="cache-mix-caption" id="cache-mix-caption" aria-label="HTTP requests since service start"
title="HTTP requests since service start">-</small>
<small class="cache-mix-caption" id="cache-mix-caption" aria-label="Classified HTTP requests since service start"
title="Classified HTTP requests since service start">-</small>
</div>
<strong id="cache-mix-headline">-</strong>
<div class="cache-mix-bar" id="cache-mix-bar" role="img"
+102 -26
View File
@@ -964,10 +964,7 @@ mod tests {
let mut request = HeaderMap::new();
let header_name = http::HeaderName::from_bytes(name.as_bytes()).unwrap();
for field in fields {
request.append(
header_name.clone(),
HeaderValue::from_str(field).unwrap(),
);
request.append(header_name.clone(), HeaderValue::from_str(field).unwrap());
}
variant_key(&[0x52; 32], &[name.to_owned()], &request)
}
@@ -992,7 +989,10 @@ mod tests {
);
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"]
)
);
assert_eq!(
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"])
);
assert_eq!(keyed("x-custom", &[" token "]), keyed("x-custom", &["token"]));
assert_eq!(
keyed("x-custom", &[" token "]),
keyed("x-custom", &["token"])
);
assert_ne!(
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!(
keyed("cookie", &["session=one; theme=dark"]),
keyed("cookie", &["session=two; theme=dark"])
@@ -1082,7 +1088,9 @@ mod tests {
equivalent.insert("user-agent", HeaderValue::from_static("AgentOne"));
let equivalent_ticket = ticket(&cache, &equivalent);
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!(
hit.response.into_body().collect().await.unwrap().to_bytes(),
Bytes::from_static(b"public-variant")
@@ -1296,6 +1304,21 @@ mod tests {
let mut validation = HeaderMap::new();
validation.insert("cache-control", HeaderValue::from_static("no-cache"));
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 hit = cache
.publish_revalidated(
@@ -1307,6 +1330,7 @@ mod tests {
Duration::ZERO,
)
.expect("validated body can be delivered");
assert_eq!(cache.view().hits, hits_before + 1);
assert_eq!(
hit.response.into_body().collect().await.unwrap().to_bytes(),
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("X-Theme, cookie"));
assert!(normalize_static_cookie_vary(
StatusCode::OK, &mut h, &settings, Duration::ZERO, true,
StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE,
));
assert_eq!(h["vary"], "Accept-Language, X-Theme");
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()]
);
assert!(!normalize_static_cookie_vary(
StatusCode::OK, &mut h, &settings, Duration::ZERO, true,
StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE,
));
}
@@ -1477,12 +1511,21 @@ mod tests {
let settings = Settings::default();
let mut h = headers(policy);
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();
assert!(!normalize_static_cookie_vary(
StatusCode::OK, &mut h, &settings, Duration::ZERO, true,
&ResponseOverrides::NONE,
), "{policy}, {vary}");
assert!(
!normalize_static_cookie_vary(
StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE,
),
"{policy}, {vary}"
);
assert_eq!(h, original, "{policy}, {vary}");
}
let mut settings = Settings::default();
@@ -1490,16 +1533,28 @@ mod tests {
h.insert("vary", HeaderValue::from_static("Cookie"));
settings.static_ignore_vary_cookie = false;
assert!(!normalize_static_cookie_vary(
StatusCode::OK, &mut h, &settings, Duration::ZERO, true,
StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE,
));
settings.static_ignore_vary_cookie = true;
assert!(!normalize_static_cookie_vary(
StatusCode::OK, &mut h, &settings, Duration::ZERO, false,
StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
false,
&ResponseOverrides::NONE,
));
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,
));
assert_eq!(h["vary"], "Cookie");
@@ -1521,10 +1576,17 @@ mod tests {
h.insert("etag", HeaderValue::from_static("\"asset\""));
}
let original = h.clone();
assert!(!normalize_static_cookie_vary(
StatusCode::OK, &mut h, &settings, Duration::ZERO, true,
&ResponseOverrides::NONE,
), "{policy}");
assert!(
!normalize_static_cookie_vary(
StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE,
),
"{policy}"
);
assert_eq!(h, original, "{policy}");
}
@@ -1535,7 +1597,11 @@ mod tests {
let mut h = headers("public");
h.insert("vary", HeaderValue::from_static("Cookie"));
assert!(normalize_static_cookie_vary(
StatusCode::OK, &mut h, &settings, Duration::ZERO, true,
StatusCode::OK,
&mut h,
&settings,
Duration::ZERO,
true,
&ResponseOverrides::NONE,
));
assert!(!h.contains_key("vary"));
@@ -1545,9 +1611,19 @@ mod tests {
fn static_vary_cookie_vhost_override_inherits_and_can_disable() {
let global = Settings::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);
assert!(!overrides.resolve(&global).unwrap().static_ignore_vary_cookie);
assert!(
!overrides
.resolve(&global)
.unwrap()
.static_ignore_vary_cookie
);
}
#[test]
+51 -8
View File
@@ -10,6 +10,48 @@ impl Cache {
None
}
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,
ticket: Ticket,
cached: &Revalidation,
@@ -17,6 +59,7 @@ impl Cache {
validation_headers: &HeaderMap,
settings: &Settings,
response_delay: Duration,
client_hit: bool,
) -> Option<Hit> {
let plan = plan(StatusCode::OK, &headers, settings, response_delay)?;
if cached.body.len() > settings.max_object_bytes {
@@ -28,7 +71,7 @@ impl Cache {
}
}
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 remaining_ttl = plan.ttl.saturating_sub(age);
let vary = plan.vary.clone();
@@ -96,11 +139,13 @@ impl Cache {
if cached.storage_key != storage_key {
self.discard_storage_key(&cached.storage_key);
}
self.counters.hits.fetch_add(1, Ordering::Relaxed);
if client_hit {
self.counters.hits.fetch_add(1, Ordering::Relaxed);
}
let mut response = cached.response(headers);
response.headers_mut().insert(::http::header::AGE,
HeaderValue::from(age),
);
response
.headers_mut()
.insert(::http::header::AGE, HeaderValue::from(age));
Some(Hit {
response,
body: cached.body.clone(),
@@ -205,9 +250,7 @@ impl Cache {
candidate.finish();
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(
parts,
Body::new(FillBody {
+40 -1
View File
@@ -38,6 +38,8 @@ pub struct Metrics {
pub websocket_duration_us: AtomicU64,
pub requests: AtomicU64,
pub completed: AtomicU64,
pub completed_success: AtomicU64,
cache_request_outcomes: [AtomicU64; 4],
pub active: AtomicU64,
pub errors: AtomicU64,
pub rejected_requests: AtomicU64,
@@ -52,6 +54,13 @@ pub struct Metrics {
pub status_4xx: 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)]
pub struct View {
pub http1_requests: u64,
@@ -83,6 +92,8 @@ pub struct View {
pub websocket_bytes_out: u64,
pub requests: u64,
pub completed: u64,
pub completed_success: u64,
pub cache_request_outcomes: CacheRequestOutcomes,
pub active: u64,
pub errors: u64,
pub rejected_requests: u64,
@@ -97,6 +108,26 @@ fn n(value: &AtomicU64) -> u64 {
value.load(Ordering::Relaxed)
}
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) {
let counter = match encoding {
crate::compression::AppliedEncoding::Gzip => &self.compression_gzip,
@@ -139,6 +170,8 @@ impl Metrics {
websocket_bytes_out: n(&self.websocket_bytes_out),
requests: n(&self.requests),
completed,
completed_success: n(&self.completed_success),
cache_request_outcomes: self.cache_request_outcomes(),
active: n(&self.active),
errors: n(&self.errors),
rejected_requests: n(&self.rejected_requests),
@@ -156,11 +189,17 @@ impl Metrics {
}
pub fn prometheus(&self, logs_dropped: u64, revision: u64) -> String {
let mut out = String::new();
let cache = self.cache_request_outcomes();
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",
"counter",
"Public requests received using HTTP/1.1.",
"Public requests received using HTTP/1.0 or HTTP/1.1.",
n(&self.http1_requests),
),
(
+8 -4
View File
@@ -214,10 +214,12 @@ fn summary_from_snapshot(detail: &Value, rates: crate::metrics::SummaryRates) ->
.as_u64()
.zip(system["memory_total_bytes"].as_u64())
.and_then(|(used, total)| percentage(used, total));
let request_error_percent = percentage(
number(&requests["errors_total"]),
number(&requests["completed_total"]),
);
let errors = number(&requests["errors_total"]);
let completed_for_ratio = requests["completed_success_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"]
.as_array()
.map_or(0u64, |items| {
@@ -481,6 +483,8 @@ fn snapshot(app: &App) -> Value {
let requests = json!({
"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,
"rejected_total": metrics.rejected_requests,
"status": {
+47
View File
@@ -90,6 +90,8 @@ pub struct Exchange {
pub status: AtomicU16,
pub cache_status: AtomicU16,
pub cache_reason: Mutex<&'static str>,
pub cache_scope: Mutex<Option<(String, String)>>,
pub cache_outcome_recorded: AtomicBool,
pub failed: AtomicBool,
pub aborted: AtomicBool,
pub request_bytes: AtomicU64,
@@ -100,6 +102,43 @@ pub struct Exchange {
pub _permit: OwnedSemaphorePermit,
}
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) {
self.source.store(source as u8, Ordering::Relaxed);
}
@@ -157,6 +196,10 @@ impl Exchange {
}
impl Drop for Exchange {
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 failed = self.failed.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);
if failed || aborted || status >= 500 {
self.metrics.errors.fetch_add(1, Ordering::Relaxed);
} else {
self.metrics
.completed_success
.fetch_add(1, Ordering::Relaxed);
}
match status / 100 {
1 => &self.metrics.status_1xx,
+46
View File
@@ -38,6 +38,8 @@ mod tests {
status: AtomicU16::new(200),
cache_status: AtomicU16::new(0),
cache_reason: Mutex::new("not_proxy_response"),
cache_scope: Mutex::new(None),
cache_outcome_recorded: AtomicBool::new(false),
failed: AtomicBool::new(false),
aborted: AtomicBool::new(false),
request_bytes: AtomicU64::new(0),
@@ -49,6 +51,50 @@ mod tests {
});
(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]
async fn optimized_empty_request_keeps_exchange_until_response() {
let (exchange, slots) = observation().await;
+56 -28
View File
@@ -55,10 +55,9 @@ fn schedule_proactive_refresh(
if !refreshed {
return;
}
context.state.cache.record(
context.state.cache.record_reason(
&context.scope,
&context.host,
"HIT",
"cache_proactive_refreshed",
);
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()
.insert(::http::header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
response.headers_mut().insert(
::http::header::CACHE_CONTROL,
HeaderValue::from_static("no-store"),
);
}
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 = (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"),
);
response.headers_mut().insert(::http::header::X_CONTENT_TYPE_OPTIONS,
response.headers_mut().insert(
::http::header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
response
@@ -123,10 +125,12 @@ fn error(status: StatusCode, detail: &'static str) -> Response {
);
(status, body).into_response()
};
response
.headers_mut()
.insert(::http::header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
response.headers_mut().insert(::http::header::X_CONTENT_TYPE_OPTIONS,
response.headers_mut().insert(
::http::header::CACHE_CONTROL,
HeaderValue::from_static("no-store"),
);
response.headers_mut().insert(
::http::header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
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());
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
}
@@ -296,7 +302,8 @@ fn finish_headers(
.unwrap_or(&snapshot.envelope.config.diagnostic_headers)
.apply(response.headers_mut(), request_id);
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"),
);
}
@@ -328,9 +335,15 @@ fn server_timing_value(
crate::vhost::TimingHeaderNames::Cdn => ("edge", "origin", "cdn-cache"),
crate::vhost::TimingHeaderNames::Legacy => ("proxy", "origin", "cache"),
};
let mut values = vec![format!("{total_name};dur={:.2}", total.as_secs_f64() * 1000.0)];
let mut values = vec![format!(
"{total_name};dur={:.2}",
total.as_secs_f64() * 1000.0
)];
if let Some(origin) = origin {
values.push(format!("{origin_name};dur={:.2}", origin.as_secs_f64() * 1000.0));
values.push(format!(
"{origin_name};dur={:.2}",
origin.as_secs_f64() * 1000.0
));
}
if let Some(cache) = cache {
values.push(format!("{cache_name};desc=\"{cache}\""));
@@ -349,33 +362,39 @@ fn apply_timing_headers(
let Some(frontend) = frontend.filter(|frontend| frontend.timing_headers) else {
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(
frontend.timing_header_names,
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),
);
if let Ok(value) = HeaderValue::from_str(&value) {
response.headers_mut().append("server-timing", value);
}
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> {
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);
};
let Some((agent, hash)) = name.rsplit_once('-') else {
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()) {
return std::borrow::Cow::Borrowed(id);
}
@@ -388,12 +407,19 @@ fn apply_backend_diagnostic_values(
backend_timing_header: bool,
) {
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 =
::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();
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) {
headers.remove(name);
}
@@ -478,7 +504,9 @@ async fn normalize_h3_h1_unknown_body(
if request.version() != Version::HTTP_3
|| upstream_version != Version::HTTP_11
|| 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()
{
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");
return None;
};
if let Some(exchange) = &template.exchange {
exchange.reset_cache_outcome();
}
let request = template.rebuild(
body.clone(),
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(
app: Arc<App>,
method: Method,
@@ -244,6 +261,7 @@ mod cache_fast_path_tests {
.await;
assert_eq!(allowed.status, StatusCode::OK);
assert_eq!(origin.requests.load(Ordering::Relaxed), 1);
assert_cache_outcomes(&fixture, 0, 0, 1, 1);
fixture.stop().await;
}
@@ -482,15 +500,18 @@ mod cache_fast_path_tests {
_ => "public, max-age=600",
}),
);
response
.headers_mut()
.insert("vary", HeaderValue::from_static(if parts.uri.path().starts_with("/vary-cookie") {
response.headers_mut().insert(
"vary",
HeaderValue::from_static(if parts.uri.path().starts_with("/vary-cookie") {
"Cookie, X-Variant"
} else {
"X-Variant"
}));
}),
);
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
.headers_mut()
@@ -772,6 +793,7 @@ mod cache_fast_path_tests {
cache_chain(&posted.headers).last().copied(),
Some("RustProxy; fwd=method; detail=\"request_method\""),
);
assert_cache_outcomes(&fixture, 1, 1, 1, 0);
fixture.stop().await;
}
@@ -790,6 +812,7 @@ mod cache_fast_path_tests {
Some("RustProxy; fwd=stale; fwd-status=503; detail=\"cache_stale_if_error\""),
);
assert_eq!(origin.requests.load(Ordering::Relaxed), 2);
assert_cache_outcomes(&fixture, 1, 1, 0, 0);
fixture.stop().await;
}
@@ -827,7 +850,10 @@ mod cache_fast_path_tests {
let cdn = fixture.get("/server-timing", &[]).await.headers;
let cdn_timing = server_timing(&cdn);
assert!(cdn_timing[0].starts_with("edge;dur="), "{cdn_timing:?}");
assert!(cdn_timing[0].ends_with(", cdn-cache;desc=\"HIT\""), "{cdn_timing:?}");
assert!(
cdn_timing[0].ends_with(", cdn-cache;desc=\"HIT\""),
"{cdn_timing:?}"
);
assert_eq!(cdn["timing-allow-origin"], "https://rum.example.com");
fixture
.change(|config| {
@@ -850,17 +876,25 @@ mod cache_fast_path_tests {
fixture.get("/stale-then-503", &[]).await;
let stale = server_timing(&fixture.get("/stale-then-503", &[]).await.headers);
assert_eq!(stale.len(), 1, "{stale:?}");
assert!(stale[0].ends_with(", proxy-cache;desc=\"STALE\""), "{stale:?}");
assert!(
stale[0].ends_with(", proxy-cache;desc=\"STALE\""),
"{stale:?}"
);
fixture.get("/cache-headers-revalidate", &[]).await;
let revalidated =
server_timing(&fixture.get("/cache-headers-revalidate", &[]).await.headers);
assert_eq!(revalidated.len(), 1, "{revalidated:?}");
assert!(revalidated[0].contains(", upstream;dur="), "{revalidated:?}");
assert!(
revalidated[0].contains(", upstream;dur="),
"{revalidated:?}"
);
assert!(
revalidated[0].ends_with(", proxy-cache;desc=\"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;
assert_eq!(server_timing(&quiet.headers), vec!["app;dur=7".to_owned()]);
let cached = fixture.get("/server-timing", &[]).await;
@@ -875,13 +909,25 @@ mod cache_fast_path_tests {
let mut config = config_for(origin.addr, true);
config.cache.expose_detailed_status = true;
let fixture = Fixture::new(config).await;
assert_eq!(fixture.get("/stale-then-503", &[]).await.headers["x-cache"], "MISS");
assert_eq!(fixture.get("/stale-then-503", &[]).await.headers["x-cache"], "STALE");
assert_eq!(
fixture.get("/stale-then-503", &[]).await.headers["x-cache"],
"MISS"
);
assert_eq!(
fixture.get("/stale-then-503", &[]).await.headers["x-cache"],
"STALE"
);
fixture.get("/cache-headers-revalidate", &[]).await;
let revalidated = fixture.get("/cache-headers-revalidate", &[]).await;
assert_eq!(revalidated.headers["x-cache"], "REVALIDATED");
assert_eq!(fixture.get("/server-timing", &[]).await.headers["x-cache"], "MISS");
assert_eq!(fixture.get("/server-timing", &[]).await.headers["x-cache"], "HIT");
assert_eq!(
fixture.get("/server-timing", &[]).await.headers["x-cache"],
"MISS"
);
assert_eq!(
fixture.get("/server-timing", &[]).await.headers["x-cache"],
"HIT"
);
let mut logged = Vec::new();
for _ in 0..50 {
logged = fixture
@@ -897,7 +943,10 @@ mod cache_fast_path_tests {
}
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 stale: u64 = dashboard.domains.iter().map(|row| row.counters.stale).sum();
let revalidated: u64 = dashboard
@@ -907,8 +956,13 @@ mod cache_fast_path_tests {
.sum();
let hits: u64 = dashboard.domains.iter().map(|row| row.counters.hits).sum();
assert_eq!((stale, revalidated, hits), (1, 1, 3));
fixture.change(|config| config.cache.expose_detailed_status = false).await;
assert_eq!(fixture.get("/stale-then-503", &[]).await.headers["x-cache"], "HIT");
fixture
.change(|config| config.cache.expose_detailed_status = false)
.await;
assert_eq!(
fixture.get("/stale-then-503", &[]).await.headers["x-cache"],
"HIT"
);
fixture.stop().await;
}
@@ -939,15 +993,30 @@ mod cache_fast_path_tests {
config.cache.static_ignore_cookies = true;
config.cache.static_ignore_vary_cookie = true;
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["vary"], "X-Variant");
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["vary"], "X-Variant");
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.body, "origin-b");
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.vhosts[0].cache.static_ignore_vary_cookie = Some(false);
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["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!(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;
assert_eq!(private.headers["vary"], "Cookie, X-Variant");
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!(fixture.app.metrics.completed.load(Ordering::Relaxed), 12);
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;
}
}
+9 -43
View File
@@ -1,5 +1,9 @@
{
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 let Some(mut hit) = state.cache.get_tiered(ticket, cache_settings).await {
let conditional = crate::cache::conditional_not_modified(
@@ -57,10 +61,9 @@ if let Some(ticket) = &cache_ticket {
tokio::spawn(async move {
let _guard = guard;
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.host,
"HIT",
"cache_stale_while_revalidate_refreshed",
);
}
@@ -100,14 +103,7 @@ if let Some(ticket) = &cache_ticket {
hit.response = crate::cache::make_not_modified(hit.response);
}
if let Some(exchange) = &exchange {
exchange.cache_status.store(1, Ordering::Relaxed);
}
state.cache.record(scope, &host, "HIT", reason);
if let Some(exchange) = &exchange {
*exchange
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner()) = reason;
exchange.set_cache_outcome(scope, &host, 1, reason);
}
cache_settings.annotate_reason_transformed_freshness(
hit.response.headers_mut(),
@@ -127,37 +123,14 @@ if let Some(ticket) = &cache_ticket {
hit.response.extensions_mut().insert(ResponseRulesApplied);
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() {
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 {
state.cache.bypass();
let reason = effective_reason.unwrap_or("configuration_changed");
state.cache.record(scope, &host, "BYPASS", reason);
if let Some(exchange) = &exchange {
exchange.cache_status.store(3, Ordering::Relaxed);
*exchange
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner()) = reason;
exchange.set_cache_outcome(scope, &host, 3, reason);
}
}
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
.extensions_mut()
.insert(OriginBackend(origin_backend.to_owned()));
state.cache.record(scope, &host, "HIT", reason);
if let Some(exchange) = &exchange {
exchange.cache_status.store(1, Ordering::Relaxed);
*exchange.cache_reason.lock().unwrap_or_else(|e| e.into_inner()) = reason;
exchange.set_cache_outcome(scope, &host, 1, reason);
}
Some(intercept_route_origin_error(hit.response, route, &snapshot))
};
@@ -283,13 +254,8 @@ if handshake.is_none()
hit.resident_age_seconds,
);
hit.response.extensions_mut().insert(ResponseRulesApplied);
state.cache.record(scope, &host, "HIT", reason);
if let Some(exchange) = &exchange {
exchange.cache_status.store(1, Ordering::Relaxed);
*exchange
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner()) = reason;
exchange.set_cache_outcome(scope, &host, 1, reason);
}
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
.as_ref()
.is_some_and(|cached| !cached.reusable_for_request(&freshness_headers));
let miss_recorded = false;
(
backend, backend_lease, affinity_cookie, admin_control_plane, cache_settings,
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,
range_selection, if_range, range_requested, effective_reason, 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,
)
}
+3 -20
View File
@@ -85,13 +85,8 @@ if response.status() == StatusCode::NOT_MODIFIED && revalidation_sent {
.extensions_mut()
.insert(OriginBackend(active_backend.id.clone()));
if let Some(exchange) = &exchange {
exchange.cache_status.store(1, Ordering::Relaxed);
*exchange
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner()) = "cache_revalidated";
exchange.set_cache_outcome(scope, &host, 1, "cache_revalidated");
}
state.cache.record(scope, &host, "HIT", "cache_revalidated");
return intercept_route_origin_error(revalidated, route, &snapshot);
}
}
@@ -133,19 +128,8 @@ let reason = effective_reason
"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 {
*exchange
.cache_reason
.lock()
.unwrap_or_else(|e| e.into_inner()) = reason;
exchange.set_cache_outcome(scope, &host, if outcome == "MISS" { 2 } else { 3 }, reason);
}
if fill_leader.is_some() && (origin_plan.is_none() || transformed_plan.is_none()) {
if let Some(ticket) = cache_ticket.as_ref() {
@@ -174,8 +158,7 @@ if let (Some(ticket), Some(plan), Some(transformed)) =
cache_settings,
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
&& !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",
);
}
// 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() {
crate::cache::shared_static_response_reason(
response.status(), response.headers(), cache_settings,
@@ -417,7 +416,6 @@ if !range_requested && handshake.is_none() {
state
.transform_metrics
.record_error(scope, transform_started.elapsed());
state.cache.record_reason(scope, &host, "transform_error");
if let Some(exchange) = &exchange {
*exchange
.cache_reason
+11 -9
View File
@@ -84,6 +84,14 @@
(needs_validation,
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 !needs_validation {
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,
hit.cache_status_ttl, "cache_hit", hit.transformed);
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 let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
exchange.cache_status.store(1, Ordering::Relaxed);
*exchange.cache_reason.lock().unwrap_or_else(|e| e.into_inner()) = "cache_hit";
exchange.set_cache_outcome(scope, &host, 1, "cache_hit");
}
response.extensions_mut().insert(ResponseRulesApplied);
response.extensions_mut().insert(StaticSourceResponse);
@@ -158,11 +164,9 @@
route.frontend.as_deref(), Some(route), false),
);
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 let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
exchange.cache_status.store(1, Ordering::Relaxed);
*exchange.cache_reason.lock().unwrap_or_else(|e| e.into_inner()) = hit.reason;
exchange.set_cache_outcome(scope, &host, 1, hit.reason);
}
hit.response.extensions_mut().insert(ResponseRulesApplied);
hit.response.extensions_mut().insert(StaticSourceResponse);
@@ -263,10 +267,8 @@
}
}
if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
exchange.cache_status.store(if outcome == "MISS" { 2 } else { 3 }, Ordering::Relaxed);
*exchange.cache_reason.lock().unwrap_or_else(|e| e.into_inner()) = reason;
exchange.set_cache_outcome(scope, &host, if outcome == "MISS" { 2 } else { 3 }, reason);
}
state.cache.record(scope, &host, outcome, reason);
let transformed = response.extensions().get::<crate::transform::Applied>().is_some();
if let Some(cached) = &cached_revalidation {
cache_settings.annotate_reason_transformed_forwarded(
+20 -16
View File
@@ -145,16 +145,21 @@ async fn forward_request(
let frontend_rank = frontend.and_then(|_| snapshot.frontend_rank(&host, local.0, tls));
let redirect = snapshot
.redirect_on(&host, &path, local.0, tls)
.filter(|_| match (frontend_rank, snapshot.redirect_rank(&host, &path, local.0, tls)) {
(Some(vhost), Some(redirect)) => redirect >= vhost,
_ => true,
.filter(|_| {
match (
frontend_rank,
snapshot.redirect_rank(&host, &path, local.0, tls),
) {
(Some(vhost), Some(redirect)) => redirect >= vhost,
_ => true,
}
});
let local_host = snapshot
.not_found_host_on(&host, local.0, tls)
.filter(|_| match (frontend_rank, snapshot.not_found_rank(&host, local.0, tls)) {
let local_host = snapshot.not_found_host_on(&host, local.0, tls).filter(|_| {
match (frontend_rank, snapshot.not_found_rank(&host, local.0, tls)) {
(Some(vhost), Some(local_host)) => local_host >= vhost,
_ => true,
});
}
});
// Requests answered by a redirect or local 404 host are logged under that host.
if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
let site = redirect
@@ -311,7 +316,9 @@ async fn forward_request(
"RustProxy: global request rate limit exceeded\n",
);
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;
}
@@ -368,7 +375,9 @@ async fn forward_request(
"RustProxy: request rate limit exceeded\n",
);
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;
}
@@ -468,10 +477,7 @@ async fn forward_request(
.as_ref()
.and_then(|selection| selection.route.as_ref());
if precomputed.is_none_or(|route| !Arc::ptr_eq(route, chosen)) {
*exchange
.routed
.lock()
.unwrap_or_else(|e| e.into_inner()) = Some(chosen.clone());
*exchange.routed.lock().unwrap_or_else(|e| e.into_inner()) = Some(chosen.clone());
}
}
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
.pool
.as_ref()
@@ -640,7 +645,6 @@ async fn forward_request(
cached_revalidation,
freshness_revalidation_reason,
pending_revalidation,
mut miss_recorded,
cache_rule_context,
static_cookie_relaxed,
shared_static_cookie_fill,
+13 -13
View File
@@ -62,7 +62,11 @@ async fn dispatch(state: Arc<App>, request: Request) -> Response {
let peer = request.extensions().get::<PeerAddr>().copied();
let local = request.extensions().get::<LocalAddr>().copied();
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
}
@@ -364,18 +368,14 @@ async fn refresh_cache_once(
pool.strip_affinity_response(&mut validation_headers);
}
let merged = cached.merge_validation_headers(&validation_headers);
return context
.state
.cache
.publish_revalidated(
ticket,
&cached,
merged,
&origin_validation_headers,
&context.cache_settings,
started.elapsed(),
)
.is_some();
return context.state.cache.publish_background_revalidated(
ticket,
&cached,
merged,
&origin_validation_headers,
&context.cache_settings,
started.elapsed(),
);
}
if origin.status() != StatusCode::OK {
return false;
+58 -36
View File
@@ -41,13 +41,10 @@ fn should_replace_error_page(response: &Response, minimal_welcome: bool) -> bool
.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) {
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());
if let Some(fill) = fill {
tokio::spawn(async move {
@@ -106,7 +103,7 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
&& request.method() == Method::CONNECT
&& websocket::h3_protocol(&request) == Some("websocket"));
match request.version() {
Version::HTTP_11 => {
Version::HTTP_10 | Version::HTTP_11 => {
state.metrics.http1_requests.fetch_add(1, Ordering::Relaxed);
}
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);
}
let Ok(permit) = state.inflight.clone().try_acquire_owned() else {
state.metrics.record_cache_request_outcome(0);
state
.metrics
.rejected_requests
@@ -242,6 +240,8 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
status: AtomicU16::new(500),
cache_status: AtomicU16::new(0),
cache_reason: Mutex::new("not_proxy_response"),
cache_scope: Mutex::new(None),
cache_outcome_recorded: AtomicBool::new(false),
failed: AtomicBool::new(false),
aborted: AtomicBool::new(false),
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()
.insert(::http::header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
response.headers_mut().insert(
::http::header::CACHE_CONTROL,
HeaderValue::from_static("no-store"),
);
} else {
if response
.extensions()
@@ -475,8 +476,10 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
// Stale-if-error copies name the backend that failed; a plain cache hit has none.
let origin = response.extensions().get::<OriginBackend>().map(|o| o.0.clone());
let origin = response
.extensions()
.get::<OriginBackend>()
.map(|o| o.0.clone());
let srv_id = lease
.as_ref()
.map(|lease| lease.member.definition.id.clone())
@@ -485,7 +488,9 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
.as_deref()
.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
.extensions()
.get::<OriginTiming>()
@@ -507,7 +512,9 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
.as_ref()
.and_then(|v| v.vhost.as_deref())
.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()),
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()),
@@ -570,6 +577,7 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
exchange
.status
.store(response.status().as_u16(), Ordering::Relaxed);
exchange.finish_cache_outcome(&state.cache);
let ws_success = response.status() == StatusCode::SWITCHING_PROTOCOLS
|| response.extensions().get::<websocket::H3Tunnel>().is_some();
if ws_attempt && !ws_success {
@@ -632,7 +640,14 @@ mod head_cache_fill_tests {
..Default::default()
};
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");
let mut origin = Response::new(Body::from("cached from HEAD"));
origin.headers_mut().insert(
@@ -643,22 +658,24 @@ mod head_cache_fill_tests {
::http::header::CONTENT_LENGTH,
HeaderValue::from_static("16"),
);
let plan = crate::cache::plan(
StatusCode::OK,
origin.headers(),
&settings,
Duration::ZERO,
)
.expect("cacheable GET representation");
let plan = crate::cache::plan(StatusCode::OK, origin.headers(), &settings, Duration::ZERO)
.expect("cacheable GET representation");
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);
assert_eq!(head.headers()[::http::header::CONTENT_LENGTH], "16");
assert!(head.body().is_end_stream(), "HEAD must have no response body");
assert!(head.extensions().get::<crate::cache::PendingFill>().is_none());
assert!(
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 {
loop {
if let Some(hit) = cache.get(&ticket) {
@@ -685,25 +702,30 @@ mod head_cache_fill_tests {
..Default::default()
};
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");
let mut origin = Response::new(Body::from(Bytes::from(vec![b'x'; 1025])));
origin.headers_mut().insert(
::http::header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=60"),
);
let plan = crate::cache::plan(
StatusCode::OK,
origin.headers(),
&settings,
Duration::ZERO,
)
.expect("cacheable headers, unknown body length");
let plan = crate::cache::plan(StatusCode::OK, origin.headers(), &settings, Duration::ZERO)
.expect("cacheable headers, unknown body length");
let mut head = cache.wrap(origin, ticket.clone(), plan, &settings);
strip_head_response_body(&mut head);
assert!(head.body().is_end_stream());
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]