v0.41.0
This commit is contained in:
1 parent
27b640a0df
commit
aa27866531
46 files changed
+3368
-189
No files matched your search
@@ -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(); } };
|
||||
}
|
||||
Reference in new issue
Block a user