File size: 11,495 Bytes
7101191
867f38c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!doctype html>
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>NGINX Cache Lab</title><style>body{font:16px system-ui;background:#0b1220;color:#e2e8f0;max-width:1100px;margin:auto;padding:24px}section{background:#152238;padding:22px;border-radius:12px;margin:20px 0}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px}input,select,textarea{box-sizing:border-box;width:100%;background:#091422;color:white;border:1px solid #64748b;border-radius:5px;padding:9px;margin:6px 0}textarea{min-height:150px}button{padding:10px;margin:8px;background:#6ee7b7;border:0;border-radius:5px;cursor:pointer}pre{white-space:pre-wrap;overflow-wrap:anywhere}a{color:#93c5fd}.warn{color:#fbbf24}#error{color:#fda4af}</style><h1>NGINX Cache Lab</h1><p>Browser-only capacity estimates and request-string tests. Traffic stays in your browser. No GPU, backend, or model calls.</p><section><h2>Capacity assumptions</h2><div id=inputs class=grid></div><p id=error role=alert></p><pre id=metrics></pre></section><section><h2>Bypass string laboratory</h2><p>Space-separated NGINX arguments. Empty strings and exactly 0 are false; all other strings trigger bypass. Quotes support concatenation. This is not a boolean-expression language.</p><label>proxy_cache_bypass<input id=rule value="$skip_method $skip_auth $skip_cookie $skip_nocache $skip_cache_control"></label><label>proxy_no_cache<input id=writeRule value="$skip_method $skip_auth $skip_cookie $skip_nocache $skip_cache_control"></label><label>JSON array or JSONL: method, uri, headers, optional host and scheme<textarea id=traffic></textarea></label><input id=file type=file accept=".json,.jsonl,.ndjson"><button id=test>Evaluate traffic</button><pre id=results></pre><p class=warn>Request-policy simulation only: not a cache-hit predictor or full NGINX parser. Supports $http_*, $arg_*, $cookie_*, $request_method, $request_uri, $host, $scheme and generated $skip_* maps. Missing imported headers are treated as absent; credential-free access logs cannot reproduce header-dependent decisions. Redact sensitive data before import.</p></section><section><h2>Configuration export</h2><button id=download>Download configuration</button><pre id=config></pre><p class=warn>Staging template only. Review host policy, TLS, public routes, filesystem capacity and timeout budgets; run nginx -t and real traffic tests. Upstream caching headers can override the fallback TTL. max_size is not a hard filesystem quota.</p></section><section><h2>Model and sources</h2><p>RPS = concurrent users × requests/user/second. Resident keys = eligible RPS × new-key fraction × inactive seconds, unless overridden. This assumes a stationary workload; hot keys and Vary variants can invalidate it. inactive = max(TTL, revisit interval) × retention factor, a policy assumption rather than an optimum.</p><p>Zone MiB = ceil(keys × metadata headroom / approximate keys per MiB). NGINX documents about 8,000 keys per MB for Open Source, or 4,000 with extended commercial metadata; this calculator uses those as approximate binary-unit planning densities. Disk MiB = ceil(keys × (body bytes + overhead allowance) × disk headroom / 1048576). Overhead is an estimate, not an NGINX constant. TTL is freshness; inactive is idle retention. Per-worker buffers and total process memory are not included.</p><p><a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html">Official proxy module</a> · <a href="https://nginx.org/en/docs/http/ngx_http_map_module.html">Official map module</a></p><p>This compact static deployment contains sizing, traffic-string evaluation and configuration export. It does not run NGINX, save traffic remotely, or replay live endpoints.</p></section><script>
const $=id=>document.getElementById(id);const specs=[['users','Concurrent users',10000],['size','Average body KiB',16],['ttl','Freshness seconds',60],['rpu','Requests per user per second',0.2],['eligible','Eligible percent',70],['novel','New-key percent',10],['revisit','Target revisit seconds',300],['retention','Inactive multiplier',2],['keys','Resident-key override (0 = estimate)',0],['mem','Metadata headroom',1.5],['disk','Disk headroom',1.25],['overhead','Per-file overhead KiB',2],['density','Keys per MiB (8000 OSS / 4000 extended)',8000]];let current='';for(const [id,label,value]of specs){const l=document.createElement('label');l.textContent=label;const i=document.createElement('input');Object.assign(i,{id,type:'number',value,min:0,step:'any'});i.oninput=update;l.append(i);$('inputs').append(l)}
function tokenize(s){s=s.trim();if(!s)throw Error('At least one argument required');if(/[;{}\\\n\r]/.test(s))throw Error('Braces, escapes, semicolons and newlines unsupported');let a=[],b='',q='',active=false;for(const c of s){if(q){if(c===q)q='';else b+=c;active=true}else if(c==='"'||c==="'"){q=c;active=true}else if(/\s/.test(c)){if(active){a.push(b);b='';active=false}}else{b+=c;active=true}}if(q)throw Error('Unclosed quote');if(active)a.push(b);return a}
function vars(r){if(!r||typeof r!=='object'||Array.isArray(r))throw Error('Expected request objects');const h={};if(r.headers&&(typeof r.headers!=='object'||Array.isArray(r.headers)))throw Error('headers must be an object');for(const[k,v]of Object.entries(r.headers||{}))h[k.toLowerCase().replace(/-/g,'_')]=String(v);const method=String(r.method||'GET').toUpperCase(),uri=String(r.uri||'/');if(!uri.startsWith('/'))throw Error('Use relative uri starting with /');const args=uri.includes('?')?uri.slice(uri.indexOf('?')+1):'',arg={},cookie={};for(const p of args.split('&')){const i=p.indexOf('='),k=(i<0?p:p.slice(0,i)).toLowerCase();if(k&&!(k in arg))arg[k]=i<0?'':p.slice(i+1)}for(const p of(h.cookie||'').split(';')){const i=p.indexOf('=');if(i>=0){const k=p.slice(0,i).trim().toLowerCase();if(!(k in cookie))cookie[k]=p.slice(i+1).trim()}}return{h,arg,cookie,base:{request_method:method,request_uri:uri,host:String(r.host||'api.example.com').toLowerCase(),scheme:String(r.scheme||'https'),skip_method:/^(GET|HEAD)$/.test(method)?'0':'1',skip_auth:h.authorization?'1':'0',skip_cookie:h.cookie?'1':'0',skip_nocache:!arg.nocache||arg.nocache==='0'?'0':'1',skip_cache_control:/(?:^|,)\s*(?:no-cache|no-store)\b/i.test(h.cache_control||'')?'1':'0'}}}
function expand(s,v){return s.replace(/\$([a-zA-Z0-9_]+)/g,(_,k)=>{if(k in v.base)return v.base[k];for(const[p,o]of[['http_',v.h],['arg_',v.arg],['cookie_',v.cookie]])if(k.startsWith(p))return o[k.slice(p.length).toLowerCase()]||'';throw Error('Unsupported variable $'+k)})}const truth=s=>s!==''&&s!=='0';
function update(){try{const v=Object.fromEntries(specs.map(([k])=>[k,Number($(k).value)]));if(Object.values(v).some(x=>!Number.isFinite(x)||x<0)||v.users<1||v.size<=0||v.ttl<1||v.rpu<=0||v.eligible>100||v.novel>100||v.retention<1||v.mem<1||v.disk<1||v.density<=0)throw Error('Use finite positive workload values, factors >=1, and percentages 0–100');const inactive=Math.ceil(Math.max(v.ttl,v.revisit)*v.retention),rps=v.users*v.rpu,keys=v.keys||Math.ceil(rps*v.eligible/100*v.novel/100*inactive),zone=Math.max(1,Math.ceil(keys*v.mem/v.density)),disk=Math.max(1,Math.ceil(keys*(v.size+v.overhead)*1024*v.disk/1048576));if([inactive,keys,zone,disk].some(x=>!Number.isSafeInteger(x)))throw Error('Values exceed safe precision');const read=tokenize($('rule').value),write=tokenize($('writeRule').value);read.concat(write).forEach(t=>expand(t,vars({})));const quote=t=>'"'+t.replace(/"/g,'\\"')+'"';$('metrics').textContent=JSON.stringify({requests_per_second:rps,resident_keys:keys,keys_zone_MiB:zone,max_size_MiB:disk,inactive_seconds:inactive},null,2);current=`# Include inside http {}; staging template, not production approval.
proxy_cache_path /var/cache/nginx/api levels=1:2 use_temp_path=off
    keys_zone=api_cache:${zone}m max_size=${disk}m inactive=${inactive}s;
map $request_method $skip_method { default 1; GET 0; HEAD 0; }
map $http_authorization $skip_auth { default 1; "" 0; }
map $http_cookie $skip_cookie { default 1; "" 0; }
map $arg_nocache $skip_nocache { default 1; "" 0; "0" 0; }
map $http_cache_control $skip_cache_control {
    default 0;
    ~*(^|,)\\s*(no-cache|no-store)\\b 1;
}
upstream api_backend { server 127.0.0.1:8080; keepalive 64; }
server {
    listen 127.0.0.1:8081;
    server_name api.example.com;
    # Loopback staging only. Add explicit host rejection and TLS before exposure.
    location /api/public/ {
        proxy_pass http://api_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host api.example.com;
        proxy_buffering on;
        proxy_cache api_cache;
        proxy_cache_methods GET HEAD;
        proxy_cache_key "$scheme|$host|$request_uri";
        proxy_cache_valid 200 ${Math.ceil(v.ttl)}s;
        proxy_cache_lock on;
        proxy_cache_revalidate on;
        proxy_cache_bypass ${read.map(quote).join(' ')};
        proxy_no_cache ${write.map(quote).join(' ')};
        add_header X-Cache-Status $upstream_cache_status always;
    }
    location / {
        proxy_cache off;
        proxy_pass http://api_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host api.example.com;
    }
}
# Origin Cache-Control, Expires and X-Accel-Expires can override fallback TTL.
# Preserve Set-Cookie and Vary protections. Review lock and upstream timeouts.
`;$('config').textContent=current;$('error').textContent='';return true}catch(e){current='';$('config').textContent='Invalid inputs';$('metrics').textContent='';$('error').textContent=e.message;return false}}
function run(){try{let rows;try{rows=JSON.parse($('traffic').value)}catch(e){rows=$('traffic').value.split(/\r?\n/).filter(x=>x.trim()).map(x=>JSON.parse(x))}if(!Array.isArray(rows)||rows.length>20000)throw Error('Expected array of at most 20000 requests');const r=tokenize($('rule').value),w=tokenize($('writeRule').value);$('results').textContent=JSON.stringify(rows.slice(0,500).map(row=>{const v=vars(row),args=r.map(t=>expand(t,v));return{method:v.base.request_method,uri:v.base.request_uri,public_route:v.base.request_uri.split('?')[0].startsWith('/api/public/'),expanded_arguments:args,read_bypass:args.some(truth),write_blocked:w.map(t=>expand(t,v)).some(truth)}}),null,2)+(rows.length>500?'\nShowing first 500 rows.':'')}catch(e){$('results').textContent=e.message}}
$('test').onclick=run;for(const id of['rule','writeRule'])$(id).oninput=()=>{update();run()};$('file').onchange=async e=>{const f=e.target.files[0];if(!f)return;if(f.size>10000000){$('results').textContent='File exceeds 10 MB';return}$('traffic').value=await f.text();run()};$('download').onclick=()=>{if(!update())return;const u=URL.createObjectURL(new Blob([current],{type:'text/plain'})),a=document.createElement('a');a.href=u;a.download='nginx-cache.conf';a.click();setTimeout(()=>URL.revokeObjectURL(u),1000)};$('traffic').value=JSON.stringify([{method:'GET',uri:'/api/public/products'},{method:'GET',uri:'/api/public/products?nocache=0'},{method:'GET',uri:'/api/public/products?nocache=false'},{method:'GET',uri:'/api/public/products',headers:{Authorization:'Bearer REDACTED'}},{method:'GET',uri:'/api/public/products',headers:{Cookie:'session=REDACTED'}},{method:'POST',uri:'/api/public/products'},{method:'HEAD',uri:'/api/public/products'},{method:'GET',uri:'/api/public/products',headers:{'Cache-Control':'no-cache'}}],null,2);update();run();
</script></html>