File size: 11,819 Bytes
38d7a6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# syntax=docker/dockerfile:1
FROM elixir:1.17-slim
ENV DEBIAN_FRONTEND=noninteractive ERL_FLAGS="+S 2:2" MIX_ENV=prod
RUN apt-get update && apt-get install -y --no-install-recommends ruby ruby-dev build-essential perl ca-certificates coreutils && gem install erb --no-document && rm -rf /var/lib/apt/lists/*
WORKDIR /app
RUN mix local.hex --force && mix local.rebar --force
RUN <<'FILES'
cat > /app/evaluate.pl <<'PERL'
use strict; use warnings; use JSON::PP;
my $d=decode_json($ARGV[0]);
my $rows=$d->{rows}//[]; die "rows" unless ref($rows) eq 'ARRAY' && @$rows<=100;
my @out;
for my $r (@$rows) {
 die "row" unless ref($r) eq 'HASH';
 my $h=$r->{headers}//{}; die "headers" unless ref($h) eq 'HASH';
 my %h=map {my $k=lc($_);$k=~tr/-/_/; ($k=>"$h->{$_}")} keys %$h;
 my $m=uc($r->{method}//'GET'); my $u=$r->{uri}//'/'; die "uri" unless $u=~m{^/};
 my %a; my $q=(split(/\?/, $u,2))[1]//'';
 for(split /&/,$q){my($k,$v)=split /=/,$_,2;$k=lc($k//'');$a{$k}=$v//'' unless exists $a{$k};}
 my %c; for(split /;/,$h{cookie}//''){my($k,$v)=split /=/,$_,2;next unless defined $v;$k=~s/^\s+|\s+$//g;$c{lc $k}=$v unless exists $c{lc $k};}
 my %v=(request_method=>$m,request_uri=>$u,host=>lc($r->{host}//'api.example.com'),scheme=>$r->{scheme}//'https',skip_method=>($m=~/^(GET|HEAD)$/?'0':'1'),skip_auth=>length($h{authorization}//'')?'1':'0',skip_cookie=>length($h{cookie}//'')?'1':'0',skip_nocache=>(!length($a{nocache}//'')||($a{nocache}//'') eq '0')?'0':'1',skip_cache_control=>(($h{cache_control}//'')=~/(?:^|,)\s*(?:no-cache|no-store)\b/i?'1':'0'));
 my %result=(method=>$m,uri=>$u,public_route=>($u=~m{^/api/public/}?JSON::PP::true:JSON::PP::false));
 for my $field ('bypass','no_cache') {
 my $terms=$d->{$field}//[map {'$'.$_} qw(skip_method skip_auth skip_cookie skip_nocache skip_cache_control)];
 die "arguments" unless ref($terms) eq 'ARRAY' && @$terms>0 && @$terms<=20;
 my @expanded;
 for my $s (@$terms){die "string" if ref($s)||!defined($s)||length($s)>500||$s=~/[\r\n{}\\]/;
 $s=~s/\$([A-Za-z0-9_]+)/exists $v{$1}?$v{$1}:$1=~m{^http_(.*)}?($h{$1}\/\/''):$1=~m{^arg_(.*)}?($a{lc $1}\/\/''):$1=~m{^cookie_(.*)}?($c{lc $1}\/\/''):die('variable')/ge;
 push @expanded,$s; }
 $result{$field}={expanded=>\@expanded,triggered=>(scalar(grep {length($_)&&$_ ne '0'} @expanded)?JSON::PP::true:JSON::PP::false)};
 }
 push @out,\%result;
}
print encode_json({results=>\@out,simulation_only=>JSON::PP::true});
PERL
cat > /app/render.rb <<'RUBY'
require 'json'
require 'erb'
s=JSON.parse(ARGV.fetch(0))
%w[zone_mib disk_mib inactive_seconds ttl_seconds].each { |k| raise 'integer' unless s[k].is_a?(Integer) && s[k]>0 }
template = <<~'NGINX'
# http-context include. Loopback staging template, not production approval.
proxy_cache_path /tmp/nginx-api levels=1:2 use_temp_path=off keys_zone=api_cache:<%= s.fetch('zone_mib') %>m max_size=<%= s.fetch('disk_mib') %>m inactive=<%= s.fetch('inactive_seconds') %>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;
 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_cache api_cache;
  proxy_cache_methods GET HEAD;
  proxy_cache_key "$scheme|$host|$request_uri";
  proxy_cache_valid 200 <%= s.fetch('ttl_seconds') %>s;
  proxy_cache_lock on;
  proxy_cache_revalidate on;
  proxy_cache_bypass $skip_method $skip_auth $skip_cookie $skip_nocache $skip_cache_control;
  proxy_no_cache $skip_method $skip_auth $skip_cookie $skip_nocache $skip_cache_control;
  add_header X-Cache-Status $upstream_cache_status always;
 }
 location / { proxy_cache off; proxy_pass http://api_backend; }
}
# Preserve upstream Cache-Control, Set-Cookie and Vary behavior.
# Select timeout budgets and host rejection/TLS before network exposure.
NGINX
puts JSON.generate({configuration: ERB.new(template).result(binding),policy: 'Fixed conservative policy; custom evaluated arguments are not exported.'})
RUBY
cat > /app/server.exs <<'ELIXIR'
Mix.install([{:plug_cowboy, "~> 2.7"}, {:jason, "~> 1.4"}])
defmodule Size do
 def compute(p) do
  defaults=%{"users"=>10000,"size_kib"=>16,"ttl"=>60,"rpu"=>0.2,"eligible_pct"=>70,"new_key_pct"=>10,"revisit"=>300,"retention"=>2,"keys"=>0,"memory_factor"=>1.5,"disk_factor"=>1.25,"overhead_kib"=>2,"density"=>8000}
  v=Map.merge(defaults,Map.take(p,Map.keys(defaults)))
  Enum.each(v,fn {_,x}->if !is_number(x) or x<0 or x>1.0e12,do: raise("number") end)
  if Enum.any?(~w(users size_kib ttl rpu density), &(v[&1]<=0)) or Enum.any?(~w(retention memory_factor disk_factor), &(v[&1]<1)) or v["eligible_pct"]>100 or v["new_key_pct"]>100,do: raise("range")
  idle=ceil(max(v["ttl"],v["revisit"])*v["retention"])
  rps=v["users"]*v["rpu"]
  keys=if v["keys"]>0,do: ceil(v["keys"]),else: ceil(rps*v["eligible_pct"]/100*v["new_key_pct"]/100*idle)
  s=%{rps: rps, resident_keys: keys, zone_mib: max(1,ceil(keys*v["memory_factor"]/v["density"])),disk_mib: max(1,ceil(keys*(v["size_kib"]+v["overhead_kib"])*1024*v["disk_factor"]/1048576)),inactive_seconds: idle,ttl_seconds: ceil(v["ttl"])}
  if Enum.any?(Map.values(s), &(&1>9.0e15)),do: raise("overflow")
  s
 end
end
defmodule Web do
 use Plug.Router
 plug :match
 plug Plug.Parsers, parsers: [:json], pass: ["application/json"], json_decoder: Jason, length: 32000
 plug :dispatch
 def worker(program,file,payload) do
  {out,status}=System.cmd("timeout",["5s",program,file,Jason.encode!(payload)],stderr_to_stdout: true)
  if status != 0,do: raise("worker")
  Jason.decode!(out)
 end
 def api(conn,fun) do
  n=:ets.update_counter(:capacity,:active,1)
  try do
   if n>4 do
    send_resp(conn,429,"busy")
   else
    value=fun.()
    conn |> put_resp_content_type("application/json") |> put_resp_header("cache-control","no-store") |> send_resp(200,Jason.encode!(value))
   end
  rescue
   _ -> send_resp(conn,422,"Invalid input or worker failure; payload not logged")
  after
   :ets.update_counter(:capacity,:active,-1)
  end
 end
 get "/health" do
  api(conn,fn -> %{status: "ready",perl: worker("perl","/app/evaluate.pl",%{"rows"=>[]}),ruby: Map.has_key?(worker("ruby","/app/render.rb",Size.compute(%{})),"configuration")} end)
 end
 post "/api/size" do
  api(conn,fn -> Size.compute(conn.body_params) end)
 end
 post "/api/evaluate" do
  api(conn,fn -> worker("perl","/app/evaluate.pl",conn.body_params) end)
 end
 post "/api/config" do
  api(conn,fn -> worker("ruby","/app/render.rb",Size.compute(conn.body_params)) end)
 end
 get "/" do
  conn |> put_resp_content_type("text/html") |> put_resp_header("cache-control","no-store") |> send_file(200,"/app/index.html")
 end
 match _ do
  send_resp(conn,404,"Not found")
 end
end
if System.get_env("BUILD_ONLY") != "1" do
 :ets.new(:capacity,[:named_table,:public,:set])
 :ets.insert(:capacity,{:active,0})
 {:ok,_}=Supervisor.start_link([{Plug.Cowboy,scheme: :http,plug: Web,options: [port: 7860,ip: {0,0,0,0}]}],strategy: :one_for_one)
 Process.sleep(:infinity)
end
ELIXIR
cat > /app/index.html <<'HTML'
<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Polyglot Cache Lab</title><style>body{font:16px system-ui;background:#171126;color:#eee;max-width:1000px;margin:auto;padding:24px}textarea{width:100%;box-sizing:border-box;min-height:200px;background:#251c37;color:white;padding:12px}button{padding:12px;margin:10px;background:#c4b5fd;border:0;border-radius:5px}pre{white-space:pre-wrap;overflow-wrap:anywhere}a{color:#c4b5fd}</style><h1>Polyglot NGINX Cache Lab</h1><p>Elixir sizing + HTTP API · Perl traffic evaluator · Ruby / ERB configuration renderer.</p><p>Privacy: requests are sent to this Space backend. Redact credentials and personal information. The application does not intentionally persist request bodies. Hosting infrastructure may maintain access logs. Public demo: not an authenticated production service.</p><h2>Sizing workload</h2><textarea id=workload aria-label="Sizing JSON"></textarea><button id=size>Calculate with Elixir</button><button id=config>Render with Ruby</button><button id=download>Download rendered configuration</button><h2>Traffic evaluator</h2><p>Arguments are JSON arrays: each element is one already-tokenized NGINX string argument. No quotation parser, arbitrary map evaluation, or regex syntax. Up to 100 rows and 32 KB per request. This is not real NGINX execution.</p><textarea id=traffic aria-label="Traffic JSON"></textarea><input type=file id=file accept=".json,.jsonl,.ndjson" aria-label="Import traffic"><button id=evaluate>Evaluate with Perl</button><button id=health>Check all runtimes</button><pre id=result role=status></pre><p>Config export always uses the displayed conservative policy, not custom evaluator arguments. TTL can be overridden by origin caching headers. inactive is idle retention, not freshness. Metadata density and file overhead are assumptions. No production optimum or live NGINX validation is claimed.</p><p><a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html">NGINX directive reference</a></p><script>const $=id=>document.getElementById(id);let conf='';$('workload').value=JSON.stringify({users:10000,size_kib:16,ttl:60,rpu:0.2,eligible_pct:70,new_key_pct:10,revisit:300,retention:2,keys:0,memory_factor:1.5,disk_factor:1.25,overhead_kib:2,density:8000},null,2);$('traffic').value=JSON.stringify({rows:[{method:'GET',uri:'/api/public/products'},{method:'GET',uri:'/api/public/products?nocache=false'},{method:'POST',uri:'/api/public/products'}]},null,2);async function call(path,body){try{const r=await fetch(path,body===undefined?{}:{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});const text=await r.text();if(!r.ok)throw Error(r.status+' '+text);const d=JSON.parse(text);$('result').textContent=JSON.stringify(d,null,2);return d}catch(e){$('result').textContent=e.message;return null}}$('size').onclick=()=>{try{call('/api/size',JSON.parse($('workload').value))}catch(e){$('result').textContent=e.message}};$('config').onclick=async()=>{conf='';try{const d=await call('/api/config',JSON.parse($('workload').value));if(d)conf=d.configuration}catch(e){$('result').textContent=e.message}};$('evaluate').onclick=()=>{try{call('/api/evaluate',JSON.parse($('traffic').value))}catch(e){$('result').textContent=e.message}};$('health').onclick=()=>call('/health');$('file').onchange=async e=>{try{const f=e.target.files[0];if(!f)return;if(f.size>30000)throw Error('Use a redacted sample below 30 KB');const s=await f.text();let rows;try{const d=JSON.parse(s);rows=Array.isArray(d)?d:d.rows}catch(e){rows=s.split(/\r?\n/).filter(x=>x.trim()).map(x=>JSON.parse(x))}if(!Array.isArray(rows))throw Error('Expected array or {rows:[]}');$('traffic').value=JSON.stringify({rows},null,2)}catch(e){$('result').textContent=e.message}};$('download').onclick=()=>{if(!conf){$('result').textContent='Render a valid configuration first';return}const u=URL.createObjectURL(new Blob([conf],{type:'text/plain'})),a=document.createElement('a');a.href=u;a.download='nginx-cache.conf';a.click();setTimeout(()=>URL.revokeObjectURL(u),1000)};</script></html>
HTML
perl -c /app/evaluate.pl
ruby -c /app/render.rb
FILES
RUN BUILD_ONLY=1 elixir /app/server.exs
RUN useradd -m -u 1000 app && cp -a /root/.mix /home/app/.mix && cp -a /root/.cache /home/app/.cache && chown -R app:app /app /home/app
USER app
ENV HOME=/home/app
EXPOSE 7860
CMD ["elixir", "/app/server.exs"]