v0.41.0
This commit is contained in:
1 parent
54b2ac0838
commit
3b953dcdc6
23 files changed
+643
-29
No files matched your search
@@ -212,7 +212,7 @@
|
||||
"value": {
|
||||
"type": "string",
|
||||
"maxLength": 8192,
|
||||
"description": "Required for set/append; omit for remove. Literal, no variable substitution."
|
||||
"description": "Value for set/append. May contain variables `%[name]`: srv_id, srv_url, location, vhost, lb_algorithm, hash_key, client_ip, country, req_id, method, host, path, and in response rules also cache_status and backend_time. Rules with variables are applied per request, last in their direction, and never cached; a missing value renders as `-`."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
|
||||
@@ -2430,3 +2430,25 @@ h2+.fine {
|
||||
font-family: var(--mono);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* Header value variables and diagnostic header presets. */
|
||||
.hdr-vars,
|
||||
.hdr-presets {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 6px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.hdr-vars-label {
|
||||
color: var(--muted);
|
||||
font: 600 10px var(--mono);
|
||||
letter-spacing: .35px;
|
||||
}
|
||||
|
||||
.hdr-var {
|
||||
border-radius: 999px;
|
||||
padding: 2px 8px;
|
||||
font: 11px var(--mono);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
// Load-balancing editor (vhost and location) with a consistent-hash distribution
|
||||
// simulator. The pure helpers at the top mirror src/balance/model.rs (rendezvous
|
||||
// scoring and hash keys) and are checked by tools/dev/test_balance_simulator.js.
|
||||
// scoring and hash keys); keep them in step with tests/fixtures/balance_rendezvous_vectors.txt.
|
||||
const lbSha256 = (() => {
|
||||
const K = new Uint32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use strict";
|
||||
let vhostCacheRulesEditor = null;
|
||||
let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null, vhostBalancingControl = null;
|
||||
let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null, vhostBalancingControl = null, vhostHeadersControl = null;
|
||||
const chartHistory = new Map();
|
||||
const backendTrafficHistory = new Map();
|
||||
const backendRequestHistory = new Map();
|
||||
@@ -87,6 +87,15 @@ function validateHeaders(value) {
|
||||
}
|
||||
} return value;
|
||||
}
|
||||
// Header value variables (src/headers/mod.rs Var::ALL); true = response rules only.
|
||||
const HEADER_VARIABLES = [["srv_id", false], ["srv_url", false], ["location", false], ["vhost", false], ["lb_algorithm", false], ["hash_key", false], ["client_ip", false], ["country", false], ["req_id", false], ["method", false], ["host", false], ["path", false], ["cache_status", true], ["backend_time", true]];
|
||||
const DIAGNOSTIC_PRESETS = [
|
||||
{ key: "hdrPresetServedBy", direction: "response", rule: { op: "set", name: "X-Served-By", value: "%[srv_id]" } },
|
||||
{ key: "hdrPresetLocation", direction: "response", rule: { op: "set", name: "X-Location", value: "%[location]" } },
|
||||
{ key: "hdrPresetBalance", direction: "response", rule: { op: "set", name: "X-LB", value: "%[lb_algorithm] %[hash_key]" } },
|
||||
{ key: "hdrPresetDebug", direction: "response", rule: { op: "set", name: "X-Debug", value: "%[vhost]/%[location] -> %[srv_id] (%[cache_status], %[backend_time])" } },
|
||||
{ key: "hdrPresetUpstream", direction: "request", rule: { op: "set", name: "X-Shard", value: "%[srv_id]" } }
|
||||
];
|
||||
function headerEditors(parent, initial, target = read("headers"), onChange = changed) {
|
||||
const holders = {}, adders = {}, emptyStates = {};
|
||||
const renumber = direction => {
|
||||
@@ -127,6 +136,20 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha
|
||||
};
|
||||
adders[direction] = add; for (const rule of initial[direction] || []) add(rule); renumber(direction);
|
||||
block.append(button("addHeader", () => { add(); sync(); }, "quiet location-add-header"));
|
||||
// %[variable] chips insert into the last focused value field of this direction.
|
||||
const chips = el("div", undefined, "hdr-vars"); chips.append(text("span", "hdrVariables", "hdr-vars-label"));
|
||||
let lastValue = null; rows.addEventListener("focusin", event => { if (event.target.name === "rule-value") lastValue = event.target; });
|
||||
for (const [name, responseOnly] of HEADER_VARIABLES) {
|
||||
if (responseOnly && direction === "request") continue;
|
||||
const chip = button("hdrVariables", () => {
|
||||
let target = lastValue?.isConnected && !lastValue.disabled ? lastValue : [...rows.querySelectorAll('[name="rule-value"]:not(:disabled)')].pop();
|
||||
if (!target) { add({ op: "set", name: "", value: "" }); target = [...rows.querySelectorAll('[name="rule-value"]')].pop(); }
|
||||
const token = `%[${name}]`, at = target.selectionStart ?? target.value.length;
|
||||
target.value = target.value.slice(0, at) + token + target.value.slice(target.selectionEnd ?? at); target.focus(); target.setSelectionRange(at + token.length, at + token.length); lastValue = target; sync();
|
||||
}, "quiet hdr-var");
|
||||
delete chip.dataset.i18n; chip.textContent = `%[${name}]`; chip.title = t(`hdrVar_${name}`); chips.append(chip);
|
||||
}
|
||||
block.append(chips);
|
||||
}
|
||||
target.addEventListener("input", () => {
|
||||
try {
|
||||
@@ -139,8 +162,8 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha
|
||||
target.setCustomValidity(""); onChange();
|
||||
} catch (error) { target.setCustomValidity(error.message || t("headersInvalid")); }
|
||||
});
|
||||
note(parent, "locationHeadersHelp");
|
||||
return { read: () => validateHeaders(JSON.parse(target.value)) };
|
||||
note(parent, "locationHeadersHelp"); note(parent, "hdrVariablesHelp");
|
||||
return { read: () => validateHeaders(JSON.parse(target.value)), add: (direction, rule) => { adders[direction](rule); renumber(direction); sync(); } };
|
||||
}
|
||||
function suspendDraft() {
|
||||
const state = {
|
||||
|
||||
@@ -211,6 +211,14 @@ function load(value = defaults(), migrationIds = [], show = true) {
|
||||
field(g, "backend-header", "vhBackendHeader", value.backend_header === true, "checkbox", { switch: true });
|
||||
field(g, "backend-timing-header", "vhBackendTimingHeader", value.backend_timing_header === true, "checkbox", { switch: true });
|
||||
note(g, "vhBackendDiagnosticsHelp");
|
||||
const diagnosticPresets = el("div", undefined, "vh-wide hdr-presets"); diagnosticPresets.append(text("span", "hdrPresets", "hdr-vars-label"));
|
||||
for (const preset of DIAGNOSTIC_PRESETS) diagnosticPresets.append(button(preset.key, () => {
|
||||
if (!vhostHeadersControl) return;
|
||||
const current = vhostHeadersControl.read()[preset.direction] || [];
|
||||
if (current.some(rule => rule.name.toLowerCase() === preset.rule.name.toLowerCase())) { toast(t("hdrPresetExists").replace("{name}", preset.rule.name)); return; }
|
||||
vhostHeadersControl.add(preset.direction, { ...preset.rule }); toast(t("hdrPresetAdded").replace("{name}", preset.rule.name));
|
||||
}, "quiet lb-preset"));
|
||||
g.append(diagnosticPresets); note(g, "hdrPresetsHelp");
|
||||
const proxyTimeouts = { ...defaultProxyTimeouts(), ...(value.proxy_timeouts || {}) };
|
||||
g = group("vhProxyTimeouts");
|
||||
field(g, "proxy-connect-timeout", "vhProxyConnectTimeout", proxyTimeouts.connect_timeout_seconds ?? 10, "number", { required: true, min: 1, max: 300 });
|
||||
@@ -561,7 +569,7 @@ function load(value = defaults(), migrationIds = [], show = true) {
|
||||
};
|
||||
transformEnabled.addEventListener("change", syncTransform); customTransformExtensions.addEventListener("change", syncTransform); syncTransform();
|
||||
note(transformOptions, "vhTransformHelp");
|
||||
g = group("vhHeaders"); headerEditors(g, value.headers || {});
|
||||
g = group("vhHeaders"); vhostHeadersControl = headerEditors(g, value.headers || {});
|
||||
g = group("vhPages"); g.classList.add("vh-pages-grid"); pagesEditor = window.rustProxyPages.vhostEditor(g, value.pages || {});
|
||||
initTabs(); dirty = false; if (latestStatus) renderStatus(latestStatus); if (show && !dialog.open) dialog.showModal();
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Location conditions editor and the routing tester. The pure helpers mirror
|
||||
// src/config/snapshot.rs (select_route) and src/vhost/conditions.rs and are checked
|
||||
// against tests/fixtures/routing_conditions_cases.json by tools/dev/test_routing_tester.js.
|
||||
// against the cases in tests/fixtures/routing_conditions_cases.json.
|
||||
const RT_SOURCES = [["header", "rtSourceHeader"], ["cookie", "rtSourceCookie"], ["query", "rtSourceQuery"], ["method", "rtSourceMethod"], ["ip", "rtSourceIp"], ["host", "rtSourceHost"], ["country", "rtSourceCountry"]];
|
||||
const RT_OPERATORS = [["equals", "rtOpEquals"], ["exists", "rtOpExists"], ["prefix", "rtOpPrefix"], ["suffix", "rtOpSuffix"], ["contains", "rtOpContains"], ["regex", "rtOpRegex"], ["cidr", "rtOpCidr"]];
|
||||
function rtOperatorsFor(source) {
|
||||
|
||||
@@ -279,8 +279,8 @@ mod hash_tests {
|
||||
assert_eq!(selection.lease.member.definition.id, expected);
|
||||
}
|
||||
|
||||
/// Reference values shared with `tools/dev/test_balance_simulator.js` (fixture `tests/fixtures/balance_rendezvous_vectors.txt`), which checks
|
||||
/// that the panel simulator ranks members exactly like the proxy.
|
||||
/// Reference values (tests/fixtures/balance_rendezvous_vectors.txt); the panel
|
||||
/// simulator in balancing.js must rank members the same way.
|
||||
#[test]
|
||||
fn rendezvous_reference_vectors() {
|
||||
let order = |key: &str| {
|
||||
|
||||
@@ -183,6 +183,36 @@ impl Pool {
|
||||
pub fn ready(&self) -> bool {
|
||||
!self.eligible_healthy_excluding(&[]).is_empty()
|
||||
}
|
||||
/// Hash key the pool uses for this request (consistent `hash` or `ip_hash`), for
|
||||
/// the `%[hash_key]` header variable.
|
||||
pub fn balance_key(
|
||||
&self,
|
||||
peer: IpAddr,
|
||||
headers: &HeaderMap,
|
||||
uri: Option<&http::Uri>,
|
||||
) -> Option<String> {
|
||||
match self.plan(peer, headers, uri) {
|
||||
(Algorithm::Hash | Algorithm::IpHash, key) => key,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Effective algorithm name (`ip_hash` sticky mode reports `ip_hash`).
|
||||
pub fn algorithm_name(&self) -> &'static str {
|
||||
let algorithm = if self.settings.sticky.mode == StickyMode::IpHash {
|
||||
Algorithm::IpHash
|
||||
} else {
|
||||
self.settings.algorithm
|
||||
};
|
||||
match algorithm {
|
||||
Algorithm::RoundRobin => "round_robin",
|
||||
Algorithm::LeastConnections => "least_connections",
|
||||
Algorithm::LeastTraffic => "least_traffic",
|
||||
Algorithm::Adaptive => "adaptive",
|
||||
Algorithm::IpHash => "ip_hash",
|
||||
Algorithm::Hash => "hash",
|
||||
Algorithm::Random => "random",
|
||||
}
|
||||
}
|
||||
/// True when selection reads the request URI (path, URI, host or query hashing).
|
||||
pub fn hashes_request_uri(&self) -> bool {
|
||||
self.settings.algorithm == Algorithm::Hash
|
||||
|
||||
@@ -21,7 +21,7 @@ mod routing_conditions_tests {
|
||||
compile(cfg, 0, &policy())
|
||||
}
|
||||
|
||||
/// Shared with tools/dev/test_routing_tester.js (panel tester parity).
|
||||
/// The panel routing tester (routing.js) must agree with these cases.
|
||||
#[test]
|
||||
fn fixture_cases_select_the_expected_location() {
|
||||
let fixture: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
|
||||
|
||||
+248
-6
@@ -30,13 +30,190 @@ pub struct CompiledRule {
|
||||
op: Operation,
|
||||
name: HeaderName,
|
||||
value: Option<HeaderValue>,
|
||||
/// Value with `%[variable]` placeholders, rendered per request.
|
||||
template: Option<Template>,
|
||||
/// Applied only on the wire (final delivery): `Age` and every response rule with
|
||||
/// variables, so per-request values are never stored in the cache.
|
||||
wire_only: bool,
|
||||
}
|
||||
|
||||
/// Variables available in header values as `%[name]` (HAProxy-style sample fetches).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Var {
|
||||
SrvId,
|
||||
SrvUrl,
|
||||
Location,
|
||||
Vhost,
|
||||
LbAlgorithm,
|
||||
HashKey,
|
||||
ClientIp,
|
||||
Country,
|
||||
ReqId,
|
||||
Method,
|
||||
Host,
|
||||
Path,
|
||||
CacheStatus,
|
||||
BackendTime,
|
||||
}
|
||||
impl Var {
|
||||
pub const ALL: [(&'static str, Var); 14] = [
|
||||
("srv_id", Var::SrvId),
|
||||
("srv_url", Var::SrvUrl),
|
||||
("location", Var::Location),
|
||||
("vhost", Var::Vhost),
|
||||
("lb_algorithm", Var::LbAlgorithm),
|
||||
("hash_key", Var::HashKey),
|
||||
("client_ip", Var::ClientIp),
|
||||
("country", Var::Country),
|
||||
("req_id", Var::ReqId),
|
||||
("method", Var::Method),
|
||||
("host", Var::Host),
|
||||
("path", Var::Path),
|
||||
("cache_status", Var::CacheStatus),
|
||||
("backend_time", Var::BackendTime),
|
||||
];
|
||||
fn parse(name: &str) -> Option<Self> {
|
||||
Self::ALL
|
||||
.iter()
|
||||
.find(|(candidate, _)| *candidate == name)
|
||||
.map(|(_, var)| *var)
|
||||
}
|
||||
/// Known only once the response exists.
|
||||
fn response_only(self) -> bool {
|
||||
matches!(self, Var::CacheStatus | Var::BackendTime)
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
enum Segment {
|
||||
Text(String),
|
||||
Var(Var),
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Template(Vec<Segment>);
|
||||
impl Template {
|
||||
fn parse(value: &str) -> Result<Option<Self>> {
|
||||
if !value.contains("%[") {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut segments = Vec::new();
|
||||
let mut rest = value;
|
||||
while let Some(start) = rest.find("%[") {
|
||||
if start > 0 {
|
||||
segments.push(Segment::Text(rest[..start].to_owned()));
|
||||
}
|
||||
let after = &rest[start + 2..];
|
||||
let end = after
|
||||
.find(']')
|
||||
.context("unterminated %[variable] in header value")?;
|
||||
let name = &after[..end];
|
||||
let var = Var::parse(name).with_context(|| {
|
||||
format!(
|
||||
"unknown header variable %[{name}]; available: {}",
|
||||
Var::ALL
|
||||
.iter()
|
||||
.map(|(n, _)| format!("%[{n}]"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
)
|
||||
})?;
|
||||
segments.push(Segment::Var(var));
|
||||
rest = &after[end + 1..];
|
||||
}
|
||||
if !rest.is_empty() {
|
||||
segments.push(Segment::Text(rest.to_owned()));
|
||||
}
|
||||
Ok(Some(Self(segments)))
|
||||
}
|
||||
pub fn uses(&self, var: Var) -> bool {
|
||||
self.0
|
||||
.iter()
|
||||
.any(|segment| matches!(segment, Segment::Var(v) if *v == var))
|
||||
}
|
||||
fn render(&self, vars: &Vars<'_>) -> Option<HeaderValue> {
|
||||
let mut out = String::new();
|
||||
for segment in &self.0 {
|
||||
match segment {
|
||||
Segment::Text(text) => out.push_str(text),
|
||||
Segment::Var(var) => out.push_str(vars.get(*var).unwrap_or("-")),
|
||||
}
|
||||
}
|
||||
// Values reflected from the request are visible ASCII; anything that is not a
|
||||
// valid header value (e.g. control characters) drops the header.
|
||||
HeaderValue::from_str(&out).ok()
|
||||
}
|
||||
}
|
||||
/// Values for header variables; `None` renders as `-`.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Vars<'a> {
|
||||
pub srv_id: Option<&'a str>,
|
||||
pub srv_url: Option<&'a str>,
|
||||
pub location: Option<&'a str>,
|
||||
pub vhost: Option<&'a str>,
|
||||
pub lb_algorithm: Option<&'a str>,
|
||||
pub hash_key: Option<&'a str>,
|
||||
pub client_ip: Option<&'a str>,
|
||||
pub country: Option<&'a str>,
|
||||
pub req_id: Option<&'a str>,
|
||||
pub method: Option<&'a str>,
|
||||
pub host: Option<&'a str>,
|
||||
pub path: Option<&'a str>,
|
||||
pub cache_status: Option<&'a str>,
|
||||
pub backend_time: Option<&'a str>,
|
||||
}
|
||||
impl Vars<'_> {
|
||||
fn get(&self, var: Var) -> Option<&str> {
|
||||
match var {
|
||||
Var::SrvId => self.srv_id,
|
||||
Var::SrvUrl => self.srv_url,
|
||||
Var::Location => self.location,
|
||||
Var::Vhost => self.vhost,
|
||||
Var::LbAlgorithm => self.lb_algorithm,
|
||||
Var::HashKey => self.hash_key,
|
||||
Var::ClientIp => self.client_ip,
|
||||
Var::Country => self.country,
|
||||
Var::ReqId => self.req_id,
|
||||
Var::Method => self.method,
|
||||
Var::Host => self.host,
|
||||
Var::Path => self.path,
|
||||
Var::CacheStatus => self.cache_status,
|
||||
Var::BackendTime => self.backend_time,
|
||||
}
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
}
|
||||
/// Request facts captured when the request is routed, for response-side variables.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct RequestVars {
|
||||
pub location: Option<String>,
|
||||
pub vhost: Option<String>,
|
||||
pub lb_algorithm: Option<String>,
|
||||
pub hash_key: Option<String>,
|
||||
pub client_ip: Option<String>,
|
||||
pub country: Option<String>,
|
||||
pub method: Option<String>,
|
||||
pub host: Option<String>,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CompiledHeaders {
|
||||
pub request: Vec<CompiledRule>,
|
||||
pub response: Vec<CompiledRule>,
|
||||
}
|
||||
impl CompiledHeaders {
|
||||
/// True when a rule value uses `var`.
|
||||
pub fn uses(&self, var: Var) -> bool {
|
||||
self.request
|
||||
.iter()
|
||||
.chain(&self.response)
|
||||
.any(|rule| rule.template.as_ref().is_some_and(|t| t.uses(var)))
|
||||
}
|
||||
pub fn has_templates(&self) -> bool {
|
||||
self.request
|
||||
.iter()
|
||||
.chain(&self.response)
|
||||
.any(|rule| rule.template.is_some())
|
||||
}
|
||||
}
|
||||
impl HeaderRules {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.request.is_empty() && self.response.is_empty()
|
||||
@@ -94,26 +271,60 @@ fn compile_rules(rules: &[Rule], direction: Direction) -> Result<Vec<CompiledRul
|
||||
"transport/identity header cannot be changed: {}",
|
||||
name
|
||||
);
|
||||
let value = match (&rule.op, &rule.value) {
|
||||
(Operation::Remove, None) => None,
|
||||
let (value, template) = match (&rule.op, &rule.value) {
|
||||
(Operation::Remove, None) => (None, None),
|
||||
(Operation::Remove, Some(_)) => bail!("remove header rule cannot include a value"),
|
||||
(_, Some(value)) => {
|
||||
ensure!(value.len() <= 8192, "header value too long");
|
||||
Some(value.parse().context("invalid header value")?)
|
||||
match Template::parse(value)? {
|
||||
Some(template) => {
|
||||
// The literal parts must form a valid header value too.
|
||||
let _: HeaderValue = value
|
||||
.replace("%[", "")
|
||||
.replace(']', "")
|
||||
.parse()
|
||||
.context("invalid header value")?;
|
||||
if direction == Direction::Request {
|
||||
if let Some(var) =
|
||||
template.0.iter().find_map(|segment| match segment {
|
||||
Segment::Var(var) if var.response_only() => Some(*var),
|
||||
_ => None,
|
||||
})
|
||||
{
|
||||
bail!(
|
||||
"%[{}] is only available in response header rules",
|
||||
Var::ALL
|
||||
.iter()
|
||||
.find(|(_, v)| *v == var)
|
||||
.map(|(n, _)| *n)
|
||||
.unwrap_or("?")
|
||||
);
|
||||
}
|
||||
}
|
||||
(None, Some(template))
|
||||
}
|
||||
None => (Some(value.parse().context("invalid header value")?), None),
|
||||
}
|
||||
}
|
||||
(_, None) => bail!("set/append header rule requires a value"),
|
||||
};
|
||||
let dynamic = template.is_some();
|
||||
Ok(CompiledRule {
|
||||
op: rule.op,
|
||||
name,
|
||||
value,
|
||||
template,
|
||||
wire_only: direction == Direction::Response
|
||||
&& rule.name.eq_ignore_ascii_case("age"),
|
||||
&& (dynamic || rule.name.eq_ignore_ascii_case("age")),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn apply_rule(headers: &mut HeaderMap, rule: &CompiledRule) {
|
||||
if rule.template.is_some() {
|
||||
// Templates need request values; see apply_with_vars / apply_wire.
|
||||
return;
|
||||
}
|
||||
match (&rule.op, &rule.value) {
|
||||
(Operation::Remove, _) => {
|
||||
headers.remove(&rule.name);
|
||||
@@ -134,12 +345,43 @@ pub fn apply(headers: &mut HeaderMap, rules: &[CompiledRule]) {
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn apply_wire_age(headers: &mut HeaderMap, rules: &[CompiledRule]) {
|
||||
fn apply_template(headers: &mut HeaderMap, rule: &CompiledRule, vars: &Vars<'_>) {
|
||||
let Some(template) = &rule.template else {
|
||||
return;
|
||||
};
|
||||
let Some(value) = template.render(vars) else {
|
||||
return;
|
||||
};
|
||||
match rule.op {
|
||||
Operation::Set => {
|
||||
headers.insert(rule.name.clone(), value);
|
||||
}
|
||||
Operation::Append => {
|
||||
headers.append(rule.name.clone(), value);
|
||||
}
|
||||
Operation::Remove => {}
|
||||
}
|
||||
}
|
||||
/// Request rules with variables (static request rules use [`apply`]).
|
||||
pub fn apply_with_vars(headers: &mut HeaderMap, rules: &[CompiledRule], vars: &Vars<'_>) {
|
||||
for rule in rules {
|
||||
apply_template(headers, rule, vars);
|
||||
}
|
||||
}
|
||||
/// Final-delivery stage for response rules: `Age` rules and rules with variables.
|
||||
pub fn apply_wire(headers: &mut HeaderMap, rules: &[CompiledRule], vars: &Vars<'_>) {
|
||||
for rule in rules {
|
||||
if rule.wire_only {
|
||||
apply_rule(headers, rule);
|
||||
if rule.template.is_some() {
|
||||
apply_template(headers, rule, vars);
|
||||
} else {
|
||||
apply_rule(headers, rule);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn apply_wire_age(headers: &mut HeaderMap, rules: &[CompiledRule]) {
|
||||
apply_wire(headers, rules, &Vars::default());
|
||||
}
|
||||
#[cfg(test)]
|
||||
include!("tests.rs");
|
||||
@@ -109,4 +109,61 @@ mod tests {
|
||||
apply_wire_age(&mut headers, &compiled.response);
|
||||
assert_eq!(headers.get_all("age").iter().count(), 2);
|
||||
}
|
||||
#[test]
|
||||
fn variables_render_per_request_and_only_on_the_wire() {
|
||||
let rules: HeaderRules = serde_json::from_value(serde_json::json!({
|
||||
"request": [{"op":"set","name":"x-shard","value":"%[srv_id]"},
|
||||
{"op":"set","name":"x-static","value":"100%"}],
|
||||
"response": [{"op":"set","name":"x-s","value":"%[srv_id]@%[location] (%[cache_status], %[backend_time])"},
|
||||
{"op":"append","name":"x-lb","value":"%[lb_algorithm]:%[hash_key]"},
|
||||
{"op":"set","name":"x-plain","value":"yes"}]
|
||||
}))
|
||||
.unwrap();
|
||||
let compiled = rules.compile().unwrap();
|
||||
assert!(compiled.has_templates());
|
||||
assert!(compiled.uses(Var::HashKey) && !compiled.uses(Var::Country));
|
||||
let vars = Vars {
|
||||
srv_id: Some("mp3_2"),
|
||||
location: Some("mp3"),
|
||||
lb_algorithm: Some("hash"),
|
||||
hash_key: Some("/a.mp3"),
|
||||
cache_status: Some("HIT"),
|
||||
..Default::default()
|
||||
};
|
||||
// Static stage: templates are skipped, so cached objects never carry them.
|
||||
let mut headers = HeaderMap::new();
|
||||
apply(&mut headers, &compiled.response);
|
||||
assert_eq!(headers["x-plain"], "yes");
|
||||
assert!(!headers.contains_key("x-s") && !headers.contains_key("x-lb"));
|
||||
apply_wire(&mut headers, &compiled.response, &vars);
|
||||
assert_eq!(headers["x-s"], "mp3_2@mp3 (HIT, -)");
|
||||
assert_eq!(headers["x-lb"], "hash:/a.mp3");
|
||||
assert_eq!(headers.get_all("x-plain").iter().count(), 1);
|
||||
let mut request = HeaderMap::new();
|
||||
apply(&mut request, &compiled.request);
|
||||
assert_eq!(request["x-static"], "100%");
|
||||
assert!(!request.contains_key("x-shard"));
|
||||
apply_with_vars(&mut request, &compiled.request, &vars);
|
||||
assert_eq!(request["x-shard"], "mp3_2");
|
||||
// Values that are not valid header values drop the header instead of failing.
|
||||
let mut bad = HeaderMap::new();
|
||||
apply_wire(&mut bad, &compiled.response, &Vars { srv_id: Some("a b"), ..vars.clone() });
|
||||
assert_eq!(bad["x-s"], "a b@mp3 (HIT, -)");
|
||||
let mut dropped = HeaderMap::new();
|
||||
apply_wire(&mut dropped, &compiled.response, &Vars { srv_id: Some("a\r\nX-Evil: 1"), ..vars });
|
||||
assert!(!dropped.contains_key("x-s"), "CR/LF never reaches a header");
|
||||
assert!(!dropped.contains_key("x-evil"));
|
||||
}
|
||||
#[test]
|
||||
fn invalid_variables_are_rejected() {
|
||||
for rules in [
|
||||
serde_json::json!({"response":[{"op":"set","name":"x","value":"%[nope]"}]}),
|
||||
serde_json::json!({"response":[{"op":"set","name":"x","value":"%[srv_id"}]}),
|
||||
serde_json::json!({"request":[{"op":"set","name":"x","value":"%[cache_status]"}]}),
|
||||
serde_json::json!({"request":[{"op":"set","name":"x","value":"%[backend_time]"}]}),
|
||||
] {
|
||||
let parsed: HeaderRules = serde_json::from_value(rules.clone()).unwrap();
|
||||
assert!(parsed.compile().is_err(), "{rules} should be rejected");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,8 @@ pub struct Exchange {
|
||||
/// Location chosen by conditional routing when it differs from the route the
|
||||
/// response layer saw before the request was forwarded.
|
||||
pub routed: Mutex<Option<Arc<crate::config::CompiledRoute>>>,
|
||||
/// Request values for response header rules with `%[variables]`.
|
||||
pub header_vars: Mutex<Option<Arc<crate::headers::RequestVars>>>,
|
||||
pub source: AtomicU8,
|
||||
pub cache_effective_enabled: AtomicU8,
|
||||
pub transform_effective_enabled: AtomicU8,
|
||||
|
||||
@@ -12,6 +12,7 @@ mod tests {
|
||||
vhost: None,
|
||||
route: Mutex::new(None),
|
||||
routed: Mutex::new(None),
|
||||
header_vars: Mutex::new(None),
|
||||
source: AtomicU8::new(ExchangeSource::Unresolved as u8),
|
||||
cache_effective_enabled: AtomicU8::new(0),
|
||||
transform_effective_enabled: AtomicU8::new(0),
|
||||
|
||||
@@ -255,6 +255,22 @@ fn apply_response_age_rules(
|
||||
crate::headers::apply_wire_age(headers, &route.headers.response);
|
||||
}
|
||||
}
|
||||
/// Final-delivery response rules: `Age` and rules with `%[variables]`.
|
||||
fn apply_response_wire_rules(
|
||||
headers: &mut http::HeaderMap,
|
||||
snapshot: &crate::config::Snapshot,
|
||||
frontend: Option<&crate::config::CompiledFrontend>,
|
||||
route: Option<&crate::config::CompiledRoute>,
|
||||
vars: &crate::headers::Vars<'_>,
|
||||
) {
|
||||
crate::headers::apply_wire(headers, &snapshot.headers.response, vars);
|
||||
if let Some(frontend) = frontend {
|
||||
crate::headers::apply_wire(headers, &frontend.headers.response, vars);
|
||||
}
|
||||
if let Some(route) = route {
|
||||
crate::headers::apply_wire(headers, &route.headers.response, vars);
|
||||
}
|
||||
}
|
||||
fn finish_headers(
|
||||
response: &mut Response,
|
||||
snapshot: &crate::config::Snapshot,
|
||||
|
||||
@@ -45,6 +45,21 @@ if route.unavailable {
|
||||
if let crate::config::CompiledSource::WebServer(service) = &route.source {
|
||||
return include!("web_source.rs");
|
||||
}
|
||||
// Header rules with %[variables] need request facts; computed only when used.
|
||||
let header_templates = snapshot.headers.has_templates()
|
||||
|| route.frontend.as_ref().is_some_and(|f| f.headers.has_templates())
|
||||
|| route.headers.has_templates();
|
||||
let template_hash_key = (header_templates
|
||||
&& [&snapshot.headers, &route.headers]
|
||||
.into_iter()
|
||||
.chain(route.frontend.as_ref().map(|f| &f.headers))
|
||||
.any(|h| h.uses(crate::headers::Var::HashKey)))
|
||||
.then(|| {
|
||||
route.pool.as_ref().and_then(|pool| {
|
||||
pool.balance_key(context.client_ip, request.headers(), Some(request.uri()))
|
||||
})
|
||||
})
|
||||
.flatten();
|
||||
let (backend, backend_lease, affinity_cookie) = if let Some(pool) = &route.pool {
|
||||
let selection = match &route.backend_id {
|
||||
Some(id) => pool.select_member_wait(id).await,
|
||||
@@ -299,6 +314,52 @@ if let Some(frontend) = &route.frontend {
|
||||
crate::headers::apply(request.headers_mut(), &frontend.headers.request);
|
||||
}
|
||||
crate::headers::apply(request.headers_mut(), &route.headers.request);
|
||||
if header_templates {
|
||||
let request_vars = crate::headers::RequestVars {
|
||||
location: Some(route.name.clone()),
|
||||
vhost: route.frontend.as_ref().map(|f| f.id.clone()),
|
||||
lb_algorithm: route.pool.as_ref().map(|p| p.algorithm_name().to_owned()),
|
||||
hash_key: template_hash_key.clone(),
|
||||
client_ip: Some(context.client_ip.to_string()),
|
||||
country: country.clone(),
|
||||
method: Some(request.method().as_str().to_owned()),
|
||||
host: Some(host.clone()),
|
||||
path: Some(path.to_string()),
|
||||
};
|
||||
let srv_id = backend_lease
|
||||
.as_ref()
|
||||
.map(|lease| lease.member.definition.id.clone())
|
||||
.unwrap_or_else(|| backend.id.rsplit('/').next().unwrap_or("").to_owned());
|
||||
let srv_url = backend_lease
|
||||
.as_ref()
|
||||
.map(|lease| lease.member.definition.url.clone())
|
||||
.unwrap_or_else(|| backend.origin.clone());
|
||||
let request_id = exchange.as_ref().map(|e| e.request_id.clone());
|
||||
let vars = crate::headers::Vars {
|
||||
srv_id: Some(&srv_id),
|
||||
srv_url: Some(&srv_url),
|
||||
location: request_vars.location.as_deref(),
|
||||
vhost: request_vars.vhost.as_deref(),
|
||||
lb_algorithm: request_vars.lb_algorithm.as_deref(),
|
||||
hash_key: request_vars.hash_key.as_deref(),
|
||||
client_ip: request_vars.client_ip.as_deref(),
|
||||
country: request_vars.country.as_deref(),
|
||||
req_id: request_id.as_deref(),
|
||||
method: request_vars.method.as_deref(),
|
||||
host: request_vars.host.as_deref(),
|
||||
path: request_vars.path.as_deref(),
|
||||
cache_status: None,
|
||||
backend_time: None,
|
||||
};
|
||||
crate::headers::apply_with_vars(request.headers_mut(), &snapshot.headers.request, &vars);
|
||||
if let Some(frontend) = &route.frontend {
|
||||
crate::headers::apply_with_vars(request.headers_mut(), &frontend.headers.request, &vars);
|
||||
}
|
||||
crate::headers::apply_with_vars(request.headers_mut(), &route.headers.request, &vars);
|
||||
if let Some(exchange) = &exchange {
|
||||
*exchange.header_vars.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(request_vars));
|
||||
}
|
||||
}
|
||||
context.apply_upstream(
|
||||
request.headers_mut(),
|
||||
route
|
||||
|
||||
@@ -216,6 +216,7 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
|
||||
vhost: frontend_context.as_ref().map(|f| f.id.clone()),
|
||||
route: Mutex::new(None),
|
||||
routed: Mutex::new(None),
|
||||
header_vars: Mutex::new(None),
|
||||
source: AtomicU8::new(ExchangeSource::Unresolved as u8),
|
||||
cache_effective_enabled: AtomicU8::new(0),
|
||||
transform_effective_enabled: AtomicU8::new(0),
|
||||
@@ -463,11 +464,71 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
|
||||
}
|
||||
}
|
||||
if !minimal_welcome {
|
||||
apply_response_age_rules(
|
||||
let request_vars = exchange
|
||||
.header_vars
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.clone();
|
||||
let lease = exchange
|
||||
.backend
|
||||
.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 srv_id = lease
|
||||
.as_ref()
|
||||
.map(|lease| lease.member.definition.id.clone())
|
||||
.or_else(|| {
|
||||
origin
|
||||
.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 backend_time = response
|
||||
.extensions()
|
||||
.get::<OriginTiming>()
|
||||
.map(|t| format!("{:.2}ms", t.0.as_secs_f64() * 1000.0));
|
||||
let cache_status = match exchange.cache_status.load(Ordering::Relaxed) {
|
||||
1 => "HIT",
|
||||
2 => "MISS",
|
||||
_ => "BYPASS",
|
||||
};
|
||||
let fallback_location = effective_route_context.map(|route| route.name.clone());
|
||||
let vars = crate::headers::Vars {
|
||||
srv_id: srv_id.as_deref(),
|
||||
srv_url: srv_url.as_deref(),
|
||||
location: request_vars
|
||||
.as_ref()
|
||||
.and_then(|v| v.location.as_deref())
|
||||
.or(fallback_location.as_deref()),
|
||||
vhost: request_vars
|
||||
.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()),
|
||||
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()),
|
||||
req_id: Some(exchange.request_id.as_str()),
|
||||
method: Some(exchange.method.as_str()),
|
||||
host: request_vars
|
||||
.as_ref()
|
||||
.and_then(|v| v.host.as_deref())
|
||||
.or(Some(exchange.host.as_str())),
|
||||
path: request_vars
|
||||
.as_ref()
|
||||
.and_then(|v| v.path.as_deref())
|
||||
.or(Some(exchange.path.as_str())),
|
||||
cache_status: Some(cache_status),
|
||||
backend_time: backend_time.as_deref(),
|
||||
};
|
||||
apply_response_wire_rules(
|
||||
response.headers_mut(),
|
||||
&snapshot,
|
||||
frontend_context.as_deref(),
|
||||
effective_route_context,
|
||||
&vars,
|
||||
);
|
||||
}
|
||||
if response
|
||||
|
||||
Reference in new issue
Block a user