v0.38.10
This commit is contained in:
1 parent
38a23e2210
commit
45b1fc04c7
36 files changed
+9594
-7892
No files matched your search
@@ -145,6 +145,7 @@ async fn cache_rules_test(
|
||||
client_ip,
|
||||
};
|
||||
let request_outcome = rules.evaluate_request(&request, false);
|
||||
request_outcome.apply_headers(&mut headers);
|
||||
request_outcome.rewrite_cookies(&mut headers);
|
||||
let query = match request_outcome.rewrite_query(uri.query()) {
|
||||
Some(rewritten) => rewritten,
|
||||
@@ -161,7 +162,10 @@ async fn cache_rules_test(
|
||||
} else if !settings.enabled {
|
||||
Some("cache_disabled")
|
||||
} else {
|
||||
crate::cache::request_policy(&method, &headers, true, &path, query.is_some(), &settings)
|
||||
crate::cache::request_policy_with_vcl_cookie(
|
||||
&method, &headers, true, &path, query.is_some(), &settings,
|
||||
request_outcome.lookup.is_some(),
|
||||
)
|
||||
.bypass_reason()
|
||||
};
|
||||
let mut response_value = Value::Null;
|
||||
@@ -175,9 +179,7 @@ async fn cache_rules_test(
|
||||
})?;
|
||||
let mut response_headers = cache_rule_headers(&response.headers)?;
|
||||
let outcome = rules.evaluate_response(&request, status, &response_headers, false);
|
||||
if outcome.overrides.strip_set_cookie {
|
||||
response_headers.remove(http::header::SET_COOKIE);
|
||||
}
|
||||
outcome.overrides.apply_headers(&mut response_headers);
|
||||
let plan = if request_policy.is_none() {
|
||||
crate::cache::plan_with(
|
||||
status,
|
||||
@@ -220,6 +222,8 @@ async fn cache_rules_test(
|
||||
"matched": request_outcome.matched,
|
||||
"overridden": request_outcome.overridden,
|
||||
"pass": request_outcome.pass,
|
||||
"lookup": request_outcome.lookup,
|
||||
"header_edits": request_outcome.header_edits,
|
||||
"target": target,
|
||||
"cookie": headers.get(http::header::COOKIE).and_then(|v| v.to_str().ok()),
|
||||
"variant": request_outcome.hash,
|
||||
|
||||
@@ -24,6 +24,7 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[
|
||||
reader_doc!("docs/WEB_SERVER.md", "guides"),
|
||||
reader_doc!("docs/PHP_FPM.md", "guides"),
|
||||
reader_doc!("docs/CACHE.md", "guides"),
|
||||
reader_doc!("docs/VCL.md", "guides"),
|
||||
reader_doc!("docs/RESPONSE_DELIVERY.md", "guides"),
|
||||
reader_doc!("docs/TRANSPORT.md", "guides"),
|
||||
reader_doc!("docs/STREAMS.md", "guides"),
|
||||
|
||||
+11
-5
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "RustProxy Administration API",
|
||||
"version": "0.38.7",
|
||||
"version": "0.38.8",
|
||||
"description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only."
|
||||
},
|
||||
"servers": [
|
||||
@@ -8770,7 +8770,7 @@
|
||||
},
|
||||
"CacheRule": {
|
||||
"type": "object",
|
||||
"description": "Cache rule (since 0.37.1). Request rules run before the cache lookup (vcl_recv/vcl_hash), response rules on a backend response (vcl_backend_response), deliver rules on every response sent to the client (vcl_deliver). Vhost rules run before global rules; for TTL, grace, pass and no_store the first matching rule wins.",
|
||||
"description": "Cache rule (since 0.37.1, extended in 0.38.8). Request rules run in vcl_recv then vcl_hash after return(hash); response rules run before origin cache admission; deliver rules run before sending headers. Vhost rules precede global rules and own their mutated header fields. Later assignments in the same scope take precedence unless a terminal return stops the stage. VCL import is a supported subset and returns warnings for unsupported operations.",
|
||||
"required": [
|
||||
"id",
|
||||
"actions"
|
||||
@@ -8856,13 +8856,14 @@
|
||||
},
|
||||
"actions": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"minItems": 0,
|
||||
"maxItems": 16,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"description": "type: pass, strip_cookies{keep}, strip_query{params,keep_only}, hash_header{name}, hash_cookie{name} (request); ttl{seconds}, grace{seconds}, no_store, ignore_cache_control, strip_set_cookie (response); set_header{name,value}, default_header{name,value} (only when the response lacks the header, since 0.37.2), remove_header{name} (deliver; deliver rules apply to every response of the vhost, also when caching is off).",
|
||||
"description": "type: pass, lookup (VCL return(hash), Cookie exception in Varnish-compatible mode), strip_cookies{keep}, strip_query{params,keep_only}, hash_header{name}, hash_cookie{name}, set_request_header{name,value}, remove_request_header{name} (request; protected auth/cache/framing headers cannot be changed); ttl{seconds}, grace{seconds}, no_store, allow_store (reverses rule no_store only; origin restrictions remain), ignore_cache_control, strip_set_cookie, set_backend_header{name,value}, remove_backend_header{name} (response, applied before cacheability and forwarded headers); set_header{name,value}, default_header{name,value}, remove_header{name} (deliver, including cache-disabled responses).",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"description": "Zero actions allowed only with stop=true (terminal return)."
|
||||
},
|
||||
"stop": {
|
||||
"type": "boolean"
|
||||
@@ -8873,6 +8874,11 @@
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Global rules only: limit to these vhost ids (empty = all)."
|
||||
},
|
||||
"hash_stage": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Run this request-stage rule in vcl_hash, after vcl_recv. Imported VCL sets this automatically."
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
+145
-40
@@ -18,11 +18,11 @@ window.rustProxyCacheRules = (() => {
|
||||
response_header: { ops: ["exists", "equals", "contains", "regex"], name: true, stages: ["response", "deliver"] },
|
||||
};
|
||||
const ACTIONS = {
|
||||
request: ["pass", "strip_cookies", "strip_query", "hash_header", "hash_cookie"],
|
||||
response: ["ttl", "grace", "no_store", "ignore_cache_control", "strip_set_cookie"],
|
||||
request: ["pass", "lookup", "strip_cookies", "strip_query", "hash_header", "hash_cookie", "set_request_header", "remove_request_header"],
|
||||
response: ["ttl", "grace", "no_store", "allow_store", "ignore_cache_control", "strip_set_cookie", "set_backend_header", "remove_backend_header"],
|
||||
deliver: ["set_header", "default_header", "remove_header"],
|
||||
};
|
||||
const ASPECTS = { pass: "pass", ttl: "ttl", grace: "grace", no_store: "store" };
|
||||
const ASPECTS = { pass: "request_routing", lookup: "request_routing", strip_cookies: "request_cookies", strip_query: "request_query", ttl: "ttl", grace: "grace", no_store: "store", allow_store: "store" };
|
||||
const tk = (prefix, value) => t(`${prefix}${String(value).split("_").map(part => part[0].toUpperCase() + part.slice(1)).join("")}`);
|
||||
const fieldLabel = field => tk("cacheRuleField", field);
|
||||
const opLabel = op => tk("cacheRuleOp", op);
|
||||
@@ -40,10 +40,11 @@ window.rustProxyCacheRules = (() => {
|
||||
return { id, name: t("cacheRuleNewName"), enabled: true, stage, match: "all", conditions: [], actions: [{ type: ACTIONS[stage][0] }], stop: false, vhosts: [] };
|
||||
}
|
||||
function normalize(rule) {
|
||||
return { id: rule.id, name: rule.name || "", enabled: rule.enabled !== false, stage: rule.stage || "request", match: rule.match || "all", conditions: (rule.conditions || []).map(c => ({ ...c, values: [...(c.values || [])] })), actions: (rule.actions || []).map(a => ({ ...a })), stop: !!rule.stop, vhosts: [...(rule.vhosts || [])] };
|
||||
return { id: rule.id, name: rule.name || "", enabled: rule.enabled !== false, stage: rule.stage || "request", match: rule.match || "all", conditions: (rule.conditions || []).map(c => ({ ...c, values: [...(c.values || [])] })), actions: (rule.actions || []).map(a => ({ ...a })), stop: !!rule.stop, hash_stage: !!rule.hash_stage, vhosts: [...(rule.vhosts || [])] };
|
||||
}
|
||||
function clean(rule, global) {
|
||||
const out = { id: rule.id, name: rule.name, enabled: rule.enabled, stage: rule.stage, match: rule.match, conditions: rule.conditions.map(c => { const item = { field: c.field, operator: c.operator, values: c.operator === "exists" ? [] : c.values }; if (FIELDS[c.field]?.name) item.name = c.name || ""; if (c.negate) item.negate = true; return item; }), actions: rule.actions.map(a => ({ ...a })), stop: rule.stop };
|
||||
if (rule.hash_stage) out.hash_stage = true;
|
||||
if (global && rule.vhosts.length) out.vhosts = rule.vhosts;
|
||||
return out;
|
||||
}
|
||||
@@ -81,15 +82,21 @@ window.rustProxyCacheRules = (() => {
|
||||
return rule.actions.map(a => {
|
||||
switch (a.type) {
|
||||
case "pass": return "return (pass);";
|
||||
case "lookup": return rule.hash_stage ? "return (lookup);" : "return (hash);";
|
||||
case "strip_cookies": return a.keep?.length ? `# keep only cookies: ${a.keep.join(", ")}\nset req.http.Cookie = regsuball(req.http.Cookie, "(^|;\\s*)(?!(${a.keep.map(reEsc).join("|")})=)[^;=]+=[^;]*", "");` : "unset req.http.Cookie;";
|
||||
case "strip_query": return a.keep_only ? `# keep only query parameters: ${(a.params || []).join(", ")}` : (a.params?.length ? `set req.url = regsuball(req.url, "([?&])(${a.params.map(p => globRe(p).replace(/\.\*/g, "[^=&]*")).join("|")})=[^&]*", "\\1");` : `set req.url = regsub(req.url, "\\?.*$", "");`);
|
||||
case "hash_header": return `hash_data(req.http.${a.name});`;
|
||||
case "hash_cookie": return `hash_data(regsub(req.http.Cookie, "^.*(?:^|;\\s*)${reEsc(a.name)}=([^;]*).*$", "\\1"));`;
|
||||
case "set_request_header": return `set req.http.${a.name} = "${esc(a.value ?? "")}";`;
|
||||
case "remove_request_header": return `unset req.http.${a.name};`;
|
||||
case "ttl": return `set beresp.ttl = ${a.seconds ?? 0}s;`;
|
||||
case "grace": return `set beresp.grace = ${a.seconds ?? 0}s;`;
|
||||
case "no_store": return "set beresp.uncacheable = true;";
|
||||
case "allow_store": return "set beresp.uncacheable = false;";
|
||||
case "ignore_cache_control": return "unset beresp.http.Cache-Control;";
|
||||
case "strip_set_cookie": return "unset beresp.http.Set-Cookie;";
|
||||
case "set_backend_header": return `set beresp.http.${a.name} = "${esc(a.value ?? "")}";`;
|
||||
case "remove_backend_header": return `unset beresp.http.${a.name};`;
|
||||
case "set_header": return `set resp.http.${a.name} = "${esc(a.value ?? "")}";`;
|
||||
case "remove_header": return `unset resp.http.${a.name};`;
|
||||
case "default_header": return `if (!resp.http.${a.name}) { set resp.http.${a.name} = "${esc(a.value ?? "")}"; }`;
|
||||
@@ -99,20 +106,39 @@ window.rustProxyCacheRules = (() => {
|
||||
}
|
||||
function ruleVcl(rule) {
|
||||
const lines = vclActions(rule).flatMap(line => line.split("\n"));
|
||||
// An imported return(deliver) may be represented by stop=true and no actions.
|
||||
// Preserve terminal control flow even when preceded by header/TTL actions.
|
||||
if (rule.stop && !lines.some(line => /^return\s*\(/.test(line)))
|
||||
lines.push(`return (${rule.stage === "request" ? (rule.hash_stage ? "lookup" : "hash") : "deliver"});`);
|
||||
const conditions = rule.conditions.map(c => vclCondition(c, rule.stage));
|
||||
const joined = conditions.join(rule.match === "any" ? " ||\n " : " &&\n ");
|
||||
const body = lines.map(line => ` ${line}`).join("\n");
|
||||
const head = `# ${rule.name || rule.id}${rule.enabled === false ? " (disabled)" : ""}${rule.vhosts?.length ? ` · vhosts: ${rule.vhosts.join(", ")}` : ""}`;
|
||||
return conditions.length ? `${head}\nif (${joined}) {\n${body}\n}` : `${head}\n${body.replace(/^ {4}/gm, "")}`;
|
||||
const limits = [];
|
||||
if (rule.enabled === false) limits.push("This rule is DISABLED in RustProxy; the preview is not executable equivalently.");
|
||||
if (rule.vhosts?.length) limits.push("Vhost targeting is stored in RustProxy config, not represented by VCL.");
|
||||
if (rule.conditions.some(c => ["client_ip", "extension", "query", "cookie"].includes(c.field)))
|
||||
limits.push("One or more graphical conditions have no guaranteed VCL import round-trip.");
|
||||
if (rule.actions.some(a => ["hash_cookie", "strip_query", "strip_cookies", "default_header", "ignore_cache_control"].includes(a.type)))
|
||||
limits.push("One or more graphical actions are only approximated in this VCL display.");
|
||||
const notes = limits.map(limit => `# PREVIEW LIMITATION: ${limit}`).join("\n");
|
||||
const description = notes ? `${head}\n${notes}` : head;
|
||||
return conditions.length ? `${description}\nif (${joined}) {\n${body}\n}` : `${description}\n${body.replace(/^ {4}/gm, "")}`;
|
||||
}
|
||||
function exportVcl(rules) {
|
||||
const subs = { request: "vcl_recv", response: "vcl_backend_response", deliver: "vcl_deliver" };
|
||||
const blocks = ["vcl 4.1;", "# Generated by RustProxy cache rules (read-only preview)"];
|
||||
const blocks = [
|
||||
"vcl 4.1;",
|
||||
"# RustProxy DISPLAY PREVIEW, not a lossless VCL backup or a deployable Varnish config.",
|
||||
"# Source of truth: saved graphical rules. Import supports only the documented subset.",
|
||||
"# Some rules (client IP, cookie allowlists, hash_cookie, disabled rules and other actions)",
|
||||
"# have no matching VCL importer syntax. Check Rules -> Cache & VCL guide."
|
||||
];
|
||||
const indent = text => text.replace(/^/gm, " ");
|
||||
for (const stage of STAGES) {
|
||||
const items = rules.filter(rule => rule.stage === stage);
|
||||
const main = items.map(rule => ({ ...rule, actions: rule.actions.filter(a => !a.type.startsWith("hash_")) })).filter(rule => rule.actions.length);
|
||||
const hash = items.map(rule => ({ ...rule, actions: rule.actions.filter(a => a.type.startsWith("hash_")) })).filter(rule => rule.actions.length);
|
||||
const main = items.filter(rule => !rule.hash_stage).map(rule => ({ ...rule, actions: rule.actions.filter(a => !a.type.startsWith("hash_")) })).filter(rule => rule.actions.length || rule.stop);
|
||||
const hash = items.map(rule => ({ ...rule, actions: rule.hash_stage ? rule.actions : rule.actions.filter(a => a.type.startsWith("hash_")) })).filter(rule => (rule.actions.length || (rule.stop && rule.hash_stage)) && stage === "request");
|
||||
if (main.length) blocks.push(`\nsub ${subs[stage]} {\n${main.map(rule => indent(ruleVcl(rule))).join("\n\n")}\n}`);
|
||||
if (hash.length) blocks.push(`\nsub vcl_hash {\n${hash.map(rule => indent(ruleVcl(rule))).join("\n\n")}\n}`);
|
||||
}
|
||||
@@ -122,8 +148,8 @@ window.rustProxyCacheRules = (() => {
|
||||
const actions = rule.actions.map(a => {
|
||||
if (a.type === "ttl" || a.type === "grace") return `${actionLabel(a.type)} ${fmtDuration(a.seconds)}`;
|
||||
if (a.type === "strip_query") return `${actionLabel(a.type)}${a.params?.length ? `: ${a.params.join(", ")}` : ""}`;
|
||||
if (a.type === "set_header" || a.type === "default_header") return `${actionLabel(a.type)}: ${a.name || "-"}${a.value ? ` = ${a.value}` : ""}`;
|
||||
if (a.type === "remove_header" || a.type === "hash_header" || a.type === "hash_cookie") return `${actionLabel(a.type)}: ${a.name || "-"}`;
|
||||
if (a.type === "set_header" || a.type === "default_header" || a.type === "set_backend_header" || a.type === "set_request_header") return `${actionLabel(a.type)}: ${a.name || "-"}${a.value ? ` = ${a.value}` : ""}`;
|
||||
if (a.type === "remove_header" || a.type === "remove_backend_header" || a.type === "remove_request_header" || a.type === "hash_header" || a.type === "hash_cookie") return `${actionLabel(a.type)}: ${a.name || "-"}`;
|
||||
return actionLabel(a.type);
|
||||
});
|
||||
return actions.join(" · ");
|
||||
@@ -142,7 +168,8 @@ window.rustProxyCacheRules = (() => {
|
||||
tracking: () => [{ name: t("cacheRuleTplTracking"), stage: "request", match: "all", conditions: [], actions: [{ type: "strip_query", params: ["utm_*", "fbclid", "gclid", "msclkid", "mc_cid", "mc_eid", "_ga"] }] }],
|
||||
api: () => [{ name: t("cacheRuleTplApi"), stage: "request", match: "all", conditions: [{ field: "path", operator: "prefix", values: ["/api/"] }], actions: [{ type: "pass" }] }],
|
||||
language: () => [{ name: t("cacheRuleTplLanguage"), stage: "request", match: "all", conditions: [], actions: [{ type: "hash_cookie", name: "lang" }] }],
|
||||
notfound: () => [{ name: t("cacheRuleTplNotFound"), stage: "response", match: "all", conditions: [{ field: "status", operator: "equals", values: ["404"] }], actions: [{ type: "ttl", seconds: 60 }] }],
|
||||
// No negative-cache template: the storage layer currently stores 200 only.
|
||||
// A TTL rule matching 404 would appear enabled but could never yield HIT.
|
||||
headers: () => [{ name: t("cacheRuleTplHeaders"), stage: "deliver", match: "all", conditions: [], actions: [{ type: "remove_header", name: "X-Powered-By" }] }],
|
||||
browser: () => [{ name: t("cacheRuleTplBrowser"), stage: "deliver", match: "all", conditions: [{ field: "extension", operator: "equals", values: ["css", "js", "mjs", "png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico", "woff", "woff2"] }, { field: "status", operator: "equals", values: ["200"] }], actions: [{ type: "set_header", name: "Cache-Control", value: "public, max-age=2592000" }] }],
|
||||
nobrowser: () => [{ name: t("cacheRuleTplNoBrowser"), stage: "deliver", match: "any", conditions: [{ field: "content_type", operator: "prefix", values: ["text/html"] }, { field: "path", operator: "prefix", values: ["/admin", "/account"] }], actions: [{ type: "set_header", name: "Cache-Control", value: "no-store" }] }],
|
||||
@@ -160,7 +187,7 @@ window.rustProxyCacheRules = (() => {
|
||||
for (const global of globals) {
|
||||
if (global.stage !== local.stage) continue;
|
||||
const shared = [...aspects(normalize(global))].filter(aspect => mine.has(aspect));
|
||||
if (shared.length) notes.push(t("cacheRulesOverrideNotice").replace("{vhost}", local.name || local.id).replace("{global}", global.name || global.id).replace("{aspects}", shared.map(aspect => t(`cacheRuleAspect${aspect[0].toUpperCase()}${aspect.slice(1)}`)).join(", ")));
|
||||
if (shared.length) notes.push(t("cacheRulesOverrideNotice").replace("{vhost}", local.name || local.id).replace("{global}", global.name || global.id).replace("{aspects}", shared.map(aspect => ({ request_cookies: actionLabel("strip_cookies"), request_query: actionLabel("strip_query") })[aspect] || t(`cacheRuleAspect${aspect[0].toUpperCase()}${aspect.slice(1)}`)).join(", ")));
|
||||
}
|
||||
}
|
||||
return notes;
|
||||
@@ -221,7 +248,20 @@ window.rustProxyCacheRules = (() => {
|
||||
const root = el("div", undefined, `cache-rules cache-rules-${scope}`);
|
||||
const changed = () => { root.dispatchEvent(new Event("input", { bubbles: true })); options.onChange?.(); };
|
||||
const toolbar = el("div", undefined, "cache-rules-toolbar");
|
||||
if (scope === "vhost") { const docs = el("a", t("cacheRulesDocs"), "docs-link"); docs.href = "/docs#doc=docs%2FCACHE.md§ion=cache-rules-vcl-style"; docs.target = "_blank"; docs.rel = "noopener noreferrer"; root.append(docs); }
|
||||
if (scope === "vhost") {
|
||||
// Both ordinary vhost and Docker assignment editors use this component.
|
||||
// The shared guide opener is delegated in settings.js, so dynamic editors
|
||||
// receive the same modal without binding additional event handlers.
|
||||
const helpLinks = el("div", undefined, "cache-rules-vhost-links");
|
||||
const docs = el("a", t("cacheRulesDocs"), "docs-link");
|
||||
docs.href = "/docs#doc=docs%2FCACHE.md§ion=cache-rules-vcl-style";
|
||||
docs.target = "_blank";
|
||||
docs.rel = "noopener noreferrer";
|
||||
const guide = el("button", t("cacheGuideOpen"), "outline cache-guide-trigger");
|
||||
guide.type = "button";
|
||||
helpLinks.append(guide, docs);
|
||||
root.append(helpLinks);
|
||||
}
|
||||
const templates = select([["", t("cacheRulesTemplates")], ...Object.keys(TEMPLATES).map(key => [key, t(`cacheRuleTpl${key[0].toUpperCase()}${key.slice(1)}`)])], "", t("cacheRulesTemplates"));
|
||||
templates.classList.add("cache-rules-templates");
|
||||
const importButton = el("button", t("cacheRulesImportVcl"), "outline"); importButton.type = "button";
|
||||
@@ -236,9 +276,21 @@ window.rustProxyCacheRules = (() => {
|
||||
const importBox = el("div", undefined, "cache-rules-import"); importBox.hidden = true;
|
||||
const importText = document.createElement("textarea"); importText.rows = 10; importText.spellcheck = false; importText.placeholder = "sub vcl_recv {\n if (req.url ~ \"^/admin\") {\n return (pass);\n }\n}";
|
||||
const importRun = el("button", t("cacheRulesImportRun"), "primary"); importRun.type = "button";
|
||||
const importApply = el("button", t("cacheRulesImportApplyPartial"), "outline"); importApply.type = "button"; importApply.hidden = true;
|
||||
const importCancel = el("button", t("cancel"), "outline"); importCancel.type = "button";
|
||||
const importResult = el("div", undefined, "cache-rules-import-result");
|
||||
const importActions = el("div", undefined, "form-actions"); importActions.append(importRun, importCancel);
|
||||
const importActions = el("div", undefined, "form-actions"); importActions.append(importRun, importApply, importCancel);
|
||||
let pendingImport = null, importGeneration = 0;
|
||||
// Any edit/close/submit supersedes older in-flight API responses. An old
|
||||
// parse result must never mutate the editor after the user cancelled it.
|
||||
const resetImportPreview = () => {
|
||||
importGeneration++;
|
||||
pendingImport = null;
|
||||
importApply.hidden = true;
|
||||
importResult.replaceChildren();
|
||||
importRun.disabled = false;
|
||||
};
|
||||
importText.addEventListener("input", resetImportPreview);
|
||||
importBox.append(el("p", t("cacheRulesImportHelp"), "fine"), importText, importActions, importResult);
|
||||
const exportBox = el("details", undefined, "cache-rules-export"); const exportSummary = el("summary", t("cacheRulesVclPreview")); const exportPre = el("pre", "", "metrics-example mono cache-rules-vcl");
|
||||
exportBox.append(exportSummary, exportPre);
|
||||
@@ -312,7 +364,7 @@ window.rustProxyCacheRules = (() => {
|
||||
const id = textInput(rule.id, "", "mono"); id.maxLength = 64; id.pattern = "[A-Za-z0-9_\\-]{1,64}";
|
||||
id.addEventListener("change", () => { const value = id.value.trim(); if (!/^[A-Za-z0-9_-]{1,64}$/.test(value) || (value !== rule.id && taken().has(value))) { id.value = rule.id; toast(t("cacheRuleIdInvalid"), true); return; } open.delete(rule.id); rule.id = value; open.add(value); changed(); });
|
||||
const stage = select(STAGES.map(value => [value, t(STAGE_KEYS[value])]), rule.stage, t("cacheRuleStage"));
|
||||
stage.addEventListener("change", () => { rule.stage = stage.value; rule.actions = rule.actions.filter(a => ACTIONS[rule.stage].includes(a.type)); if (!rule.actions.length) rule.actions = [{ type: ACTIONS[rule.stage][0] }]; rule.conditions = rule.conditions.filter(c => FIELDS[c.field].stages.includes(rule.stage)); render(); changed(); });
|
||||
stage.addEventListener("change", () => { rule.stage = stage.value; if (rule.stage !== "request") rule.hash_stage = false; rule.actions = rule.actions.filter(a => ACTIONS[rule.stage].includes(a.type)); if (!rule.actions.length && !rule.stop) rule.actions = [{ type: ACTIONS[rule.stage][0] }]; rule.conditions = rule.conditions.filter(c => FIELDS[c.field].stages.includes(rule.stage)); render(); changed(); });
|
||||
const match = select([["all", t("cacheRuleMatchAll")], ["any", t("cacheRuleMatchAny")]], rule.match, t("cacheRuleMatch"));
|
||||
match.addEventListener("change", () => { rule.match = match.value; changed(); syncPreview(); });
|
||||
const stop = el("input", undefined, "switch"); stop.type = "checkbox"; stop.checked = rule.stop; stop.addEventListener("change", () => { rule.stop = stop.checked; changed(); });
|
||||
@@ -378,7 +430,7 @@ window.rustProxyCacheRules = (() => {
|
||||
const row = el("div", undefined, "cache-rule-row");
|
||||
const type = select(ACTIONS[rule.stage].map(value => [value, actionLabel(value)]), action.type, t("cacheRuleAction"));
|
||||
const params = el("span", undefined, "cache-rule-params");
|
||||
const remove = el("button", "×", "quiet"); remove.type = "button"; remove.setAttribute("aria-label", t("remove")); remove.disabled = rule.actions.length <= 1;
|
||||
const remove = el("button", "×", "quiet"); remove.type = "button"; remove.setAttribute("aria-label", t("remove")); remove.disabled = rule.actions.length <= 1 && !rule.stop;
|
||||
type.addEventListener("change", () => { rule.actions[index] = { type: type.value }; render(); changed(); });
|
||||
remove.addEventListener("click", () => { rule.actions.splice(index, 1); render(); changed(); });
|
||||
const listInput = (key, placeholder) => { const node = textInput((action[key] || []).join(", "), placeholder); node.addEventListener("input", () => { action[key] = splitList(node.value); changed(); }); return node; };
|
||||
@@ -393,6 +445,8 @@ window.rustProxyCacheRules = (() => {
|
||||
case "hash_header": params.append(nameInput("Accept-Language")); break;
|
||||
case "hash_cookie": params.append(nameInput("lang")); break;
|
||||
case "ttl": case "grace": params.append(durationInput(action.seconds ?? (action.type === "ttl" ? 3600 : 60), seconds => { action.seconds = seconds; changed(); })); if (action.seconds == null) action.seconds = action.type === "ttl" ? 3600 : 60; break;
|
||||
case "set_backend_header": case "set_request_header": { const value = textInput(action.value, t("cacheRuleHeaderValue")); value.addEventListener("input", () => { action.value = value.value; changed(); }); params.append(nameInput(action.type === "set_request_header" ? "X-Device" : "Cache-Control"), value); break; }
|
||||
case "remove_backend_header": case "remove_request_header": params.append(nameInput(action.type === "remove_request_header" ? "X-Tracking" : "Cache-Control")); break;
|
||||
case "set_header": { const value = textInput(action.value, t("cacheRuleHeaderValue")); value.addEventListener("input", () => { action.value = value.value; changed(); }); params.append(nameInput("X-Cache-Rule"), value); break; }
|
||||
case "default_header": { const value = textInput(action.value, t("cacheRuleHeaderValue")); value.addEventListener("input", () => { action.value = value.value; changed(); }); params.append(nameInput("Cache-Control"), value); break; }
|
||||
case "remove_header": params.append(nameInput("X-Powered-By")); break;
|
||||
@@ -404,33 +458,53 @@ window.rustProxyCacheRules = (() => {
|
||||
function buildTester() {
|
||||
const node = el("details", undefined, "cache-rules-tester");
|
||||
node.append(el("summary", t("cacheRulesTester")));
|
||||
const grid = el("div", undefined, "cache-rules-tester-grid");
|
||||
const bodyWrap = el("div", undefined, "cache-rules-tester-body");
|
||||
const sections = el("div", undefined, "cache-rules-tester-sections");
|
||||
const requestPane = el("section", undefined, "cache-rules-tester-pane");
|
||||
requestPane.append(el("h4", t("cacheRulesTesterRequestTitle"), "cache-rules-tester-heading"));
|
||||
const requestGrid = el("div", undefined, "cache-rules-tester-grid cache-rules-tester-request-grid");
|
||||
const method = select(["GET", "HEAD", "POST"].map(value => [value, value]), "GET", t("cacheRuleFieldMethod"));
|
||||
const url = textInput("", scope === "vhost" ? "/produkt?id=7&utm_source=fb" : "https://shop.example.com/produkt?id=7&utm_source=fb", "mono");
|
||||
const vhostSelect = select([["", t("cacheRulesTesterNoVhost")], ...targetList().map(target => [target.id, targetTitle(target)])], vhostId, t("cacheRulesTesterVhost"));
|
||||
if (scope === "global") document.addEventListener("rustproxy-cache-targets", () => {
|
||||
if (!root.isConnected) return;
|
||||
const current = vhostSelect.value;
|
||||
vhostSelect.replaceChildren(...[["", t("cacheRulesTesterNoVhost")], ...targetList().map(target => [target.id, targetTitle(target)])].map(([value, text]) => { const option = el("option", text); option.value = value; return option; }));
|
||||
vhostSelect.value = [...vhostSelect.options].some(option => option.value === current) ? current : "";
|
||||
});
|
||||
const headers = document.createElement("textarea"); headers.rows = 3; headers.placeholder = "Cookie: lang=pl; sid=1\nAccept-Language: pl"; headers.spellcheck = false;
|
||||
const headers = document.createElement("textarea"); headers.rows = 2; headers.placeholder = "Cookie: lang=pl; sid=1\nAccept-Language: pl"; headers.spellcheck = false;
|
||||
const clientIp = textInput("", "203.0.113.10", "mono");
|
||||
const status = el("input"); status.type = "number"; status.min = 100; status.max = 599; status.value = 200;
|
||||
const responseHeaders = document.createElement("textarea"); responseHeaders.rows = 3; responseHeaders.placeholder = "Cache-Control: public, max-age=60\nContent-Type: text/html"; responseHeaders.spellcheck = false;
|
||||
const responseHeaders = document.createElement("textarea"); responseHeaders.rows = 2; responseHeaders.placeholder = "Cache-Control: public, max-age=60\nContent-Type: text/html"; responseHeaders.spellcheck = false;
|
||||
const run = el("button", t("cacheRulesTesterRun"), "primary"); run.type = "button";
|
||||
const result = el("div", undefined, "cache-rules-tester-result");
|
||||
const field = (key, control) => { const label = el("label", undefined, "cache-rule-field"); label.append(el("span", t(key)), control); return label; };
|
||||
grid.append(field("cacheRuleFieldMethod", method), field("cacheRulesTesterUrl", url));
|
||||
if (scope === "global") grid.append(field("cacheRulesTesterVhost", vhostSelect));
|
||||
grid.append(field("cacheRulesTesterHeaders", headers), field("cacheRuleFieldClientIp", clientIp), field("cacheRuleFieldStatus", status), field("cacheRulesTesterResponseHeaders", responseHeaders));
|
||||
const result = el("div", undefined, "cache-rules-tester-result"); result.setAttribute("aria-live", "polite");
|
||||
const field = (key, control, cls) => { const label = el("label", undefined, `cache-rule-field ${cls}`); label.append(el("span", t(key)), control); return label; };
|
||||
requestGrid.append(field("cacheRuleFieldMethod", method, "is-method"), field("cacheRulesTesterUrl", url, "is-url"));
|
||||
if (scope === "global") requestGrid.append(field("cacheRulesTesterVhost", vhostSelect, "is-vhost"));
|
||||
requestGrid.append(field("cacheRuleFieldClientIp", clientIp, "is-ip"), field("cacheRulesTesterHeaders", headers, "is-headers"));
|
||||
requestPane.append(requestGrid);
|
||||
const responsePane = el("section", undefined, "cache-rules-tester-pane");
|
||||
responsePane.append(el("h4", t("cacheRulesTesterResponseTitle"), "cache-rules-tester-heading"));
|
||||
const responseGrid = el("div", undefined, "cache-rules-tester-grid cache-rules-tester-response-grid");
|
||||
responseGrid.append(field("cacheRuleFieldStatus", status, "is-status"), field("cacheRulesTesterResponseHeaders", responseHeaders, "is-response-headers"));
|
||||
responsePane.append(responseGrid);
|
||||
sections.append(requestPane, responsePane);
|
||||
const pairs = text => String(text || "").split(/\r?\n/).map(line => line.trim()).filter(Boolean).map(line => { const at = line.indexOf(":"); return at > 0 ? [line.slice(0, at).trim(), line.slice(at + 1).trim()] : [line, ""]; });
|
||||
run.addEventListener("click", async () => {
|
||||
run.disabled = true; result.replaceChildren(el("p", t("cacheRulesTesterRunning"), "fine"));
|
||||
try {
|
||||
const body = { request: { method: method.value, url: url.value.trim(), headers: pairs(headers.value), client_ip: clientIp.value.trim() || null }, response: { status: Number(status.value) || 200, headers: pairs(responseHeaders.value) } };
|
||||
if (scope === "global") { body.global_rules = read(); body.vhost_id = vhostSelect.value || null; }
|
||||
else { body.vhost_id = vhostId || null; body.vhost_rules = read(); body.ignore_global_rules = ignoreGlobal; if (!vhostId) body.vhost_id = null; }
|
||||
renderResult(await api("/api/cache/rules/test", { method: "POST", body: JSON.stringify(body) }));
|
||||
const requestHeaders = pairs(headers.value);
|
||||
// A draft/new vhost has no stored frontend.hosts entry yet. With a
|
||||
// path-only test use its current editor hostname, not an empty Host,
|
||||
// so global host conditions are evaluated consistently.
|
||||
if (scope === "vhost" && url.value.trim().startsWith("/") && !requestHeaders.some(([name]) => name.toLowerCase() === "host")) {
|
||||
const host = String(typeof options.testHost === "function" ? options.testHost() || "" : "").trim();
|
||||
if (host && !host.startsWith("*.")) requestHeaders.push(["Host", host]);
|
||||
}
|
||||
const payload = { request: { method: method.value, url: url.value.trim(), headers: requestHeaders, client_ip: clientIp.value.trim() || null }, response: { status: Number(status.value) || 200, headers: pairs(responseHeaders.value) } };
|
||||
if (scope === "global") { payload.global_rules = read(); payload.vhost_id = vhostSelect.value || null; }
|
||||
else { payload.vhost_id = vhostId || null; payload.vhost_rules = read(); payload.ignore_global_rules = ignoreGlobal; }
|
||||
renderResult(await api("/api/cache/rules/test", { method: "POST", body: JSON.stringify(payload) }));
|
||||
} catch (error) { result.replaceChildren(el("p", error.message, "fine is-error")); }
|
||||
finally { run.disabled = false; }
|
||||
});
|
||||
@@ -441,6 +515,7 @@ window.rustProxyCacheRules = (() => {
|
||||
const request = data.request || {};
|
||||
line(t("cacheRulesResultDecision"), request.cacheable ? (data.response?.stored ? t("cacheRulesResultHit").replace("{ttl}", fmtDuration(data.response.ttl)).replace("{grace}", fmtDuration(data.response.grace)) : t("cacheRulesResultNotStored").replace("{reason}", data.response?.reason || "-")) : t("cacheRulesResultPass").replace("{reason}", request.reason || "-"), request.cacheable && data.response?.stored ? "is-ok" : "is-warn");
|
||||
line(t("cacheRulesResultRequest"), names(request.matched));
|
||||
if (request.header_edits?.length) line(t("cacheRulesResultRequestHeaders"), request.header_edits.map(edit => edit.type === "set" ? `${edit.name}: ${edit.value}` : `−${edit.name}`).join(", "));
|
||||
line(t("cacheRulesResultKey"), `${data.host || "-"}${request.target || ""}${request.variant?.length ? ` + ${request.variant.join(", ")}` : ""}`);
|
||||
if (request.cookie != null) line(t("cacheRulesResultCookie"), request.cookie || "—");
|
||||
if (data.response) line(t("cacheRulesResultResponse"), names(data.response.matched));
|
||||
@@ -448,8 +523,10 @@ window.rustProxyCacheRules = (() => {
|
||||
for (const item of [...(request.overridden || []), ...(data.response?.overridden || [])]) line(t("cacheRulesResultOverridden"), t("cacheRulesResultOverriddenText").replace("{winner}", item.winner).replace("{ignored}", item.ignored).replace("{aspect}", t(`cacheRuleAspect${item.aspect[0].toUpperCase()}${item.aspect.slice(1)}`)), "is-warn");
|
||||
result.replaceChildren(...items);
|
||||
}
|
||||
const actions = el("div", undefined, "form-actions"); actions.append(run);
|
||||
node.append(el("p", t("cacheRulesTesterHelp"), "fine"), grid, actions, result);
|
||||
const footer = el("div", undefined, "cache-rules-tester-footer");
|
||||
footer.append(el("p", t(scope === "global" ? "cacheRulesTesterHelpGlobal" : "cacheRulesTesterHelpVhost"), "fine"), run);
|
||||
bodyWrap.append(sections, footer, result);
|
||||
node.append(bodyWrap);
|
||||
return { node };
|
||||
}
|
||||
function addRules(items) {
|
||||
@@ -464,28 +541,56 @@ window.rustProxyCacheRules = (() => {
|
||||
}
|
||||
templates.addEventListener("change", () => { const make = TEMPLATES[templates.value]; templates.value = ""; if (!make) return; const added = addRules(make()); if (added) toast(t("cacheRulesTemplateAdded").replace("{count}", added)); });
|
||||
addButton.addEventListener("click", () => { const rule = blankRule(taken()); rules.push(rule); open.add(rule.id); render(); changed(); list.lastElementChild?.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); });
|
||||
importButton.addEventListener("click", () => { importBox.hidden = !importBox.hidden; if (!importBox.hidden) importText.focus(); });
|
||||
importCancel.addEventListener("click", () => { importBox.hidden = true; importResult.replaceChildren(); });
|
||||
importButton.addEventListener("click", () => { importBox.hidden = !importBox.hidden; if (importBox.hidden) resetImportPreview(); else importText.focus(); });
|
||||
importCancel.addEventListener("click", () => { importBox.hidden = true; resetImportPreview(); });
|
||||
importRun.addEventListener("click", async () => {
|
||||
importRun.disabled = true; importResult.replaceChildren();
|
||||
resetImportPreview();
|
||||
const generation = importGeneration;
|
||||
importRun.disabled = true;
|
||||
const source = importText.value;
|
||||
try {
|
||||
const data = await api("/api/cache/rules/import-vcl", { method: "POST", body: JSON.stringify({ vcl: importText.value }) });
|
||||
const data = await api("/api/cache/rules/import-vcl", { method: "POST", body: JSON.stringify({ vcl: source }) });
|
||||
// The user must opt into a partial/approximated import after seeing
|
||||
// warnings. Previously incomplete VCL was added before any warning was shown.
|
||||
if (generation !== importGeneration || importText.value !== source || importBox.hidden) return;
|
||||
if (data.warnings?.length) {
|
||||
const list = el("ul", undefined, "cache-rules-warnings");
|
||||
for (const warning of data.warnings) list.append(el("li", warning));
|
||||
importResult.append(el("p", t("cacheRulesImportWarnings"), "fine is-warn"), list);
|
||||
if (data.rules?.length) {
|
||||
pendingImport = data.rules;
|
||||
importApply.hidden = false;
|
||||
importResult.append(el("p", t("cacheRulesImportPending").replace("{count}", data.rules.length), "fine"));
|
||||
} else {
|
||||
importResult.append(el("p", t("cacheRulesImportNoActions"), "fine"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const added = addRules(data.rules || []);
|
||||
importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok"));
|
||||
if (data.warnings?.length) { const list = el("ul", undefined, "cache-rules-warnings"); for (const warning of data.warnings) list.append(el("li", warning)); importResult.append(el("p", t("cacheRulesImportWarnings"), "fine"), list); }
|
||||
} catch (error) { importResult.append(el("p", error.message, "fine is-error")); }
|
||||
finally { importRun.disabled = false; }
|
||||
importResult.append(el("p", added ? t("cacheRulesImportDone").replace("{count}", added) : t("cacheRulesImportNoActions"), "fine is-ok"));
|
||||
} catch (error) {
|
||||
if (generation === importGeneration && !importBox.hidden)
|
||||
importResult.append(el("p", error.message, "fine is-error"));
|
||||
} finally {
|
||||
if (generation === importGeneration) importRun.disabled = false;
|
||||
}
|
||||
});
|
||||
importApply.addEventListener("click", () => {
|
||||
if (!pendingImport) return;
|
||||
const added = addRules(pendingImport);
|
||||
resetImportPreview();
|
||||
importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok"));
|
||||
});
|
||||
exportButton.addEventListener("click", async () => { exportBox.open = true; exportBox.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); try { await navigator.clipboard.writeText(exportPre.textContent); toast(t("copied")); } catch { } });
|
||||
ignoreBox.addEventListener("change", () => { ignoreGlobal = ignoreBox.checked; renderNotices(); changed(); });
|
||||
function read() {
|
||||
for (const rule of rules) {
|
||||
if (!rule.actions.length) throw new Error(t("cacheRuleNeedsAction").replace("{rule}", rule.name || rule.id));
|
||||
if (!rule.actions.length && !rule.stop) throw new Error(t("cacheRuleNeedsAction").replace("{rule}", rule.name || rule.id));
|
||||
for (const c of rule.conditions) {
|
||||
if (FIELDS[c.field].name && !c.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
|
||||
if (c.operator !== "exists" && !(c.values || []).length) throw new Error(t("cacheRuleNeedsValue").replace("{rule}", rule.name || rule.id));
|
||||
}
|
||||
for (const a of rule.actions) if (["hash_header", "hash_cookie", "set_header", "default_header", "remove_header"].includes(a.type) && !a.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
|
||||
for (const a of rule.actions) if (["hash_header", "hash_cookie", "set_request_header", "remove_request_header", "set_backend_header", "remove_backend_header", "set_header", "default_header", "remove_header"].includes(a.type) && !a.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
|
||||
}
|
||||
return rules.map(rule => clean(rule, scope === "global"));
|
||||
}
|
||||
|
||||
@@ -102,18 +102,18 @@
|
||||
rows as a subgrid, so a caption that wraps to more lines makes the whole
|
||||
caption row taller and every control in the row still starts on the same
|
||||
line. Multi-line text areas take the whole row instead of a narrow column. */
|
||||
:is(.vh-grid>.vh-field, .cache-rules-tester-grid>.cache-rule-field, .field-grid>label:not([class])) {
|
||||
:is(.vh-grid>.vh-field, .field-grid>label:not([class])) {
|
||||
grid-row: span 2;
|
||||
}
|
||||
|
||||
:is(.vh-grid>.vh-field, .cache-rules-tester-grid>.cache-rule-field, .field-grid>label:not([class])):has(>:nth-child(2):last-child) {
|
||||
:is(.vh-grid>.vh-field, .field-grid>label:not([class])):has(>:nth-child(2):last-child) {
|
||||
display: grid;
|
||||
grid-template-rows: subgrid;
|
||||
row-gap: 4px;
|
||||
align-content: start;
|
||||
}
|
||||
|
||||
:is(.vh-grid>.vh-field, .cache-rules-tester-grid>.cache-rule-field, .field-grid>label:not([class])):has(>:nth-child(2):last-child)>:first-child {
|
||||
:is(.vh-grid>.vh-field, .field-grid>label:not([class])):has(>:nth-child(2):last-child)>:first-child {
|
||||
align-self: end;
|
||||
}
|
||||
|
||||
|
||||
@@ -2700,35 +2700,184 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* Shared compact rule tester (global Cache, Vhosts and Docker vhosts).
|
||||
Keep controls aligned without the vhost editor's two-row subgrid. */
|
||||
.cache-rules-vhost-links {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 14px;
|
||||
}
|
||||
|
||||
.cache-rules-vhost-links>.cache-guide-trigger {
|
||||
width: auto;
|
||||
min-height: 30px;
|
||||
padding: 5px 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.cache-rules-tester {
|
||||
padding: 10px 12px;
|
||||
width: 100%;
|
||||
max-width: 1120px;
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--rp-radius-surface, 0px);
|
||||
container-type: inline-size;
|
||||
}
|
||||
|
||||
.cache-rules-tester>summary {
|
||||
padding: 9px 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.cache-rules-tester[open]>summary {
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.cache-rules-tester-body {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
padding: 11px 12px 12px;
|
||||
}
|
||||
|
||||
.cache-rules-tester-sections {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 390px), 1fr));
|
||||
gap: 10px;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.cache-rules-tester-pane {
|
||||
min-width: 0;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--rp-radius-surface, 0px);
|
||||
background: var(--panel2);
|
||||
}
|
||||
|
||||
.cache-rules-tester-heading {
|
||||
margin: 0 0 8px;
|
||||
font-size: 11px;
|
||||
letter-spacing: .05em;
|
||||
text-transform: uppercase;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.cache-rules-tester-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
gap: 10px 14px;
|
||||
margin-top: 8px;
|
||||
grid-template-columns: minmax(100px, .65fr) repeat(2, minmax(0, 1fr));
|
||||
gap: 8px 10px;
|
||||
margin: 0;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.cache-rules-tester-grid>.cache-rule-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
grid-row: auto;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.cache-rules-tester-grid>.cache-rule-field>span {
|
||||
display: block;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.cache-rules-tester-grid :is(input, select, textarea) {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
margin: 0;
|
||||
padding: 6px 8px;
|
||||
box-sizing: border-box;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.cache-rules-tester-grid :is(input, select) {
|
||||
height: 34px;
|
||||
min-height: 34px;
|
||||
}
|
||||
|
||||
.cache-rules-tester-grid textarea {
|
||||
min-height: 52px;
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
line-height: 1.35;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.cache-rules-tester-request-grid>.is-url,
|
||||
.cache-rules-tester-request-grid>.is-vhost {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
.cache-rules-tester-request-grid>.is-headers {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.cache-rules-tester-response-grid {
|
||||
grid-template-columns: 110px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.cache-rules-tester-footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px 12px;
|
||||
}
|
||||
|
||||
.cache-rules-tester-footer>.fine {
|
||||
flex: 1 1 370px;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
font-size: 11px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.cache-rules-tester-footer>button {
|
||||
flex: 0 0 auto;
|
||||
width: auto;
|
||||
min-height: 32px;
|
||||
padding: 6px 13px;
|
||||
}
|
||||
|
||||
.cache-rules-tester-result {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
margin-top: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cache-rules-tester-result:empty { display: none; }
|
||||
|
||||
.cache-rules-result-line {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(140px, 200px) minmax(0, 1fr);
|
||||
gap: 10px;
|
||||
grid-template-columns: minmax(120px, 190px) minmax(0, 1fr);
|
||||
gap: 8px 10px;
|
||||
padding: 6px 9px;
|
||||
border: 1px solid var(--line);
|
||||
overflow-wrap: anywhere;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.cache-rules-result-line>strong { min-width: 0; }
|
||||
|
||||
@container (max-width: 550px) {
|
||||
.cache-rules-tester-body { padding: 9px; }
|
||||
.cache-rules-tester-pane { padding: 9px; }
|
||||
.cache-rules-tester-request-grid { grid-template-columns: minmax(105px, 1fr) minmax(0, 1fr); }
|
||||
.cache-rules-tester-request-grid>.is-url,
|
||||
.cache-rules-tester-request-grid>.is-vhost { grid-column: 1 / -1; }
|
||||
.cache-rules-tester-request-grid>.is-ip { grid-column: span 1; }
|
||||
.cache-rules-tester-response-grid { grid-template-columns: minmax(0, 1fr); }
|
||||
.cache-rules-tester-response-grid>.is-status { max-width: 170px; }
|
||||
.cache-rules-tester-response-grid>.is-response-headers { grid-column: 1 / -1; }
|
||||
.cache-rules-result-line { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
||||
}
|
||||
|
||||
.cache-rules-result-line.is-ok>strong {
|
||||
@@ -3404,3 +3553,71 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
/* Contextual cache / VCL help in Settings -> Cache. */
|
||||
.cache-guide-heading-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-left: auto;
|
||||
}
|
||||
#cache-form .cache-guide-trigger { width: auto; }
|
||||
#cache-form [data-cache-settings-page=rules]>.cache-guide-trigger { margin-left: 10px; }
|
||||
.cache-vcl-guide-dialog {
|
||||
width: calc(min(980px, 100vw - 24px) / var(--ui-scale, 1));
|
||||
max-height: calc((100dvh - 28px) / var(--ui-scale, 1));
|
||||
overflow: hidden;
|
||||
}
|
||||
.cache-guide-dialog-heading { justify-content: space-between; }
|
||||
.cache-guide-dialog-heading h2 { margin: 3px 0 0; }
|
||||
.cache-guide-content {
|
||||
overflow-y: auto;
|
||||
max-height: calc((100dvh - 110px) / var(--ui-scale, 1));
|
||||
padding: 14px;
|
||||
}
|
||||
.cache-guide-content>.fine { margin: 0 0 12px; }
|
||||
.cache-guide-current {
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel2);
|
||||
padding: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.cache-guide-current-pills { display: flex; flex-wrap: wrap; gap: 7px; margin-bottom: 8px; }
|
||||
.cache-guide-current p { margin: 5px 0 0; }
|
||||
.cache-guide-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
align-items: stretch;
|
||||
gap: 10px;
|
||||
}
|
||||
.cache-guide-card {
|
||||
min-width: 0;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel);
|
||||
padding: 13px;
|
||||
}
|
||||
.cache-guide-card h3 { margin: 0 0 8px; font-size: 14px; }
|
||||
.cache-guide-card p { font-size: 12px; line-height: 1.55; margin: 0; }
|
||||
.cache-guide-card p+p { margin-top: 9px; }
|
||||
.cache-guide-card pre {
|
||||
margin: 9px 0;
|
||||
padding: 10px;
|
||||
max-width: 100%;
|
||||
overflow: auto;
|
||||
color: var(--text);
|
||||
background: var(--panel2);
|
||||
border: 1px solid var(--line);
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
tab-size: 2;
|
||||
}
|
||||
.cache-guide-card pre code { white-space: pre; }
|
||||
.cache-guide-import-example { margin-top: 4px; width: auto; }
|
||||
.cache-guide-footer { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; margin-top: 13px; }
|
||||
.cache-guide-footer>.fine { flex: 1 1 100%; margin: 0; }
|
||||
@media (max-width: 720px) {
|
||||
.cache-guide-grid { grid-template-columns: minmax(0, 1fr); }
|
||||
.cache-guide-content { padding: 10px; }
|
||||
.cache-guide-card { padding: 11px; }
|
||||
}
|
||||
@@ -758,13 +758,13 @@
|
||||
if (!picked.length) return { acl_profile_ids: [], inherit_acl_profiles: !inherited.length };
|
||||
return { acl_profile_ids: picked, inherit_acl_profiles: true };
|
||||
}
|
||||
function cacheEditor(assignment, agent, key, enabled) {
|
||||
function cacheEditor(assignment, agent, key, enabled, testHost) {
|
||||
const details = el("details", undefined, "docker-cache-editor"), summary = el("summary"); summary.append(el("span", t("dockerCacheSettings")), el("small", t("dockerCacheSettingsHelp"), "fine")); details.append(summary);
|
||||
const grid = el("div", undefined, "field-grid docker-cache-grid");
|
||||
const ttl = input(assignment?.cache_default_ttl_seconds ?? "", "number", "docker-cache-ttl"); ttl.min = 0; ttl.max = 31536000; ttl.placeholder = String(envelope?.config?.cache?.default_ttl_seconds ?? "");
|
||||
grid.append(labeled("dockerCacheTtl", ttl, t("dockerCacheTtlHelp")));
|
||||
const vhostId = poolRoutes.find(item => item.agent_id === agent.id && item.service_key === key)?.pool_id || "";
|
||||
const rules = window.rustProxyCacheRules?.create?.({ scope: "vhost", vhostId, rules: assignment?.cache_rules || [], ignoreGlobal: assignment?.cache_ignore_global_rules === true, ignoreId: "", autoLoadHits: false });
|
||||
const rules = window.rustProxyCacheRules?.create?.({ scope: "vhost", vhostId, rules: assignment?.cache_rules || [], ignoreGlobal: assignment?.cache_ignore_global_rules === true, ignoreId: "", autoLoadHits: false, testHost });
|
||||
if (rules?.node) { rules.node.classList.add("docker-cache-rules"); details._rules = rules; }
|
||||
details.append(grid); if (rules?.node) details.append(rules.node);
|
||||
details.addEventListener("toggle", () => { if (details.open && !details.hidden) void rules?.refreshHits?.(); });
|
||||
@@ -1063,7 +1063,7 @@
|
||||
protocolOptions.append(h1, checkboxField("dockerHttp2Enabled", h2Enabled), checkboxField("dockerHttp3Enabled", h3Enabled));
|
||||
protocolBox.append(protocolSummary, protocolOptions);
|
||||
route.append(hostField, aliases.node, backendIpSettings, labeled("dockerBackendScheme", scheme), switches); syncHostHelp();
|
||||
editor.append(route, protocolBox, aclEditor(assignment, agent), securityEditor(assignment), cacheEditor(assignment, agent, key, cacheEnabled), diagnosticsEditor(assignment), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment));
|
||||
editor.append(route, protocolBox, aclEditor(assignment, agent), securityEditor(assignment), cacheEditor(assignment, agent, key, cacheEnabled, () => expandedHost(host.value.trim() || technical, domainSelect.value)), diagnosticsEditor(assignment), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment));
|
||||
const actions = el("div", undefined, "docker-service-actions"); apply = el("button", t("dockerApplyService"), "outline docker-apply"); apply.type = "button"; apply.disabled = !publish.checked; apply.addEventListener("click", async () => { apply.disabled = true; try { await saveAssignment(agent.id, row, true); } catch (error) { toast(error.message, true); } finally { if (row.isConnected) apply.disabled = !publish.checked; } }); actions.append(apply); editor.append(actions);
|
||||
function updateHint() { syncCertificateHint(); editorHint.textContent = hintFor({ hostname: host.value.trim(), domain: domainSelect.value, targetLabel: target.selectedOptions?.[0]?.textContent || t("dockerBackendIpAuto"), scheme: scheme.value, h2: h2Enabled.checked, h3: h3Enabled.checked, aliasCount: aliases.count() }); } updateHint();
|
||||
for (const control of [host, aliases.input, target, scheme]) { control.addEventListener("input", updateHint); control.addEventListener("change", updateHint); }
|
||||
|
||||
+138
-14
@@ -2739,8 +2739,12 @@
|
||||
hidden="" id="settings-page-cache" role="tabpanel">
|
||||
<form class="card edit-form" id="cache-form">
|
||||
<div class="card-heading">
|
||||
<h2 data-i18n="cacheSettings">Cache</h2><span class="pill live"
|
||||
data-i18n="hotApply">LIVE APPLY</span>
|
||||
<h2 data-i18n="cacheSettings">Cache</h2>
|
||||
<div class="cache-guide-heading-actions">
|
||||
<button class="outline cache-guide-trigger" type="button"
|
||||
data-i18n="cacheGuideOpen">Cache & VCL guide</button>
|
||||
<span class="pill live" data-i18n="hotApply">LIVE APPLY</span>
|
||||
</div>
|
||||
</div>
|
||||
<nav aria-label="Cache settings" class="settings-tabs sub-tabs" id="cache-settings-tabs"
|
||||
role="tablist">
|
||||
@@ -2761,6 +2765,8 @@
|
||||
href="/docs#doc=docs%2FCACHE.md&section=cache-rules-vcl-style"
|
||||
target="_blank" rel="noopener noreferrer" data-i18n="cacheRulesDocs">Cache rules
|
||||
documentation</a>
|
||||
<button class="outline cache-guide-trigger" type="button"
|
||||
data-i18n="cacheGuideOpen">Cache & VCL guide</button>
|
||||
<div id="cache-rules-root"></div>
|
||||
</div>
|
||||
<div data-cache-settings-page="general">
|
||||
@@ -2768,10 +2774,10 @@
|
||||
</h3>
|
||||
<label class="check"><input class="switch" id="cache-enabled" type="checkbox" /><span
|
||||
data-i18n="enableCache">Enable shared cache</span></label>
|
||||
<p class="fine" data-i18n="cacheSafety">Only complete public-safe GET responses.
|
||||
Authorization, cookies and private/no-store responses still bypass the cache.
|
||||
One byte range can be served from a complete cached object;
|
||||
multipart/unsupported ranges pass through.</p>
|
||||
<p class="fine" data-i18n="cacheSafety">Only eligible GET/HEAD responses.
|
||||
Authorization and private/no-store responses bypass storage. Cookies normally
|
||||
bypass unless an eligible compatible VCL rule explicitly opts in. A single range
|
||||
may use a complete cached object; unsupported ranges bypass.</p>
|
||||
<div class="cache-varnish-setting">
|
||||
<label class="check"><input class="switch" id="cache-varnish-compatible"
|
||||
type="checkbox" /><span
|
||||
@@ -2790,12 +2796,15 @@
|
||||
during grace); existing cookie rules, Authorization, Vary,
|
||||
PURGE/BAN, HOT/COLD and transformations stay active.</p>
|
||||
<p class="fine" data-i18n="cacheVarnishCompatibleBackendHelp">Origin
|
||||
no-cache with a validator remains revalidatable. If an explicit
|
||||
fallback TTL is set, public no-cache responses may instead be reused
|
||||
for that TTL, even without a validator. Private/no-store/Set-Cookie
|
||||
and Surrogate-Control: no-store remain blocked. Zero-TTL objects may
|
||||
be retained for stale-if-error or revalidation; explicit
|
||||
stale-while-revalidate=0 is respected.</p>
|
||||
no-cache with ETag/Last-Modified remains revalidatable. With a
|
||||
positive fallback TTL, compatible mode can cache eligible no-cache
|
||||
responses even without public or a validator. Private, no-store,
|
||||
Set-Cookie and Surrogate-Control: no-store remain blocked.
|
||||
This is a configured override, not vanilla Varnish behavior.</p>
|
||||
<p class="fine" data-i18n="cacheVarnishCompatibleVclHelp">Use
|
||||
return(pass) for session cookies before return(hash) for selected
|
||||
public routes. In Rules, the Cache & VCL guide explains Vary,
|
||||
header edits and importer limits. Per-vhost overrides take precedence.</p>
|
||||
<p class="fine" data-i18n="cacheVarnishCompatibleModeHelp">Implicit
|
||||
grace (60 seconds by default, configurable below) only applies to
|
||||
eligible fresh-at-storage responses without an explicit
|
||||
@@ -2811,8 +2820,7 @@
|
||||
<input id="cache-varnish-grace" type="number" min="0" max="604800" step="1"
|
||||
required />
|
||||
</div>
|
||||
<label data-i18n="cacheDefaultTtl" for="cache-default-ttl">Fallback TTL for public
|
||||
responses (0 = off)</label><input id="cache-default-ttl" max="604800" min="0"
|
||||
<label data-i18n="cacheDefaultTtl" for="cache-default-ttl">Fallback TTL (seconds): public, or headerless/no-cache in compatibility mode (0 = off)</label><input id="cache-default-ttl" max="604800" min="0"
|
||||
required="" type="number" />
|
||||
<label class="check"><input class="switch" id="cache-query" type="checkbox" /><span
|
||||
data-i18n="bypassQuery">Bypass URLs with a query string</span></label>
|
||||
@@ -4126,6 +4134,122 @@
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
<dialog aria-labelledby="cache-vcl-guide-title" aria-modal="true"
|
||||
class="vhost-dialog cache-vcl-guide-dialog" id="cache-vcl-guide-dialog">
|
||||
<div class="window-heading cache-guide-dialog-heading">
|
||||
<div>
|
||||
<span class="small-label" data-i18n="cacheGuideEyebrow">CACHE SETTINGS · VCL SUBSET</span>
|
||||
<h2 data-i18n="cacheGuideTitle" id="cache-vcl-guide-title">Practical cache & VCL guide</h2>
|
||||
</div>
|
||||
<button class="outline" data-i18n="close" id="cache-vcl-guide-close" type="button">Close</button>
|
||||
</div>
|
||||
<div class="cache-guide-content">
|
||||
<p class="fine" data-i18n="cacheGuideIntro">Practical notes for RustProxy, not a promise of complete Varnish VCL compatibility. Only imported and accepted rules are executed.</p>
|
||||
<div class="cache-guide-current" role="status" aria-live="polite">
|
||||
<div class="cache-guide-current-pills">
|
||||
<span class="pill" id="cache-guide-mode"></span>
|
||||
<span class="pill" id="cache-guide-ttl"></span>
|
||||
<span class="pill" id="cache-guide-grace"></span>
|
||||
<span class="pill" id="cache-guide-context"></span>
|
||||
</div>
|
||||
<p class="fine" id="cache-guide-current-note"></p>
|
||||
<p class="fine" id="cache-guide-scope-note"></p>
|
||||
<p class="fine" data-i18n="cacheGuideUnsaved">Values reflect the current form, which may contain unsaved changes.</p>
|
||||
</div>
|
||||
<div class="cache-guide-grid">
|
||||
<section class="cache-guide-card">
|
||||
<h3 data-i18n="cacheGuideFreshnessTitle">no-cache, TTL and grace</h3>
|
||||
<p data-i18n="cacheGuideFreshnessText">With Varnish compatibility and a positive fallback TTL, an eligible Cache-Control: no-cache response can be served as HIT for that TTL without public. With compatibility off, no-cache requires validation before reuse. Grace is a separate stale-response window, not a fallback TTL.</p>
|
||||
<pre><code>Cache-Control: no-cache
|
||||
Fallback TTL: 60 s
|
||||
Varnish-compatible: ON</code></pre>
|
||||
<p class="fine" data-i18n="cacheGuideFreshnessWarning">Do not expect a HIT for private/no-store/Set-Cookie or when the request is BYPASS. This override is not the default Varnish VCL behavior.</p>
|
||||
</section>
|
||||
<section class="cache-guide-card">
|
||||
<h3 data-i18n="cacheGuideCookieTitle">Cookie and return(hash)</h3>
|
||||
<p data-i18n="cacheGuideCookieText">Cookies normally trigger BYPASS. In compatible mode, an explicit return(hash) can admit eligible Cookie requests; the full Cookie remains on the backend request and partitions the cache. Catch session cookies with return(pass) first.</p>
|
||||
<pre><code>sub vcl_recv {
|
||||
if (req.http.Cookie ~ "session=") {
|
||||
return (pass);
|
||||
}
|
||||
if (req.url ~ "^/public/") {
|
||||
return (hash);
|
||||
}
|
||||
}</code></pre>
|
||||
<button class="outline cache-guide-import-example" type="button"
|
||||
data-i18n="cacheGuideInsert">Insert into VCL importer</button>
|
||||
<p class="fine" data-i18n="cacheGuideCookieWarning">unset req.http.Cookie removes ALL cookies, including from the request sent to the backend. Authorization and authentication protections still apply.</p>
|
||||
</section>
|
||||
<section class="cache-guide-card">
|
||||
<h3 data-i18n="cacheGuideVaryTitle">Vary and cache variants</h3>
|
||||
<p data-i18n="cacheGuideVaryText">set/unset beresp.http.Vary changes variant selection before storing. set/unset resp.http.Vary only changes what the client sees; it does not repair the stored cache key. An assignment replaces the whole Vary list.</p>
|
||||
<pre><code>sub vcl_backend_response {
|
||||
set beresp.http.Vary =
|
||||
"Accept-Encoding, Accept-Language";
|
||||
}
|
||||
sub vcl_deliver {
|
||||
unset resp.http.X-Powered-By;
|
||||
}</code></pre>
|
||||
<button class="outline cache-guide-import-example" type="button"
|
||||
data-i18n="cacheGuideInsert">Insert into VCL importer</button>
|
||||
<p class="fine" data-i18n="cacheGuideVaryWarning">Never remove a required Vary dimension for a personalized or encoded response. RustProxy may restore Vary: Cookie for cookie-partitioned objects; static Ignore Vary: Cookie requires public and other safety checks.</p>
|
||||
</section>
|
||||
<section class="cache-guide-card">
|
||||
<h3 data-i18n="cacheGuideHeadersTitle">set/unset headers</h3>
|
||||
<p data-i18n="cacheGuideHeadersText">beresp.http.* edits the backend response before the cache decision; resp.http.* edits only the delivered response. Removing beresp.http.Cache-Control can change cache eligibility, while removing resp.http.Cache-Control cannot.</p>
|
||||
<pre><code>sub vcl_backend_response {
|
||||
unset beresp.http.X-Debug;
|
||||
set beresp.http.Cache-Control =
|
||||
"public, max-age=60";
|
||||
}
|
||||
sub vcl_deliver {
|
||||
unset resp.http.X-Powered-By;
|
||||
}</code></pre>
|
||||
<button class="outline cache-guide-import-example" type="button"
|
||||
data-i18n="cacheGuideInsert">Insert into VCL importer</button>
|
||||
<p class="fine" data-i18n="cacheGuideHeadersWarning">Only literal string assignments are imported; protected transport/body headers cannot be edited. Removing Set-Cookie requires a dedicated backend action and is unsafe for session responses.</p>
|
||||
</section>
|
||||
<section class="cache-guide-card">
|
||||
<h3 data-i18n="cacheGuideRequestTitle">Request headers and storage overrides</h3>
|
||||
<p data-i18n="cacheGuideRequestText">Safe set/unset req.http headers are applied before subsequent rules, hashing and forwarding to the origin. beresp.uncacheable = false reverses an earlier rule's no-store decision, but does not override origin private/no-store/Set-Cookie.</p>
|
||||
<pre><code>sub vcl_recv {
|
||||
unset req.http.X-Tracking;
|
||||
set req.http.X-Device = "mobile";
|
||||
}
|
||||
sub vcl_backend_response {
|
||||
set beresp.uncacheable = false;
|
||||
}</code></pre>
|
||||
<button class="outline cache-guide-import-example" type="button"
|
||||
data-i18n="cacheGuideInsert">Insert into VCL importer</button>
|
||||
<p class="fine" data-i18n="cacheGuideRequestWarning">Authorization, Cookie (except dedicated unset), Cache-Control and forwarding/transport headers are protected in request rules. Complex URL rewrites are warned about, not guessed. Always review import warnings.</p>
|
||||
<p class="fine" data-i18n="cacheGuideUncacheableDifference">RustProxy's beresp.uncacheable = false applies only to a previous cache-rule restriction; this is not Varnish's exact behavior. The backend's private/no-store and Set-Cookie protections remain unless deliberately rewritten by a separate trusted rule.</p>
|
||||
</section>
|
||||
<section class="cache-guide-card">
|
||||
<h3 data-i18n="cacheGuideStagesTitle">VCL stages and rule precedence</h3>
|
||||
<p data-i18n="cacheGuideStagesText">vcl_recv handles pass/hash and request rewrites; vcl_hash supports selected hash_data(req.http.X); vcl_backend_response handles TTL, grace and backend headers; vcl_deliver edits final headers, even on HIT or BYPASS.</p>
|
||||
<p class="fine" data-i18n="cacheGuidePrecedenceText">Rules for the vhost are evaluated before matching global rules. Per-vhost changes win on conflicting supported settings and headers, or global rules may be disabled for the vhost. Importing VCL converts it into graphical rules; review warnings and the resulting order before saving.</p>
|
||||
<p class="fine" data-i18n="cacheGuideUnsupportedText">Not yet a full Varnish interpreter: vcl_hit/vcl_miss/vcl_pass hooks, arbitrary sub/call, VMOD, ACL expressions, beresp.keep, hit-for-miss/pass, restart, retry, synth and purge are not executed as VCL.</p>
|
||||
<p class="fine" data-i18n="cacheGuideBuiltInHash">hash_data(req.url) and hash_data(req.http.Host) are already included in the internal cache key. vcl_hash can add one extra req.http.* header, but it does not automatically generate a matching Vary header.</p>
|
||||
<p class="fine" data-i18n="cacheGuideStatusRestriction">RustProxy currently stores only HTTP 200 responses. A TTL rule for 404/301 does not enable caching of those statuses; the former 404 template was removed to avoid suggesting otherwise.</p>
|
||||
<p class="fine" data-i18n="cacheGuideVclPreviewWarning">VCL export is a readable preview, not a lossless round-trip. If import reports warnings, rules are not added until you explicitly accept the partial result. Editing the source or closing the importer discards any pending import.</p>
|
||||
</section>
|
||||
<section class="cache-guide-card">
|
||||
<h3 data-i18n="cacheGuideDiagnoseTitle">Why isn't it a HIT?</h3>
|
||||
<p data-i18n="cacheGuideDiagnoseText">Enable X-Cache and detailed reason headers; disable Only on HIT while debugging. Send two identical GET requests with curl (not a browser hard reload), then compare the cache outcome and origin headers.</p>
|
||||
<pre><code>curl -sS -D - -o /dev/null \
|
||||
https://example.com/public/page
|
||||
curl -sS -D - -o /dev/null \
|
||||
https://example.com/public/page</code></pre>
|
||||
<p class="fine" data-i18n="cacheGuideDiagnoseReasons">BYPASS usually means request exclusion (Cookie, Authorization, route or query). MISS means the backend was contacted, but does not prove that the response was stored. Check X-Cache-Reason, Cache-Control, Set-Cookie, Vary and Age.</p>
|
||||
</section>
|
||||
</div>
|
||||
<div class="cache-guide-footer">
|
||||
<p class="fine" data-i18n="cacheGuideScope">These VCL rules affect reverse-proxy vhosts; they do not execute on the embedded administration panel or all Web Server sources. Test on a non-production vhost first.</p>
|
||||
<a class="docs-link" href="/docs#doc=docs%2FVCL.md" target="_blank" rel="noopener noreferrer" data-i18n="cacheGuideDocsVcl">Complete supported VCL syntax and limits</a>
|
||||
<a class="docs-link" href="/docs#doc=docs%2FCACHE.md" target="_blank" rel="noopener noreferrer" data-i18n="cacheGuideDocsCache">HTTP cache policy and diagnostics</a>
|
||||
</div>
|
||||
</div>
|
||||
</dialog>
|
||||
<dialog aria-labelledby="cache-invalidation-title" class="vhost-dialog cache-operation-dialog"
|
||||
id="cache-invalidation-dialog">
|
||||
<article class="card">
|
||||
|
||||
@@ -103,6 +103,54 @@
|
||||
button.addEventListener("keydown", event => { const index = cacheTabs.indexOf(button); let next; if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % cacheTabs.length; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + cacheTabs.length - 1) % cacheTabs.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = cacheTabs.length - 1; else return; event.preventDefault(); selectCacheTab(cacheTabs[next].dataset.cacheSettingsTab, true); });
|
||||
}
|
||||
selectCacheTab("general");
|
||||
const cacheGuideDialog = $("cache-vcl-guide-dialog");
|
||||
let guideEditor = null;
|
||||
let guideIsLocal = false;
|
||||
function openCacheGuide(trigger) {
|
||||
if (!cacheGuideDialog) return;
|
||||
// One guide serves the static global editor and both dynamic vhost editors.
|
||||
// Keep its destination tied to the button that opened it; never silently
|
||||
// insert a vhost example into global rules or vice versa.
|
||||
guideEditor = trigger?.closest(".cache-rules") || $("cache-rules-root")?.querySelector(".cache-rules") || null;
|
||||
guideIsLocal = guideEditor?.classList.contains("cache-rules-vhost") === true;
|
||||
const isDocker = guideIsLocal && !!guideEditor.closest(".docker-cache-editor");
|
||||
const compatible = $("cache-varnish-compatible").checked;
|
||||
const enabled = $("cache-enabled").checked;
|
||||
const ttl = Math.max(0, Number($("cache-default-ttl").value) || 0);
|
||||
const grace = Math.max(0, Number($("cache-varnish-grace").value) || 0);
|
||||
const mode = $("cache-guide-mode");
|
||||
mode.textContent = t(compatible ? "cacheGuideModeOn" : "cacheGuideModeOff");
|
||||
mode.classList.toggle("live", compatible);
|
||||
$("cache-guide-ttl").textContent = t("cacheGuideTtlStatus").replace("{seconds}", ttl);
|
||||
$("cache-guide-grace").textContent = t("cacheGuideGraceStatus").replace("{seconds}", grace);
|
||||
$("cache-guide-current-note").textContent = t(!enabled ? "cacheGuideCacheOffNote" : !compatible ? "cacheGuideRfcNote" : ttl > 0 ? "cacheGuideCompatNote" : "cacheGuideCompatZeroNote");
|
||||
$("cache-guide-context").textContent = t(isDocker ? "cacheGuideContextDocker" : guideIsLocal ? "cacheGuideContextVhost" : "cacheGuideContextGlobal");
|
||||
$("cache-guide-scope-note").textContent = t(isDocker ? "cacheGuideScopeDocker" : guideIsLocal ? "cacheGuideScopeVhost" : "cacheGuideScopeGlobal");
|
||||
if (!cacheGuideDialog.open) cacheGuideDialog.showModal();
|
||||
}
|
||||
// Event delegation is needed: the ordinary vhost dialog and the Docker
|
||||
// service editors are created after settings.js has registered its events.
|
||||
document.addEventListener("click", event => {
|
||||
const button = event.target.closest?.(".cache-guide-trigger");
|
||||
if (!button) return;
|
||||
event.preventDefault();
|
||||
openCacheGuide(button);
|
||||
});
|
||||
$("cache-vcl-guide-close")?.addEventListener("click", () => cacheGuideDialog.close());
|
||||
cacheGuideDialog?.querySelectorAll(".cache-guide-import-example").forEach(button => button.addEventListener("click", () => {
|
||||
const source = button.closest(".cache-guide-card")?.querySelector("pre code")?.textContent?.trim();
|
||||
const importer = guideEditor?.isConnected ? guideEditor.querySelector(".cache-rules-import") : null;
|
||||
const editor = importer?.querySelector("textarea");
|
||||
if (!source || !editor) { toast(t("cacheGuideImporterUnavailable"), true); return; }
|
||||
editor.value = [editor.value.trim(), source].filter(Boolean).join("\n\n");
|
||||
// Invalidates any pending partial-import preview from an older source.
|
||||
editor.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
importer.hidden = false;
|
||||
cacheGuideDialog.close();
|
||||
if (!guideIsLocal) selectCacheTab("rules");
|
||||
importer.scrollIntoView({ block: "nearest", behavior: "smooth" });
|
||||
editor.focus({ preventScroll: true });
|
||||
}));
|
||||
const loggingTabs = [...document.querySelectorAll("[data-logging-settings-tab]")];
|
||||
function selectLoggingTab(name, focus = false) {
|
||||
if (!loggingTabs.some(button => button.dataset.loggingSettingsTab === name)) return;
|
||||
|
||||
@@ -536,7 +536,10 @@ function load(value = defaults(), migrationIds = [], show = true) {
|
||||
note(unsafeCacheFields, "vhCacheForceHelp");
|
||||
const cacheRulesFields = el("div", undefined, "vh-wide vh-cache-rules"); cacheOptions.append(cacheRulesFields);
|
||||
cacheRulesFields.append(el("h4", t("vhCacheRulesTitle")), el("p", t("vhCacheRulesHelp"), "fine"));
|
||||
vhostCacheRulesEditor = window.rustProxyCacheRules.create({ scope: "vhost", vhostId: editing || "", rules: cache.rules || [], ignoreGlobal: cache.ignore_global_rules === true });
|
||||
vhostCacheRulesEditor = window.rustProxyCacheRules.create({
|
||||
scope: "vhost", vhostId: editing || "", rules: cache.rules || [], ignoreGlobal: cache.ignore_global_rules === true,
|
||||
testHost: () => lines(read("hosts")?.value || "").find(host => host && !host.startsWith("*.")) || "",
|
||||
});
|
||||
cacheRulesFields.append(vhostCacheRulesEditor.node);
|
||||
if (editing) cacheOptions.append(button("vhPurgeCache", () => purge(editing)));
|
||||
const syncCacheVisibility = () => {
|
||||
|
||||
Reference in new issue
Block a user