v0.41.0
This commit is contained in:
1 parent
27b640a0df
commit
aa27866531
46 files changed
+3368
-189
No files matched your search
@@ -20,6 +20,7 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[
|
||||
reader_doc!("docs/HEADLESS.md", "guides"),
|
||||
reader_doc!("docs/VHOSTS.md", "guides"),
|
||||
reader_doc!("docs/CUSTOM_LOCATIONS.md", "guides"),
|
||||
reader_doc!("docs/LOAD_BALANCING.md", "guides"),
|
||||
reader_doc!("docs/ACCESS.md", "guides"),
|
||||
reader_doc!("docs/WEB_SERVER.md", "guides"),
|
||||
reader_doc!("docs/PHP_FPM.md", "guides"),
|
||||
|
||||
+183
-4
@@ -290,7 +290,34 @@
|
||||
},
|
||||
"backend_id": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
"nullable": true,
|
||||
"description": "Pin one Vhost backend. Cannot be combined with backend_ids or load_balancing."
|
||||
},
|
||||
"backend_ids": {
|
||||
"type": "array",
|
||||
"maxItems": 64,
|
||||
"uniqueItems": true,
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Backend group of this location (Vhost backend ids). Empty: the Vhost pool. Members with pool_eligible=false serve only locations that list them."
|
||||
},
|
||||
"load_balancing": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/LocationBalancing"
|
||||
}
|
||||
],
|
||||
"nullable": true,
|
||||
"description": "Own algorithm/hash/affinity for this location; null inherits the Vhost settings."
|
||||
},
|
||||
"conditions": {
|
||||
"type": "array",
|
||||
"maxItems": 16,
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/RouteCondition"
|
||||
},
|
||||
"description": "Extra request conditions; all must hold (AND). A location whose conditions fail is skipped and the next candidate is tried. Responses of conditional locations are never cached (cache must be null or false)."
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
@@ -328,10 +355,11 @@
|
||||
"prefix_priority",
|
||||
"exact",
|
||||
"regex",
|
||||
"regex_insensitive"
|
||||
"regex_insensitive",
|
||||
"any"
|
||||
],
|
||||
"default": "prefix",
|
||||
"description": "Nginx-style location matching: prefix, priority prefix (^~), exact (=), regex (~), or case-insensitive regex (~*)."
|
||||
"description": "`any` matches every path: a whole-host rule selected only by its `conditions` (required), evaluated with regular expressions in list order."
|
||||
},
|
||||
"rewrite": {
|
||||
"type": "object",
|
||||
@@ -5204,9 +5232,12 @@
|
||||
"least_connections",
|
||||
"least_traffic",
|
||||
"adaptive",
|
||||
"random",
|
||||
"hash",
|
||||
"ip_hash"
|
||||
],
|
||||
"default": "least_connections"
|
||||
"default": "least_connections",
|
||||
"description": "`hash` uses the consistent (weighted rendezvous) hash configured in `hash`; `random` picks the less loaded of two random members; `ip_hash` equals `hash` with source `ip`."
|
||||
},
|
||||
"health_check": {
|
||||
"$ref": "#/components/schemas/DockerHealthCheck",
|
||||
@@ -5330,6 +5361,9 @@
|
||||
"minimum": 0,
|
||||
"maximum": 300,
|
||||
"default": 10
|
||||
},
|
||||
"hash": {
|
||||
"$ref": "#/components/schemas/HashSettings"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -9006,6 +9040,151 @@
|
||||
"description": "Resolved effective cache settings; only in full Cache responses."
|
||||
}
|
||||
}
|
||||
},
|
||||
"HashSettings": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"description": "Key of the `hash` algorithm. Hashing is always consistent: removing or ejecting a member only moves its own keys. Omitted when all fields have their defaults.",
|
||||
"properties": {
|
||||
"source": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"path",
|
||||
"uri",
|
||||
"host",
|
||||
"ip",
|
||||
"header",
|
||||
"cookie",
|
||||
"query"
|
||||
],
|
||||
"default": "path",
|
||||
"description": "path: request path without query as received from the client; uri: path and query; host: host name without port; ip: client address; header/cookie/query: value named by `name`."
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"maxLength": 128,
|
||||
"description": "Header, cookie or query parameter name; required for header/cookie/query and rejected for other sources."
|
||||
},
|
||||
"path_depth": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 32,
|
||||
"default": 0,
|
||||
"description": "For path/uri: number of leading directories hashed; 0 hashes the whole path."
|
||||
},
|
||||
"ignore_case": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
},
|
||||
"balance_factor": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 1000,
|
||||
"default": 0,
|
||||
"description": "Bounded load in percent of the weighted average (HAProxy hash-balance-factor). 0 disables; otherwise 101..1000."
|
||||
},
|
||||
"fallback": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"round_robin",
|
||||
"least_connections",
|
||||
"least_traffic",
|
||||
"adaptive",
|
||||
"random"
|
||||
],
|
||||
"default": "round_robin",
|
||||
"description": "Algorithm for requests without a key value."
|
||||
}
|
||||
}
|
||||
},
|
||||
"LocationBalancing": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"description": "Location-specific balancing over the location's backend group (or the whole Vhost pool). Members, health and limits are shared with the Vhost pool.",
|
||||
"properties": {
|
||||
"algorithm": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"round_robin",
|
||||
"least_connections",
|
||||
"least_traffic",
|
||||
"adaptive",
|
||||
"random",
|
||||
"hash",
|
||||
"ip_hash"
|
||||
],
|
||||
"default": "hash"
|
||||
},
|
||||
"hash": {
|
||||
"$ref": "#/components/schemas/HashSettings"
|
||||
},
|
||||
"sticky": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"off",
|
||||
"cookie",
|
||||
"ip_hash"
|
||||
],
|
||||
"default": "off",
|
||||
"description": "Location affinity. The cookie is named `<vhost affinity cookie>__<location id>`."
|
||||
}
|
||||
}
|
||||
},
|
||||
"RouteCondition": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"description": "One request condition of a location. Matches when any of `values` matches; `negate` inverts it.",
|
||||
"properties": {
|
||||
"source": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"header",
|
||||
"cookie",
|
||||
"query",
|
||||
"method",
|
||||
"ip",
|
||||
"host",
|
||||
"country"
|
||||
],
|
||||
"default": "header"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"maxLength": 128,
|
||||
"description": "Header, cookie or query parameter name (required for those sources, rejected otherwise)."
|
||||
},
|
||||
"operator": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"equals",
|
||||
"exists",
|
||||
"prefix",
|
||||
"suffix",
|
||||
"contains",
|
||||
"regex",
|
||||
"cidr"
|
||||
],
|
||||
"default": "equals",
|
||||
"description": "`cidr` only for `ip` (and the only operator for it); `method` and `country` use `equals`; `exists` takes no values and is not available for `host`."
|
||||
},
|
||||
"values": {
|
||||
"type": "array",
|
||||
"maxItems": 64,
|
||||
"items": {
|
||||
"type": "string",
|
||||
"maxLength": 1024
|
||||
}
|
||||
},
|
||||
"negate": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
},
|
||||
"ignore_case": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Case-insensitive comparison for header, cookie and query values. Host, method and country always compare case-insensitively."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -125,6 +125,8 @@ fn admin_vhosts_javascript() -> &'static str {
|
||||
include_str!("web/vhosts/protocol.js"),
|
||||
include_str!("web/vhosts/health.js"),
|
||||
include_str!("web/vhosts/rates.js"),
|
||||
include_str!("web/vhosts/balancing.js"),
|
||||
include_str!("web/vhosts/routing.js"),
|
||||
include_str!("web/vhosts/editor.js"),
|
||||
include_str!("web/vhosts/render.js"),
|
||||
"})();",
|
||||
|
||||
@@ -2183,4 +2183,250 @@ h2+.fine {
|
||||
transform: rotate(90deg);
|
||||
justify-self: start;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Load-balancing editor and distribution simulator (vhost and location). */
|
||||
.lb-editor {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.lb-presets {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.lb-presets-label,
|
||||
.lb-equivalent>span,
|
||||
.lb-sim-down>span,
|
||||
.location-group-title {
|
||||
color: var(--muted);
|
||||
font: 600 10px var(--mono);
|
||||
letter-spacing: .35px;
|
||||
}
|
||||
|
||||
.lb-preset {
|
||||
border-radius: 999px;
|
||||
padding: 4px 10px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.lb-description {
|
||||
margin: 0;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.lb-hash {
|
||||
border-left: 2px solid var(--accent);
|
||||
padding-left: 10px;
|
||||
}
|
||||
|
||||
.lb-equivalent pre {
|
||||
margin: 4px 0 0;
|
||||
padding: 7px 9px;
|
||||
background: var(--code-bg);
|
||||
border: 1px solid var(--line);
|
||||
font: 11px var(--mono);
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.lb-simulator {
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel2);
|
||||
}
|
||||
|
||||
.lb-simulator>summary {
|
||||
cursor: pointer;
|
||||
padding: 9px 10px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.lb-sim-body {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
border-top: 1px solid var(--line);
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.lb-sim-inputs {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 2fr) minmax(0, 1fr);
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.lb-sim-down-list,
|
||||
.location-group-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.lb-bars {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.lb-bar {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(70px, 160px) minmax(0, 1fr) 90px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.lb-bar-label {
|
||||
font-family: var(--mono);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.lb-bar-track {
|
||||
height: 8px;
|
||||
background: var(--field-bg);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.lb-bar-fill {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: var(--green);
|
||||
}
|
||||
|
||||
.lb-bar-value {
|
||||
color: var(--muted);
|
||||
font-family: var(--mono);
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.lb-sim-summary {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.lb-sim-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.lb-sim-table :is(th, td) {
|
||||
border-bottom: 1px solid var(--row-line);
|
||||
padding: 4px 6px;
|
||||
text-align: left;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.lb-sim-table tr.is-moved td {
|
||||
background: var(--notice-bg);
|
||||
}
|
||||
|
||||
.lb-sim-table tr.is-fallback td {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.lb-moved {
|
||||
color: var(--notice-text);
|
||||
font-family: var(--mono);
|
||||
}
|
||||
|
||||
.location-group {
|
||||
border: 1px solid var(--line);
|
||||
padding: 8px 10px;
|
||||
}
|
||||
|
||||
/* Location conditions and routing tester. */
|
||||
.rt-conditions {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.rt-condition-list {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.rt-condition {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(110px, 150px) minmax(90px, 160px) minmax(120px, 170px) minmax(140px, 1fr) auto auto auto;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.rt-condition :is(select, input[type=text], textarea) {
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.rt-condition textarea {
|
||||
min-height: 32px;
|
||||
resize: vertical;
|
||||
font-family: var(--mono);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.rt-flag {
|
||||
white-space: nowrap;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.rt-empty {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.rt-tester {
|
||||
border: 1px solid var(--accent);
|
||||
background: var(--panel2);
|
||||
}
|
||||
|
||||
.rt-tester>summary {
|
||||
cursor: pointer;
|
||||
padding: 9px 10px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.rt-tester-body {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
border-top: 1px solid var(--line);
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.rt-verdict {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.rt-target {
|
||||
font-family: var(--mono);
|
||||
}
|
||||
|
||||
.rt-badge {
|
||||
border: 1px solid var(--notice-line);
|
||||
padding: 1px 6px;
|
||||
}
|
||||
|
||||
.rt-trace tr.is-winner td {
|
||||
background: var(--nav-selected-bg);
|
||||
}
|
||||
|
||||
.rt-ok {
|
||||
color: var(--green);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.rt-no,
|
||||
.rt-error {
|
||||
color: var(--red);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.rt-cond {
|
||||
font-family: var(--mono);
|
||||
font-size: 11px;
|
||||
}
|
||||
@@ -402,6 +402,18 @@
|
||||
.traffic-donut {
|
||||
width: 120px;
|
||||
}
|
||||
|
||||
.lb-sim-inputs {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.rt-condition {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
.lb-bar {
|
||||
grid-template-columns: minmax(60px, 110px) minmax(0, 1fr) 70px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width:700px) {
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
// 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.
|
||||
const lbSha256 = (() => {
|
||||
const K = new Uint32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]);
|
||||
return bytes => {
|
||||
const length = bytes.length, total = ((length + 9 + 63) >> 6) << 6, data = new Uint8Array(total);
|
||||
data.set(bytes); data[length] = 0x80;
|
||||
const view = new DataView(data.buffer); view.setUint32(total - 8, Math.floor(length / 0x20000000)); view.setUint32(total - 4, (length << 3) >>> 0);
|
||||
const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]), w = new Uint32Array(64);
|
||||
const rotr = (x, n) => (x >>> n) | (x << (32 - n));
|
||||
for (let offset = 0; offset < total; offset += 64) {
|
||||
for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4);
|
||||
for (let i = 16; i < 64; i++) {
|
||||
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
|
||||
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
|
||||
}
|
||||
let [a, b, c, d, e, f, g, hh] = h;
|
||||
for (let i = 0; i < 64; i++) {
|
||||
const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) >>> 0;
|
||||
const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;
|
||||
hh = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
|
||||
}
|
||||
const out = new Uint8Array(32), outView = new DataView(out.buffer); h.forEach((value, i) => outView.setUint32(i * 4, value)); return out;
|
||||
};
|
||||
})();
|
||||
const lbEncoder = new TextEncoder();
|
||||
const LB_U64_SPAN = Number(2n ** 64n - 1n) + 2, LB_MIN_POSITIVE = 2.2250738585072014e-308;
|
||||
// Same as rendezvous_score() in src/balance/model.rs: lowest score wins.
|
||||
function lbScore(poolId, key, memberId, weight) {
|
||||
const digest = lbSha256(lbEncoder.encode(`${poolId}|${key}|${memberId}`));
|
||||
let n = 0n; for (let i = 0; i < 8; i++) n = (n << 8n) | BigInt(digest[i]);
|
||||
const unit = (Number(n) + 1) / LB_U64_SPAN;
|
||||
return -Math.log(Math.max(unit, LB_MIN_POSITIVE)) / Math.max(1, Number(weight) || 1);
|
||||
}
|
||||
function lbRank(poolId, key, members) {
|
||||
return members.map(member => ({ member, score: lbScore(poolId, key, member.id, member.weight) })).sort((a, b) => a.score - b.score).map(item => item.member);
|
||||
}
|
||||
function lbPathDepth(path, depth) {
|
||||
if (!depth) return path; let seen = 0;
|
||||
for (let i = 1; i < path.length; i++) if (path[i] === "/" && ++seen === depth) return path.slice(0, i);
|
||||
return path;
|
||||
}
|
||||
// Parses one simulator sample: "/path?query", "https://host/path?query" or "host/path".
|
||||
function lbParseSample(line) {
|
||||
let rest = line.trim(), host = "";
|
||||
const scheme = rest.match(/^[a-z][a-z0-9+.-]*:\/\//i);
|
||||
if (scheme) { rest = rest.slice(scheme[0].length); const slash = rest.search(/[/?]/); host = slash < 0 ? rest : rest.slice(0, slash); rest = slash < 0 ? "/" : rest.slice(slash); }
|
||||
else if (!rest.startsWith("/")) { const slash = rest.search(/[/?]/); host = slash < 0 ? rest : rest.slice(0, slash); rest = slash < 0 ? "/" : rest.slice(slash); }
|
||||
if (rest.startsWith("?")) rest = `/${rest}`;
|
||||
const mark = rest.indexOf("?");
|
||||
const bracketed = host.match(/^\[([^\]]*)\]/);
|
||||
host = bracketed ? bracketed[1] : host.includes(":") && host.indexOf(":") === host.lastIndexOf(":") ? host.replace(/:\d*$/, "") : host;
|
||||
return { host: host.replace(/\.$/, "").toLowerCase(), path: mark < 0 ? rest : rest.slice(0, mark), query: mark < 0 ? null : rest.slice(mark + 1) };
|
||||
}
|
||||
// Mirrors HashSettings::key(); header/cookie/IP samples are the raw value itself.
|
||||
function lbHashKey(settings, line) {
|
||||
const source = settings.source || "path", value = String(line).trim(); if (!value) return null;
|
||||
if (source === "ip") return value;
|
||||
let key;
|
||||
if (["header", "cookie"].includes(source)) key = value;
|
||||
else {
|
||||
const sample = lbParseSample(value), depth = Number(settings.path_depth) || 0;
|
||||
if (source === "host") return sample.host || null;
|
||||
if (source === "path") key = lbPathDepth(sample.path, depth);
|
||||
else if (source === "uri") key = lbPathDepth(sample.path, depth) + (sample.query !== null ? `?${sample.query}` : "");
|
||||
else if (source === "query") {
|
||||
if (sample.query === null) return null;
|
||||
const pair = sample.query.split("&").map(item => { const at = item.indexOf("="); return at < 0 ? [item, ""] : [item.slice(0, at), item.slice(at + 1)]; }).find(([name]) => name === settings.name);
|
||||
key = pair?.[1] || null;
|
||||
}
|
||||
}
|
||||
if (!key) return null;
|
||||
return settings.ignore_case ? key.toLowerCase() : key;
|
||||
}
|
||||
// Which members a request may use (mirrors candidates: enabled, not draining, backups
|
||||
// only when no primary is left).
|
||||
function lbEligible(members, explicit, down = new Set()) {
|
||||
const usable = members.filter(m => m.enabled && !m.drain && (explicit || m.pool_eligible) && !down.has(m.id));
|
||||
return usable.some(m => !m.backup) ? usable.filter(m => !m.backup) : usable;
|
||||
}
|
||||
function lbSimulate({ poolId, settings, members, explicit = false, samples, down = new Set() }) {
|
||||
const before = lbEligible(members, explicit), after = lbEligible(members, explicit, down);
|
||||
return samples.map(sample => {
|
||||
const key = lbHashKey(settings, sample);
|
||||
if (key === null) return { sample, key, member: null, previous: null };
|
||||
return { sample, key, previous: lbRank(poolId, key, before)[0]?.id || null, member: lbRank(poolId, key, after)[0]?.id || null };
|
||||
});
|
||||
}
|
||||
if (typeof window !== "undefined") window.rustProxyBalancingCore = { sha256: lbSha256, score: lbScore, rank: lbRank, hashKey: lbHashKey, simulate: lbSimulate, eligible: lbEligible };
|
||||
|
||||
const LB_ALGORITHMS = [["round_robin", "vhRoundRobin"], ["least_connections", "vhLeastConnections"], ["least_traffic", "vhLeastTraffic"], ["adaptive", "vhAdaptive"], ["random", "lbRandom"], ["hash", "lbHash"], ["ip_hash", "vhIpHash"]];
|
||||
const LB_SOURCES = [["path", "lbSourcePath"], ["uri", "lbSourceUri"], ["host", "lbSourceHost"], ["header", "lbSourceHeader"], ["cookie", "lbSourceCookie"], ["query", "lbSourceQuery"], ["ip", "lbSourceIp"]];
|
||||
const LB_FALLBACKS = [["round_robin", "vhRoundRobin"], ["least_connections", "vhLeastConnections"], ["random", "lbRandom"]];
|
||||
const LB_PRESETS = [
|
||||
{ key: "lbPresetFiles", algorithm: "hash", hash: { source: "path", ignore_case: true }, samples: "/media/intro.mp3\n/media/album/01.mp3\n/media/album/02.mp3\n/video/teaser.mp4\n/img/cover.jpg\n/media/album/03.mp3" },
|
||||
{ key: "lbPresetCookie", algorithm: "hash", hash: { source: "cookie", name: "session" }, samples: "u-1001\nu-1002\nu-1003\nu-1004\nu-1005" },
|
||||
{ key: "lbPresetTenant", algorithm: "hash", hash: { source: "header", name: "X-Tenant" }, samples: "acme\nglobex\ninitech\numbrella" },
|
||||
{ key: "lbPresetQuery", algorithm: "hash", hash: { source: "query", name: "id" }, samples: "/api/items?id=1\n/api/items?id=2\n/api/items?id=3\n/api/items" },
|
||||
{ key: "lbPresetIp", algorithm: "hash", hash: { source: "ip" }, samples: "203.0.113.10\n203.0.113.11\n198.51.100.7\n2001:db8::42" },
|
||||
{ key: "lbPresetEven", algorithm: "least_connections", hash: {} }
|
||||
];
|
||||
// HAProxy-style one-liner describing the configuration (helps people migrating).
|
||||
function lbHaproxyLine(algorithm, hash) {
|
||||
const map = { round_robin: "balance roundrobin", least_connections: "balance leastconn", random: "balance random(2)", ip_hash: "balance source\nhash-type consistent" };
|
||||
if (map[algorithm]) return map[algorithm];
|
||||
if (algorithm !== "hash") return "";
|
||||
const depth = Number(hash.path_depth) ? ` depth ${hash.path_depth}` : "";
|
||||
const lower = hash.ignore_case ? ",lower" : "";
|
||||
const source = { path: depth ? `balance uri path-only${depth}` : `balance hash path${lower}`, uri: `balance uri whole${depth}`, host: "balance hdr(host) use-domain-only", header: `balance hdr(${hash.name || "?"})`, cookie: `balance hash req.cook(${hash.name || "?"})`, query: `balance url_param ${hash.name || "?"}`, ip: "balance source" }[hash.source || "path"];
|
||||
return `${source}\nhash-type consistent${Number(hash.balance_factor) ? `\nhash-balance-factor ${hash.balance_factor}` : ""}`;
|
||||
}
|
||||
|
||||
// Balancing editor. options: { names: input name prefix, value: {algorithm, hash, sticky},
|
||||
// members(): [{id, weight, enabled, drain, backup, pool_eligible}], explicit(): bool,
|
||||
// poolId(): string, stickyField: include a location affinity select, onChange() }.
|
||||
function balancingEditor(parent, options) {
|
||||
const value = options.value || {}, hash = { ...(value.hash || {}) }, prefix = options.names;
|
||||
const box = el("div", undefined, "vh-wide lb-editor"); parent.append(box);
|
||||
const presets = el("div", undefined, "lb-presets"); presets.append(text("span", "lbPresets", "lb-presets-label")); box.append(presets);
|
||||
const grid = el("div", undefined, "vh-grid"); box.append(grid);
|
||||
const algorithm = field(grid, `${prefix}algorithm`, "vhAlgorithm", value.algorithm || "least_connections", "select", { values: LB_ALGORITHMS });
|
||||
const sticky = options.stickyField ? field(grid, `${prefix}sticky`, "lbLocationSticky", value.sticky || "off", "select", { values: [["off", "vhOff"], ["cookie", "vhCookie"], ["ip_hash", "vhIpHash"]] }) : null;
|
||||
const description = el("p", "", "fine vh-wide lb-description"); grid.append(description);
|
||||
const hashBox = el("div", undefined, "vh-wide vh-grid lb-hash"); grid.append(hashBox);
|
||||
const source = field(hashBox, `${prefix}hash-source`, "lbHashSource", hash.source || "path", "select", { values: LB_SOURCES });
|
||||
const name = field(hashBox, `${prefix}hash-name`, "lbHashName", hash.name || "", "text", { maxLength: 128 });
|
||||
const depth = field(hashBox, `${prefix}hash-depth`, "lbHashDepth", hash.path_depth ?? 0, "number", { min: 0, max: 32, step: 1 });
|
||||
const factor = field(hashBox, `${prefix}hash-factor`, "lbHashFactor", hash.balance_factor ?? 0, "number", { min: 0, max: 1000, step: 1 });
|
||||
const fallback = field(hashBox, `${prefix}hash-fallback`, "lbHashFallback", hash.fallback || "round_robin", "select", { values: LB_FALLBACKS });
|
||||
const ignoreCase = field(hashBox, `${prefix}hash-case`, "lbHashIgnoreCase", hash.ignore_case === true, "checkbox", { switch: true });
|
||||
const keyHelp = el("p", "", "fine vh-wide lb-key-help"); hashBox.append(keyHelp);
|
||||
const equivalent = el("div", undefined, "vh-wide lb-equivalent"); const equivalentCode = el("pre", ""); equivalent.append(text("span", "lbHaproxyEquivalent"), equivalentCode); grid.append(equivalent);
|
||||
|
||||
const simulator = el("details", undefined, "vh-wide lb-simulator"); simulator.append(text("summary", "lbSimulator")); box.append(simulator);
|
||||
const simBody = el("div", undefined, "lb-sim-body"); simulator.append(simBody);
|
||||
const simInputs = el("div", undefined, "lb-sim-inputs"); simBody.append(simInputs);
|
||||
const sampleLabel = el("label", undefined, "vh-field lb-sim-samples"), sampleTitle = el("span", ""), samples = document.createElement("textarea");
|
||||
samples.rows = 7; samples.spellcheck = false; samples.maxLength = 20000; samples.value = options.samples || "/media/intro.mp3\n/media/album/01.mp3\n/media/album/02.mp3\n/img/cover.jpg";
|
||||
sampleLabel.append(sampleTitle, samples); simInputs.append(sampleLabel);
|
||||
const downBox = el("div", undefined, "lb-sim-down"); downBox.append(text("span", "lbSimulateDown")); const downList = el("div", undefined, "lb-sim-down-list"); downBox.append(downList); simInputs.append(downBox);
|
||||
const simOut = el("div", undefined, "lb-sim-out"); simBody.append(simOut);
|
||||
const down = new Set();
|
||||
|
||||
const readHash = () => {
|
||||
const result = { source: source.value };
|
||||
if (["header", "cookie", "query"].includes(source.value)) result.name = name.value.trim();
|
||||
if (["path", "uri"].includes(source.value) && Number(depth.value) > 0) result.path_depth = Number(depth.value);
|
||||
if (ignoreCase.checked && source.value !== "ip" && source.value !== "host") result.ignore_case = true;
|
||||
if (Number(factor.value) > 0) result.balance_factor = Number(factor.value);
|
||||
if (fallback.value !== "round_robin") result.fallback = fallback.value;
|
||||
return result;
|
||||
};
|
||||
const members = () => (options.members() || []).filter(m => m.id);
|
||||
const renderDown = () => {
|
||||
const explicit = options.explicit?.() === true, list = members().filter(m => explicit || m.pool_eligible);
|
||||
for (const id of [...down]) if (!list.some(m => m.id === id)) down.delete(id);
|
||||
downList.replaceChildren(...list.map(member => {
|
||||
const label = el("label", undefined, "check lb-sim-member"), box = document.createElement("input"); box.type = "checkbox"; box.checked = down.has(member.id);
|
||||
box.addEventListener("change", () => { if (box.checked) down.add(member.id); else down.delete(member.id); simulate(); });
|
||||
box.setAttribute("aria-label", `${t("lbSimulateDown")}: ${member.id}`);
|
||||
label.append(box, el("span", member.id)); return label;
|
||||
}));
|
||||
};
|
||||
const simulate = () => {
|
||||
simOut.replaceChildren();
|
||||
const list = members(), explicit = options.explicit?.() === true, eligible = lbEligible(list, explicit);
|
||||
if (!eligible.length) { simOut.append(text("p", "lbSimNoMembers", "fine")); return; }
|
||||
if (algorithm.value !== "hash" && algorithm.value !== "ip_hash") {
|
||||
const total = eligible.reduce((sum, m) => sum + Math.max(1, Number(m.weight) || 1), 0);
|
||||
simOut.append(text("p", "lbSimLoadBased", "fine"));
|
||||
simOut.append(lbBars(eligible.map(m => [m.id, Math.max(1, Number(m.weight) || 1) / total])));
|
||||
return;
|
||||
}
|
||||
const settings = algorithm.value === "ip_hash" ? { source: "ip" } : readHash();
|
||||
const lines = samples.value.split("\n").map(line => line.trim()).filter(Boolean).slice(0, 500);
|
||||
const rows = lbSimulate({ poolId: options.poolId() || "vhost", settings, members: list, explicit, samples: lines, down });
|
||||
const counts = new Map(eligible.filter(m => !down.has(m.id)).map(m => [m.id, 0]));
|
||||
const table = el("table", undefined, "lb-sim-table"), head = el("tr");
|
||||
for (const key of ["lbSimRequest", "lbSimKey", "backend"]) head.append(text("th", key));
|
||||
table.append(head);
|
||||
let moved = 0, fallbackRows = 0;
|
||||
for (const row of rows) {
|
||||
const tr = el("tr"), keyCell = el("td"), target = el("td");
|
||||
tr.append(el("td", row.sample));
|
||||
if (row.key === null) { fallbackRows++; keyCell.append(text("em", "lbSimNoKey")); target.textContent = `${t("lbSimFallback")}: ${t(LB_FALLBACKS.find(([v]) => v === (settings.fallback || "round_robin"))?.[1] || "vhRoundRobin")}`; tr.classList.add("is-fallback"); }
|
||||
else {
|
||||
keyCell.append(el("code", row.key));
|
||||
target.append(el("strong", row.member || "-"));
|
||||
if (row.member) counts.set(row.member, (counts.get(row.member) || 0) + 1);
|
||||
if (row.previous && row.member !== row.previous) { moved++; tr.classList.add("is-moved"); target.append(el("span", ` ← ${row.previous}`, "lb-moved")); }
|
||||
}
|
||||
tr.append(keyCell, target); table.append(tr);
|
||||
}
|
||||
const hashed = rows.length - fallbackRows;
|
||||
simOut.append(lbBars([...counts].map(([id, count]) => [id, hashed ? count / hashed : 0, count])));
|
||||
const summary = el("p", "", "fine lb-sim-summary");
|
||||
summary.textContent = down.size ? t("lbSimMoved").replace("{moved}", String(moved)).replace("{total}", String(hashed)) : t("lbSimStable");
|
||||
simOut.append(summary, table);
|
||||
};
|
||||
const lbBars = entries => {
|
||||
const bars = el("div", undefined, "lb-bars");
|
||||
for (const [id, share, count] of entries) {
|
||||
const row = el("div", undefined, "lb-bar"), track = el("span", undefined, "lb-bar-track"), fill = el("span", undefined, "lb-bar-fill");
|
||||
fill.style.width = `${Math.round(share * 100)}%`; track.append(fill);
|
||||
row.append(el("span", id, "lb-bar-label"), track, el("span", `${Math.round(share * 100)}%${count !== undefined ? ` · ${count}` : ""}`, "lb-bar-value")); bars.append(row);
|
||||
}
|
||||
return bars;
|
||||
};
|
||||
const sync = () => {
|
||||
const isHash = algorithm.value === "hash", needsName = ["header", "cookie", "query"].includes(source.value);
|
||||
hashBox.hidden = !isHash;
|
||||
for (const [control, show] of [[name, needsName], [depth, ["path", "uri"].includes(source.value)], [ignoreCase, !["ip", "host"].includes(source.value)], [fallback, source.value !== "ip"]]) { control.closest("label").hidden = !show; control.disabled = !isHash || !show; }
|
||||
name.required = isHash && needsName;
|
||||
name.placeholder = { header: "X-Tenant", cookie: "session", query: "id" }[source.value] || "";
|
||||
description.textContent = t(`lbDescribe_${algorithm.value}`);
|
||||
keyHelp.textContent = t(`lbKeyHelp_${source.value}`);
|
||||
sampleTitle.textContent = t(algorithm.value === "hash" && ["header", "cookie", "ip"].includes(source.value) ? `lbSimSamples_${source.value}` : algorithm.value === "ip_hash" ? "lbSimSamples_ip" : "lbSimSamples");
|
||||
const line = lbHaproxyLine(algorithm.value, readHash()); equivalent.hidden = !line; equivalentCode.textContent = line;
|
||||
renderDown(); if (simulator.open) simulate();
|
||||
};
|
||||
for (const preset of LB_PRESETS) {
|
||||
presets.append(button(preset.key, () => {
|
||||
algorithm.value = preset.algorithm; source.value = preset.hash.source || "path"; name.value = preset.hash.name || ""; depth.value = 0; factor.value = 0; fallback.value = "round_robin"; ignoreCase.checked = preset.hash.ignore_case === true;
|
||||
if (preset.samples) samples.value = preset.samples;
|
||||
sync(); simulator.open = preset.algorithm === "hash"; if (simulator.open) simulate(); options.onChange?.();
|
||||
}, "quiet lb-preset"));
|
||||
}
|
||||
// The simulator is a scratch pad: its inputs never mark the vhost as changed.
|
||||
for (const type of ["input", "change"]) simulator.addEventListener(type, event => { event.stopPropagation(); if (event.target === samples) simulate(); });
|
||||
box.addEventListener("input", () => { sync(); options.onChange?.(); });
|
||||
box.addEventListener("change", () => { sync(); options.onChange?.(); });
|
||||
simulator.addEventListener("toggle", () => { if (simulator.open) { renderDown(); simulate(); } });
|
||||
sync();
|
||||
return {
|
||||
algorithm: () => algorithm.value,
|
||||
hash: () => algorithm.value === "hash" ? readHash() : undefined,
|
||||
sticky: () => sticky?.value || "off",
|
||||
refresh: sync,
|
||||
validate() { if (algorithm.value === "hash" && ["header", "cookie", "query"].includes(source.value) && !name.value.trim()) throw new Error(t("lbHashNameRequired")); }
|
||||
};
|
||||
}
|
||||
// Reads the vhost backend rows for the balancing editors and simulators.
|
||||
function balancingMembers() {
|
||||
return [...form.querySelectorAll(".vh-member")].map(row => ({
|
||||
id: str("member-id", row), weight: Number(str("member-weight", row)) || 1,
|
||||
enabled: yes("member-enabled", row), drain: yes("member-drain", row), backup: yes("member-backup", row), pool_eligible: yes("member-pool", row)
|
||||
}));
|
||||
}
|
||||
@@ -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;
|
||||
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;
|
||||
const chartHistory = new Map();
|
||||
const backendTrafficHistory = new Map();
|
||||
const backendRequestHistory = new Map();
|
||||
@@ -345,22 +345,31 @@ function openLocationHelp(topic = "locations") {
|
||||
}
|
||||
dialog.showModal();
|
||||
}
|
||||
const LOCATION_GROUP = "__group__";
|
||||
function locationsEditor(parent, values) {
|
||||
const toolbar = el("div", undefined, "vh-wide location-toolbar"), rows = el("div", undefined, "vh-wide vh-locations");
|
||||
const addTop = button("locationAdd", () => { add(); sync(); }, "primary");
|
||||
toolbar.append(addTop, button("documentation", () => openLocationHelp("locations")));
|
||||
parent.append(toolbar); note(parent, "locationHelp"); parent.append(rows); let reloading = false;
|
||||
const addHostRule = button("rtAddHostRule", () => { add({ id: nextId("host-rule"), match_type: "any", conditions: [{ source: "header", name: "", operator: "equals", values: [] }] }, true); sync(); });
|
||||
toolbar.append(addTop, addHostRule, button("documentation", () => openLocationHelp("locations")));
|
||||
parent.append(toolbar); note(parent, "locationHelp"); note(parent, "rtOrderHelp");
|
||||
const tester = routingTester(parent, () => readRows());
|
||||
parent.append(rows); let reloading = false;
|
||||
const nextId = base => { const used = new Set([...rows.children].map(r => str("location-id", r))); let n = 1; while (used.has(`${base}-${n}`)) n++; return `${base}-${n}`; };
|
||||
function readRows() {
|
||||
return [...rows.children].map(r => {
|
||||
const action = str("location-action", r), rewriteMode = str("location-rewrite-mode", r);
|
||||
const handled = action === "proxy" || action === "web_server";
|
||||
const internal = yes("location-internal", r), fallbackTarget = str("location-error-target", r);
|
||||
const fallbackStatuses = lines(str("location-error-statuses", r)).map(value => Number(value));
|
||||
const matchType = internal ? "prefix" : str("location-match", r), conditions = internal ? [] : r.readConditions();
|
||||
return {
|
||||
id: str("location-id", r), internal, path_prefix: internal ? "/" : str("location-path", r), match_type: internal ? "prefix" : str("location-match", r),
|
||||
id: str("location-id", r), internal, path_prefix: internal || matchType === "any" ? "/" : str("location-path", r), match_type: matchType,
|
||||
...(conditions.length ? { conditions } : {}),
|
||||
source: action === "web_server" ? { type: "web_server", web_service_id: str("location-web-service", r) } : { type: "reverse_proxy" },
|
||||
backend_id: action === "proxy" ? (str("location-backend", r) || null) : null,
|
||||
enabled: yes("location-enabled", r), cache: action === "proxy" ? (str("location-cache", r) === "" ? null : str("location-cache", r) === "on") : false,
|
||||
backend_id: action === "proxy" && !["", LOCATION_GROUP].includes(str("location-backend", r)) ? str("location-backend", r) : null,
|
||||
backend_ids: action === "proxy" && str("location-backend", r) === LOCATION_GROUP ? r.groupIds() : [],
|
||||
load_balancing: action === "proxy" && ["", LOCATION_GROUP].includes(str("location-backend", r)) ? r.readBalancing() : null,
|
||||
enabled: yes("location-enabled", r), cache: action === "proxy" && !conditions.length ? (str("location-cache", r) === "" ? null : str("location-cache", r) === "on") : conditions.length ? null : false,
|
||||
acl_profile_id: str("location-acl-profile", r) || null,
|
||||
acl: r.readAcl(),
|
||||
country_access: { mode: str("location-country-mode", r), countries: lines(str("location-country-list", r)).map(value => value.toUpperCase()) },
|
||||
@@ -373,24 +382,57 @@ function locationsEditor(parent, values) {
|
||||
};
|
||||
});
|
||||
}
|
||||
function sync() { if (reloading) return; try { read("paths").value = JSON.stringify(readRows(), null, 2); changed(); } catch { } }
|
||||
function memberOptions(select, chosen = select.value) { const base = text("option", "locationPool"); base.value = ""; select.replaceChildren(base, ...[...form.querySelectorAll(".vh-member")].map(m => { const id = str("member-id", m), o = el("option", `${id} / ${str("member-url", m)}`); o.value = id; return o; })); if (chosen && !Array.from(select.options).some(o => o.value === chosen)) { const o = el("option", `${chosen} / ${t("locationMissing")}`); o.value = chosen; select.append(o); } select.value = chosen; }
|
||||
function add(value = {}) {
|
||||
function sync() { if (reloading) return; try { read("paths").value = JSON.stringify(readRows(), null, 2); changed(); } catch { } tester?.run(); }
|
||||
function memberOptions(select, chosen = select.value) { const base = text("option", "locationPool"); base.value = ""; const groupOption = text("option", "locationBackendGroup"); groupOption.value = LOCATION_GROUP; select.replaceChildren(base, groupOption, ...[...form.querySelectorAll(".vh-member")].map(m => { const id = str("member-id", m), o = el("option", `${id} / ${str("member-url", m)}`); o.value = id; return o; })); if (chosen && !Array.from(select.options).some(o => o.value === chosen)) { const o = el("option", `${chosen} / ${t("locationMissing")}`); o.value = chosen; select.append(o); } select.value = chosen; }
|
||||
function add(value = {}, openConditions = false) {
|
||||
if (rows.children.length >= 64) { toast(t("locationLimit"), true); return; }
|
||||
const row = el("details", undefined, "vh-location"); row.open = true;
|
||||
const summary = el("summary", undefined, "location-summary"), body = el("div", undefined, "vh-grid location-body"); row.append(summary, body);
|
||||
const used = new Set([...rows.children].map(r => str("location-id", r))); let suffix = 1; while (used.has(`location-${suffix}`)) suffix++;
|
||||
field(body, "location-id", "locationId", value.id || `location-${suffix}`, "text", { required: true, pattern: "[A-Za-z0-9_\\-]{1,64}", maxLength: 64 });
|
||||
const match = field(body, "location-match", "locationMatchType", value.match_type || "prefix", "select", { values: [["prefix", "locationMatchPrefix"], ["prefix_priority", "locationMatchPriority"], ["exact", "locationMatchExact"], ["regex", "locationMatchRegex"], ["regex_insensitive", "locationMatchRegexI"]] });
|
||||
const match = field(body, "location-match", "locationMatchType", value.match_type || "prefix", "select", { values: [["prefix", "locationMatchPrefix"], ["prefix_priority", "locationMatchPriority"], ["exact", "locationMatchExact"], ["regex", "locationMatchRegex"], ["regex_insensitive", "locationMatchRegexI"], ["any", "locationMatchAny"]] });
|
||||
const path = field(body, "location-path", "locationPathPattern", value.path_prefix || "/", "text", { required: true, maxLength: 1024 }); path.placeholder = "/api or ^/api/v[0-9]+/";
|
||||
const internal = field(body, "location-internal", "locationInternal", value.internal === true, "checkbox", { switch: true });
|
||||
const initialAction = value.response ? "return" : value.redirect ? "redirect" : value.source?.type === "web_server" ? "web_server" : "proxy";
|
||||
const action = field(body, "location-action", "locationAction", initialAction, "select", { values: [["proxy", "locationProxyAction"], ["web_server", "locationWebServerAction"], ["redirect", "locationRedirectAction"], ["return", "locationReturnAction"]] });
|
||||
const backend = field(body, "location-backend", "backend", value.backend_id || "", "select"); memberOptions(backend, value.backend_id || "");
|
||||
const initialTarget = value.backend_ids?.length ? LOCATION_GROUP : value.backend_id || "";
|
||||
const backend = field(body, "location-backend", "locationTarget", initialTarget, "select"); memberOptions(backend, initialTarget);
|
||||
const webService = field(body, "location-web-service", "webService", value.source?.web_service_id || "", "select"); fillWebServices(webService, value.source?.web_service_id || "");
|
||||
field(body, "location-enabled", "enabled", value.enabled !== false, "checkbox", { switch: true });
|
||||
const cache = field(body, "location-cache", "cacheEnabled", value.cache === true ? "on" : value.cache === false ? "off" : "", "select", { values: [["", "inherit"], ["on", "enabled"], ["off", "notEnabled"]] });
|
||||
|
||||
const conditionBox = el("details", undefined, "vh-wide location-section location-conditions"), conditionBody = el("div", undefined, "vh-grid"); conditionBox.append(text("summary", "rtConditions"), conditionBody); body.append(conditionBox);
|
||||
conditionBox.open = openConditions || Boolean(value.conditions?.length);
|
||||
note(conditionBody, "rtConditionsHelp");
|
||||
const conditions = conditionsEditor(conditionBody, value.conditions || [], () => { syncUi(); sync(); }); row.readConditions = conditions.read;
|
||||
const conditionCacheNote = text("p", "rtNotCachedHelp", "fine vh-wide"); conditionBody.append(conditionCacheNote);
|
||||
const balancing = el("details", undefined, "vh-wide location-section location-balancing"), balancingBody = el("div", undefined, "vh-grid"); balancing.append(text("summary", "locationBalancing"), balancingBody); body.append(balancing);
|
||||
balancing.open = Boolean(value.backend_ids?.length || value.load_balancing);
|
||||
const groupBox = el("div", undefined, "vh-wide location-group"); groupBox.append(text("span", "locationGroupMembers", "location-group-title"));
|
||||
const groupList = el("div", undefined, "location-group-list"); groupBox.append(groupList, text("p", "locationGroupHelp", "fine")); balancingBody.append(groupBox);
|
||||
const groupSelected = new Set(value.backend_ids || []);
|
||||
const renderGroup = () => {
|
||||
const all = balancingMembers(); for (const id of [...groupSelected]) if (!all.some(m => m.id === id)) groupSelected.delete(id);
|
||||
groupList.replaceChildren(...all.filter(m => m.id).map(member => {
|
||||
const label = el("label", undefined, "check location-group-member"), box = document.createElement("input"); box.type = "checkbox"; box.checked = groupSelected.has(member.id);
|
||||
box.addEventListener("change", () => { if (box.checked) groupSelected.add(member.id); else groupSelected.delete(member.id); balancingControl.refresh(); });
|
||||
const tags = [member.pool_eligible ? "" : t("locationOnlyTag"), member.backup ? t("vhBackup") : "", member.enabled ? "" : t("vhOff")].filter(Boolean).join(" · ");
|
||||
label.append(box, el("span", member.id), el("small", tags ? ` ${tags}` : "", "fine")); return label;
|
||||
}));
|
||||
};
|
||||
row.groupIds = () => { const ids = balancingMembers().map(m => m.id).filter(id => groupSelected.has(id)); if (!ids.length) throw new Error(t("locationGroupEmpty").replace("{location}", str("location-id", row))); return ids; };
|
||||
backend.addEventListener("change", () => { if (backend.value === LOCATION_GROUP) balancing.open = true; });
|
||||
const ownBalancing = field(balancingBody, "location-lb-custom", "lbLocationOwn", Boolean(value.load_balancing), "checkbox", { switch: true });
|
||||
const balancingSlot = el("div", undefined, "vh-wide vh-grid"); balancingBody.append(balancingSlot);
|
||||
const balancingControl = balancingEditor(balancingSlot, {
|
||||
names: "location-lb-", value: value.load_balancing || { algorithm: "hash", hash: { source: "path" } }, stickyField: true,
|
||||
members: () => backend.value === LOCATION_GROUP ? balancingMembers().filter(m => groupSelected.has(m.id)) : balancingMembers(),
|
||||
explicit: () => backend.value === LOCATION_GROUP, poolId: () => str("id"), onChange: sync
|
||||
});
|
||||
const inheritNote = text("p", "lbLocationInherit", "fine vh-wide"); balancingBody.append(inheritNote);
|
||||
row.readBalancing = () => { if (!ownBalancing.checked) return null; balancingControl.validate(); const hash = balancingControl.hash(); return { algorithm: balancingControl.algorithm(), ...(hash ? { hash } : {}), sticky: balancingControl.sticky() }; };
|
||||
row.refreshBalancing = () => { renderGroup(); balancingControl.refresh(); };
|
||||
renderGroup();
|
||||
const handling = el("details", undefined, "vh-wide location-section"), handlingBody = el("div", undefined, "vh-grid"); handling.append(text("summary", "locationHandling"), handlingBody); body.append(handling);
|
||||
field(handlingBody, "location-error-target", "locationErrorFallbackTarget", value.error_fallback?.target || "", "text", { maxLength: 64, pattern: "[A-Za-z0-9_\\-]{0,64}" });
|
||||
field(handlingBody, "location-error-statuses", "locationErrorFallbackStatuses", (value.error_fallback?.statuses || [404]).join(", "), "text", { maxLength: 64 });
|
||||
@@ -442,23 +484,32 @@ function locationsEditor(parent, values) {
|
||||
preview.append(previewGrid); body.append(preview);
|
||||
|
||||
const actions = el("div", undefined, "vh-wide location-actions");
|
||||
const dedicated = button("locationAddBackend", () => { const members = form.querySelector(".vh-members"); let i = 1; const ids = new Set([...members.children].map(r => str("member-id", r))); while (ids.has(`location-origin-${i}`)) i++; const id = `location-origin-${i}`; memberRow(members, { id, url: "http://127.0.0.1:9001", weight: 1, enabled: true, pool_eligible: false, allow_private: false }); memberOptions(backend, id); sync(); activateTab("backends"); });
|
||||
actions.append(dedicated, button("remove", () => { row.remove(); sync(); })); body.append(actions);
|
||||
const dedicated = button("locationAddBackend", () => { const members = form.querySelector(".vh-members"); let i = 1; const ids = new Set([...members.children].map(r => str("member-id", r))); while (ids.has(`location-origin-${i}`)) i++; const id = `location-origin-${i}`; memberRow(members, { id, url: "http://127.0.0.1:9001", weight: 1, enabled: true, pool_eligible: false, allow_private: false }); if (backend.value === LOCATION_GROUP) { groupSelected.add(id); memberOptions(backend, LOCATION_GROUP); row.refreshBalancing(); } else memberOptions(backend, id); sync(); activateTab("backends"); });
|
||||
const moveUp = button("rtMoveUp", () => { if (row.previousElementSibling) { rows.insertBefore(row, row.previousElementSibling); sync(); } });
|
||||
const moveDown = button("rtMoveDown", () => { if (row.nextElementSibling) { rows.insertBefore(row.nextElementSibling, row); sync(); } });
|
||||
actions.append(moveUp, moveDown, dedicated, button("remove", () => { row.remove(); sync(); })); body.append(actions);
|
||||
|
||||
const syncUi = () => {
|
||||
const isReturn = action.value === "return", isRedirect = action.value === "redirect", isWeb = action.value === "web_server", isProxy = action.value === "proxy", isRegex = match.value === "regex" || match.value === "regex_insensitive";
|
||||
match.disabled = path.disabled = internal.checked;
|
||||
backend.disabled = !isProxy; cache.disabled = !isProxy; dedicated.disabled = !isProxy;
|
||||
match.disabled = internal.checked; path.disabled = internal.checked || match.value === "any";
|
||||
const conditional = !internal.checked && conditions.count() > 0;
|
||||
conditionBox.hidden = internal.checked; conditionCacheNote.hidden = !conditional;
|
||||
if (conditional) cache.value = "";
|
||||
backend.disabled = !isProxy; cache.disabled = !isProxy || conditional; dedicated.disabled = !isProxy;
|
||||
const isGroup = isProxy && backend.value === LOCATION_GROUP, pinned = isProxy && !["", LOCATION_GROUP].includes(backend.value);
|
||||
balancing.hidden = !isProxy || pinned; groupBox.hidden = !isGroup;
|
||||
ownBalancing.disabled = !isProxy || pinned; balancingSlot.hidden = !ownBalancing.checked; inheritNote.hidden = ownBalancing.checked;
|
||||
webService.disabled = !isWeb; webService.required = isWeb;
|
||||
returnBox.hidden = !isReturn; redirectBox.hidden = !isRedirect; rewriteMode.disabled = isReturn || isRedirect; rewriteValue.disabled = isReturn || isRedirect || rewriteMode.value === "preserve" || rewriteMode.value === "strip_prefix";
|
||||
for (const option of rewriteMode.options) if (option.value === "regex") option.disabled = !isRegex;
|
||||
if (!isRegex && rewriteMode.value === "regex") rewriteMode.value = "preserve";
|
||||
path.placeholder = isRegex ? "^/api/v[0-9]+/" : "/api/";
|
||||
const id = str("location-id", row) || t("locationId"), pattern = internal.checked ? `@${id}` : (str("location-path", row) || "/");
|
||||
summary.textContent = `${id} · ${internal.checked ? t("locationInternal") : t(`locationMatch_${match.value}`)} · ${pattern} · ${t(isReturn ? "locationReturnShort" : isRedirect ? "locationRedirectShort" : isWeb ? "locationWebServerShort" : "locationProxyShort")}`;
|
||||
const id = str("location-id", row) || t("locationId"), pattern = internal.checked ? `@${id}` : match.value === "any" ? "*" : (str("location-path", row) || "/");
|
||||
const conditionNote = conditional ? ` · ${t("rtConditionCount").replace("{count}", String(conditions.count()))}` : "";
|
||||
summary.textContent = `${id} · ${internal.checked ? t("locationInternal") : t(`locationMatch_${match.value}`)} · ${pattern} · ${t(isReturn ? "locationReturnShort" : isRedirect ? "locationRedirectShort" : isWeb ? "locationWebServerShort" : "locationProxyShort")}${conditionNote}`;
|
||||
|
||||
previewStatus.hidden = yes("location-enabled", row);
|
||||
previewValues.match.textContent = `${t(`locationMatch_${match.value}`)} · ${pattern}`;
|
||||
previewValues.match.textContent = `${t(`locationMatch_${match.value}`)} · ${pattern}${conditionNote}`;
|
||||
if (isReturn) {
|
||||
const status = str("location-response-status", row) || "200", type = str("location-response-type", row) || "text/plain";
|
||||
previewValues.handling.textContent = `${t("locationReturnAction")}: HTTP ${status} · ${type} · ${t("locationPreviewBackendSkipped")}`;
|
||||
@@ -475,8 +526,9 @@ function locationsEditor(parent, values) {
|
||||
previewValues.handling.textContent = `${t("locationWebServerAction")}: ${selected}`;
|
||||
previewValues.cache.textContent = t("notEnabled");
|
||||
} else {
|
||||
const selected = backend.selectedOptions?.[0]?.textContent || t("locationPool");
|
||||
previewValues.handling.textContent = `${t("locationProxyAction")}: ${selected}`;
|
||||
const selected = backend.value === LOCATION_GROUP ? `${t("locationBackendGroup")} (${[...groupSelected].join(", ") || "-"})` : backend.selectedOptions?.[0]?.textContent || t("locationPool");
|
||||
const algorithmLabel = ownBalancing.checked && !balancing.hidden ? ` · ${t(LB_ALGORITHMS.find(([v]) => v === balancingControl.algorithm())?.[1] || "vhAlgorithm")}${balancingControl.algorithm() === "hash" ? ` (${t(LB_SOURCES.find(([v]) => v === balancingControl.hash().source)?.[1] || "lbHash")})` : ""}` : "";
|
||||
previewValues.handling.textContent = `${t("locationProxyAction")}: ${selected}${algorithmLabel}`;
|
||||
previewValues.cache.textContent = t(cache.value === "on" ? "enabled" : cache.value === "off" ? "notEnabled" : "inherit");
|
||||
}
|
||||
const rewriteLabels = { preserve: "locationRewritePreserve", strip_prefix: "locationRewriteStrip", replace_prefix: "locationRewriteReplace", regex: "locationRewriteRegex" };
|
||||
@@ -499,7 +551,8 @@ function locationsEditor(parent, values) {
|
||||
}
|
||||
for (const value of values) add(value);
|
||||
const bottom = el("div", undefined, "vh-wide location-toolbar location-toolbar-bottom"); bottom.append(button("locationAdd", () => { add(); sync(); }, "primary")); parent.append(bottom);
|
||||
form.querySelector(".vh-members").addEventListener("input", () => { for (const select of rows.querySelectorAll('[name="location-backend"]')) memberOptions(select); });
|
||||
const refreshMembers = () => { for (const select of rows.querySelectorAll('[name="location-backend"]')) memberOptions(select); for (const row of rows.children) row.refreshBalancing?.(); };
|
||||
form.querySelector(".vh-members").addEventListener("input", refreshMembers); form.querySelector(".vh-members").addEventListener("change", refreshMembers);
|
||||
read("paths").addEventListener("change", () => { try { const data = JSON.parse(str("paths")); if (!Array.isArray(data) || data.length > 64) return; reloading = true; rows.replaceChildren(); for (const value of data) add(value); } catch { } finally { reloading = false; } });
|
||||
sync(); return readRows;
|
||||
}
|
||||
@@ -221,7 +221,8 @@ function load(value = defaults(), migrationIds = [], show = true) {
|
||||
const settings = value.load_balancing || {}, health = settings.health_check || {}, keepalive = settings.keepalive || {}, retry = settings.retry || {}, sticky = settings.sticky || {};
|
||||
g = group("vhBalancing");
|
||||
const schedulingFields = subsection(g, "vhBalancerAlgorithmSection");
|
||||
field(schedulingFields, "algorithm", "vhAlgorithm", settings.algorithm || "least_connections", "select", { values: [["round_robin", "vhRoundRobin"], ["least_connections", "vhLeastConnections"], ["least_traffic", "vhLeastTraffic"], ["adaptive", "vhAdaptive"], ["ip_hash", "vhIpHash"]] });
|
||||
vhostBalancingControl = balancingEditor(schedulingFields, { names: "", value: settings, members: balancingMembers, poolId: () => str("id"), onChange: changed });
|
||||
members.addEventListener("input", () => vhostBalancingControl?.refresh()); members.addEventListener("change", () => vhostBalancingControl?.refresh());
|
||||
field(schedulingFields, "slow-start", "vhSlowStart", settings.slow_start_seconds ?? 10, "number", { required: true, min: 0, max: 300 });
|
||||
const retryFields = subsection(g, "vhBalancerRetrySection");
|
||||
field(retryFields, "retry-max", "vhRetryMax", retry.max_retries ?? 1, "number", { required: true, min: 0, max: 3 });
|
||||
@@ -645,7 +646,7 @@ function collect() {
|
||||
timeout_seconds: num("oidc-timeout"), session_ttl_seconds: num("oidc-ttl") },
|
||||
backends: members, routes: paths, acl, headers,
|
||||
load_balancing: {
|
||||
algorithm: str("algorithm"), slow_start_seconds: num("slow-start"), keepalive: { enabled: yes("keepalive"), idle_timeout_seconds: num("idle-timeout"), max_idle_per_host: num("max-idle"), tcp_keepalive_seconds: num("tcp-keepalive"), pool_recycle_requests: num("pool-recycle-requests"), pool_recycle_seconds: num("pool-recycle-seconds"), http1_max_buffer_bytes: num("http1-max-buffer") },
|
||||
algorithm: str("algorithm"), ...(vhostBalancingControl?.hash() ? { hash: vhostBalancingControl.hash() } : {}), slow_start_seconds: num("slow-start"), keepalive: { enabled: yes("keepalive"), idle_timeout_seconds: num("idle-timeout"), max_idle_per_host: num("max-idle"), tcp_keepalive_seconds: num("tcp-keepalive"), pool_recycle_requests: num("pool-recycle-requests"), pool_recycle_seconds: num("pool-recycle-seconds"), http1_max_buffer_bytes: num("http1-max-buffer") },
|
||||
retry: { max_retries: num("retry-max"), retry_connect_errors: yes("retry-connect"), retry_timeouts: yes("retry-timeouts"), retry_statuses: str("retry-statuses").split(/[\s,]+/).filter(Boolean).map(value => Number(value)) },
|
||||
health_check: { mode: str("health-mode"), path: str("health-path"), host: nullable("health-host"), port: optionalPort("health-port"), expect_body: nullable("health-expect-body"), interval_ms: num("interval"), timeout_ms: num("timeout"), slow_response_ms: num("slow"), fall: num("fall"), rise: num("rise"), expected_status_min: num("status-min"), expected_status_max: num("status-max") },
|
||||
passive_health: {
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
// 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.
|
||||
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) {
|
||||
if (source === "ip") return ["cidr"];
|
||||
if (source === "method" || source === "country") return ["equals"];
|
||||
if (source === "host") return ["equals", "prefix", "suffix", "contains", "regex"];
|
||||
return ["equals", "exists", "prefix", "suffix", "contains", "regex"];
|
||||
}
|
||||
// Rust regex → JS RegExp (common subset; a leading (?i) becomes the i flag).
|
||||
function rtRegex(pattern, insensitive = false) {
|
||||
let flags = insensitive ? "i" : "", body = pattern;
|
||||
const inline = body.match(/^\(\?([imsx]+)\)/);
|
||||
if (inline) { body = body.slice(inline[0].length); if (inline[1].includes("i")) flags += flags.includes("i") ? "" : "i"; if (inline[1].includes("s")) flags += "s"; if (inline[1].includes("m")) flags += "m"; }
|
||||
return new RegExp(body, `${flags}u`);
|
||||
}
|
||||
function rtIpToBits(text) {
|
||||
const value = String(text).trim();
|
||||
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(value)) {
|
||||
const parts = value.split(".").map(Number); if (parts.some(p => p > 255)) return null;
|
||||
return { v6: false, bits: parts.reduce((acc, p) => (acc << 8n) | BigInt(p), 0n) };
|
||||
}
|
||||
if (!value.includes(":")) return null;
|
||||
let [head, tail] = value.split("::"); if (value.split("::").length > 2) return null;
|
||||
const hextets = s => (s ? s.split(":") : []);
|
||||
let left = hextets(head), right = tail === undefined ? [] : hextets(tail);
|
||||
const last = (right.length ? right : left)[(right.length ? right : left).length - 1];
|
||||
const v4 = last && last.includes(".") ? rtIpToBits(last) : null;
|
||||
if (v4) { const list = right.length ? right : left; list.pop(); list.push(((v4.bits >> 16n) & 0xffffn).toString(16), (v4.bits & 0xffffn).toString(16)); }
|
||||
const fill = 8 - left.length - right.length; if (tail === undefined && fill !== 0) return null; if (fill < 0) return null;
|
||||
const all = [...left, ...Array(tail === undefined ? 0 : fill).fill("0"), ...right];
|
||||
if (all.length !== 8 || all.some(h => !/^[0-9a-f]{1,4}$/i.test(h))) return null;
|
||||
const bits = all.reduce((acc, h) => (acc << 16n) | BigInt(parseInt(h, 16)), 0n);
|
||||
if (bits >> 32n === 0xffffn) return { v6: false, bits: bits & 0xffffffffn }; // IPv4-mapped, like canonical_ip()
|
||||
return { v6: true, bits };
|
||||
}
|
||||
function rtCidrContains(network, ip) {
|
||||
const [addr, len] = String(network).trim().split("/"); const net = rtIpToBits(addr), target = rtIpToBits(ip);
|
||||
if (!net || !target || net.v6 !== target.v6) return false;
|
||||
const width = net.v6 ? 128 : 32, prefix = len === undefined ? width : Number(len);
|
||||
if (!Number.isInteger(prefix) || prefix < 0 || prefix > width) return false;
|
||||
const shift = BigInt(width - prefix); return (net.bits >> shift) === (target.bits >> shift);
|
||||
}
|
||||
function rtHeaderValues(request, name) {
|
||||
const lower = name.toLowerCase(); return (request.headers || []).filter(([key]) => key.toLowerCase() === lower).map(([, value]) => value.trim());
|
||||
}
|
||||
function rtConditionValues(condition, request) {
|
||||
const name = (condition.name || "").trim();
|
||||
switch (condition.source) {
|
||||
case "header": return rtHeaderValues(request, name);
|
||||
case "cookie": return rtHeaderValues(request, "cookie").flatMap(v => v.split(";")).map(p => p.trim()).filter(p => p.includes("=")).map(p => [p.slice(0, p.indexOf("=")), p.slice(p.indexOf("=") + 1)]).filter(([n]) => n === name).map(([, v]) => v.trim());
|
||||
case "query": return request.query === null || request.query === undefined ? [] : request.query.split("&").map(p => p.includes("=") ? [p.slice(0, p.indexOf("=")), p.slice(p.indexOf("=") + 1)] : [p, ""]).filter(([n]) => n === name).map(([, v]) => v);
|
||||
case "method": return [String(request.method || "GET").toUpperCase()];
|
||||
case "host": return [String(request.host || "").replace(/\.$/, "").toLowerCase()];
|
||||
case "country": return request.country ? [String(request.country).toUpperCase()] : [];
|
||||
case "ip": return [String(request.client_ip || "")];
|
||||
default: return [];
|
||||
}
|
||||
}
|
||||
// Mirrors CompiledCondition::matches(). Throws for patterns the browser cannot run.
|
||||
function rtConditionMatches(condition, request) {
|
||||
const op = condition.operator || "equals", source = condition.source || "header";
|
||||
const fold = (condition.ignore_case && ["header", "cookie", "query"].includes(source)) || source === "host";
|
||||
const values = (condition.values || []).map(v => String(v).trim());
|
||||
const raw = rtConditionValues(condition, request);
|
||||
const norm = value => {
|
||||
if (source === "method" || source === "country") return value.toUpperCase();
|
||||
if (source === "host") return value.replace(/\.$/, "").toLowerCase();
|
||||
return fold ? value.toLowerCase() : value;
|
||||
};
|
||||
let hit;
|
||||
if (op === "exists") hit = raw.length > 0;
|
||||
else if (op === "cidr") hit = values.some(net => rtCidrContains(net, request.client_ip));
|
||||
else if (op === "regex") { const list = values.map(v => rtRegex(v, fold)); hit = raw.some(v => list.some(r => r.test(v))); }
|
||||
else {
|
||||
const patterns = values.map(norm), test = { equals: (v, p) => v === p, prefix: (v, p) => v.startsWith(p), suffix: (v, p) => v.endsWith(p), contains: (v, p) => v.includes(p) }[op];
|
||||
hit = raw.some(v => patterns.some(p => test(norm(v), p)));
|
||||
}
|
||||
return hit !== Boolean(condition.negate);
|
||||
}
|
||||
function rtNormalizePrefix(prefix) { let value = String(prefix || "/").trim(); if (!value.startsWith("/")) value = `/${value}`; if (value.length > 1) value = value.replace(/\/+$/, ""); return value || "/"; }
|
||||
function rtPrefixMatches(prefix, path) { return prefix === "/" || path === prefix || path.startsWith(`${prefix}/`); }
|
||||
// Evaluates every location like select_route() and returns the winner plus a trace.
|
||||
function rtEvaluate(routes, request) {
|
||||
const path = String(request.path || "/").replace(/%2f/gi, "/");
|
||||
const trace = routes.map((route, index) => {
|
||||
const type = route.match_type || "prefix", internal = route.internal === true, enabled = route.enabled !== false;
|
||||
let pathMatch = false, error = null;
|
||||
try {
|
||||
if (type === "exact") pathMatch = route.path_prefix === path;
|
||||
else if (type === "prefix" || type === "prefix_priority") pathMatch = rtPrefixMatches(rtNormalizePrefix(route.path_prefix), path);
|
||||
else if (type === "regex" || type === "regex_insensitive") pathMatch = rtRegex(route.path_prefix, type === "regex_insensitive").test(path);
|
||||
else if (type === "any") pathMatch = true;
|
||||
} catch (cause) { error = cause.message; }
|
||||
const conditions = (route.conditions || []).map(condition => { try { return rtConditionMatches(condition, request); } catch (cause) { error = cause.message; return false; } });
|
||||
const usable = enabled && !internal && !error && conditions.every(Boolean);
|
||||
return { route, index, type, pathMatch, conditions, usable, error, conditional: (route.conditions || []).length > 0, prefixLength: rtNormalizePrefix(route.path_prefix).length };
|
||||
});
|
||||
const ok = item => item.pathMatch && item.usable;
|
||||
const exact = trace.filter(i => i.type === "exact" && ok(i));
|
||||
if (exact.length) return { winner: exact.find(i => i.conditional) || exact[0], trace };
|
||||
let prefix = null;
|
||||
for (const item of trace) {
|
||||
if (!["prefix", "prefix_priority"].includes(item.type) || !ok(item)) continue;
|
||||
if (!prefix || item.prefixLength > prefix.prefixLength || (item.prefixLength === prefix.prefixLength && item.conditional && !prefix.conditional)) prefix = item;
|
||||
}
|
||||
if (prefix?.type === "prefix_priority") return { winner: prefix, trace };
|
||||
const regex = trace.find(i => ["regex", "regex_insensitive", "any"].includes(i.type) && ok(i));
|
||||
return { winner: regex || prefix || null, trace };
|
||||
}
|
||||
if (typeof window !== "undefined") window.rustProxyRoutingCore = { evaluate: rtEvaluate, conditionMatches: rtConditionMatches, cidrContains: rtCidrContains };
|
||||
|
||||
// Editor for a location's conditions. Returns read() → array of conditions.
|
||||
function conditionsEditor(parent, values = [], onChange = () => { }) {
|
||||
const box = el("div", undefined, "vh-wide rt-conditions"), list = el("div", undefined, "rt-condition-list"); box.append(list); parent.append(box);
|
||||
const empty = text("p", "rtNoConditions", "fine rt-empty"); box.prepend(empty);
|
||||
const add = (value = { source: "header", operator: "equals", values: [] }) => {
|
||||
if (list.children.length >= 16) { toast(t("rtTooMany"), true); return; }
|
||||
const row = el("div", undefined, "rt-condition");
|
||||
const source = document.createElement("select"), name = document.createElement("input"), operator = document.createElement("select"), valuesInput = document.createElement("textarea");
|
||||
source.setAttribute("aria-label", t("rtSource")); operator.setAttribute("aria-label", t("rtOperator")); name.setAttribute("aria-label", t("rtName")); valuesInput.setAttribute("aria-label", t("rtValues"));
|
||||
for (const [v, key] of RT_SOURCES) { const o = text("option", key); o.value = v; source.append(o); }
|
||||
source.value = value.source || "header"; name.type = "text"; name.maxLength = 128; name.value = value.name || ""; valuesInput.rows = 1; valuesInput.spellcheck = false; valuesInput.maxLength = 8192; valuesInput.value = (value.values || []).join("\n");
|
||||
const negate = document.createElement("input"), ignore = document.createElement("input"); negate.type = ignore.type = "checkbox"; negate.className = ignore.className = "switch"; negate.checked = value.negate === true; ignore.checked = value.ignore_case === true;
|
||||
const negateLabel = el("label", undefined, "check rt-flag"), ignoreLabel = el("label", undefined, "check rt-flag"); negateLabel.append(negate, text("span", "rtNegate")); ignoreLabel.append(ignore, text("span", "lbHashIgnoreCase"));
|
||||
const remove = button("remove", () => { row.remove(); refresh(); onChange(); });
|
||||
const fillOperators = chosen => { operator.replaceChildren(...rtOperatorsFor(source.value).map(v => { const o = text("option", RT_OPERATORS.find(([x]) => x === v)[1]); o.value = v; return o; })); operator.value = rtOperatorsFor(source.value).includes(chosen) ? chosen : rtOperatorsFor(source.value)[0]; };
|
||||
const syncRow = () => {
|
||||
const named = ["header", "cookie", "query"].includes(source.value);
|
||||
// .check labels set their own display, so the hidden attribute is not enough.
|
||||
name.hidden = !named; ignoreLabel.hidden = !named; ignoreLabel.style.display = named ? "" : "none"; valuesInput.hidden = operator.value === "exists";
|
||||
name.placeholder = { header: "X-Beta", cookie: "session", query: "tenant" }[source.value] || "";
|
||||
valuesInput.placeholder = { ip: "10.0.0.0/8\n2001:db8::/32", method: "POST\nPUT", country: "PL\nDE", host: "beta.example.com" }[source.value] || t("rtValuesPlaceholder");
|
||||
};
|
||||
fillOperators(value.operator || "equals"); syncRow();
|
||||
source.addEventListener("change", () => { fillOperators(operator.value); syncRow(); });
|
||||
operator.addEventListener("change", syncRow);
|
||||
row.read = () => {
|
||||
const result = { source: source.value, operator: operator.value };
|
||||
if (!name.hidden) result.name = name.value.trim();
|
||||
if (operator.value !== "exists") result.values = valuesInput.value.split("\n").map(v => v.trim()).filter(Boolean);
|
||||
if (negate.checked) result.negate = true;
|
||||
if (!ignoreLabel.hidden && ignore.checked) result.ignore_case = true;
|
||||
return result;
|
||||
};
|
||||
row.append(source, name, operator, valuesInput, negateLabel, ignoreLabel, remove); list.append(row); refresh();
|
||||
};
|
||||
const refresh = () => { empty.hidden = list.children.length > 0; };
|
||||
box.append(button("rtAddCondition", () => { add(); onChange(); }));
|
||||
for (const value of values) add(value); refresh();
|
||||
return { read: () => [...list.children].map(row => row.read()), count: () => list.children.length };
|
||||
}
|
||||
|
||||
// Routing tester for the Locations tab: works on the unsaved draft.
|
||||
function routingTester(parent, readRoutes) {
|
||||
const box = el("details", undefined, "vh-wide rt-tester"); box.append(text("summary", "rtTester")); parent.append(box);
|
||||
const body = el("div", undefined, "rt-tester-body"); box.append(body);
|
||||
const grid = el("div", undefined, "vh-grid"); body.append(grid);
|
||||
const method = field(grid, "rt-method", "rtSourceMethod", "GET", "select", { values: ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].map(m => [m, m]) });
|
||||
const url = field(grid, "rt-url", "rtUrl", "/", "text", { maxLength: 4096 }); url.placeholder = "https://app.example.com/api/v2/items?tenant=acme";
|
||||
const ip = field(grid, "rt-ip", "rtSourceIp", "203.0.113.10", "text", { maxLength: 64 });
|
||||
const country = field(grid, "rt-country", "rtSourceCountry", "", "text", { maxLength: 2 }); country.placeholder = "PL";
|
||||
const headers = field(grid, "rt-headers", "rtHeaders", "", "textarea", { rows: 3, maxLength: 8192 }); headers.placeholder = "X-Beta: 1\nCookie: session=abc; staff=1\nUser-Agent: Mozilla/5.0";
|
||||
for (const control of [method, url, ip, country, headers]) control.removeAttribute("name");
|
||||
const out = el("div", undefined, "rt-result"); body.append(out);
|
||||
const run = () => {
|
||||
out.replaceChildren();
|
||||
let routes; try { routes = readRoutes(); } catch (cause) { out.append(el("p", cause.message, "fine rt-error")); return; }
|
||||
const parsed = lbParseSample(url.value || "/"), hosts = lines(read("hosts")?.value || "");
|
||||
const request = {
|
||||
method: method.value, path: parsed.path || "/", query: parsed.query, host: parsed.host || hosts.find(h => !h.startsWith("*")) || "",
|
||||
client_ip: ip.value.trim(), country: country.value.trim().toUpperCase() || null,
|
||||
headers: headers.value.split("\n").map(line => line.trim()).filter(line => line.includes(":")).map(line => [line.slice(0, line.indexOf(":")).trim(), line.slice(line.indexOf(":") + 1).trim()])
|
||||
};
|
||||
const { winner, trace } = rtEvaluate(routes, request);
|
||||
const verdict = el("div", undefined, "rt-verdict");
|
||||
const routeName = winner ? winner.route.id : t("rtMainSource");
|
||||
verdict.append(text("span", "rtResult"), el("strong", routeName));
|
||||
const target = rtTarget(winner?.route || null, request); if (target) verdict.append(el("span", ` → ${target}`, "rt-target"));
|
||||
if (winner?.conditional) verdict.append(text("span", "rtNotCached", "fine rt-badge"));
|
||||
out.append(verdict);
|
||||
const table = el("table", undefined, "lb-sim-table rt-trace"), head = el("tr");
|
||||
for (const key of ["locationId", "locationMatchType", "rtPathColumn", "rtConditionsColumn"]) head.append(text("th", key));
|
||||
table.append(head);
|
||||
for (const item of trace) {
|
||||
const tr = el("tr"); if (item === winner) tr.classList.add("is-winner");
|
||||
const mark = ok => el("span", ok ? "✓" : "✗", ok ? "rt-ok" : "rt-no");
|
||||
const conditionsCell = el("td");
|
||||
if (item.error) conditionsCell.append(el("span", `${t("rtBrowserRegex")}: ${item.error}`, "rt-no"));
|
||||
else if (!item.conditional) conditionsCell.append(el("span", "—", "fine"));
|
||||
else item.conditions.forEach((ok, i) => { const c = item.route.conditions[i]; conditionsCell.append(mark(ok), el("span", ` ${c.negate ? "!" : ""}${c.source}${c.name ? `(${c.name})` : ""} ${c.operator || "equals"} `, "rt-cond")); });
|
||||
const pathCell = el("td"); pathCell.append(mark(item.pathMatch)); if (item.route.enabled === false || item.route.internal) pathCell.append(el("span", ` ${t(item.route.internal ? "locationInternal" : "vhOff")}`, "fine"));
|
||||
tr.append(el("td", item.route.id), el("td", t(`locationMatch_${item.type}`)), pathCell, conditionsCell); table.append(tr);
|
||||
}
|
||||
out.append(table, text("p", "rtTesterHelp", "fine"));
|
||||
};
|
||||
// Backend for the chosen route: pinned backend, group or vhost pool + algorithm.
|
||||
const rtTarget = (route, request) => {
|
||||
if (route && (route.response || route.redirect)) return t(route.response ? "locationReturnShort" : "locationRedirectShort");
|
||||
if (route?.source?.type === "web_server") return `${t("locationWebServerShort")} ${route.source.web_service_id || ""}`;
|
||||
if (route?.backend_id) return route.backend_id;
|
||||
const members = balancingMembers(), explicit = Boolean(route?.backend_ids?.length);
|
||||
const pool = lbEligible(explicit ? members.filter(m => route.backend_ids.includes(m.id)) : members, explicit);
|
||||
if (!pool.length) return t("lbSimNoMembers");
|
||||
const own = route?.load_balancing, algorithm = own ? own.algorithm : str("algorithm"), hash = own ? own.hash || { source: "path" } : vhostBalancingControl?.hash() || {};
|
||||
const sticky = own ? own.sticky || "off" : str("sticky-mode");
|
||||
const label = t(LB_ALGORITHMS.find(([v]) => v === algorithm)?.[1] || "vhAlgorithm");
|
||||
let key = null;
|
||||
if (sticky === "ip_hash" || algorithm === "ip_hash") key = request.client_ip;
|
||||
else if (algorithm === "hash") {
|
||||
const settings = hash, source = settings.source || "path";
|
||||
if (source === "header") key = rtHeaderValues(request, settings.name || "").join(",") || null;
|
||||
else if (source === "cookie") key = rtConditionValues({ source: "cookie", name: settings.name }, request)[0] || null;
|
||||
else if (source === "ip") key = request.client_ip;
|
||||
else key = lbHashKey(settings, `https://${request.host || "host"}${request.path}${request.query !== null && request.query !== undefined ? `?${request.query}` : ""}`);
|
||||
if (key && settings.ignore_case && !["ip", "host"].includes(source)) key = key.toLowerCase();
|
||||
}
|
||||
if (key) return `${lbRank(str("id") || "vhost", key, pool)[0].id} (${label}, ${t("lbSimKey")}: ${key})`;
|
||||
return `${pool.map(m => m.id).join(", ")} (${label})`;
|
||||
};
|
||||
box.addEventListener("input", event => { event.stopPropagation(); run(); });
|
||||
box.addEventListener("change", event => event.stopPropagation());
|
||||
box.addEventListener("toggle", () => { if (box.open) run(); });
|
||||
return { run: () => { if (box.open) run(); } };
|
||||
}
|
||||
@@ -7,3 +7,5 @@ include!("balance/pool_view.rs");
|
||||
|
||||
#[cfg(test)]
|
||||
include!("balance/tests.rs");
|
||||
#[cfg(test)]
|
||||
include!("balance/hash_tests.rs");
|
||||
@@ -0,0 +1,426 @@
|
||||
mod hash_tests {
|
||||
use super::*;
|
||||
|
||||
fn policy() -> crate::config::ValidationPolicy {
|
||||
crate::config::ValidationPolicy {
|
||||
proxy_addr: "127.0.0.1:8080".parse().unwrap(),
|
||||
admin_addr: "127.0.0.1:9090".parse().unwrap(),
|
||||
tls_addr: None,
|
||||
cert_dir: None,
|
||||
data_dir: None,
|
||||
}
|
||||
}
|
||||
fn compile(value: serde_json::Value) -> anyhow::Result<crate::config::Snapshot> {
|
||||
let cfg = serde_json::from_value(value)?;
|
||||
crate::config::compile(cfg, 0, &policy())
|
||||
}
|
||||
fn shards(load_balancing: serde_json::Value) -> Arc<Pool> {
|
||||
compile(serde_json::json!({
|
||||
"listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]},
|
||||
"vhosts":[{
|
||||
"id":"files","frontend":{"hosts":["files.localhost"],"listener_ids":["http"]},
|
||||
"backends":[
|
||||
{"id":"s1","url":"http://127.0.0.1:9001","allow_private":true},
|
||||
{"id":"s2","url":"http://127.0.0.1:9002","allow_private":true},
|
||||
{"id":"s3","url":"http://127.0.0.1:9003","allow_private":true}],
|
||||
"load_balancing":load_balancing
|
||||
}]
|
||||
}))
|
||||
.unwrap()
|
||||
.pools[0]
|
||||
.clone()
|
||||
}
|
||||
fn uri(value: &str) -> http::Uri {
|
||||
value.parse().unwrap()
|
||||
}
|
||||
fn peer() -> IpAddr {
|
||||
"192.0.2.10".parse().unwrap()
|
||||
}
|
||||
fn pick(pool: &Pool, path: &str, headers: &HeaderMap) -> String {
|
||||
let selection = pool
|
||||
.select_uri(peer(), headers, Some(&uri(path)), false)
|
||||
.expect("selection");
|
||||
selection.lease.member.definition.id.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_keys_follow_the_configured_source() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("host", "Files.Example.com:8443".parse().unwrap());
|
||||
headers.insert("x-tenant", "Acme".parse().unwrap());
|
||||
headers.insert("cookie", "a=1; session=XYZ; b=2".parse().unwrap());
|
||||
let request = uri("/music/Album/track.MP3?user=42&x");
|
||||
let key = |value: serde_json::Value| {
|
||||
let settings: HashSettings = serde_json::from_value(value).unwrap();
|
||||
settings.validate().unwrap();
|
||||
settings.key(peer(), &headers, Some(&request))
|
||||
};
|
||||
assert_eq!(key(serde_json::json!({})).as_deref(), Some("/music/Album/track.MP3"));
|
||||
assert_eq!(
|
||||
key(serde_json::json!({"ignore_case":true})).as_deref(),
|
||||
Some("/music/album/track.mp3")
|
||||
);
|
||||
assert_eq!(key(serde_json::json!({"path_depth":1})).as_deref(), Some("/music"));
|
||||
assert_eq!(key(serde_json::json!({"path_depth":2})).as_deref(), Some("/music/Album"));
|
||||
assert_eq!(
|
||||
key(serde_json::json!({"path_depth":9})).as_deref(),
|
||||
Some("/music/Album/track.MP3")
|
||||
);
|
||||
assert_eq!(
|
||||
key(serde_json::json!({"source":"uri"})).as_deref(),
|
||||
Some("/music/Album/track.MP3?user=42&x")
|
||||
);
|
||||
assert_eq!(
|
||||
key(serde_json::json!({"source":"host"})).as_deref(),
|
||||
Some("files.example.com")
|
||||
);
|
||||
assert_eq!(key(serde_json::json!({"source":"ip"})).as_deref(), Some("192.0.2.10"));
|
||||
assert_eq!(
|
||||
key(serde_json::json!({"source":"header","name":"X-Tenant"})).as_deref(),
|
||||
Some("Acme")
|
||||
);
|
||||
assert_eq!(
|
||||
key(serde_json::json!({"source":"cookie","name":"session"})).as_deref(),
|
||||
Some("XYZ")
|
||||
);
|
||||
assert_eq!(
|
||||
key(serde_json::json!({"source":"query","name":"user"})).as_deref(),
|
||||
Some("42")
|
||||
);
|
||||
assert_eq!(key(serde_json::json!({"source":"query","name":"x"})), None);
|
||||
assert_eq!(key(serde_json::json!({"source":"query","name":"missing"})), None);
|
||||
assert_eq!(key(serde_json::json!({"source":"cookie","name":"missing"})), None);
|
||||
assert_eq!(key(serde_json::json!({"source":"header","name":"x-missing"})), None);
|
||||
// HTTP/2 requests carry the authority in the URI.
|
||||
let settings: HashSettings = serde_json::from_value(serde_json::json!({"source":"host"})).unwrap();
|
||||
assert_eq!(
|
||||
settings
|
||||
.key(peer(), &HeaderMap::new(), Some(&uri("https://[2001:db8::1]:443/x")))
|
||||
.as_deref(),
|
||||
Some("2001:db8::1")
|
||||
);
|
||||
let mut v6 = HeaderMap::new();
|
||||
v6.insert("host", "[2001:db8::1]:8443".parse().unwrap());
|
||||
assert_eq!(settings.key(peer(), &v6, None).as_deref(), Some("2001:db8::1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_settings_are_validated() {
|
||||
let invalid = [
|
||||
serde_json::json!({"source":"header"}),
|
||||
serde_json::json!({"source":"header","name":"bad header"}),
|
||||
serde_json::json!({"source":"cookie","name":"a;b"}),
|
||||
serde_json::json!({"source":"path","name":"x"}),
|
||||
serde_json::json!({"path_depth":33}),
|
||||
serde_json::json!({"balance_factor":100}),
|
||||
serde_json::json!({"balance_factor":1001}),
|
||||
serde_json::json!({"fallback":"hash"}),
|
||||
serde_json::json!({"fallback":"ip_hash"}),
|
||||
];
|
||||
for value in invalid {
|
||||
let settings: HashSettings = serde_json::from_value(value.clone()).unwrap();
|
||||
assert!(settings.validate().is_err(), "{value} should be rejected");
|
||||
}
|
||||
assert!(serde_json::from_value::<HashSettings>(serde_json::json!({"unknown":1})).is_err());
|
||||
let ok: HashSettings =
|
||||
serde_json::from_value(serde_json::json!({"balance_factor":125,"fallback":"random"})).unwrap();
|
||||
ok.validate().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_settings_serialize_without_hash_block() {
|
||||
let value = serde_json::to_value(Settings::default()).unwrap();
|
||||
assert!(value.get("hash").is_none());
|
||||
let mut settings = Settings::default();
|
||||
settings.algorithm = Algorithm::Hash;
|
||||
settings.hash.source = HashSource::Cookie;
|
||||
settings.hash.name = Some("sid".into());
|
||||
let value = serde_json::to_value(&settings).unwrap();
|
||||
assert_eq!(value["algorithm"], "hash");
|
||||
assert_eq!(value["hash"]["source"], "cookie");
|
||||
let back: Settings = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(back.hash, settings.hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_hash_is_stable_and_spreads_keys() {
|
||||
let pool = shards(serde_json::json!({"algorithm":"hash","health_check":{"mode":"off"}}));
|
||||
let mut counts = std::collections::HashMap::<String, usize>::new();
|
||||
for n in 0..3000 {
|
||||
let path = format!("/media/{n}.mp3");
|
||||
let first = pick(&pool, &path, &HeaderMap::new());
|
||||
for _ in 0..3 {
|
||||
assert_eq!(pick(&pool, &path, &HeaderMap::new()), first);
|
||||
}
|
||||
*counts.entry(first).or_default() += 1;
|
||||
}
|
||||
assert_eq!(counts.len(), 3);
|
||||
for (member, count) in counts {
|
||||
assert!((800..=1200).contains(&count), "{member} got {count} of 3000 keys");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_member_only_moves_its_own_keys() {
|
||||
let pool = shards(serde_json::json!({"algorithm":"hash","health_check":{"mode":"off"}}));
|
||||
let paths: Vec<String> = (0..600).map(|n| format!("/f/{n}")).collect();
|
||||
let before: Vec<String> = paths.iter().map(|p| pick(&pool, p, &HeaderMap::new())).collect();
|
||||
let down = pool.members.iter().find(|m| m.definition.id == "s2").unwrap();
|
||||
down.state.set_healthy_for_test(false);
|
||||
for (path, previous) in paths.iter().zip(&before) {
|
||||
let now = pick(&pool, path, &HeaderMap::new());
|
||||
if previous == "s2" {
|
||||
assert_ne!(now, "s2");
|
||||
} else {
|
||||
assert_eq!(&now, previous, "{path} moved although its member stayed up");
|
||||
}
|
||||
}
|
||||
down.state.set_healthy_for_test(true);
|
||||
for (path, previous) in paths.iter().zip(&before) {
|
||||
assert_eq!(&pick(&pool, path, &HeaderMap::new()), previous);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weights_shift_the_share_of_keys() {
|
||||
let pool = compile(serde_json::json!({
|
||||
"listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]},
|
||||
"vhosts":[{
|
||||
"id":"w","frontend":{"hosts":["w.localhost"],"listener_ids":["http"]},
|
||||
"backends":[
|
||||
{"id":"big","url":"http://127.0.0.1:9001","allow_private":true,"weight":3},
|
||||
{"id":"small","url":"http://127.0.0.1:9002","allow_private":true,"weight":1}],
|
||||
"load_balancing":{"algorithm":"hash","health_check":{"mode":"off"}}
|
||||
}]
|
||||
}))
|
||||
.unwrap()
|
||||
.pools[0]
|
||||
.clone();
|
||||
let big = (0..4000)
|
||||
.filter(|n| pick(&pool, &format!("/k/{n}"), &HeaderMap::new()) == "big")
|
||||
.count();
|
||||
assert!((2700..=3300).contains(&big), "weight 3:1 gave {big} of 4000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_key_uses_fallback_algorithm() {
|
||||
let pool = shards(serde_json::json!({
|
||||
"algorithm":"hash","slow_start_seconds":0,
|
||||
"hash":{"source":"cookie","name":"sid","fallback":"round_robin"},
|
||||
"health_check":{"mode":"off"}
|
||||
}));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for _ in 0..6 {
|
||||
seen.insert(pick(&pool, "/", &HeaderMap::new()));
|
||||
}
|
||||
assert_eq!(seen.len(), 3, "round robin fallback should visit every member");
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("cookie", "sid=user-7".parse().unwrap());
|
||||
let first = pick(&pool, "/", &headers);
|
||||
for _ in 0..10 {
|
||||
assert_eq!(pick(&pool, "/other", &headers), first);
|
||||
}
|
||||
assert_eq!(pool.preview(peer(), &headers, None).0.as_deref(), Some(first.as_str()));
|
||||
assert!(!pool.hashes_request_uri());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_load_moves_overflow_to_the_next_member_for_the_key() {
|
||||
let pool = shards(serde_json::json!({
|
||||
"algorithm":"hash","hash":{"balance_factor":125},"health_check":{"mode":"off"}
|
||||
}));
|
||||
let path = "/hot/object.mp3";
|
||||
let owner = pool.preview(peer(), &HeaderMap::new(), Some(&uri(path))).0.unwrap();
|
||||
let mut leases = Vec::new();
|
||||
// Keep the owner busy: with 125% and 3 members its cap is soon exceeded.
|
||||
for _ in 0..4 {
|
||||
let selection = pool.select_uri(peer(), &HeaderMap::new(), Some(&uri(path)), false).unwrap();
|
||||
leases.push(selection);
|
||||
}
|
||||
let owners: std::collections::HashSet<_> = leases
|
||||
.iter()
|
||||
.map(|s| s.lease.member.definition.id.clone())
|
||||
.collect();
|
||||
assert!(owners.contains(&owner));
|
||||
assert!(owners.len() > 1, "bounded load should spill a hot key: {owners:?}");
|
||||
drop(leases);
|
||||
assert_eq!(pick(&pool, path, &HeaderMap::new()), owner);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_two_choices_only_uses_eligible_members() {
|
||||
let pool = shards(serde_json::json!({"algorithm":"random","slow_start_seconds":0,"health_check":{"mode":"off"}}));
|
||||
pool.members[0].state.set_healthy_for_test(false);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for _ in 0..200 {
|
||||
let selection = pool.select(peer(), &HeaderMap::new(), false).unwrap();
|
||||
seen.insert(selection.lease.member.definition.id.clone());
|
||||
}
|
||||
assert!(!seen.contains("s1"));
|
||||
assert_eq!(seen.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ip_hash_keeps_previous_member_mapping() {
|
||||
// Same inputs and formula as before 0.40.2: pool id | client IP | member id.
|
||||
let pool = shards(serde_json::json!({"algorithm":"ip_hash","health_check":{"mode":"off"}}));
|
||||
let expected = pool
|
||||
.members
|
||||
.iter()
|
||||
.min_by(|a, b| {
|
||||
rendezvous_score("files", "192.0.2.10", &a.definition.id, 1)
|
||||
.total_cmp(&rendezvous_score("files", "192.0.2.10", &b.definition.id, 1))
|
||||
})
|
||||
.unwrap()
|
||||
.definition
|
||||
.id
|
||||
.clone();
|
||||
let selection = pool.select(peer(), &HeaderMap::new(), false).unwrap();
|
||||
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.
|
||||
#[test]
|
||||
fn rendezvous_reference_vectors() {
|
||||
let order = |key: &str| {
|
||||
let mut ids = vec![("s1", 1u16), ("s2", 1), ("s3", 2)];
|
||||
ids.sort_by(|a, b| {
|
||||
rendezvous_score("files", key, a.0, a.1).total_cmp(&rendezvous_score("files", key, b.0, b.1))
|
||||
});
|
||||
ids.into_iter().map(|(id, _)| id).collect::<Vec<_>>().join(",")
|
||||
};
|
||||
let vectors: Vec<(String, String)> = ["/a.mp3", "/music/b.mp3", "/c", "tenant-42", "192.0.2.10"]
|
||||
.iter()
|
||||
.map(|key| (key.to_string(), order(key)))
|
||||
.collect();
|
||||
let rendered = vectors
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{k}={v}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(";");
|
||||
let expected = include_str!("../../tests/fixtures/balance_rendezvous_vectors.txt").trim();
|
||||
assert_eq!(rendered, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn location_backend_group_balances_by_path_and_shares_member_state() {
|
||||
let snapshot = compile(serde_json::json!({
|
||||
"listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]},
|
||||
"vhosts":[{
|
||||
"id":"site","frontend":{"hosts":["site.localhost"],"listener_ids":["http"]},
|
||||
"backends":[
|
||||
{"id":"app","url":"http://127.0.0.1:9000","allow_private":true},
|
||||
{"id":"mp3_1","url":"http://127.0.0.1:9011","allow_private":true,"pool_eligible":false},
|
||||
{"id":"mp3_2","url":"http://127.0.0.1:9012","allow_private":true,"pool_eligible":false},
|
||||
{"id":"mp3_3","url":"http://127.0.0.1:9013","allow_private":true,"pool_eligible":false}],
|
||||
"load_balancing":{"algorithm":"least_connections","health_check":{"mode":"off"},
|
||||
"sticky":{"mode":"cookie"}},
|
||||
"routes":[{
|
||||
"id":"mp3","path_prefix":"\\.mp3$","match_type":"regex_insensitive",
|
||||
"backend_ids":["mp3_1","mp3_2","mp3_3"],
|
||||
"load_balancing":{"algorithm":"hash","hash":{"source":"path"}}
|
||||
}]
|
||||
}]
|
||||
}))
|
||||
.unwrap();
|
||||
let vhost_pool = snapshot.pools[0].clone();
|
||||
let route = snapshot.select("site.localhost", "/music/song.MP3").expect("mp3 route");
|
||||
let pool = route.pool.clone().unwrap();
|
||||
assert_eq!(pool.route.as_deref(), Some("mp3"));
|
||||
assert_eq!(pool.members.len(), 3);
|
||||
assert!(!pool.cookie_affinity(), "location balancing replaces vhost affinity");
|
||||
assert!(pool.hashes_request_uri());
|
||||
for member in &pool.members {
|
||||
let shared = vhost_pool
|
||||
.members
|
||||
.iter()
|
||||
.find(|m| m.definition.id == member.definition.id)
|
||||
.unwrap();
|
||||
assert!(Arc::ptr_eq(&member.state, &shared.state));
|
||||
}
|
||||
let mut owners = std::collections::HashSet::new();
|
||||
for n in 0..60 {
|
||||
let path = format!("/music/{n}.mp3");
|
||||
let a = pick(&pool, &path, &HeaderMap::new());
|
||||
assert_eq!(pick(&pool, &path, &HeaderMap::new()), a);
|
||||
assert!(a.starts_with("mp3_"));
|
||||
owners.insert(a);
|
||||
}
|
||||
assert_eq!(owners.len(), 3);
|
||||
// The vhost pool itself never uses location-only backends.
|
||||
for _ in 0..10 {
|
||||
let selection = vhost_pool.select(peer(), &HeaderMap::new(), false).unwrap();
|
||||
assert_eq!(selection.lease.member.definition.id, "app");
|
||||
}
|
||||
// Main pages still go to the vhost pool.
|
||||
let main = snapshot.select("site.localhost", "/index.html").unwrap();
|
||||
assert!(Arc::ptr_eq(main.pool.as_ref().unwrap(), &vhost_pool));
|
||||
// Affinity cookies of the vhost pool are not forwarded by the location pool.
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("cookie", "RP_AFFINITY_site=abc; keep=1".parse().unwrap());
|
||||
pool.strip_affinity(&mut headers);
|
||||
assert_eq!(headers.get("cookie").unwrap(), "keep=1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn location_group_without_override_inherits_vhost_balancing() {
|
||||
let snapshot = compile(serde_json::json!({
|
||||
"listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]},
|
||||
"vhosts":[{
|
||||
"id":"site","frontend":{"hosts":["site.localhost"],"listener_ids":["http"]},
|
||||
"backends":[
|
||||
{"id":"a","url":"http://127.0.0.1:9001","allow_private":true},
|
||||
{"id":"b","url":"http://127.0.0.1:9002","allow_private":true},
|
||||
{"id":"c","url":"http://127.0.0.1:9003","allow_private":true}],
|
||||
"load_balancing":{"algorithm":"round_robin","slow_start_seconds":0,"health_check":{"mode":"off"},
|
||||
"sticky":{"mode":"cookie"}},
|
||||
"routes":[{"id":"api","path_prefix":"/api","backend_ids":["b","c"]}]
|
||||
}]
|
||||
}))
|
||||
.unwrap();
|
||||
let pool = snapshot.select("site.localhost", "/api/x").unwrap().pool.clone().unwrap();
|
||||
assert_eq!(pool.settings.algorithm, Algorithm::RoundRobin);
|
||||
assert!(pool.cookie_affinity());
|
||||
let selection = pool.select(peer(), &HeaderMap::new(), false).unwrap();
|
||||
let cookie = selection.cookie.unwrap();
|
||||
assert!(cookie.to_str().unwrap().starts_with("RP_AFFINITY_site__api="));
|
||||
// The vhost pool strips location affinity cookies before the origin.
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("cookie", "RP_AFFINITY_site__api=x; app=1".parse().unwrap());
|
||||
snapshot.pools[0].strip_affinity(&mut headers);
|
||||
assert_eq!(headers.get("cookie").unwrap(), "app=1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_location_groups_are_rejected() {
|
||||
let base = |route: serde_json::Value| {
|
||||
serde_json::json!({
|
||||
"listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]},
|
||||
"vhosts":[{
|
||||
"id":"site","frontend":{"hosts":["site.localhost"],"listener_ids":["http"]},
|
||||
"backends":[
|
||||
{"id":"a","url":"http://127.0.0.1:9001","allow_private":true},
|
||||
{"id":"b","url":"http://127.0.0.1:9002","allow_private":true}],
|
||||
"load_balancing":{"health_check":{"mode":"off"}},
|
||||
"routes":[route]
|
||||
}]
|
||||
})
|
||||
};
|
||||
for route in [
|
||||
serde_json::json!({"id":"x","path_prefix":"/x","backend_ids":["missing"]}),
|
||||
serde_json::json!({"id":"x","path_prefix":"/x","backend_ids":["a","a"]}),
|
||||
serde_json::json!({"id":"x","path_prefix":"/x","backend_id":"a","backend_ids":["b"]}),
|
||||
serde_json::json!({"id":"x","path_prefix":"/x","backend_id":"a","load_balancing":{"algorithm":"hash"}}),
|
||||
serde_json::json!({"id":"x","path_prefix":"/x","load_balancing":{"algorithm":"hash","hash":{"source":"header"}}}),
|
||||
serde_json::json!({"id":"x","path_prefix":"/x","load_balancing":{"algorithm":"hash","hash":{"balance_factor":50}}}),
|
||||
] {
|
||||
assert!(compile(base(route.clone())).is_err(), "{route} should be rejected");
|
||||
}
|
||||
assert!(compile(base(serde_json::json!({
|
||||
"id":"x","path_prefix":"/x","backend_ids":["a","b"],
|
||||
"load_balancing":{"algorithm":"hash","hash":{"source":"query","name":"id","fallback":"least_connections"}}
|
||||
})))
|
||||
.is_ok());
|
||||
}
|
||||
}
|
||||
@@ -464,6 +464,14 @@ pub struct Pool {
|
||||
cookie_name: String,
|
||||
cursor: AtomicU64,
|
||||
scheduling: Mutex<std::collections::HashMap<String, f64>>,
|
||||
/// Location backend group: members were chosen explicitly, so `pool_eligible`
|
||||
/// (which only controls membership of the vhost-wide pool) is ignored.
|
||||
explicit_members: bool,
|
||||
/// Location id for a pool derived from the vhost pool.
|
||||
pub route: Option<String>,
|
||||
/// Shared by a vhost pool and its location pools: set when any of them issues an
|
||||
/// affinity cookie, so every one of them strips those cookies.
|
||||
affinity_cookies: Arc<AtomicBool>,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct Lease {
|
||||
|
||||
@@ -29,6 +29,257 @@ pub enum Algorithm {
|
||||
LeastTraffic,
|
||||
Adaptive,
|
||||
IpHash,
|
||||
/// Consistent (rendezvous) hash of a request attribute selected by [`HashSettings`].
|
||||
Hash,
|
||||
/// Power of two random choices: two random members, the less loaded one wins.
|
||||
Random,
|
||||
}
|
||||
impl Algorithm {
|
||||
/// Algorithms usable when a hash key is missing from a request.
|
||||
pub fn valid_hash_fallback(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::RoundRobin | Self::LeastConnections | Self::LeastTraffic | Self::Adaptive | Self::Random
|
||||
)
|
||||
}
|
||||
}
|
||||
/// Request attribute used as the key of the `hash` algorithm.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum HashSource {
|
||||
/// Request path without the query string (HAProxy `balance hash path` / `balance uri`).
|
||||
#[default]
|
||||
Path,
|
||||
/// Path and query string (HAProxy `balance uri whole`).
|
||||
Uri,
|
||||
/// Request host name without the port.
|
||||
Host,
|
||||
/// Client address as seen by RustProxy (same input as `ip_hash`).
|
||||
Ip,
|
||||
/// Value of one request header (`name`).
|
||||
Header,
|
||||
/// Value of one request cookie (`name`).
|
||||
Cookie,
|
||||
/// Value of one query string parameter (`name`).
|
||||
Query,
|
||||
}
|
||||
impl HashSource {
|
||||
pub fn needs_name(self) -> bool {
|
||||
matches!(self, Self::Header | Self::Cookie | Self::Query)
|
||||
}
|
||||
}
|
||||
fn default_hash_fallback() -> Algorithm {
|
||||
Algorithm::RoundRobin
|
||||
}
|
||||
/// Settings of the `hash` algorithm. Hashing is always consistent: members are ranked
|
||||
/// with weighted rendezvous hashing, so adding, removing or ejecting a member only moves
|
||||
/// the keys that belong to that member.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct HashSettings {
|
||||
pub source: HashSource,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// Number of leading path directories to hash; 0 hashes the whole path.
|
||||
pub path_depth: u8,
|
||||
pub ignore_case: bool,
|
||||
/// Consistent hashing with bounded loads (percent of the average load per member);
|
||||
/// 0 disables the bound, otherwise 101..=1000.
|
||||
pub balance_factor: u16,
|
||||
/// Algorithm used when the request has no value for the key.
|
||||
#[serde(default = "default_hash_fallback")]
|
||||
pub fallback: Algorithm,
|
||||
}
|
||||
impl Default for HashSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
source: HashSource::Path,
|
||||
name: None,
|
||||
path_depth: 0,
|
||||
ignore_case: false,
|
||||
balance_factor: 0,
|
||||
fallback: default_hash_fallback(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl HashSettings {
|
||||
pub fn is_default(&self) -> bool {
|
||||
self == &Self::default()
|
||||
}
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if self.source.needs_name() {
|
||||
let name = self.name.as_deref().unwrap_or("");
|
||||
ensure!(
|
||||
!name.is_empty() && name.len() <= 128,
|
||||
"hash key name is required for header, cookie and query keys (1..128 characters)"
|
||||
);
|
||||
if self.source == HashSource::Header {
|
||||
ensure!(
|
||||
http::HeaderName::from_bytes(name.as_bytes()).is_ok(),
|
||||
"hash header name is not a valid HTTP header name"
|
||||
);
|
||||
} else {
|
||||
ensure!(
|
||||
name.bytes()
|
||||
.all(|b| b.is_ascii_graphic() && !matches!(b, b';' | b'=' | b'&' | b',')),
|
||||
"hash cookie/query name must be printable ASCII without ; = & or ,"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
ensure!(
|
||||
self.name.as_deref().is_none_or(str::is_empty),
|
||||
"hash key name is only used with header, cookie and query keys"
|
||||
);
|
||||
}
|
||||
ensure!(self.path_depth <= 32, "hash path_depth must be 0..32");
|
||||
ensure!(
|
||||
self.balance_factor == 0 || (101..=1000).contains(&self.balance_factor),
|
||||
"hash balance_factor must be 0 (off) or 101..1000"
|
||||
);
|
||||
ensure!(
|
||||
self.fallback.valid_hash_fallback(),
|
||||
"hash fallback must be round_robin, least_connections, least_traffic, adaptive or random"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
/// Extracts the hash key for a request; `None` when the request has no value.
|
||||
pub fn key(&self, peer: IpAddr, headers: &HeaderMap, uri: Option<&http::Uri>) -> Option<String> {
|
||||
let raw: String = match self.source {
|
||||
HashSource::Ip => return Some(crate::vhost::canonical_ip(peer).to_string()),
|
||||
HashSource::Path => {
|
||||
let path = uri.map(http::Uri::path).filter(|p| !p.is_empty())?;
|
||||
limit_path_depth(path, self.path_depth).to_owned()
|
||||
}
|
||||
HashSource::Uri => {
|
||||
let uri = uri?;
|
||||
let path = limit_path_depth(uri.path(), self.path_depth);
|
||||
match uri.query() {
|
||||
Some(query) => format!("{path}?{query}"),
|
||||
None => path.to_owned(),
|
||||
}
|
||||
}
|
||||
HashSource::Host => {
|
||||
let host = uri
|
||||
.and_then(http::Uri::host)
|
||||
.map(|h| h.trim_start_matches('[').trim_end_matches(']').to_owned())
|
||||
.or_else(|| {
|
||||
headers
|
||||
.get(http::header::HOST)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(|v| strip_port(v).to_owned())
|
||||
})?;
|
||||
let host = host.trim_end_matches('.').to_ascii_lowercase();
|
||||
if host.is_empty() {
|
||||
return None;
|
||||
}
|
||||
return Some(host);
|
||||
}
|
||||
HashSource::Header => {
|
||||
let name = self.name.as_deref()?;
|
||||
let values: Vec<&str> = headers
|
||||
.get_all(name)
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.map(str::trim)
|
||||
.collect();
|
||||
let joined = values.join(",");
|
||||
if joined.is_empty() {
|
||||
return None;
|
||||
}
|
||||
joined
|
||||
}
|
||||
HashSource::Cookie => {
|
||||
let name = self.name.as_deref()?;
|
||||
headers
|
||||
.get_all(http::header::COOKIE)
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.flat_map(|v| v.split(';'))
|
||||
.filter_map(|pair| pair.trim().split_once('='))
|
||||
.find(|(n, _)| *n == name)
|
||||
.map(|(_, v)| v.trim().to_owned())
|
||||
.filter(|v| !v.is_empty())?
|
||||
}
|
||||
HashSource::Query => {
|
||||
let name = self.name.as_deref()?;
|
||||
uri?.query()?
|
||||
.split('&')
|
||||
.map(|pair| pair.split_once('=').unwrap_or((pair, "")))
|
||||
.find(|(n, _)| *n == name)
|
||||
.map(|(_, v)| v.to_owned())
|
||||
.filter(|v| !v.is_empty())?
|
||||
}
|
||||
};
|
||||
Some(if self.ignore_case {
|
||||
raw.to_lowercase()
|
||||
} else {
|
||||
raw
|
||||
})
|
||||
}
|
||||
}
|
||||
fn strip_port(host: &str) -> &str {
|
||||
if let Some(rest) = host.strip_prefix('[') {
|
||||
return rest.split_once(']').map_or(host, |(inner, _)| inner);
|
||||
}
|
||||
match host.rsplit_once(':') {
|
||||
Some((name, port)) if !name.contains(':') && port.bytes().all(|b| b.is_ascii_digit()) => name,
|
||||
_ => host,
|
||||
}
|
||||
}
|
||||
/// Keeps the first `depth` directories of a path (`/a/b/c.mp3`, depth 2 → `/a/b`).
|
||||
fn limit_path_depth(path: &str, depth: u8) -> &str {
|
||||
if depth == 0 {
|
||||
return path;
|
||||
}
|
||||
let mut seen = 0u8;
|
||||
for (index, byte) in path.bytes().enumerate() {
|
||||
if byte == b'/' && index > 0 {
|
||||
seen += 1;
|
||||
if seen == depth {
|
||||
return &path[..index];
|
||||
}
|
||||
}
|
||||
}
|
||||
path
|
||||
}
|
||||
/// Rendezvous score of one member for a key; the lowest score wins.
|
||||
pub(crate) fn rendezvous_score(pool_id: &str, key: &str, member_id: &str, weight: u16) -> f64 {
|
||||
let mut hash = Sha256::new();
|
||||
hash.update(pool_id.as_bytes());
|
||||
hash.update(b"|");
|
||||
hash.update(key.as_bytes());
|
||||
hash.update(b"|");
|
||||
hash.update(member_id.as_bytes());
|
||||
let digest = hash.finalize();
|
||||
let n = u64::from_be_bytes([
|
||||
digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7],
|
||||
]);
|
||||
let unit = (n as f64 + 1.0) / (u64::MAX as f64 + 2.0);
|
||||
-unit.max(f64::MIN_POSITIVE).ln() / f64::from(weight.max(1))
|
||||
}
|
||||
/// Per-location balancing override: the location uses its own algorithm over its
|
||||
/// backend group while sharing health state with the vhost pool.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct RouteBalancing {
|
||||
pub algorithm: Algorithm,
|
||||
#[serde(skip_serializing_if = "HashSettings::is_default")]
|
||||
pub hash: HashSettings,
|
||||
pub sticky: StickyMode,
|
||||
}
|
||||
impl Default for RouteBalancing {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
algorithm: Algorithm::Hash,
|
||||
hash: HashSettings::default(),
|
||||
sticky: StickyMode::Off,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl RouteBalancing {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
self.hash.validate()
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -197,6 +448,8 @@ pub struct Settings {
|
||||
pub retry: RetryPolicy,
|
||||
pub sticky: Sticky,
|
||||
pub slow_start_seconds: u64,
|
||||
#[serde(skip_serializing_if = "HashSettings::is_default")]
|
||||
pub hash: HashSettings,
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
@@ -208,6 +461,7 @@ impl Default for Settings {
|
||||
retry: RetryPolicy::default(),
|
||||
sticky: Sticky::default(),
|
||||
slow_start_seconds: 10,
|
||||
hash: HashSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -233,6 +487,7 @@ impl Settings {
|
||||
passive
|
||||
}
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
self.hash.validate()?;
|
||||
let h = &self.health_check;
|
||||
let k = &self.keepalive;
|
||||
ensure!(
|
||||
|
||||
+281
-101
@@ -10,6 +10,7 @@ impl Pool {
|
||||
"invalid compiled pool"
|
||||
);
|
||||
let fingerprint = Sha256::digest(serde_json::to_vec(&(definitions, &settings))?).to_vec();
|
||||
let settings_cookie = settings.sticky.mode == StickyMode::Cookie;
|
||||
let cookie_name = settings
|
||||
.sticky
|
||||
.cookie_name
|
||||
@@ -45,8 +46,85 @@ impl Pool {
|
||||
cookie_name,
|
||||
cursor: AtomicU64::new(0),
|
||||
scheduling: Mutex::new(std::collections::HashMap::new()),
|
||||
explicit_members: false,
|
||||
route: None,
|
||||
affinity_cookies: Arc::new(AtomicBool::new(settings_cookie)),
|
||||
})
|
||||
}
|
||||
/// Builds the pool of one location from this (vhost) pool. Members are shared, so
|
||||
/// health checks, passive ejection, concurrency limits and statistics stay common;
|
||||
/// only the selection (members, algorithm, hash key, affinity) is location-specific.
|
||||
/// `member_ids` empty means every member of the vhost pool.
|
||||
pub fn derive(
|
||||
&self,
|
||||
route_id: &str,
|
||||
member_ids: &[String],
|
||||
balancing: Option<&RouteBalancing>,
|
||||
) -> Result<Self> {
|
||||
let members: Vec<Arc<Member>> = if member_ids.is_empty() {
|
||||
self.members.clone()
|
||||
} else {
|
||||
member_ids
|
||||
.iter()
|
||||
.map(|id| {
|
||||
self.members
|
||||
.iter()
|
||||
.find(|m| &m.definition.id == id)
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow::anyhow!("location {route_id} references unknown backend {id}"))
|
||||
})
|
||||
.collect::<Result<_>>()?
|
||||
};
|
||||
ensure!(!members.is_empty(), "location {route_id} has an empty backend group");
|
||||
let mut settings = self.settings.clone();
|
||||
if let Some(balancing) = balancing {
|
||||
balancing.validate()?;
|
||||
settings.algorithm = balancing.algorithm;
|
||||
settings.hash = balancing.hash.clone();
|
||||
settings.sticky.mode = balancing.sticky;
|
||||
}
|
||||
if settings.sticky.mode == StickyMode::Cookie {
|
||||
self.affinity_cookies.store(true, Ordering::Relaxed);
|
||||
}
|
||||
let fingerprint = Sha256::digest(serde_json::to_vec(&(
|
||||
&self.fingerprint,
|
||||
route_id,
|
||||
member_ids,
|
||||
balancing,
|
||||
))?)
|
||||
.to_vec();
|
||||
Ok(Self {
|
||||
id: self.id.clone(),
|
||||
settings,
|
||||
members,
|
||||
fingerprint,
|
||||
cookie_name: format!("{}__{}", self.cookie_name, route_id),
|
||||
cursor: AtomicU64::new(0),
|
||||
scheduling: Mutex::new(std::collections::HashMap::new()),
|
||||
explicit_members: !member_ids.is_empty(),
|
||||
route: Some(route_id.to_owned()),
|
||||
affinity_cookies: self.affinity_cookies.clone(),
|
||||
})
|
||||
}
|
||||
fn affinity_cookie_name(&self, name: &str) -> bool {
|
||||
// A location pool strips the vhost cookie too, and the vhost pool strips the
|
||||
// cookies of its locations (`<vhost cookie>__<location>`), so affinity tokens
|
||||
// never reach an origin.
|
||||
let base = self
|
||||
.route
|
||||
.as_ref()
|
||||
.and_then(|route| self.cookie_name.strip_suffix(&format!("__{route}")))
|
||||
.unwrap_or(&self.cookie_name);
|
||||
name == self.cookie_name
|
||||
|| name == base
|
||||
|| name.strip_prefix(base).is_some_and(|rest| rest.starts_with("__"))
|
||||
}
|
||||
fn member_selectable(&self, m: &Member) -> bool {
|
||||
(self.explicit_members || m.definition.pool_eligible)
|
||||
&& m.definition.enabled
|
||||
&& !m.definition.drain
|
||||
&& m.state.healthy()
|
||||
}
|
||||
pub fn reuse_observations(&mut self, previous: &Pool) {
|
||||
for member in &mut self.members {
|
||||
let Some(old) = previous
|
||||
@@ -92,10 +170,7 @@ impl Pool {
|
||||
.members
|
||||
.iter()
|
||||
.filter(|m| {
|
||||
m.definition.pool_eligible
|
||||
&& m.definition.enabled
|
||||
&& !m.definition.drain
|
||||
&& m.state.healthy()
|
||||
self.member_selectable(m)
|
||||
&& m.state.has_capacity(m.definition.max_concurrent_requests)
|
||||
&& !excluded.iter().any(|id| id == &m.definition.id)
|
||||
})
|
||||
@@ -108,6 +183,15 @@ impl Pool {
|
||||
pub fn ready(&self) -> bool {
|
||||
!self.eligible_healthy_excluding(&[]).is_empty()
|
||||
}
|
||||
/// 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
|
||||
&& self.settings.sticky.mode != StickyMode::IpHash
|
||||
&& matches!(
|
||||
self.settings.hash.source,
|
||||
HashSource::Path | HashSource::Uri | HashSource::Host | HashSource::Query
|
||||
)
|
||||
}
|
||||
pub fn cookie_affinity(&self) -> bool {
|
||||
self.settings.sticky.mode == StickyMode::Cookie
|
||||
}
|
||||
@@ -128,7 +212,7 @@ impl Pool {
|
||||
}
|
||||
}
|
||||
pub fn strip_affinity_response(&self, headers: &mut HeaderMap) {
|
||||
if !self.cookie_affinity() {
|
||||
if !self.cookie_affinity() && !self.affinity_cookies.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let retained: Vec<_> = headers
|
||||
@@ -139,7 +223,7 @@ impl Pool {
|
||||
.to_str()
|
||||
.ok()
|
||||
.and_then(|v| v.split_once('='))
|
||||
.is_none_or(|(name, _)| name.trim() != self.cookie_name)
|
||||
.is_none_or(|(name, _)| !self.affinity_cookie_name(name.trim()))
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
@@ -149,7 +233,7 @@ impl Pool {
|
||||
}
|
||||
}
|
||||
pub fn strip_affinity(&self, headers: &mut HeaderMap) {
|
||||
if !self.cookie_affinity() {
|
||||
if !self.cookie_affinity() && !self.affinity_cookies.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let values: Vec<HeaderValue> = headers
|
||||
@@ -164,7 +248,7 @@ impl Pool {
|
||||
.filter(|part| {
|
||||
part.trim()
|
||||
.split_once('=')
|
||||
.is_none_or(|(n, _)| n != self.cookie_name)
|
||||
.is_none_or(|(n, _)| !self.affinity_cookie_name(n))
|
||||
})
|
||||
.map(str::trim)
|
||||
.collect::<Vec<_>>()
|
||||
@@ -208,15 +292,13 @@ impl Pool {
|
||||
&self,
|
||||
peer: IpAddr,
|
||||
headers: &HeaderMap,
|
||||
uri: Option<&http::Uri>,
|
||||
tls: bool,
|
||||
excluded: &[String],
|
||||
) -> Option<Selection> {
|
||||
if self.members.len() == 1 && !self.cookie_affinity() {
|
||||
let member = &self.members[0];
|
||||
if !member.definition.pool_eligible
|
||||
|| !member.definition.enabled
|
||||
|| member.definition.drain
|
||||
|| !member.state.healthy()
|
||||
if !self.member_selectable(member)
|
||||
|| excluded.iter().any(|id| id == &member.definition.id)
|
||||
|| !member
|
||||
.state
|
||||
@@ -243,7 +325,7 @@ impl Pool {
|
||||
let matched = existing.and_then(|token| {
|
||||
self.members.iter().find(|m| {
|
||||
m.token == token
|
||||
&& m.definition.pool_eligible
|
||||
&& (self.explicit_members || m.definition.pool_eligible)
|
||||
&& m.definition.enabled
|
||||
&& m.state.healthy()
|
||||
&& m.state.has_capacity(m.definition.max_concurrent_requests)
|
||||
@@ -253,94 +335,9 @@ impl Pool {
|
||||
if members.is_empty() && matched.is_none() {
|
||||
return None;
|
||||
}
|
||||
let cursor = self.cursor.fetch_add(1, Ordering::Relaxed);
|
||||
let selected = if let Some(member) = matched {
|
||||
member
|
||||
} else {
|
||||
if self.settings.algorithm == Algorithm::RoundRobin
|
||||
&& self.settings.sticky.mode != StickyMode::IpHash
|
||||
{
|
||||
let mut scheduling = lock(&self.scheduling);
|
||||
let mut chosen = members[0];
|
||||
let mut best = f64::NEG_INFINITY;
|
||||
let mut total = 0.0;
|
||||
for member in &members {
|
||||
let weight = member
|
||||
.state
|
||||
.weight(member.definition.weight, self.settings.slow_start_seconds);
|
||||
let current =
|
||||
if let Some(current) = scheduling.get_mut(member.definition.id.as_str()) {
|
||||
current
|
||||
} else {
|
||||
scheduling
|
||||
.entry(member.definition.id.clone())
|
||||
.or_insert(0.0)
|
||||
};
|
||||
*current += weight;
|
||||
total += weight;
|
||||
if *current > best {
|
||||
best = *current;
|
||||
chosen = *member;
|
||||
}
|
||||
}
|
||||
if let Some(current) = scheduling.get_mut(&chosen.definition.id) {
|
||||
*current -= total;
|
||||
}
|
||||
chosen
|
||||
} else {
|
||||
let mut chosen = members[(cursor as usize) % members.len()];
|
||||
let mut best = f64::INFINITY;
|
||||
let algorithm = if self.settings.sticky.mode == StickyMode::IpHash {
|
||||
Algorithm::IpHash
|
||||
} else {
|
||||
self.settings.algorithm
|
||||
};
|
||||
let hash_ip = (algorithm == Algorithm::IpHash)
|
||||
.then(|| crate::vhost::canonical_ip(peer).to_string());
|
||||
for offset in 0..members.len() {
|
||||
let index = ((cursor as usize) % members.len() + offset) % members.len();
|
||||
let member = members[index];
|
||||
let active = member.state.active.load(Ordering::Relaxed) as f64;
|
||||
let score = match algorithm {
|
||||
Algorithm::IpHash => {
|
||||
let mut hash = Sha256::new();
|
||||
hash.update(self.id.as_bytes());
|
||||
hash.update(b"|");
|
||||
hash.update(hash_ip.as_deref().expect("hash address").as_bytes());
|
||||
hash.update(b"|");
|
||||
hash.update(member.definition.id.as_bytes());
|
||||
let digest = hash.finalize();
|
||||
let n = u64::from_be_bytes([
|
||||
digest[0], digest[1], digest[2], digest[3], digest[4], digest[5],
|
||||
digest[6], digest[7],
|
||||
]);
|
||||
let unit = (n as f64 + 1.0) / (u64::MAX as f64 + 2.0);
|
||||
-unit.max(f64::MIN_POSITIVE).ln() / member.definition.weight as f64
|
||||
}
|
||||
_ => {
|
||||
let weight = member
|
||||
.state
|
||||
.weight(member.definition.weight, self.settings.slow_start_seconds);
|
||||
match algorithm {
|
||||
Algorithm::LeastTraffic => {
|
||||
(member.state.traffic_rate() + (active + 1.0) * 1024.0) / weight
|
||||
}
|
||||
Algorithm::Adaptive => {
|
||||
((active + 1.0) * member.state.latency()
|
||||
+ member.state.traffic_rate() / 16_384.0)
|
||||
/ weight
|
||||
}
|
||||
_ => (active + 1.0) / weight,
|
||||
}
|
||||
}
|
||||
};
|
||||
if score < best {
|
||||
best = score;
|
||||
chosen = member;
|
||||
}
|
||||
}
|
||||
chosen
|
||||
}
|
||||
let selected = match matched {
|
||||
Some(member) => member,
|
||||
None => self.choose(&members, peer, headers, uri)?,
|
||||
};
|
||||
if !selected
|
||||
.state
|
||||
@@ -371,4 +368,187 @@ impl Pool {
|
||||
cookie,
|
||||
})
|
||||
}
|
||||
/// Effective algorithm and hash key for a request. `ip_hash` affinity overrides the
|
||||
/// algorithm; a `hash` request without a key value uses the configured fallback.
|
||||
fn plan(
|
||||
&self,
|
||||
peer: IpAddr,
|
||||
headers: &HeaderMap,
|
||||
uri: Option<&http::Uri>,
|
||||
) -> (Algorithm, Option<String>) {
|
||||
let algorithm = if self.settings.sticky.mode == StickyMode::IpHash {
|
||||
Algorithm::IpHash
|
||||
} else {
|
||||
self.settings.algorithm
|
||||
};
|
||||
match algorithm {
|
||||
Algorithm::IpHash => (
|
||||
Algorithm::IpHash,
|
||||
Some(crate::vhost::canonical_ip(peer).to_string()),
|
||||
),
|
||||
Algorithm::Hash => match self.settings.hash.key(peer, headers, uri) {
|
||||
Some(key) => (Algorithm::Hash, Some(key)),
|
||||
None => (self.settings.hash.fallback, None),
|
||||
},
|
||||
other => (other, None),
|
||||
}
|
||||
}
|
||||
/// Members ordered by rendezvous score for `key` (best first).
|
||||
fn rendezvous_order<'a>(&self, members: &[&'a Arc<Member>], key: &str) -> Vec<&'a Arc<Member>> {
|
||||
let mut ranked: Vec<(f64, &Arc<Member>)> = members
|
||||
.iter()
|
||||
.map(|m| {
|
||||
(
|
||||
rendezvous_score(&self.id, key, &m.definition.id, m.definition.weight),
|
||||
*m,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
ranked.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
ranked.into_iter().map(|(_, m)| m).collect()
|
||||
}
|
||||
fn choose<'a>(
|
||||
&self,
|
||||
members: &[&'a Arc<Member>],
|
||||
peer: IpAddr,
|
||||
headers: &HeaderMap,
|
||||
uri: Option<&http::Uri>,
|
||||
) -> Option<&'a Arc<Member>> {
|
||||
let (algorithm, key) = self.plan(peer, headers, uri);
|
||||
let cursor = self.cursor.fetch_add(1, Ordering::Relaxed);
|
||||
match algorithm {
|
||||
Algorithm::IpHash => {
|
||||
let ordered = self.rendezvous_order(members, key.as_deref()?);
|
||||
ordered.first().copied()
|
||||
}
|
||||
Algorithm::Hash => {
|
||||
let ordered = self.rendezvous_order(members, key.as_deref()?);
|
||||
let factor = self.settings.hash.balance_factor;
|
||||
if factor == 0 || ordered.len() < 2 {
|
||||
return ordered.first().copied();
|
||||
}
|
||||
// Consistent hashing with bounded loads: a member may take a new request
|
||||
// only while its in-flight count stays within `factor`% of its weighted
|
||||
// share of the pool load; otherwise the next member in the key's
|
||||
// rendezvous order is used, so overflow stays deterministic per key.
|
||||
let total_active: u64 = members
|
||||
.iter()
|
||||
.map(|m| m.state.active.load(Ordering::Relaxed))
|
||||
.sum();
|
||||
let total_weight: f64 = members
|
||||
.iter()
|
||||
.map(|m| f64::from(m.definition.weight.max(1)))
|
||||
.sum();
|
||||
let load = (total_active + 1) as f64 * f64::from(factor) / 100.0;
|
||||
ordered
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|m| {
|
||||
let share = f64::from(m.definition.weight.max(1)) / total_weight;
|
||||
let cap = (load * share).ceil().max(1.0);
|
||||
(m.state.active.load(Ordering::Relaxed) + 1) as f64 <= cap
|
||||
})
|
||||
.or_else(|| ordered.first().copied())
|
||||
}
|
||||
Algorithm::RoundRobin => Some(self.smooth_round_robin(members)),
|
||||
Algorithm::Random => {
|
||||
let len = members.len();
|
||||
if len == 1 {
|
||||
return Some(members[0]);
|
||||
}
|
||||
let mut rng = rand::rng();
|
||||
let first = rng.random_range(0..len);
|
||||
let mut second = rng.random_range(0..len - 1);
|
||||
if second >= first {
|
||||
second += 1;
|
||||
}
|
||||
let score = |m: &Arc<Member>| {
|
||||
let weight = m
|
||||
.state
|
||||
.weight(m.definition.weight, self.settings.slow_start_seconds);
|
||||
(m.state.active.load(Ordering::Relaxed) as f64 + 1.0) / weight
|
||||
};
|
||||
let (a, b) = (members[first], members[second]);
|
||||
Some(if score(b) < score(a) { b } else { a })
|
||||
}
|
||||
Algorithm::LeastConnections | Algorithm::LeastTraffic | Algorithm::Adaptive => {
|
||||
let mut chosen = members[(cursor as usize) % members.len()];
|
||||
let mut best = f64::INFINITY;
|
||||
for offset in 0..members.len() {
|
||||
let index = ((cursor as usize) % members.len() + offset) % members.len();
|
||||
let member = members[index];
|
||||
let active = member.state.active.load(Ordering::Relaxed) as f64;
|
||||
let weight = member
|
||||
.state
|
||||
.weight(member.definition.weight, self.settings.slow_start_seconds);
|
||||
let score = match algorithm {
|
||||
Algorithm::LeastTraffic => {
|
||||
(member.state.traffic_rate() + (active + 1.0) * 1024.0) / weight
|
||||
}
|
||||
Algorithm::Adaptive => {
|
||||
((active + 1.0) * member.state.latency()
|
||||
+ member.state.traffic_rate() / 16_384.0)
|
||||
/ weight
|
||||
}
|
||||
_ => (active + 1.0) / weight,
|
||||
};
|
||||
if score < best {
|
||||
best = score;
|
||||
chosen = member;
|
||||
}
|
||||
}
|
||||
Some(chosen)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn smooth_round_robin<'a>(&self, members: &[&'a Arc<Member>]) -> &'a Arc<Member> {
|
||||
let mut scheduling = lock(&self.scheduling);
|
||||
let mut chosen = members[0];
|
||||
let mut best = f64::NEG_INFINITY;
|
||||
let mut total = 0.0;
|
||||
for member in members {
|
||||
let weight = member
|
||||
.state
|
||||
.weight(member.definition.weight, self.settings.slow_start_seconds);
|
||||
let current = if let Some(current) = scheduling.get_mut(member.definition.id.as_str()) {
|
||||
current
|
||||
} else {
|
||||
scheduling
|
||||
.entry(member.definition.id.clone())
|
||||
.or_insert(0.0)
|
||||
};
|
||||
*current += weight;
|
||||
total += weight;
|
||||
if *current > best {
|
||||
best = *current;
|
||||
chosen = *member;
|
||||
}
|
||||
}
|
||||
if let Some(current) = scheduling.get_mut(&chosen.definition.id) {
|
||||
*current -= total;
|
||||
}
|
||||
chosen
|
||||
}
|
||||
/// Which member would serve a request right now, without taking a lease. Used by
|
||||
/// the panel and diagnostics; returns the member id and the hash key (if any).
|
||||
pub fn preview(
|
||||
&self,
|
||||
peer: IpAddr,
|
||||
headers: &HeaderMap,
|
||||
uri: Option<&http::Uri>,
|
||||
) -> (Option<String>, Option<String>) {
|
||||
let members = self.candidates_excluding(&[]);
|
||||
if members.is_empty() {
|
||||
return (None, None);
|
||||
}
|
||||
let (algorithm, key) = self.plan(peer, headers, uri);
|
||||
let member = match (&algorithm, &key) {
|
||||
(Algorithm::Hash | Algorithm::IpHash, Some(key)) => self
|
||||
.rendezvous_order(&members, key)
|
||||
.first()
|
||||
.map(|m| m.definition.id.clone()),
|
||||
_ => None,
|
||||
};
|
||||
(member, key)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,15 @@
|
||||
impl Pool {
|
||||
pub fn select(&self, peer: IpAddr, headers: &HeaderMap, tls: bool) -> Option<Selection> {
|
||||
self.select_excluding(peer, headers, tls, &[])
|
||||
self.select_excluding(peer, headers, None, tls, &[])
|
||||
}
|
||||
pub fn select_uri(
|
||||
&self,
|
||||
peer: IpAddr,
|
||||
headers: &HeaderMap,
|
||||
uri: Option<&http::Uri>,
|
||||
tls: bool,
|
||||
) -> Option<Selection> {
|
||||
self.select_excluding(peer, headers, uri, tls, &[])
|
||||
}
|
||||
pub fn select_retry(
|
||||
&self,
|
||||
@@ -9,17 +18,14 @@ impl Pool {
|
||||
tls: bool,
|
||||
excluded: &[String],
|
||||
) -> Option<Selection> {
|
||||
self.select_excluding(peer, headers, tls, excluded)
|
||||
self.select_excluding(peer, headers, None, tls, excluded)
|
||||
}
|
||||
fn eligible_healthy_excluding(&self, excluded: &[String]) -> Vec<&Arc<Member>> {
|
||||
let all: Vec<_> = self
|
||||
.members
|
||||
.iter()
|
||||
.filter(|m| {
|
||||
m.definition.pool_eligible
|
||||
&& m.definition.enabled
|
||||
&& !m.definition.drain
|
||||
&& m.state.healthy()
|
||||
self.member_selectable(m)
|
||||
&& !excluded.iter().any(|id| id == &m.definition.id)
|
||||
})
|
||||
.collect();
|
||||
@@ -65,7 +71,17 @@ impl Pool {
|
||||
headers: &HeaderMap,
|
||||
tls: bool,
|
||||
) -> Result<Selection, SelectionFailure> {
|
||||
self.select_retry_wait(peer, headers, tls, &[]).await
|
||||
self.select_retry_wait_uri(peer, headers, None, tls, &[]).await
|
||||
}
|
||||
/// Like [`Pool::select_wait`], with the request URI for path/URI/host/query hashing.
|
||||
pub async fn select_wait_uri(
|
||||
&self,
|
||||
peer: IpAddr,
|
||||
headers: &HeaderMap,
|
||||
uri: Option<&http::Uri>,
|
||||
tls: bool,
|
||||
) -> Result<Selection, SelectionFailure> {
|
||||
self.select_retry_wait_uri(peer, headers, uri, tls, &[]).await
|
||||
}
|
||||
pub async fn select_member_wait(&self, id: &str) -> Result<Selection, SelectionFailure> {
|
||||
let Some(member) = self.members.iter().find(|m| {
|
||||
@@ -108,7 +124,18 @@ impl Pool {
|
||||
tls: bool,
|
||||
excluded: &[String],
|
||||
) -> Result<Selection, SelectionFailure> {
|
||||
if let Some(selection) = self.select_retry(peer, headers, tls, excluded) {
|
||||
self.select_retry_wait_uri(peer, headers, None, tls, excluded)
|
||||
.await
|
||||
}
|
||||
pub async fn select_retry_wait_uri(
|
||||
&self,
|
||||
peer: IpAddr,
|
||||
headers: &HeaderMap,
|
||||
uri: Option<&http::Uri>,
|
||||
tls: bool,
|
||||
excluded: &[String],
|
||||
) -> Result<Selection, SelectionFailure> {
|
||||
if let Some(selection) = self.select_excluding(peer, headers, uri, tls, excluded) {
|
||||
return Ok(selection);
|
||||
}
|
||||
let Some(wait_ms) = self.capacity_wait_ms(excluded) else {
|
||||
@@ -119,7 +146,7 @@ impl Pool {
|
||||
if self.eligible_healthy_excluding(excluded).is_empty() {
|
||||
return Err(SelectionFailure::Unavailable);
|
||||
}
|
||||
if let Some(selection) = self.select_retry(peer, headers, tls, excluded) {
|
||||
if let Some(selection) = self.select_excluding(peer, headers, uri, tls, excluded) {
|
||||
return Ok(selection);
|
||||
}
|
||||
if wait_ms == 0 || started.elapsed() >= Duration::from_millis(wait_ms) {
|
||||
|
||||
@@ -12,3 +12,5 @@ include!("config/tests.rs");
|
||||
include!("config/route_policy_tests.rs");
|
||||
#[cfg(test)]
|
||||
include!("config/transport_tests.rs");
|
||||
#[cfg(test)]
|
||||
include!("config/routing_conditions_tests.rs");
|
||||
@@ -244,6 +244,8 @@ pub struct CompiledLocationRedirect {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CompiledRoute {
|
||||
/// Request conditions besides the path (all must hold); `None` for plain locations.
|
||||
pub conditions: Option<Arc<crate::vhost::CompiledConditions>>,
|
||||
pub backend_id: Option<String>,
|
||||
pub bindings: Vec<crate::vhost::Listener>,
|
||||
pub frontend: Option<Arc<CompiledFrontend>>,
|
||||
@@ -272,6 +274,11 @@ pub struct CompiledRoute {
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct CompiledFrontend {
|
||||
/// Some enabled location has request conditions: the route is selected again
|
||||
/// with the final client address (and country) before forwarding.
|
||||
pub conditional_routes: bool,
|
||||
/// Some location condition tests the client country.
|
||||
pub route_conditions_country: bool,
|
||||
pub websockets: bool,
|
||||
pub websocket_legacy_support: bool,
|
||||
pub websocket_rfc8441: bool,
|
||||
|
||||
+60
-7
@@ -235,6 +235,17 @@ fn compile_routing(
|
||||
.map(|entry| (entry.acl.clone(), entry.countries.clone()))
|
||||
.unwrap_or_else(|| (None, crate::rate_limit::CountryAccess::default()));
|
||||
let frontend = Arc::new(CompiledFrontend {
|
||||
conditional_routes: host
|
||||
.routes
|
||||
.iter()
|
||||
.any(|route| route.enabled && !route.conditions.is_empty()),
|
||||
route_conditions_country: host.routes.iter().any(|route| {
|
||||
route.enabled
|
||||
&& route
|
||||
.conditions
|
||||
.iter()
|
||||
.any(|c| c.source == crate::vhost::ConditionSource::Country)
|
||||
}),
|
||||
metrics,
|
||||
websockets: host.websockets,
|
||||
websocket_legacy_support: host.websocket_legacy_support,
|
||||
@@ -315,6 +326,7 @@ fn compile_routing(
|
||||
),
|
||||
};
|
||||
let fallback = Arc::new(CompiledRoute {
|
||||
conditions: None,
|
||||
backend_id: None,
|
||||
bindings: frontend.bindings.clone(),
|
||||
frontend: Some(frontend.clone()),
|
||||
@@ -395,13 +407,35 @@ fn compile_routing(
|
||||
normalize_prefix(&mut route.path_prefix)?;
|
||||
None
|
||||
}
|
||||
crate::vhost::PathMatch::Any => {
|
||||
route.path_prefix = "/".into();
|
||||
None
|
||||
}
|
||||
};
|
||||
if !route.internal {
|
||||
let route_conditions = crate::vhost::CompiledConditions::compile(&route.conditions)
|
||||
.with_context(|| format!("vhost {} location {}", host.id, route.id))?
|
||||
.map(Arc::new);
|
||||
// Locations with conditions may share a path: the first whose conditions
|
||||
// hold is used, the others are skipped.
|
||||
if !route.internal && route.conditions.is_empty() {
|
||||
ensure!(
|
||||
path_bindings.insert((route.match_type, route.path_prefix.clone())),
|
||||
"location {}: another location already uses the same path and match type",
|
||||
route.id
|
||||
);
|
||||
} else if !route.internal
|
||||
&& matches!(
|
||||
route.match_type,
|
||||
crate::vhost::PathMatch::Regex | crate::vhost::PathMatch::RegexInsensitive
|
||||
)
|
||||
{
|
||||
// Regular expressions are tried in list order, so a conditional copy of an
|
||||
// earlier unconditional pattern could never be reached.
|
||||
ensure!(
|
||||
!path_bindings.contains(&(route.match_type, route.path_prefix.clone())),
|
||||
"location {}: an earlier location without conditions already uses this regular expression, so this one would never match; move it above that location",
|
||||
route.id
|
||||
);
|
||||
}
|
||||
validate_route_rewrite(route, path_regex.as_ref())?;
|
||||
validate_location_response(route.response.as_ref())?;
|
||||
@@ -443,6 +477,22 @@ fn compile_routing(
|
||||
route.id
|
||||
)
|
||||
})?;
|
||||
let pool = if route.backend_ids.is_empty()
|
||||
&& route.load_balancing.is_none()
|
||||
{
|
||||
pool.clone()
|
||||
} else {
|
||||
Arc::new(
|
||||
pool.derive(
|
||||
&route.id,
|
||||
&route.backend_ids,
|
||||
route.load_balancing.as_ref(),
|
||||
)
|
||||
.with_context(|| {
|
||||
format!("vhost {} location {}", host.id, route.id)
|
||||
})?,
|
||||
)
|
||||
};
|
||||
let backend = if let Some(id) = route.backend_id.as_deref() {
|
||||
pool.members
|
||||
.iter()
|
||||
@@ -452,11 +502,7 @@ fn compile_routing(
|
||||
} else {
|
||||
pool.members[0].backend.clone()
|
||||
};
|
||||
(
|
||||
CompiledSource::ReverseProxy,
|
||||
Some(pool.clone()),
|
||||
Some(backend),
|
||||
)
|
||||
(CompiledSource::ReverseProxy, Some(pool), Some(backend))
|
||||
}
|
||||
crate::vhost::Source::WebServer { web_service_id } => (
|
||||
CompiledSource::WebServer(web_services[web_service_id].clone()),
|
||||
@@ -466,11 +512,18 @@ fn compile_routing(
|
||||
}
|
||||
};
|
||||
let compiled = Arc::new(CompiledRoute {
|
||||
conditions: route_conditions,
|
||||
backend_id: route.backend_id.clone(),
|
||||
bindings: frontend.bindings.clone(),
|
||||
frontend: Some(frontend.clone()),
|
||||
pool: route_pool,
|
||||
cache: route.cache,
|
||||
// Responses of a conditional location depend on request attributes
|
||||
// outside the cache key, so they are never cached.
|
||||
cache: if route.conditions.is_empty() {
|
||||
route.cache
|
||||
} else {
|
||||
Some(false)
|
||||
},
|
||||
name: route.id.clone(),
|
||||
id: format!("{}/{}", host.id, route.id),
|
||||
internal: route.internal,
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
#[cfg(test)]
|
||||
mod routing_conditions_tests {
|
||||
use super::*;
|
||||
|
||||
const FIXTURE: &str = include_str!("../../tests/fixtures/routing_conditions_cases.json");
|
||||
|
||||
fn policy() -> ValidationPolicy {
|
||||
ValidationPolicy {
|
||||
proxy_addr: "127.0.0.1:8080".parse().unwrap(),
|
||||
admin_addr: "127.0.0.1:9090".parse().unwrap(),
|
||||
tls_addr: None,
|
||||
cert_dir: None,
|
||||
data_dir: None,
|
||||
}
|
||||
}
|
||||
fn config(vhost: serde_json::Value) -> anyhow::Result<Snapshot> {
|
||||
let cfg = serde_json::from_value(serde_json::json!({
|
||||
"listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]},
|
||||
"vhosts":[vhost]
|
||||
}))?;
|
||||
compile(cfg, 0, &policy())
|
||||
}
|
||||
|
||||
/// Shared with tools/dev/test_routing_tester.js (panel tester parity).
|
||||
#[test]
|
||||
fn fixture_cases_select_the_expected_location() {
|
||||
let fixture: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
|
||||
let snapshot = config(fixture["vhost"].clone()).unwrap();
|
||||
let local: std::net::SocketAddr = "127.0.0.1:8080".parse().unwrap();
|
||||
for case in fixture["cases"].as_array().unwrap() {
|
||||
let name = case["name"].as_str().unwrap();
|
||||
let method: http::Method = case["method"].as_str().unwrap_or("GET").parse().unwrap();
|
||||
let host = case["host"].as_str().unwrap_or("site.test");
|
||||
let path = case["path"].as_str().unwrap();
|
||||
let mut headers = http::HeaderMap::new();
|
||||
if let Some(map) = case["headers"].as_object() {
|
||||
for (key, value) in map {
|
||||
headers.insert(
|
||||
http::HeaderName::from_bytes(key.as_bytes()).unwrap(),
|
||||
value.as_str().unwrap().parse().unwrap(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let facts = crate::vhost::RouteRequest {
|
||||
method: &method,
|
||||
headers: &headers,
|
||||
query: case["query"].as_str(),
|
||||
host,
|
||||
client_ip: case["client_ip"].as_str().unwrap_or("203.0.113.5").parse().unwrap(),
|
||||
country: case["country"].as_str(),
|
||||
};
|
||||
let route = snapshot
|
||||
.select_on_request(host, path, local, false, Some(&facts))
|
||||
.unwrap_or_else(|| panic!("{name}: no route"));
|
||||
assert_eq!(route.name, case["expect"].as_str().unwrap(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_locations_are_skipped_without_request_facts_and_never_cached() {
|
||||
let fixture: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
|
||||
let snapshot = config(fixture["vhost"].clone()).unwrap();
|
||||
let local: std::net::SocketAddr = "127.0.0.1:8080".parse().unwrap();
|
||||
let route = snapshot.select_on("site.test", "/api/x", local, false).unwrap();
|
||||
assert_eq!(route.name, "api");
|
||||
let route = snapshot.select_on("site.test", "/a.mp3", local, false).unwrap();
|
||||
assert_eq!(route.name, "mp3");
|
||||
let frontend = snapshot.frontend("site.test", local, false).unwrap();
|
||||
assert!(frontend.conditional_routes);
|
||||
assert!(frontend.route_conditions_country);
|
||||
let fixture_routes = fixture["vhost"]["routes"].as_array().unwrap();
|
||||
let conditional = fixture_routes
|
||||
.iter()
|
||||
.filter(|r| r.get("conditions").is_some())
|
||||
.count();
|
||||
assert!(conditional >= 5);
|
||||
// A conditional location never uses the cache.
|
||||
let headers = {
|
||||
let mut h = http::HeaderMap::new();
|
||||
h.insert("x-beta", "1".parse().unwrap());
|
||||
h
|
||||
};
|
||||
let facts = crate::vhost::RouteRequest {
|
||||
method: &http::Method::GET,
|
||||
headers: &headers,
|
||||
query: None,
|
||||
host: "site.test",
|
||||
client_ip: "203.0.113.5".parse().unwrap(),
|
||||
country: None,
|
||||
};
|
||||
let beta = snapshot
|
||||
.select_on_request("site.test", "/api/x", local, false, Some(&facts))
|
||||
.unwrap();
|
||||
assert_eq!(beta.name, "api-beta");
|
||||
assert_eq!(beta.cache, Some(false));
|
||||
assert_eq!(beta.pool.as_ref().unwrap().members.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_conditions_are_rejected() {
|
||||
let vhost = |routes: serde_json::Value| {
|
||||
serde_json::json!({
|
||||
"id":"v","frontend":{"hosts":["v.test"],"listener_ids":["http"]},
|
||||
"backends":[{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}],
|
||||
"load_balancing":{"health_check":{"mode":"off"}},
|
||||
"routes":routes
|
||||
})
|
||||
};
|
||||
for routes in [
|
||||
serde_json::json!([{"id":"x","match_type":"any"}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","values":["1"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","name":"bad name","values":["1"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"ip","values":["10.0.0.0/8"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"ip","operator":"cidr","values":["nope"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"method","operator":"prefix","values":["GE"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"country","values":["POL"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","name":"a","operator":"exists","values":["1"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","name":"a","operator":"regex","values":["("]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","name":"a","values":[]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","cache":true,"conditions":[{"source":"method","values":["GET"]}]}]),
|
||||
serde_json::json!([{"id":"x","internal":true,"conditions":[{"source":"method","values":["GET"]}]}]),
|
||||
serde_json::json!([
|
||||
{"id":"x","match_type":"regex","path_prefix":"\\.js$"},
|
||||
{"id":"y","match_type":"regex","path_prefix":"\\.js$","conditions":[{"source":"method","values":["GET"]}]}
|
||||
]),
|
||||
serde_json::json!([
|
||||
{"id":"x","path_prefix":"/x"},
|
||||
{"id":"y","path_prefix":"/x"}
|
||||
]),
|
||||
] {
|
||||
assert!(config(vhost(routes.clone())).is_err(), "{routes} should be rejected");
|
||||
}
|
||||
// A conditional copy before the unconditional regex is fine, and two
|
||||
// conditional prefixes may share a path.
|
||||
assert!(config(vhost(serde_json::json!([
|
||||
{"id":"y","match_type":"regex","path_prefix":"\\.js$","conditions":[{"source":"method","values":["GET"]}]},
|
||||
{"id":"x","match_type":"regex","path_prefix":"\\.js$"},
|
||||
{"id":"p1","path_prefix":"/p","conditions":[{"source":"header","name":"a","operator":"exists"}]},
|
||||
{"id":"p2","path_prefix":"/p","conditions":[{"source":"header","name":"b","operator":"exists"}]}
|
||||
])))
|
||||
.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_routes_serialize_without_new_fields() {
|
||||
let route: crate::vhost::PathRoute =
|
||||
serde_json::from_value(serde_json::json!({"id":"a","path_prefix":"/a"})).unwrap();
|
||||
let value = serde_json::to_value(&route).unwrap();
|
||||
for key in ["conditions", "backend_ids", "load_balancing"] {
|
||||
assert!(value.get(key).is_none(), "{key} should be omitted");
|
||||
}
|
||||
let condition: crate::vhost::RouteCondition = serde_json::from_value(
|
||||
serde_json::json!({"source":"header","name":"X-A","values":["1"]}),
|
||||
)
|
||||
.unwrap();
|
||||
let value = serde_json::to_value(&condition).unwrap();
|
||||
assert!(value.get("negate").is_none() && value.get("ignore_case").is_none());
|
||||
}
|
||||
}
|
||||
+70
-27
@@ -71,6 +71,17 @@ impl Snapshot {
|
||||
path: &str,
|
||||
local: SocketAddr,
|
||||
tls: bool,
|
||||
) -> Option<&Arc<CompiledRoute>> {
|
||||
self.select_on_request(host, path, local, tls, None)
|
||||
}
|
||||
/// Route selection with request facts, so locations with conditions can match.
|
||||
pub fn select_on_request(
|
||||
&self,
|
||||
host: &str,
|
||||
path: &str,
|
||||
local: SocketAddr,
|
||||
tls: bool,
|
||||
request: Option<&crate::vhost::RouteRequest<'_>>,
|
||||
) -> Option<&Arc<CompiledRoute>> {
|
||||
Self::find_host_pattern(host, |pattern| {
|
||||
let fallback = self.fallbacks.get(pattern).and_then(|routes| {
|
||||
@@ -81,9 +92,12 @@ impl Snapshot {
|
||||
self.routes
|
||||
.get(pattern)
|
||||
.and_then(|routes| {
|
||||
select_route(routes, path, |r| {
|
||||
r.bindings.iter().any(|l| l.matches(local, tls))
|
||||
})
|
||||
select_route(
|
||||
routes,
|
||||
path,
|
||||
|r| r.bindings.iter().any(|l| l.matches(local, tls)),
|
||||
request,
|
||||
)
|
||||
})
|
||||
.or(Some(fallback))
|
||||
})
|
||||
@@ -263,7 +277,7 @@ impl Snapshot {
|
||||
.and_then(|routes| routes.first())?;
|
||||
self.routes
|
||||
.get(pattern)
|
||||
.and_then(|routes| select_route(routes, path, |_| true))
|
||||
.and_then(|routes| select_route(routes, path, |_| true, None))
|
||||
.or(Some(fallback))
|
||||
.map(Arc::as_ref)
|
||||
})
|
||||
@@ -276,48 +290,77 @@ fn host_pattern_rank(pattern: &str, host: &str) -> usize {
|
||||
pattern.len()
|
||||
}
|
||||
}
|
||||
/// Location selection. Order: exact → prefix-priority → regex and any-path rules (list
|
||||
/// order) → longest prefix. A location with `conditions` is a candidate only when all of
|
||||
/// them hold for `request`; without request facts (cache refresh, early response
|
||||
/// handling) conditional locations are skipped. Among equal candidates a conditional
|
||||
/// location wins over an unconditional one (exact paths, prefixes of equal length).
|
||||
fn select_route<'a, F>(
|
||||
routes: &'a [Arc<CompiledRoute>],
|
||||
path: &str,
|
||||
allowed: F,
|
||||
request: Option<&crate::vhost::RouteRequest<'_>>,
|
||||
) -> Option<&'a Arc<CompiledRoute>>
|
||||
where
|
||||
F: Fn(&CompiledRoute) -> bool,
|
||||
{
|
||||
if let Some(exact) = routes.iter().find(|route| {
|
||||
let usable = |route: &CompiledRoute| {
|
||||
!route.internal
|
||||
&& allowed(route)
|
||||
&& route.match_type == crate::vhost::PathMatch::Exact
|
||||
&& route
|
||||
.conditions
|
||||
.as_ref()
|
||||
.is_none_or(|conditions| request.is_some_and(|r| conditions.matches(r)))
|
||||
};
|
||||
let exact = |route: &&Arc<CompiledRoute>| {
|
||||
route.match_type == crate::vhost::PathMatch::Exact
|
||||
&& route.path_prefix == path
|
||||
}) {
|
||||
&& usable(route)
|
||||
};
|
||||
if let Some(exact) = routes
|
||||
.iter()
|
||||
.filter(|route| route.conditions.is_some())
|
||||
.find(exact)
|
||||
.or_else(|| routes.iter().find(exact))
|
||||
{
|
||||
return Some(exact);
|
||||
}
|
||||
let prefix = routes
|
||||
.iter()
|
||||
.filter(|route| {
|
||||
!route.internal
|
||||
&& allowed(route)
|
||||
&& matches!(
|
||||
route.match_type,
|
||||
crate::vhost::PathMatch::Prefix | crate::vhost::PathMatch::PrefixPriority
|
||||
)
|
||||
&& prefix_matches(&route.path_prefix, path)
|
||||
})
|
||||
.max_by_key(|route| route.path_prefix.len());
|
||||
let mut prefix: Option<&Arc<CompiledRoute>> = None;
|
||||
for route in routes {
|
||||
if !matches!(
|
||||
route.match_type,
|
||||
crate::vhost::PathMatch::Prefix | crate::vhost::PathMatch::PrefixPriority
|
||||
) || !prefix_matches(&route.path_prefix, path)
|
||||
|| !usable(route)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let better = match prefix {
|
||||
None => true,
|
||||
Some(best) => {
|
||||
route.path_prefix.len() > best.path_prefix.len()
|
||||
|| (route.path_prefix.len() == best.path_prefix.len()
|
||||
&& route.conditions.is_some()
|
||||
&& best.conditions.is_none())
|
||||
}
|
||||
};
|
||||
if better {
|
||||
prefix = Some(route);
|
||||
}
|
||||
}
|
||||
if prefix.is_some_and(|route| route.match_type == crate::vhost::PathMatch::PrefixPriority) {
|
||||
return prefix;
|
||||
}
|
||||
if let Some(regex) = routes.iter().find(|route| {
|
||||
!route.internal
|
||||
&& allowed(route)
|
||||
&& matches!(
|
||||
route.match_type,
|
||||
crate::vhost::PathMatch::Regex | crate::vhost::PathMatch::RegexInsensitive
|
||||
)
|
||||
&& route
|
||||
let path_matches = match route.match_type {
|
||||
crate::vhost::PathMatch::Regex | crate::vhost::PathMatch::RegexInsensitive => route
|
||||
.path_regex
|
||||
.as_ref()
|
||||
.is_some_and(|regex| regex.is_match(path))
|
||||
.is_some_and(|regex| regex.is_match(path)),
|
||||
crate::vhost::PathMatch::Any => true,
|
||||
_ => false,
|
||||
};
|
||||
path_matches && usable(route)
|
||||
}) {
|
||||
return Some(regex);
|
||||
}
|
||||
|
||||
@@ -53,6 +53,9 @@ pub struct Exchange {
|
||||
pub vhost_metrics: Option<Arc<crate::metrics::VhostMetrics>>,
|
||||
pub vhost: Option<String>,
|
||||
pub route: Mutex<Option<String>>,
|
||||
/// 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>>>,
|
||||
pub source: AtomicU8,
|
||||
pub cache_effective_enabled: AtomicU8,
|
||||
pub transform_effective_enabled: AtomicU8,
|
||||
|
||||
@@ -11,6 +11,7 @@ mod tests {
|
||||
vhost_metrics: None,
|
||||
vhost: None,
|
||||
route: Mutex::new(None),
|
||||
routed: Mutex::new(None),
|
||||
source: AtomicU8::new(ExchangeSource::Unresolved as u8),
|
||||
cache_effective_enabled: AtomicU8::new(0),
|
||||
transform_effective_enabled: AtomicU8::new(0),
|
||||
|
||||
@@ -49,7 +49,7 @@ 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,
|
||||
None => pool
|
||||
.select_wait(context.client_ip, request.headers(), tls)
|
||||
.select_wait_uri(context.client_ip, request.headers(), balance_uri.as_ref(), tls)
|
||||
.await,
|
||||
};
|
||||
let selection = match selection {
|
||||
|
||||
@@ -213,9 +213,10 @@ let upstream_result = loop {
|
||||
break result;
|
||||
};
|
||||
let selection = match pool
|
||||
.select_retry_wait(
|
||||
.select_retry_wait_uri(
|
||||
context.client_ip,
|
||||
retry_headers,
|
||||
balance_uri.as_ref(),
|
||||
tls,
|
||||
&attempted_backends,
|
||||
)
|
||||
|
||||
@@ -312,7 +312,8 @@ async fn forward_request(
|
||||
.profile_policies
|
||||
.iter()
|
||||
.any(|profile| profile.countries.needs_geoip())
|
||||
|| frontend.rate_limit.needs_geoip())
|
||||
|| frontend.rate_limit.needs_geoip()
|
||||
|| frontend.route_conditions_country)
|
||||
{
|
||||
country = cloudflare_country
|
||||
.clone()
|
||||
@@ -437,6 +438,32 @@ async fn forward_request(
|
||||
} else {
|
||||
snapshot.select_internal_on(&host, &dispatch.vhost_id, &dispatch.target, local.0, tls)
|
||||
}
|
||||
} else if frontend.is_some_and(|frontend| frontend.conditional_routes) {
|
||||
// Locations with request conditions are selected here, with the final client
|
||||
// address and country; earlier stages only saw unconditional locations.
|
||||
let facts = crate::vhost::RouteRequest {
|
||||
method: request.method(),
|
||||
headers: request.headers(),
|
||||
query: request.uri().query(),
|
||||
host: &host,
|
||||
client_ip: context.client_ip,
|
||||
country: country.as_deref(),
|
||||
};
|
||||
let chosen = snapshot.select_on_request(&host, &path, local.0, tls, Some(&facts));
|
||||
if let (Some(chosen), Some(exchange)) =
|
||||
(chosen, request.extensions().get::<Arc<Exchange>>())
|
||||
{
|
||||
let precomputed = selected_context
|
||||
.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());
|
||||
}
|
||||
}
|
||||
chosen.map(Arc::as_ref)
|
||||
} else if let Some(selection) = &selected_context {
|
||||
selection.route.as_deref()
|
||||
} else {
|
||||
@@ -559,6 +586,13 @@ 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()
|
||||
.is_some_and(|pool| pool.hashes_request_uri())
|
||||
.then(|| request.uri().clone());
|
||||
let fallback_body =
|
||||
match prepare_error_fallback_body(&mut request, route.error_fallback.is_some()).await {
|
||||
Ok(body) => body,
|
||||
|
||||
@@ -215,6 +215,7 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
|
||||
vhost_metrics: frontend_context.as_ref().map(|f| f.metrics.clone()),
|
||||
vhost: frontend_context.as_ref().map(|f| f.id.clone()),
|
||||
route: Mutex::new(None),
|
||||
routed: Mutex::new(None),
|
||||
source: AtomicU8::new(ExchangeSource::Unresolved as u8),
|
||||
cache_effective_enabled: AtomicU8::new(0),
|
||||
transform_effective_enabled: AtomicU8::new(0),
|
||||
@@ -262,8 +263,14 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
|
||||
.extensions()
|
||||
.get::<FinalRouteContext>()
|
||||
.map(|context| context.0.clone());
|
||||
let routed_context = exchange
|
||||
.routed
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.clone();
|
||||
let effective_route_context = final_route_context
|
||||
.as_deref()
|
||||
.or(routed_context.as_deref())
|
||||
.or(route_context.as_deref());
|
||||
let minimal_welcome = response
|
||||
.extensions()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
include!("vhost/model.rs");
|
||||
include!("vhost/conditions.rs");
|
||||
include!("vhost/error_fallback.rs");
|
||||
include!("vhost/redirect.rs");
|
||||
include!("vhost/validation.rs");
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
// Request conditions of a location (routing rules beyond the path). All conditions of
|
||||
// a location must hold (AND); each condition matches when any of its values matches
|
||||
// (OR); `negate` inverts one condition. Locations that do not match are skipped and
|
||||
// selection continues with the next candidate, so "OR" between rules is written as
|
||||
// several locations.
|
||||
|
||||
/// Request attribute tested by a [`RouteCondition`].
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ConditionSource {
|
||||
#[default]
|
||||
Header,
|
||||
Cookie,
|
||||
Query,
|
||||
Method,
|
||||
/// Client address as determined by RustProxy (trusted forwarding / Cloudflare).
|
||||
Ip,
|
||||
/// Request host name without port (useful with wildcard vhosts).
|
||||
Host,
|
||||
/// ISO country code from the GeoIP database or Cloudflare.
|
||||
Country,
|
||||
}
|
||||
impl ConditionSource {
|
||||
pub fn needs_name(self) -> bool {
|
||||
matches!(self, Self::Header | Self::Cookie | Self::Query)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ConditionOperator {
|
||||
#[default]
|
||||
Equals,
|
||||
Exists,
|
||||
Prefix,
|
||||
Suffix,
|
||||
Contains,
|
||||
Regex,
|
||||
/// IP address or CIDR network (only for `ip`).
|
||||
Cidr,
|
||||
}
|
||||
|
||||
fn is_false(value: &bool) -> bool {
|
||||
!*value
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct RouteCondition {
|
||||
pub source: ConditionSource,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
pub operator: ConditionOperator,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub values: Vec<String>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub negate: bool,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub ignore_case: bool,
|
||||
}
|
||||
|
||||
pub const MAX_ROUTE_CONDITIONS: usize = 16;
|
||||
const MAX_CONDITION_VALUES: usize = 64;
|
||||
|
||||
impl RouteCondition {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
self.compile().map(|_| ())
|
||||
}
|
||||
pub fn compile(&self) -> Result<CompiledCondition> {
|
||||
use ConditionOperator as Op;
|
||||
use ConditionSource as Src;
|
||||
let name = self.name.as_deref().unwrap_or("").trim();
|
||||
if self.source.needs_name() {
|
||||
ensure!(
|
||||
!name.is_empty() && name.len() <= 128,
|
||||
"condition on {:?} needs a name (1..128 characters)",
|
||||
self.source
|
||||
);
|
||||
if self.source == Src::Header {
|
||||
ensure!(
|
||||
http::HeaderName::from_bytes(name.as_bytes()).is_ok(),
|
||||
"condition header name {name:?} is not a valid HTTP header name"
|
||||
);
|
||||
} else {
|
||||
ensure!(
|
||||
name.bytes()
|
||||
.all(|b| b.is_ascii_graphic() && !matches!(b, b';' | b'=' | b'&' | b',')),
|
||||
"condition cookie/query name must be printable ASCII without ; = & or ,"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
ensure!(
|
||||
name.is_empty(),
|
||||
"a name is only used by header, cookie and query conditions"
|
||||
);
|
||||
}
|
||||
let allowed = match self.source {
|
||||
Src::Ip => matches!(self.operator, Op::Cidr),
|
||||
Src::Method | Src::Country => matches!(self.operator, Op::Equals),
|
||||
Src::Host => !matches!(self.operator, Op::Cidr | Op::Exists),
|
||||
Src::Header | Src::Cookie | Src::Query => !matches!(self.operator, Op::Cidr),
|
||||
};
|
||||
ensure!(
|
||||
allowed,
|
||||
"operator {:?} cannot be used with a {:?} condition",
|
||||
self.operator,
|
||||
self.source
|
||||
);
|
||||
let values: Vec<String> = self.values.iter().map(|v| v.trim().to_owned()).collect();
|
||||
if self.operator == Op::Exists {
|
||||
ensure!(values.is_empty(), "an exists condition takes no values");
|
||||
} else {
|
||||
ensure!(
|
||||
(1..=MAX_CONDITION_VALUES).contains(&values.len()),
|
||||
"condition needs 1..{MAX_CONDITION_VALUES} values"
|
||||
);
|
||||
for value in &values {
|
||||
ensure!(
|
||||
!value.is_empty() && value.len() <= 1024 && !value.chars().any(char::is_control),
|
||||
"condition values must be 1..1024 characters without control characters"
|
||||
);
|
||||
}
|
||||
}
|
||||
let fold = (self.ignore_case && self.source.needs_name()) || self.source == Src::Host;
|
||||
let matcher = match self.operator {
|
||||
Op::Exists => Matcher::Exists,
|
||||
Op::Cidr => Matcher::Cidr(
|
||||
values
|
||||
.iter()
|
||||
.map(|value| {
|
||||
value
|
||||
.parse::<ipnet::IpNet>()
|
||||
.or_else(|_| value.parse::<IpAddr>().map(ipnet::IpNet::from))
|
||||
.map(|net| net.trunc())
|
||||
.map_err(|_| anyhow::anyhow!("invalid IP address or CIDR {value:?}"))
|
||||
})
|
||||
.collect::<Result<_>>()?,
|
||||
),
|
||||
Op::Regex => Matcher::Regex(
|
||||
values
|
||||
.iter()
|
||||
.map(|value| {
|
||||
regex::RegexBuilder::new(value)
|
||||
.case_insensitive(fold)
|
||||
.size_limit(1024 * 1024)
|
||||
.dfa_size_limit(1024 * 1024)
|
||||
.build()
|
||||
.map_err(|_| anyhow::anyhow!("invalid or too complex regular expression {value:?}"))
|
||||
})
|
||||
.collect::<Result<_>>()?,
|
||||
),
|
||||
op => {
|
||||
let mut list = values.clone();
|
||||
match self.source {
|
||||
Src::Method => {
|
||||
for value in &mut list {
|
||||
*value = value.to_ascii_uppercase();
|
||||
ensure!(
|
||||
http::Method::from_bytes(value.as_bytes()).is_ok(),
|
||||
"invalid HTTP method {value:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Src::Country => {
|
||||
for value in &mut list {
|
||||
*value = value.to_ascii_uppercase();
|
||||
ensure!(
|
||||
value.len() == 2 && value.bytes().all(|b| b.is_ascii_uppercase()),
|
||||
"country codes must be two letters (ISO 3166-1 alpha-2)"
|
||||
);
|
||||
}
|
||||
}
|
||||
Src::Host => {
|
||||
for value in &mut list {
|
||||
*value = value.trim_end_matches('.').to_ascii_lowercase();
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if fold {
|
||||
for value in &mut list {
|
||||
*value = value.to_lowercase();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
match op {
|
||||
Op::Equals => Matcher::Equals(list),
|
||||
Op::Prefix => Matcher::Prefix(list),
|
||||
Op::Suffix => Matcher::Suffix(list),
|
||||
_ => Matcher::Contains(list),
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(CompiledCondition {
|
||||
source: self.source,
|
||||
name: (!name.is_empty()).then(|| name.to_owned()),
|
||||
matcher,
|
||||
negate: self.negate,
|
||||
fold,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum Matcher {
|
||||
Exists,
|
||||
Equals(Vec<String>),
|
||||
Prefix(Vec<String>),
|
||||
Suffix(Vec<String>),
|
||||
Contains(Vec<String>),
|
||||
Regex(Vec<regex::Regex>),
|
||||
Cidr(Vec<ipnet::IpNet>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CompiledCondition {
|
||||
source: ConditionSource,
|
||||
name: Option<String>,
|
||||
matcher: Matcher,
|
||||
negate: bool,
|
||||
fold: bool,
|
||||
}
|
||||
|
||||
/// Request attributes available to location conditions.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct RouteRequest<'a> {
|
||||
pub method: &'a http::Method,
|
||||
pub headers: &'a http::HeaderMap,
|
||||
pub query: Option<&'a str>,
|
||||
pub host: &'a str,
|
||||
pub client_ip: IpAddr,
|
||||
pub country: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl CompiledCondition {
|
||||
pub fn source(&self) -> ConditionSource {
|
||||
self.source
|
||||
}
|
||||
fn values<'a>(&self, request: &RouteRequest<'a>) -> Vec<std::borrow::Cow<'a, str>> {
|
||||
use std::borrow::Cow;
|
||||
let name = self.name.as_deref().unwrap_or("");
|
||||
match self.source {
|
||||
ConditionSource::Header => request
|
||||
.headers
|
||||
.get_all(name)
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.map(|v| Cow::Borrowed(v.trim()))
|
||||
.collect(),
|
||||
ConditionSource::Cookie => request
|
||||
.headers
|
||||
.get_all(http::header::COOKIE)
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.flat_map(|v| v.split(';'))
|
||||
.filter_map(|pair| pair.trim().split_once('='))
|
||||
.filter(|(n, _)| *n == name)
|
||||
.map(|(_, v)| Cow::Borrowed(v.trim()))
|
||||
.collect(),
|
||||
ConditionSource::Query => request
|
||||
.query
|
||||
.into_iter()
|
||||
.flat_map(|q| q.split('&'))
|
||||
.map(|pair| pair.split_once('=').unwrap_or((pair, "")))
|
||||
.filter(|(n, _)| *n == name)
|
||||
.map(|(_, v)| Cow::Borrowed(v))
|
||||
.collect(),
|
||||
ConditionSource::Method => vec![Cow::Borrowed(request.method.as_str())],
|
||||
ConditionSource::Host => vec![Cow::Owned(
|
||||
request.host.trim_end_matches('.').to_ascii_lowercase(),
|
||||
)],
|
||||
ConditionSource::Country => request
|
||||
.country
|
||||
.map(|c| Cow::Owned(c.to_ascii_uppercase()))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
ConditionSource::Ip => vec![Cow::Owned(
|
||||
crate::vhost::canonical_ip(request.client_ip).to_string(),
|
||||
)],
|
||||
}
|
||||
}
|
||||
pub fn matches(&self, request: &RouteRequest<'_>) -> bool {
|
||||
let raw = self.values(request);
|
||||
let fold = |value: &str| -> String {
|
||||
if self.fold && self.source != ConditionSource::Host {
|
||||
value.to_lowercase()
|
||||
} else {
|
||||
value.to_owned()
|
||||
}
|
||||
};
|
||||
let hit = match &self.matcher {
|
||||
Matcher::Exists => !raw.is_empty(),
|
||||
Matcher::Cidr(nets) => {
|
||||
let ip = crate::vhost::canonical_ip(request.client_ip);
|
||||
nets.iter().any(|net| net.contains(&ip))
|
||||
}
|
||||
Matcher::Regex(list) => raw.iter().any(|v| list.iter().any(|r| r.is_match(v))),
|
||||
Matcher::Equals(list) => raw
|
||||
.iter()
|
||||
.any(|v| list.iter().any(|p| fold(v) == *p)),
|
||||
Matcher::Prefix(list) => raw
|
||||
.iter()
|
||||
.any(|v| list.iter().any(|p| fold(v).starts_with(p.as_str()))),
|
||||
Matcher::Suffix(list) => raw
|
||||
.iter()
|
||||
.any(|v| list.iter().any(|p| fold(v).ends_with(p.as_str()))),
|
||||
Matcher::Contains(list) => raw
|
||||
.iter()
|
||||
.any(|v| list.iter().any(|p| fold(v).contains(p.as_str()))),
|
||||
};
|
||||
hit != self.negate
|
||||
}
|
||||
}
|
||||
|
||||
/// All conditions of one location.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CompiledConditions(Vec<CompiledCondition>);
|
||||
impl CompiledConditions {
|
||||
pub fn compile(conditions: &[RouteCondition]) -> Result<Option<Self>> {
|
||||
ensure!(
|
||||
conditions.len() <= MAX_ROUTE_CONDITIONS,
|
||||
"at most {MAX_ROUTE_CONDITIONS} conditions per location"
|
||||
);
|
||||
if conditions.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(Self(
|
||||
conditions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, condition)| {
|
||||
condition
|
||||
.compile()
|
||||
.with_context(|| format!("condition {}", index + 1))
|
||||
})
|
||||
.collect::<Result<_>>()?,
|
||||
)))
|
||||
}
|
||||
pub fn matches(&self, request: &RouteRequest<'_>) -> bool {
|
||||
self.0.iter().all(|condition| condition.matches(request))
|
||||
}
|
||||
/// Result of every condition, for the panel tester.
|
||||
pub fn explain(&self, request: &RouteRequest<'_>) -> Vec<bool> {
|
||||
self.0.iter().map(|condition| condition.matches(request)).collect()
|
||||
}
|
||||
pub fn needs_country(&self) -> bool {
|
||||
self.0
|
||||
.iter()
|
||||
.any(|condition| condition.source == ConditionSource::Country)
|
||||
}
|
||||
}
|
||||
@@ -238,6 +238,9 @@ pub enum PathMatch {
|
||||
Exact,
|
||||
Regex,
|
||||
RegexInsensitive,
|
||||
/// Any path: a vhost-wide rule selected only by its `conditions`. Evaluated with
|
||||
/// regex locations, in list order.
|
||||
Any,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -533,6 +536,16 @@ pub struct PathRoute {
|
||||
pub source: Source,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub backend_id: Option<String>,
|
||||
/// Backend group of this location (ids of vhost backends). Empty: the vhost pool
|
||||
/// (or `backend_id`). Like a HAProxy `use_backend` target sharing the vhost servers.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub backend_ids: Vec<String>,
|
||||
/// Location-specific balancing (algorithm, hash key, affinity) over its backends.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub load_balancing: Option<crate::balance::RouteBalancing>,
|
||||
/// Extra request conditions (all must hold) besides the path.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub conditions: Vec<RouteCondition>,
|
||||
pub id: String,
|
||||
#[serde(default)]
|
||||
pub internal: bool,
|
||||
|
||||
+69
-2
@@ -3,6 +3,9 @@ impl Default for PathRoute {
|
||||
Self {
|
||||
source: Source::default(),
|
||||
backend_id: None,
|
||||
backend_ids: Vec::new(),
|
||||
load_balancing: None,
|
||||
conditions: Vec::new(),
|
||||
id: "root".into(),
|
||||
internal: false,
|
||||
path_prefix: root(),
|
||||
@@ -29,6 +32,9 @@ impl PathRoute {
|
||||
&& self.enabled
|
||||
&& self.source == Source::ReverseProxy
|
||||
&& self.backend_id.is_none()
|
||||
&& self.backend_ids.is_empty()
|
||||
&& self.load_balancing.is_none()
|
||||
&& self.conditions.is_empty()
|
||||
&& !self.internal
|
||||
&& self.cache.is_none()
|
||||
&& self.acl_profile_id.is_none()
|
||||
@@ -175,9 +181,70 @@ impl Vhost {
|
||||
route.country_access.validate()?;
|
||||
route.method_policy.validate()?;
|
||||
ensure!(
|
||||
route.source.is_reverse_proxy() || route.backend_id.is_none(),
|
||||
"Web Server location cannot pin a reverse-proxy backend"
|
||||
route.source.is_reverse_proxy()
|
||||
|| (route.backend_id.is_none()
|
||||
&& route.backend_ids.is_empty()
|
||||
&& route.load_balancing.is_none()),
|
||||
"Web Server location cannot pin a reverse-proxy backend or balancing"
|
||||
);
|
||||
ensure!(
|
||||
route.backend_id.is_none()
|
||||
|| (route.backend_ids.is_empty() && route.load_balancing.is_none()),
|
||||
"location {}: a pinned backend cannot be combined with a backend group or location balancing",
|
||||
route.id
|
||||
);
|
||||
ensure!(
|
||||
route.backend_ids.len() <= 64,
|
||||
"location {}: at most 64 backends in a location backend group",
|
||||
route.id
|
||||
);
|
||||
{
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for id in &route.backend_ids {
|
||||
ensure!(
|
||||
crate::config::valid_id(id) && seen.insert(id.as_str()),
|
||||
"location {}: backend group id {:?} is invalid or listed twice",
|
||||
route.id,
|
||||
id
|
||||
);
|
||||
ensure!(
|
||||
self.backends.iter().any(|b| &b.id == id),
|
||||
"location {}: backend group references unknown backend {}",
|
||||
route.id,
|
||||
id
|
||||
);
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
route.conditions.len() <= MAX_ROUTE_CONDITIONS,
|
||||
"location {}: at most {MAX_ROUTE_CONDITIONS} conditions",
|
||||
route.id
|
||||
);
|
||||
for (index, condition) in route.conditions.iter().enumerate() {
|
||||
condition.validate().map_err(|e| {
|
||||
anyhow::anyhow!("location {} condition {}: {e}", route.id, index + 1)
|
||||
})?;
|
||||
}
|
||||
ensure!(
|
||||
route.match_type != PathMatch::Any || !route.conditions.is_empty(),
|
||||
"location {}: an any-path (vhost-wide) rule needs at least one condition",
|
||||
route.id
|
||||
);
|
||||
ensure!(
|
||||
!route.internal || route.conditions.is_empty(),
|
||||
"location {}: internal locations cannot have conditions",
|
||||
route.id
|
||||
);
|
||||
ensure!(
|
||||
route.conditions.is_empty() || route.cache != Some(true),
|
||||
"location {}: locations with conditions are never cached (their responses depend on request attributes outside the cache key); leave cache on inherit or off",
|
||||
route.id
|
||||
);
|
||||
if let Some(balancing) = &route.load_balancing {
|
||||
balancing.validate().map_err(|e| {
|
||||
anyhow::anyhow!("location {}: {e}", route.id)
|
||||
})?;
|
||||
}
|
||||
if let Some(fallback) = &mut route.error_fallback {
|
||||
fallback.validate()?;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user