Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

Make the micro-cache a real page cache

Juan Denisd148ccc24786
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index c28fd3ef..0b11c83b 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -1666,6 +1666,16 @@ def set_micro_cache(app_id):
if 'enabled' not in data:
return jsonify({'error': "'enabled' is required"}), 400
+ from app.services.nginx_service import NginxService
+ if 'ttl' in data:
+ ttl = data['ttl']
+ if ttl is not None and (isinstance(ttl, bool) or not isinstance(ttl, int)
+ or not 1 <= ttl <= NginxService.MICROCACHE_TTL_MAX):
+ from app.exceptions import ValidationError
+ raise ValidationError("'ttl' must be whole seconds from 1 to "
+ f'{NginxService.MICROCACHE_TTL_MAX}')
+ app.micro_cache_ttl = ttl
+
app.micro_cache_enabled = bool(data['enabled'])
db.session.commit()
@@ -1685,6 +1695,7 @@ def set_micro_cache(app_id):
response = {
'message': f"Micro-cache {'enabled' if app.micro_cache_enabled else 'disabled'}",
'micro_cache_enabled': bool(app.micro_cache_enabled),
+ 'micro_cache_ttl': app.micro_cache_ttl,
'applied': applied,
}
if note:
@@ -1697,12 +1708,10 @@ def set_micro_cache(app_id):
@apps_bp.route('/<int:app_id>/micro-cache/purge', methods=['POST'])
@jwt_required()
def purge_micro_cache(app_id):
- """Manually clear the micro-cache.
+ """Clear this site's cached pages (plan 86 §B3).
- The cache is ONE shared nginx zone for all opted-in sites (zones must be
- declared statically, so per-site zones don't scale) — purging therefore
- wipes cached entries for every opted-in site. With the 10-second TTL this
- is near-harmless, and no nginx reload is needed.
+ The zone is shared, but the cache key carries the host, so only entries
+ for this app's domains are removed. No nginx reload is needed.
"""
user = get_current_user()
app = Application.query_active().filter_by(id=app_id).first()
@@ -1711,15 +1720,17 @@ def purge_micro_cache(app_id):
if not _can_edit_app(user, app):
return jsonify({'error': 'Access denied'}), 403
+ hosts = [d.name for d in app.live_domains if d.name]
+ if not hosts:
+ return jsonify({'message': 'Nothing cached: this service has no domain yet',
+ 'purged': 0}), 200
+
from app.services.nginx_service import NginxService
- result = NginxService.purge_micro_cache()
+ result = NginxService.purge_micro_cache(hosts)
if not result.get('success'):
return jsonify({'error': result.get('error', 'Purge failed')}), 500
-
- response = {'message': result.get('message', 'Micro-cache cleared')}
- if result.get('note'):
- response['note'] = result['note']
- return jsonify(response), 200
+ return jsonify({'message': result.get('message', 'Micro-cache cleared'),
+ 'purged': result.get('purged', 0)}), 200
@apps_bp.route('/<int:app_id>/scale-policy', methods=['GET'])
diff --git a/backend/app/models/application.py b/backend/app/models/application.py
index 3a1dcde7..743f9ae3 100644
--- a/backend/app/models/application.py
+++ b/backend/app/models/application.py
@@ -111,6 +111,9 @@ class Application(JsonColumnMixin, TimestampMixin, SoftDeleteMixin, db.Model):
# the site's vhost, with bypasses for auth/admin/cart traffic. NULL/False
# = off (today's behavior).
micro_cache_enabled = db.Column(db.Boolean, default=False, nullable=True)
+ # Page-cache TTL in seconds (plan 86 §B3). NULL = the 10s default; the
+ # renderer clamps to NginxService.MICROCACHE_TTL_MAX.
+ micro_cache_ttl = db.Column(db.Integer, nullable=True)
# Environment linking
environment_type = db.Column(db.String(20), default='standalone') # 'production', 'development', 'staging', 'standalone'
@@ -229,6 +232,7 @@ class Application(JsonColumnMixin, TimestampMixin, SoftDeleteMixin, db.Model):
'private_slug': self.private_slug,
'private_url_enabled': self.private_url_enabled,
'micro_cache_enabled': bool(self.micro_cache_enabled),
+ 'micro_cache_ttl': self.micro_cache_ttl,
'environment_type': self.environment_type,
'linked_app_id': self.linked_app_id,
'shared_config': self._json_read('shared_config', None),
diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.py
index 305c8345..29015980 100644
--- a/backend/app/services/nginx_service.py
+++ b/backend/app/services/nginx_service.py
@@ -416,20 +416,18 @@ log_format serverkit_timed '$remote_addr - $remote_user [$time_local] "$request"
# Design tradeoff — ONE shared zone/path for every opted-in site: nginx
# cache zones must be declared statically in the http context, so a zone
# per site does not scale (and can't be added/removed without touching a
- # global file per site). Consequence: a manual purge is a full-zone wipe
- # that clears cached entries for ALL opted-in sites. That is acceptable
- # because the TTL is only 10 seconds — the purge button exists for the
- # "I need it gone *now*" case, not for cache hygiene. proxy_* and
- # fastcgi_* caches cannot share a keys_zone, hence two zones over one
- # base directory (both wiped together on purge).
+ # global file per site). Purge is still per site: the cache key carries
+ # $host, and purge_micro_cache(hosts) deletes only the files whose KEY
+ # line names that host (plan 86 §B3). proxy_* and fastcgi_* caches cannot
+ # share a keys_zone, hence two zones over one base directory.
MICROCACHE_CONF_NAME = 'serverkit-microcache.conf'
MICROCACHE_DIR = '/var/cache/nginx/serverkit-microcache'
MICROCACHE_ZONE_SNIPPET = '''# ServerKit micro-cache zones (auto-generated; do not edit).
# One shared zone pair serves every site with micro-cache enabled — nginx
# requires cache zones to be declared statically in the http context, so
-# per-site zones are not practical. Entries expire after 10s; a manual purge
-# wipes the whole directory (all opted-in sites).
+# per-site zones are not practical. Each site sets its own TTL; a purge
+# removes only that site's entries (the cache key carries the host).
proxy_cache_path /var/cache/nginx/serverkit-microcache/proxy levels=1:2 keys_zone=serverkit_microcache:10m max_size=256m inactive=10m use_temp_path=off;
fastcgi_cache_path /var/cache/nginx/serverkit-microcache/fastcgi levels=1:2 keys_zone=serverkit_microcache_php:10m max_size=256m inactive=10m use_temp_path=off;
'''
@@ -446,17 +444,33 @@ fastcgi_cache_path /var/cache/nginx/serverkit-microcache/fastcgi levels=1:2 keys
if ($request_uri ~* "^/(wp-admin|wp-login|admin|login|cart|checkout|my-account)") { set $sk_skip_cache 1; }
'''
+ # Page-cache behaviour (plan 86 §B3):
+ # * the key is `$scheme://$host$request_uri`, so the cache files of one
+ # site can be found by host and purged alone (the proxy default key is
+ # `$scheme$proxy_host$request_uri` — the upstream port, not the site);
+ # * a failing or slow upstream serves the last good copy (use_stale), an
+ # expired entry is refreshed in the background while the stale copy is
+ # served, and cache_lock sends one request upstream per missing entry
+ # instead of a stampede. The zone's inactive=10m bounds how long a stale
+ # copy survives, so the TTL is capped well below it.
+ MICROCACHE_TTL_DEFAULT = 10
+ MICROCACHE_TTL_MAX = 300
+
MICROCACHE_PROXY_BLOCK = ''' proxy_cache serverkit_microcache;
- proxy_cache_valid 200 301 10s;
- proxy_cache_use_stale updating error timeout;
+ proxy_cache_key $scheme://$host$request_uri;
+ proxy_cache_valid 200 301 {ttl}s;
+ proxy_cache_use_stale error timeout updating http_500 http_502 http_503;
+ proxy_cache_background_update on;
proxy_cache_lock on;
proxy_no_cache $sk_skip_cache;
add_header X-SK-Cache $upstream_cache_status;
'''
MICROCACHE_FASTCGI_BLOCK = ''' fastcgi_cache serverkit_microcache_php;
- fastcgi_cache_valid 200 301 10s;
- fastcgi_cache_use_stale updating error timeout;
+ fastcgi_cache_key $scheme://$host$request_uri;
+ fastcgi_cache_valid 200 301 {ttl}s;
+ fastcgi_cache_use_stale error timeout updating http_500 http_503;
+ fastcgi_cache_background_update on;
fastcgi_cache_lock on;
fastcgi_cache_bypass $sk_skip_cache;
fastcgi_no_cache $sk_skip_cache;
@@ -614,6 +628,7 @@ location /p/ {{
ssl_cert: str = None, ssl_key: str = None,
upstream: str = None,
micro_cache: bool = False,
+ micro_cache_ttl: Optional[int] = None,
wordpress_protection: bool = False) -> Dict:
"""Render the vhost config for a site to a string — no side effects.
@@ -684,7 +699,7 @@ location /p/ {{
if micro_cache:
# Inject before the SSL wrap so the redirect server block (which
# also carries a server_name line) never receives cache directives.
- config = cls._with_micro_cache(config, app_type)
+ config = cls._with_micro_cache(config, app_type, micro_cache_ttl)
if wordpress_protection:
if app_type != 'docker' or not port:
@@ -742,7 +757,8 @@ location /p/ {{
return {'success': False, 'error': str(e)}
@classmethod
- def _with_micro_cache(cls, config: str, app_type: str) -> str:
+ def _with_micro_cache(cls, config: str, app_type: str,
+ ttl: Optional[int] = None) -> str:
"""Inject the shared-zone micro-cache directives into a rendered vhost.
fastcgi_cache for PHP-FPM-served sites, proxy_cache for reverse-proxied
@@ -751,11 +767,13 @@ location /p/ {{
zones are declared once in conf.d by :meth:`ensure_cache_zone`.
"""
t = (app_type or '').lower()
+ ttl = cls.clamp_micro_cache_ttl(ttl)
if t in ('php', 'wordpress'):
anchor = ' include fastcgi_params;\n'
if anchor not in config:
return config
- config = config.replace(anchor, anchor + cls.MICROCACHE_FASTCGI_BLOCK, 1)
+ config = config.replace(
+ anchor, anchor + cls.MICROCACHE_FASTCGI_BLOCK.format(ttl=ttl), 1)
elif t in ('flask', 'django', 'python', 'docker', 'remote'):
# proxy_cache_bypass may only be declared once per location, so
# fold $sk_skip_cache into the template's existing $http_upgrade
@@ -766,7 +784,7 @@ location /p/ {{
config = config.replace(
anchor,
' proxy_cache_bypass $sk_skip_cache $http_upgrade;\n'
- + cls.MICROCACHE_PROXY_BLOCK,
+ + cls.MICROCACHE_PROXY_BLOCK.format(ttl=ttl),
1,
)
else:
@@ -779,6 +797,14 @@ location /p/ {{
match.group(1), match.group(1) + '\n' + cls.MICROCACHE_SKIP_BLOCK, 1)
return config
+ @classmethod
+ def clamp_micro_cache_ttl(cls, ttl) -> int:
+ """A stored TTL as the seconds the vhost uses: unset → the 10s
+ default, anything else clamped to 1..MICROCACHE_TTL_MAX."""
+ if ttl in (None, ''):
+ return cls.MICROCACHE_TTL_DEFAULT
+ return max(1, min(int(ttl), cls.MICROCACHE_TTL_MAX))
+
@classmethod
def ensure_cache_zone(cls) -> Dict:
"""Write the shared micro-cache zone declaration to conf.d (idempotent).
@@ -916,28 +942,56 @@ location /p/ {{
except Exception as e: # noqa: BLE001 - best-effort, never blocks a vhost
return {'success': False, 'error': str(e)}
- @classmethod
- def purge_micro_cache(cls) -> Dict:
- """Wipe the shared micro-cache directory contents. Linux-only.
+ # rm argv batch size for a per-site purge (keeps argv far below ARG_MAX).
+ PURGE_BATCH = 200
- Full-zone wipe by design (see the tradeoff note at the MICROCACHE_*
- constants): the zone is shared across all opted-in sites, and with a
- 10s TTL a per-site purge buys almost nothing. nginx recreates cache
- entries on demand — no reload needed.
+ @classmethod
+ def purge_micro_cache(cls, hosts: Optional[List[str]] = None) -> Dict:
+ """Clear cached pages. Linux-only; no nginx reload needed.
+
+ With ``hosts`` only that site's entries go (plan 86 §B3). nginx writes
+ each entry's key as a ``KEY: <scheme>://<host><uri>`` header line in
+ the cache file, so a fixed-string grep for ``KEY: http[s]://<host>/``
+ finds exactly this site's files; the trailing ``/`` keeps
+ ``shop.example.com`` from matching ``shop.example.com.evil``. Entries
+ cached under the pre-§B3 key (before the vhost was rewritten) aren't
+ found this way, and expire on their own TTL.
+
+ Without ``hosts`` the whole shared directory is wiped (every site).
"""
if os.name == 'nt':
return {'success': False,
'error': 'Micro-cache purge is only available on Linux hosts'}
+ subdirs = [os.path.join(cls.MICROCACHE_DIR, d) for d in ('proxy', 'fastcgi')]
try:
- subdirs = [os.path.join(cls.MICROCACHE_DIR, d) for d in ('proxy', 'fastcgi')]
- process = run_privileged(['rm', '-rf'] + subdirs)
- if process.returncode != 0:
- return {'success': False, 'error': process.stderr}
- run_privileged(['mkdir', '-p'] + subdirs)
- return {'success': True, 'message': 'Micro-cache cleared',
- 'note': ('The micro-cache is one shared zone, so purging clears '
- 'cached entries for every site that uses it. Entries '
- 'expire within 10 seconds regardless.')}
+ if hosts is None:
+ process = run_privileged(['rm', '-rf'] + subdirs)
+ if process.returncode != 0:
+ return {'success': False, 'error': process.stderr}
+ run_privileged(['mkdir', '-p'] + subdirs)
+ return {'success': True, 'message': 'Micro-cache cleared for every site'}
+
+ hosts = [h.lower() for h in hosts if h]
+ bad = [h for h in hosts if not _validate_domain(h)]
+ if bad or not hosts:
+ return {'success': False,
+ 'error': f"Invalid host: {bad[0] if bad else '(none)'}"}
+ argv = ['grep', '-rlaF']
+ for host in hosts:
+ argv += ['-e', f'KEY: http://{host}/', '-e', f'KEY: https://{host}/']
+ found = run_privileged(argv + subdirs, timeout=60)
+ # grep: 0 = matches, 1 = none; 2 = an error such as a missing
+ # subdir, which only matters if it hid every result.
+ if found.returncode not in (0, 1) and not (found.stdout or '').strip():
+ if 'No such file' not in (found.stderr or ''):
+ return {'success': False, 'error': (found.stderr or 'grep failed').strip()}
+ files = [f for f in (found.stdout or '').splitlines() if f.strip()]
+ for i in range(0, len(files), cls.PURGE_BATCH):
+ removed = run_privileged(['rm', '-f', '--'] + files[i:i + cls.PURGE_BATCH])
+ if removed.returncode != 0:
+ return {'success': False, 'error': removed.stderr}
+ return {'success': True, 'purged': len(files),
+ 'message': f'Cleared {len(files)} cached page(s) for this site'}
except Exception as e:
return {'success': False, 'error': str(e)}
@@ -946,6 +1000,7 @@ location /p/ {{
root_path: str = None, port: int = None, php_version: str = '8.2',
ssl_cert: str = None, ssl_key: str = None,
upstream: str = None, micro_cache: bool = False,
+ micro_cache_ttl: Optional[int] = None,
wordpress_protection: bool = False) -> Dict:
"""Create a new site configuration.
@@ -959,6 +1014,7 @@ location /p/ {{
name, app_type, domains, root_path=root_path, port=port,
php_version=php_version, ssl_cert=ssl_cert, ssl_key=ssl_key,
upstream=upstream, micro_cache=micro_cache,
+ micro_cache_ttl=micro_cache_ttl,
wordpress_protection=wordpress_protection,
)
if not rendered.get('success'):
diff --git a/backend/app/services/site_domain_service.py b/backend/app/services/site_domain_service.py
index 4c1554da..61ed39fd 100644
--- a/backend/app/services/site_domain_service.py
+++ b/backend/app/services/site_domain_service.py
@@ -492,7 +492,8 @@ class SiteDomainService:
# (app_vhost_kwargs -> render_site_config) always agree on it —
# an enabled cache must never show up as config drift.
base = dict(name=app.name, domains=domains, ssl_cert=ssl_cert, ssl_key=ssl_key,
- micro_cache=bool(getattr(app, 'micro_cache_enabled', False)))
+ micro_cache=bool(getattr(app, 'micro_cache_enabled', False)),
+ micro_cache_ttl=getattr(app, 'micro_cache_ttl', None))
# Reverse-proxy to a local container/app port.
if t in ('docker', 'wordpress'):
if not app.port:
diff --git a/backend/migrations/versions/101_micro_cache_ttl.py b/backend/migrations/versions/101_micro_cache_ttl.py
new file mode 100644
index 00000000..04c1df2b
--- /dev/null
+++ b/backend/migrations/versions/101_micro_cache_ttl.py
@@ -0,0 +1,19 @@
+"""Per-site micro-cache TTL (plan 86 §B3). NULL keeps the 10s default."""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '101_micro_cache_ttl'
+down_revision = '100_app_request_metrics'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ inspector = sa.inspect(op.get_bind())
+ # Add-if-missing: the pre-alembic schema sync may already have added it.
+ if 'micro_cache_ttl' not in {c['name'] for c in inspector.get_columns('applications')}:
+ op.add_column('applications', sa.Column('micro_cache_ttl', sa.Integer, nullable=True))
+
+
+def downgrade():
+ op.drop_column('applications', 'micro_cache_ttl')
diff --git a/backend/tests/test_micro_cache.py b/backend/tests/test_micro_cache.py
index eed9808e..ac2c6eaf 100644
--- a/backend/tests/test_micro_cache.py
+++ b/backend/tests/test_micro_cache.py
@@ -16,6 +16,8 @@ Proving points:
save-only note when not; POST .../purge wipes the shared cache dir
(Linux-guarded); both require auth
"""
+import shutil
+import os
import pytest
from app import db
@@ -50,7 +52,10 @@ def test_php_site_gets_fastcgi_cache_with_all_bypasses():
cfg = res['config']
assert 'fastcgi_cache serverkit_microcache_php;' in cfg
assert 'fastcgi_cache_valid 200 301 10s;' in cfg
- assert 'fastcgi_cache_use_stale updating error timeout;' in cfg
+ assert 'fastcgi_cache_key $scheme://$host$request_uri;' in cfg
+ assert ('fastcgi_cache_use_stale error timeout updating http_500 http_503;'
+ in cfg)
+ assert 'fastcgi_cache_background_update on;' in cfg
assert 'fastcgi_cache_lock on;' in cfg
assert 'fastcgi_cache_bypass $sk_skip_cache;' in cfg
assert 'fastcgi_no_cache $sk_skip_cache;' in cfg
@@ -67,7 +72,12 @@ def test_docker_site_gets_proxy_cache_with_folded_bypass():
cfg = res['config']
assert 'proxy_cache serverkit_microcache;' in cfg
assert 'proxy_cache_valid 200 301 10s;' in cfg
- assert 'proxy_cache_use_stale updating error timeout;' in cfg
+ # Keyed on the site's host (the proxy default is the upstream port), so
+ # one site's entries can be purged alone (plan 86 §B3).
+ assert 'proxy_cache_key $scheme://$host$request_uri;' in cfg
+ assert ('proxy_cache_use_stale error timeout updating http_500 http_502 '
+ 'http_503;' in cfg)
+ assert 'proxy_cache_background_update on;' in cfg
assert 'proxy_cache_lock on;' in cfg
assert 'proxy_no_cache $sk_skip_cache;' in cfg
for marker in BYPASS_MARKERS:
@@ -346,22 +356,44 @@ def test_api_requires_auth(client, app):
assert client.post('/api/v1/apps/1/micro-cache/purge').status_code == 401
-def test_api_purge_happy_path(client, auth_headers, app, monkeypatch):
- site = _api_site(name='api-mc-purge', host=None)
+def test_api_purge_clears_only_this_sites_hosts(client, auth_headers, app, monkeypatch):
+ site = _api_site(name='api-mc-purge', host='purge-mc.lvh.me')
+ seen = []
monkeypatch.setattr(NginxService, 'purge_micro_cache',
- classmethod(lambda cls: {'success': True, 'message': 'Micro-cache cleared',
- 'note': 'shared zone'}))
+ classmethod(lambda cls, hosts=None: seen.append(hosts) or
+ {'success': True, 'purged': 3, 'message': 'Cleared 3'}))
resp = client.post(f'/api/v1/apps/{site.id}/micro-cache/purge', headers=auth_headers)
assert resp.status_code == 200
- data = resp.get_json()
- assert data['message'] == 'Micro-cache cleared'
- assert data['note'] == 'shared zone'
+ assert resp.get_json() == {'message': 'Cleared 3', 'purged': 3}
+ assert seen == [['purge-mc.lvh.me']], 'purge must never fall back to every site'
+
+
+def test_api_purge_without_a_domain_touches_nothing(client, auth_headers, app, monkeypatch):
+ site = _api_site(name='api-mc-purge-nodom', host=None)
+ monkeypatch.setattr(NginxService, 'purge_micro_cache',
+ classmethod(lambda cls, hosts=None: pytest.fail('purged')))
+ resp = client.post(f'/api/v1/apps/{site.id}/micro-cache/purge', headers=auth_headers)
+ assert resp.status_code == 200
+ assert resp.get_json()['purged'] == 0
+
+
+def test_api_put_sets_and_validates_the_ttl(client, auth_headers, app, monkeypatch):
+ site = _api_site(host=None, name='api-mc-ttl')
+ url = f'/api/v1/apps/{site.id}/micro-cache'
+ ok = client.put(url, headers=auth_headers, json={'enabled': True, 'ttl': 60})
+ assert ok.status_code == 200 and ok.get_json()['micro_cache_ttl'] == 60
+ for bad in (0, NginxService.MICROCACHE_TTL_MAX + 1, '60', True, 1.5):
+ resp = client.put(url, headers=auth_headers, json={'enabled': True, 'ttl': bad})
+ assert resp.status_code == 400, bad
+ assert Application.query.get(site.id).micro_cache_ttl == 60
+ reset = client.put(url, headers=auth_headers, json={'enabled': True, 'ttl': None})
+ assert reset.get_json()['micro_cache_ttl'] is None
def test_api_purge_failure_is_500_with_error(client, auth_headers, app, monkeypatch):
- site = _api_site(name='api-mc-purgefail', host=None)
+ site = _api_site(name='api-mc-purgefail', host='purgefail-mc.lvh.me')
monkeypatch.setattr(NginxService, 'purge_micro_cache',
- classmethod(lambda cls: {'success': False, 'error': 'boom'}))
+ classmethod(lambda cls, hosts=None: {'success': False, 'error': 'boom'}))
resp = client.post(f'/api/v1/apps/{site.id}/micro-cache/purge', headers=auth_headers)
assert resp.status_code == 500
assert resp.get_json() == {'error': 'boom'}
@@ -375,9 +407,8 @@ def test_purge_wipes_and_recreates_cache_dirs(fake_subprocess, monkeypatch):
fake_subprocess.script(['rm'])
fake_subprocess.script(['mkdir'])
- res = NginxService.purge_micro_cache()
+ res = NginxService.purge_micro_cache() # no hosts: every site
assert res['success'] is True
- assert 'shared' in res['note'] # documents the full-zone tradeoff
rm, mkdir = fake_subprocess.commands()
assert rm[:2] == ['rm', '-rf']
assert f'{NginxService.MICROCACHE_DIR}/proxy'.replace('/', _os.sep) in [p.replace('/', _os.sep) for p in rm]
@@ -392,3 +423,66 @@ def test_purge_is_linux_guarded(fake_subprocess, monkeypatch):
assert res['success'] is False
assert 'Linux' in res['error']
assert fake_subprocess.commands() == []
+
+
+# ── per-site purge + TTL (plan 86 §B3) ───────────────────────────────────────
+
[email protected]('ttl,expected', [
+ (None, '10s'), (60, '60s'), (0, '1s'), (99999, f'{NginxService.MICROCACHE_TTL_MAX}s'),
+])
+def test_ttl_is_rendered_and_clamped(ttl, expected):
+ cfg = NginxService.render_site_config(
+ 'shop', 'docker', ['shop.lvh.me'], port=8300, micro_cache=True,
+ micro_cache_ttl=ttl)['config']
+ assert f'proxy_cache_valid 200 301 {expected};' in cfg
+
+
+def test_ttl_cap_stays_below_the_zone_inactive_window():
+ """A stale copy only survives `inactive`; a TTL above it would leave
+ use_stale nothing to serve."""
+ assert 'inactive=10m' in NginxService.MICROCACHE_ZONE_SNIPPET
+ assert NginxService.MICROCACHE_TTL_MAX < 600
+
+
+def test_app_vhost_kwargs_carry_the_ttl(app):
+ site = _mk_site(_mk_owner().id, name='mc-ttl-kwargs', host='mc-ttl.lvh.me')
+ site.micro_cache_ttl = 45
+ kwargs, _warn = SiteDomainService.app_vhost_kwargs(site)
+ assert kwargs['micro_cache_ttl'] == 45
+
+
[email protected](shutil.which('grep') is None, reason='needs grep')
+def test_per_site_purge_removes_only_that_hosts_files(tmp_path, monkeypatch):
+ """Real grep over real cache-shaped files: nginx writes the key as a
+ `KEY: ...` header line near the start of each cache file."""
+ import subprocess as _sp
+ monkeypatch.setattr(os, 'name', 'posix')
+ monkeypatch.setattr(NginxService, 'MICROCACHE_DIR', str(tmp_path))
+ monkeypatch.setattr('app.services.nginx_service.run_privileged',
+ lambda argv, **kw: _sp.run(argv, capture_output=True, text=True,
+ timeout=kw.get('timeout', 30)))
+ entries = {
+ 'proxy/a/1/shop1': 'KEY: https://shop.lvh.me/\n',
+ 'proxy/a/2/shop2': 'KEY: http://shop.lvh.me/cart?x=1\n',
+ 'fastcgi/b/3/shop3': 'KEY: https://shop.lvh.me/blog\n',
+ 'proxy/c/4/other': 'KEY: https://blog.lvh.me/\n',
+ 'proxy/c/5/lookalike': 'KEY: https://shop.lvh.me.evil.test/\n',
+ }
+ for rel, key in entries.items():
+ path = tmp_path / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b'\x05\x00binary-header\n' + key.encode() + b'\r\nbody')
+
+ res = NginxService.purge_micro_cache(['shop.lvh.me'])
+
+ assert res['success'] is True, res
+ assert res['purged'] == 3
+ left = sorted(p.name for p in tmp_path.rglob('*') if p.is_file())
+ assert left == ['lookalike', 'other']
+
+
+def test_per_site_purge_rejects_a_bad_host(monkeypatch, fake_subprocess):
+ monkeypatch.setattr(os, 'name', 'posix')
+ res = NginxService.purge_micro_cache(['shop.lvh.me; rm -rf /'])
+ assert res['success'] is False
+ assert fake_subprocess.commands() == []
diff --git a/backend/tests/test_real_nginx_vhost_syntax.py b/backend/tests/test_real_nginx_vhost_syntax.py
index b318c575..7604786c 100644
--- a/backend/tests/test_real_nginx_vhost_syntax.py
+++ b/backend/tests/test_real_nginx_vhost_syntax.py
@@ -113,6 +113,10 @@ def _render(**kwargs):
('docker-micro-cache', dict(name='fast', app_type='docker',
domains=['fast.example.com'], port=8004,
micro_cache=True)),
+ ('php-micro-cache', dict(name='fastphp', app_type='php',
+ domains=['fastphp.example.com'],
+ root_path='/var/www/fastphp', micro_cache=True,
+ micro_cache_ttl=120)),
('wordpress-proxy', dict(name='wp', app_type='docker',
domains=['wp.example.com'], port=8005,
wordpress_protection=True)),
diff --git a/frontend/src/components/apps/MicroCachePanel.jsx b/frontend/src/components/apps/MicroCachePanel.jsx
index 53090ca5..893b9c0f 100644
--- a/frontend/src/components/apps/MicroCachePanel.jsx
+++ b/frontend/src/components/apps/MicroCachePanel.jsx
@@ -1,50 +1,87 @@
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import { Zap, Eraser } from 'lucide-react';
import api from '../../services/api';
import { useToast } from '../../contexts/useToast.js';
import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { useConfirm } from '@/hooks/useConfirm';
+import { formatPercent } from '@/utils/intl';
import { useTranslation } from 'react-i18next';
-// Micro-cache panel (task #21) — opt-in nginx page cache per site. The
-// backend rewrites the site's vhost with short-TTL cache directives plus
+// Must match NginxService.MICROCACHE_TTL_DEFAULT / MICROCACHE_TTL_MAX.
+const TTL_DEFAULT = 10;
+const TTL_MAX = 300;
+
+// Micro-cache panel (task #21, plan 86 §B3) — opt-in nginx page cache per
+// site. The backend rewrites the site's vhost with the cache directives plus
// hard bypasses for anything personalized (logged-in cookies, carts,
-// admin/login paths, non-GET requests, query strings).
+// admin/login paths, non-GET requests, query strings). Stale copies are served
+// while the app is down or the entry refreshes.
const MicroCachePanel = ({ app, onChanged }) => {
const { t } = useTranslation();
const toast = useToast();
const { confirm } = useConfirm();
const [enabled, setEnabled] = useState(!!app.micro_cache_enabled);
+ const [ttl, setTtl] = useState(String(app.micro_cache_ttl ?? TTL_DEFAULT));
const [saving, setSaving] = useState(false);
const [purging, setPurging] = useState(false);
+ const [hitRatio, setHitRatio] = useState(null);
- async function handleToggle(next) {
+ useEffect(() => {
+ if (!enabled) return undefined;
+ let cancelled = false;
+ api.getAppRequestMetrics(app.id, '24h')
+ .then((data) => { if (!cancelled) setHitRatio(data?.summary?.cache_hit_ratio ?? null); })
+ .catch(() => {});
+ return () => { cancelled = true; };
+ }, [app.id, enabled]);
+
+ const ttlNumber = Number(ttl);
+ const ttlValid = Number.isInteger(ttlNumber) && ttlNumber >= 1 && ttlNumber <= TTL_MAX;
+ const ttlDirty = ttlValid && ttlNumber !== (app.micro_cache_ttl ?? TTL_DEFAULT);
+
+ async function save(nextEnabled, nextTtl) {
setSaving(true);
- setEnabled(next); // optimistic; reverted on failure
try {
- const data = await api.setMicroCache(app.id, next);
+ const data = await api.setMicroCache(app.id, nextEnabled, nextTtl);
if (data.warning) toast.warning(data.warning);
- if (data.note) {
- toast.info(data.note);
- } else {
+ if (data.note) toast.info(data.note);
+ onChanged?.();
+ return data;
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ async function handleToggle(next) {
+ setEnabled(next); // optimistic; reverted on failure
+ try {
+ const data = await save(next, ttlValid ? ttlNumber : undefined);
+ if (!data.note) {
toast.success(next
? t('app.microCachePanel.microCacheEnabledTheSiteConfig', 'Micro-cache enabled — the site config was updated.')
: t('app.microCachePanel.microCacheDisabledTheSiteConfig', 'Micro-cache disabled — the site config was updated.'));
}
- onChanged?.();
} catch (err) {
setEnabled(!next);
toast.error(err.message || t('app.microCachePanel.failedToUpdateMicroCache', 'Failed to update micro-cache'));
- } finally {
- setSaving(false);
+ }
+ }
+
+ async function handleSaveTtl() {
+ try {
+ await save(enabled, ttlNumber);
+ toast.success(t('app.microCachePanel.cacheLifetimeSaved', 'Cache lifetime saved.'));
+ } catch (err) {
+ toast.error(err.message || t('app.microCachePanel.failedToUpdateMicroCache', 'Failed to update micro-cache'));
}
}
async function handlePurge() {
if (!await confirm({
title: t('app.microCachePanel.clearMicroCache', 'Clear micro-cache'),
- message: t('app.microCachePanel.clearCachedPagesForEverySite', 'Clear cached pages for every site using the shared cache? Entries normally expire within 10 seconds.'),
+ message: t('app.microCachePanel.clearCachedPagesForThisSite', 'Clear the cached pages for this site? Other sites keep their cache.'),
confirmText: t('app.microCachePanel.clearCache', 'Clear cache'),
})) return;
setPurging(true);
@@ -66,7 +103,7 @@ const MicroCachePanel = ({ app, onChanged }) => {
</div>
<div className="app-panel-body">
<p className="app-panel-hint">
- {t('app.microCachePanel.cachesFullPagesInNginxFor', 'Caches full pages in nginx for 10 seconds, so traffic spikes hit the cache instead of your app — a big, cheap win for WordPress and PHP sites. It is safe to enable: requests from logged-in users, carts and checkouts, admin and login pages, non-GET requests, and URLs with query strings always bypass the cache and reach the app directly.')}
+ {t('app.microCachePanel.cachesFullPagesInNginx', 'Caches full pages in nginx for a few seconds, so traffic spikes hit the cache instead of your app, and visitors still get the last good page while the app restarts or errors. It is safe to enable: requests from logged-in users, carts and checkouts, admin and login pages, non-GET requests, and URLs with query strings always bypass the cache and reach the app directly.')}
</p>
<div className="settings-row">
@@ -88,20 +125,66 @@ const MicroCachePanel = ({ app, onChanged }) => {
</div>
{enabled && (
- <div className="settings-row">
- <div className="settings-label">
- <span>{t('app.microCachePanel.clearCache', 'Clear cache')}</span>
- <span className="settings-hint">
- {t('app.microCachePanel.entriesExpireOnTheirOwnWithin', 'Entries expire on their own within 10 seconds; use this when a change must be visible immediately. The cache is shared, so this clears it for every site that uses it.')}
- </span>
+ <>
+ <div className="settings-row">
+ <div className="settings-label">
+ <label htmlFor={`micro-cache-ttl-${app.id}`}>
+ {t('app.microCachePanel.cacheLifetime', 'Cache lifetime (seconds)')}
+ </label>
+ <span className="settings-hint">
+ {t('app.microCachePanel.cacheLifetimeHint', 'How long a page is served from the cache before the app is asked again (1–{{max}}). Longer means fewer requests reach the app, and changes take longer to show.', { max: TTL_MAX })}
+ </span>
+ </div>
+ <div className="settings-control micro-cache__ttl">
+ <Input
+ id={`micro-cache-ttl-${app.id}`}
+ type="number"
+ min={1}
+ max={TTL_MAX}
+ value={ttl}
+ onChange={(e) => setTtl(e.target.value)}
+ disabled={saving}
+ />
+ <Button variant="outline" size="sm" onClick={handleSaveTtl}
+ disabled={saving || !ttlDirty}>
+ {t('common.actions.save', 'Save')}
+ </Button>
+ </div>
+ </div>
+
+ <div className="settings-row">
+ <div className="settings-label">
+ <span>{t('app.microCachePanel.hitRatio', 'Hit ratio (24 h)')}</span>
+ <span className="settings-hint">
+ {t('app.microCachePanel.hitRatioHint', 'Share of cacheable requests answered from the cache. Bypassed requests are not counted.')}
+ </span>
+ </div>
+ <div className="settings-control">
+ <span className="micro-cache__ratio">
+ {hitRatio === null
+ ? t('app.microCachePanel.noCachedTrafficYet', 'No cached traffic yet')
+ : formatPercent(hitRatio * 100)}
+ </span>
+ </div>
</div>
- <div className="settings-control">
- <Button variant="outline" size="sm" onClick={handlePurge} disabled={purging}>
- <Eraser size={14} />
- {purging ? 'Clearing…' : 'Clear cache'}
- </Button>
+
+ <div className="settings-row">
+ <div className="settings-label">
+ <span>{t('app.microCachePanel.clearCache', 'Clear cache')}</span>
+ <span className="settings-hint">
+ {t('app.microCachePanel.clearThisSitesEntries', 'Entries expire on their own after the cache lifetime; use this when a change must be visible now. Only this site\'s pages are cleared.')}
+ </span>
+ </div>
+ <div className="settings-control">
+ <Button variant="outline" size="sm" onClick={handlePurge} disabled={purging}>
+ <Eraser size={14} />
+ {purging
+ ? t('app.microCachePanel.clearing', 'Clearing…')
+ : t('app.microCachePanel.clearCache', 'Clear cache')}
+ </Button>
+ </div>
</div>
- </div>
+ </>
)}
<p className="app-panel-hint">
diff --git a/frontend/src/components/service-detail/SettingsTab.jsx b/frontend/src/components/service-detail/SettingsTab.jsx
index 3a79853d..33b5d151 100644
--- a/frontend/src/components/service-detail/SettingsTab.jsx
+++ b/frontend/src/components/service-detail/SettingsTab.jsx
@@ -337,8 +337,9 @@ const SettingsTab = ({ app, deployConfig, domains, primaryDomain, onUpdate }) =>
</div>
)}
- {/* Cache — opt-in nginx micro-cache (task #21): 10s page cache
- with auth/admin/cart bypasses and a manual purge. */}
+ {/* Cache — opt-in nginx micro-cache (task #21, plan 86 §B3):
+ short-TTL page cache with auth/admin/cart bypasses, stale
+ serving, and a per-site purge. */}
{section === 'cache' && (
<div className="svc-settings__section">
<h3 className="svc-settings__section-title">{t('app.settingsTab.cache', 'Cache')}</h3>
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index a2b0fdea..0b4eb265 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -3001,12 +3001,9 @@
"workers": "العمال"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "يقوم بتخزين صفحات كاملة مؤقتًا في nginx لمدة 10 ثوانٍ، وبالتالي فإن ارتفاع حركة المرور يصل إلى ذاكرة التخزين المؤقت بدلاً من تطبيقك - وهو فوز كبير ورخيص لمواقع WordPress وPHP. من الآمن التمكين: الطلبات الواردة من المستخدمين الذين قاموا بتسجيل الدخول، وعربات التسوق والخروج، وصفحات الإدارة وتسجيل الدخول، والطلبات غير GET، وURLs مع سلاسل الاستعلام تتجاوز دائمًا ذاكرة التخزين المؤقت وتصل إلى التطبيق مباشرة.",
"clearCache": "مسح ذاكرة التخزين المؤقت",
- "clearCachedPagesForEverySite": "هل تريد مسح الصفحات المخزنة مؤقتًا لكل موقع يستخدم ذاكرة التخزين المؤقت المشتركة؟ تنتهي صلاحية الإدخالات عادةً خلال 10 ثوانٍ.",
"clearMicroCache": "مسح ذاكرة التخزين المؤقت الصغيرة",
"enableMicroCache": "تمكين ذاكرة التخزين المؤقت الصغيرة",
- "entriesExpireOnTheirOwnWithin": "تنتهي صلاحية الإدخالات من تلقاء نفسها خلال 10 ثوانٍ؛ استخدم هذا عندما يجب أن يكون التغيير مرئيًا على الفور. تتم مشاركة ذاكرة التخزين المؤقت، لذلك يؤدي هذا إلى مسحها لكل موقع يستخدمها.",
"failedToClearTheMicroCache": "فشل في مسح ذاكرة التخزين المؤقت الصغيرة",
"failedToUpdateMicroCache": "فشل في تحديث ذاكرة التخزين المؤقت الصغيرة",
"meansThePageCameFromThe": "يعني أن الصفحة جاءت من ذاكرة التخزين المؤقت،",
diff --git a/frontend/src/i18n/locales/bn.json b/frontend/src/i18n/locales/bn.json
index 7e40fe72..dcb18e08 100644
--- a/frontend/src/i18n/locales/bn.json
+++ b/frontend/src/i18n/locales/bn.json
@@ -3001,12 +3001,9 @@
"workers": "শ্রমিকরা"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "nginx-এ 10 সেকেন্ডের জন্য সম্পূর্ণ পৃষ্ঠাগুলি ক্যাশে করে, তাই ট্রাফিক স্পাইকগুলি আপনার অ্যাপের পরিবর্তে ক্যাশে আঘাত করে — WordPress এবং PHP সাইটগুলির জন্য একটি বড়, সস্তা জয়৷ এটি সক্ষম করা নিরাপদ: লগ-ইন করা ব্যবহারকারীদের কাছ থেকে অনুরোধ, কার্ট এবং চেকআউট, অ্যাডমিন এবং লগইন পৃষ্ঠাগুলি, নন-GET অনুরোধ, এবং URL কোয়েরি স্ট্রিংগুলি সবসময় ক্যাশে বাইপাস করে এবং সরাসরি অ্যাপে পৌঁছায়৷",
"clearCache": "ক্যাশে সাফ করুন",
- "clearCachedPagesForEverySite": "শেয়ার্ড ক্যাশে ব্যবহার করে প্রতিটি সাইটের জন্য ক্যাশে করা পৃষ্ঠাগুলি সাফ করবেন? এন্ট্রি সাধারণত 10 সেকেন্ডের মধ্যে মেয়াদ শেষ হয়.",
"clearMicroCache": "মাইক্রো-ক্যাশে সাফ করুন",
"enableMicroCache": "মাইক্রো-ক্যাশে সক্ষম করুন",
- "entriesExpireOnTheirOwnWithin": "এন্ট্রিগুলি 10 সেকেন্ডের মধ্যে নিজেরাই শেষ হয়ে যায়; এটি ব্যবহার করুন যখন একটি পরিবর্তন অবিলম্বে দৃশ্যমান হবে। ক্যাশে শেয়ার করা হয়েছে, তাই এটি ব্যবহার করে এমন প্রতিটি সাইটের জন্য এটি পরিষ্কার করে।",
"failedToClearTheMicroCache": "মাইক্রো-ক্যাশে সাফ করতে ব্যর্থ হয়েছে৷",
"failedToUpdateMicroCache": "মাইক্রো-ক্যাশে আপডেট করতে ব্যর্থ হয়েছে৷",
"meansThePageCameFromThe": "মানে পৃষ্ঠাটি ক্যাশে থেকে এসেছে,",
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index 2bb5ec97..1383fa65 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -3001,12 +3001,9 @@
"workers": "Arbeiter"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "Speichert ganze Seiten 10 Sekunden lang in Nginx zwischen, sodass Traffic-Spitzen den Cache und nicht Ihre App treffen – ein großer, günstiger Gewinn für WordPress- und PHP-Sites. Es ist sicher zu aktivieren: Anfragen von angemeldeten Benutzern, Warenkörben und Kassen, Admin- und Anmeldeseiten, Nicht-GET-Anfragen und URLs mit Abfragezeichenfolgen umgehen immer den Cache und erreichen die App direkt.",
"clearCache": "Cache leeren",
- "clearCachedPagesForEverySite": "Zwischengespeicherte Seiten für jede Website mithilfe des gemeinsamen Caches löschen? Einträge verfallen normalerweise innerhalb von 10 Sekunden.",
"clearMicroCache": "Mikrocache löschen",
"enableMicroCache": "Mikrocache aktivieren",
- "entriesExpireOnTheirOwnWithin": "Einträge verfallen innerhalb von 10 Sekunden von selbst; Verwenden Sie dies, wenn eine Änderung sofort sichtbar sein muss. Der Cache wird gemeinsam genutzt, daher wird er für jede Site gelöscht, die ihn verwendet.",
"failedToClearTheMicroCache": "Der Mikrocache konnte nicht geleert werden",
"failedToUpdateMicroCache": "Mikrocache konnte nicht aktualisiert werden",
"meansThePageCameFromThe": "bedeutet, dass die Seite aus dem Cache stammt,",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index b40a8a21..18c56086 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -3193,19 +3193,26 @@
"workers": "Workers"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "Caches full pages in nginx for 10 seconds, so traffic spikes hit the cache instead of your app — a big, cheap win for WordPress and PHP sites. It is safe to enable: requests from logged-in users, carts and checkouts, admin and login pages, non-GET requests, and URLs with query strings always bypass the cache and reach the app directly.",
+ "cacheLifetime": "Cache lifetime (seconds)",
+ "cacheLifetimeHint": "How long a page is served from the cache before the app is asked again (1–{{max}}). Longer means fewer requests reach the app, and changes take longer to show.",
+ "cacheLifetimeSaved": "Cache lifetime saved.",
+ "cachesFullPagesInNginx": "Caches full pages in nginx for a few seconds, so traffic spikes hit the cache instead of your app, and visitors still get the last good page while the app restarts or errors. It is safe to enable: requests from logged-in users, carts and checkouts, admin and login pages, non-GET requests, and URLs with query strings always bypass the cache and reach the app directly.",
"clearCache": "Clear cache",
- "clearCachedPagesForEverySite": "Clear cached pages for every site using the shared cache? Entries normally expire within 10 seconds.",
+ "clearCachedPagesForThisSite": "Clear the cached pages for this site? Other sites keep their cache.",
"clearMicroCache": "Clear micro-cache",
+ "clearThisSitesEntries": "Entries expire on their own after the cache lifetime; use this when a change must be visible now. Only this site's pages are cleared.",
+ "clearing": "Clearing…",
"enableMicroCache": "Enable micro-cache",
- "entriesExpireOnTheirOwnWithin": "Entries expire on their own within 10 seconds; use this when a change must be visible immediately. The cache is shared, so this clears it for every site that uses it.",
"failedToClearTheMicroCache": "Failed to clear the micro-cache",
"failedToUpdateMicroCache": "Failed to update micro-cache",
+ "hitRatio": "Hit ratio (24 h)",
+ "hitRatioHint": "Share of cacheable requests answered from the cache. Bypassed requests are not counted.",
"meansThePageCameFromThe": "means the page came from the cache,",
"microCache": "Micro-cache",
"microCacheCleared": "Micro-cache cleared",
"microCacheDisabledTheSiteConfig": "Micro-cache disabled — the site config was updated.",
"microCacheEnabledTheSiteConfig": "Micro-cache enabled — the site config was updated.",
+ "noCachedTrafficYet": "No cached traffic yet",
"responseHeaderOnTheSite": "response header on the site:",
"rewritesThisSiteSNginxConfig": "Rewrites this site's nginx config with the cache rules. Turning it off removes them again.",
"thatABypassRuleApplied": "that a bypass rule applied.",
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index 4d919097..14e9859a 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -3001,12 +3001,9 @@
"workers": "Workers"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "Almacena páginas completas en la caché de nginx durante 10 segundos, de modo que los picos de tráfico llegan a la caché en lugar de a tu app: una gran mejora y casi gratis para sitios de WordPress y PHP. Es seguro activarla: las peticiones de usuarios con sesión iniciada, los carritos y las pantallas de pago, las páginas de administración y de inicio de sesión, las peticiones que no son GET y las URL con parámetros de consulta siempre omiten la caché y llegan directamente a la app.",
"clearCache": "Limpiar la caché",
- "clearCachedPagesForEverySite": "¿Limpiar las páginas en caché de todos los sitios que usan la caché compartida? Las entradas caducan normalmente en 10 segundos.",
"clearMicroCache": "Limpiar la microcaché",
"enableMicroCache": "Activar la microcaché",
- "entriesExpireOnTheirOwnWithin": "Las entradas caducan por sí solas en 10 segundos; usa esto cuando un cambio deba verse de inmediato. La caché es compartida, así que se limpia para todos los sitios que la usan.",
"failedToClearTheMicroCache": "No se pudo limpiar la microcaché",
"failedToUpdateMicroCache": "No se pudo actualizar la microcaché",
"meansThePageCameFromThe": "significa que la página vino de la caché,",
@@ -3019,7 +3016,17 @@
"thatABypassRuleApplied": "que se aplicó una regla de omisión.",
"thatItWasFetchedFreshAnd": "que se obtuvo directamente, y",
"toVerifyItWorksCheckThe": "Para verificar que funciona, revisa la",
- "xSkCache": "X-SK-Cache"
+ "xSkCache": "X-SK-Cache",
+ "cacheLifetime": "Duración de la caché (segundos)",
+ "cacheLifetimeHint": "Cuánto tiempo se sirve una página desde la caché antes de volver a pedirla a la app (1–{{max}}). Más tiempo significa menos solicitudes a la app, y los cambios tardan más en verse.",
+ "cacheLifetimeSaved": "Duración de la caché guardada.",
+ "cachesFullPagesInNginx": "Guarda páginas completas en nginx durante unos segundos, para que los picos de tráfico lleguen a la caché y no a tu app, y los visitantes sigan viendo la última página buena mientras la app se reinicia o falla. Es seguro activarla: las solicitudes de usuarios con sesión iniciada, carritos y pagos, páginas de administración e inicio de sesión, solicitudes que no son GET y URL con parámetros siempre evitan la caché y llegan directamente a la app.",
+ "clearCachedPagesForThisSite": "¿Borrar las páginas en caché de este sitio? Los demás sitios conservan su caché.",
+ "clearThisSitesEntries": "Las entradas caducan solas tras la duración de la caché; úsalo cuando un cambio deba verse ya. Solo se borran las páginas de este sitio.",
+ "clearing": "Borrando…",
+ "hitRatio": "Tasa de aciertos (24 h)",
+ "hitRatioHint": "Proporción de solicitudes cacheables respondidas desde la caché. Las solicitudes que evitan la caché no cuentan.",
+ "noCachedTrafficYet": "Aún no hay tráfico en caché"
},
"migrationHistoryTab": {
"aDatabaseBackupIsCreatedFirst": "Primero se crea una copia de seguridad de la base de datos y luego el esquema se actualiza de {{value}} a {{value2}}.",
diff --git a/frontend/src/i18n/locales/fr.json b/frontend/src/i18n/locales/fr.json
index b81585a0..2171b277 100644
--- a/frontend/src/i18n/locales/fr.json
+++ b/frontend/src/i18n/locales/fr.json
@@ -3001,12 +3001,9 @@
"workers": "Ouvriers"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "Met en cache les pages complètes dans nginx pendant 10 secondes, de sorte que les pics de trafic touchent le cache plutôt que votre application – une victoire importante et bon marché pour les sites WordPress et PHP. Il est sûr d'activer : les requêtes des utilisateurs connectés, les paniers et les paiements, les pages d'administration et de connexion, les requêtes non-GET et les URL avec des chaînes de requête contournent toujours le cache et atteignent directement l'application.",
"clearCache": "Vider le cache",
- "clearCachedPagesForEverySite": "Effacer les pages mises en cache pour chaque site utilisant le cache partagé ? Les inscriptions expirent normalement dans les 10 secondes.",
"clearMicroCache": "Effacer le micro-cache",
"enableMicroCache": "Activer le micro-cache",
- "entriesExpireOnTheirOwnWithin": "Les inscriptions expirent d’elles-mêmes dans les 10 secondes ; utilisez-le lorsqu'un changement doit être visible immédiatement. Le cache est partagé, il est donc effacé pour chaque site qui l'utilise.",
"failedToClearTheMicroCache": "Échec de la suppression du micro-cache",
"failedToUpdateMicroCache": "Échec de la mise à jour du micro-cache",
"meansThePageCameFromThe": "signifie que la page provient du cache,",
diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json
index 8e83e098..5f37ebf7 100644
--- a/frontend/src/i18n/locales/id.json
+++ b/frontend/src/i18n/locales/id.json
@@ -3001,12 +3001,9 @@
"workers": "Pekerja"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "Menyimpan halaman penuh dalam cache di nginx selama 10 detik, sehingga lonjakan lalu lintas akan mengenai cache, bukan aplikasi Anda — sebuah kemenangan besar dan murah untuk situs WordPress dan PHP. Aman untuk diaktifkan: permintaan dari pengguna yang masuk, keranjang dan checkout, halaman admin dan login, permintaan non-GET, dan URL dengan string kueri selalu melewati cache dan menjangkau aplikasi secara langsung.",
"clearCache": "Hapus cache",
- "clearCachedPagesForEverySite": "Hapus halaman cache untuk setiap situs menggunakan cache bersama? Entri biasanya kedaluwarsa dalam 10 detik.",
"clearMicroCache": "Hapus cache mikro",
"enableMicroCache": "Aktifkan cache mikro",
- "entriesExpireOnTheirOwnWithin": "Entri kedaluwarsa dengan sendirinya dalam 10 detik; gunakan ini ketika perubahan harus segera terlihat. Cache dibagikan, jadi ini akan menghapusnya untuk setiap situs yang menggunakannya.",
"failedToClearTheMicroCache": "Gagal menghapus cache mikro",
"failedToUpdateMicroCache": "Gagal memperbarui cache mikro",
"meansThePageCameFromThe": "berarti halaman tersebut berasal dari cache,",
diff --git a/frontend/src/i18n/locales/it.json b/frontend/src/i18n/locales/it.json
index 69d09b3e..a78727d1 100644
--- a/frontend/src/i18n/locales/it.json
+++ b/frontend/src/i18n/locales/it.json
@@ -3001,12 +3001,9 @@
"workers": "Lavoratori"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "Memorizza nella cache pagine intere in nginx per 10 secondi, in modo che i picchi di traffico colpiscano la cache anziché la tua app: una grande ed economica vittoria per i siti WordPress e PHP. È sicuro abilitare: richieste da utenti che hanno effettuato l'accesso, carrelli e casse, pagine di amministrazione e accesso, richieste non GET e URL con stringhe di query ignorano sempre la cache e raggiungono direttamente l'app.",
"clearCache": "Svuota cache",
- "clearCachedPagesForEverySite": "Cancellare le pagine memorizzate nella cache per ogni sito utilizzando la cache condivisa? Le voci normalmente scadono entro 10 secondi.",
"clearMicroCache": "Cancella la microcache",
"enableMicroCache": "Abilita la microcache",
- "entriesExpireOnTheirOwnWithin": "Le voci scadono da sole entro 10 secondi; utilizzare questo quando una modifica deve essere immediatamente visibile. La cache è condivisa, quindi la cancella per ogni sito che la utilizza.",
"failedToClearTheMicroCache": "Impossibile cancellare la micro-cache",
"failedToUpdateMicroCache": "Impossibile aggiornare la micro-cache",
"meansThePageCameFromThe": "significa che la pagina proviene dalla cache,",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index d7aa248a..17dfb57a 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -3001,12 +3001,9 @@
"workers": "노동자"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "nginx에서 10초 동안 전체 페이지를 캐시하므로 트래픽 급증이 앱 대신 캐시에 도달합니다. 이는 WordPress 및 PHP 사이트에 있어 크고 저렴한 승리입니다. 활성화하는 것이 안전합니다. 로그인한 사용자, 장바구니 및 체크아웃, 관리 및 로그인 페이지, GET이 아닌 요청, 쿼리 문자열이 있는 URL의 요청은 항상 캐시를 우회하고 앱에 직접 연결됩니다.",
"clearCache": "캐시 지우기",
- "clearCachedPagesForEverySite": "공유 캐시를 사용하여 모든 사이트의 캐시된 페이지를 지우시겠습니까? 항목은 일반적으로 10초 이내에 만료됩니다.",
"clearMicroCache": "마이크로 캐시 지우기",
"enableMicroCache": "마이크로 캐시 활성화",
- "entriesExpireOnTheirOwnWithin": "항목은 10초 이내에 자동으로 만료됩니다. 변경 사항이 즉시 표시되어야 할 때 이것을 사용하십시오. 캐시는 공유되므로 캐시를 사용하는 모든 사이트에서 캐시가 지워집니다.",
"failedToClearTheMicroCache": "마이크로 캐시를 지우지 못했습니다.",
"failedToUpdateMicroCache": "마이크로 캐시를 업데이트하지 못했습니다.",
"meansThePageCameFromThe": "페이지가 캐시에서 왔다는 의미입니다.",
diff --git a/frontend/src/i18n/locales/pl.json b/frontend/src/i18n/locales/pl.json
index adad754f..f477ca13 100644
--- a/frontend/src/i18n/locales/pl.json
+++ b/frontend/src/i18n/locales/pl.json
@@ -3001,12 +3001,9 @@
"workers": "Pracownicy"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "Buforuje całe strony w nginx przez 10 sekund, więc skoki ruchu trafiają do pamięci podręcznej zamiast do Twojej aplikacji — duża i tania korzyść dla witryn WordPress i PHP. Bezpieczne jest włączenie: żądania od zalogowanych użytkowników, koszyków i kas, stron administratora i logowania, żądania inne niż GET i URL z ciągami zapytań zawsze omijają pamięć podręczną i docierają bezpośrednio do aplikacji.",
"clearCache": "Wyczyść pamięć podręczną",
- "clearCachedPagesForEverySite": "Wyczyścić strony z pamięci podręcznej dla każdej witryny przy użyciu udostępnionej pamięci podręcznej? Wpisy zwykle wygasają w ciągu 10 sekund.",
"clearMicroCache": "Wyczyść mikro-cache",
"enableMicroCache": "Włącz mikro-cache",
- "entriesExpireOnTheirOwnWithin": "Wpisy wygasają samoistnie w ciągu 10 sekund; użyj tego, gdy zmiana musi być widoczna natychmiast. Pamięć podręczna jest współdzielona, więc zostanie ona wyczyszczona dla każdej witryny, która z niej korzysta.",
"failedToClearTheMicroCache": "Nie udało się wyczyścić mikro-pamięci podręcznej",
"failedToUpdateMicroCache": "Nie udało się zaktualizować mikro-cache",
"meansThePageCameFromThe": "oznacza, że strona pochodzi z pamięci podręcznej,",
diff --git a/frontend/src/i18n/locales/pt.json b/frontend/src/i18n/locales/pt.json
index 5bc3826b..c7539fe8 100644
--- a/frontend/src/i18n/locales/pt.json
+++ b/frontend/src/i18n/locales/pt.json
@@ -3001,12 +3001,9 @@
"workers": "Trabalhadores"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "Armazena páginas inteiras em cache no nginx por 10 segundos, para que os picos de tráfego atinjam o cache em vez de seu aplicativo – uma vitória grande e barata para sites WordPress e PHP. É seguro habilitar: solicitações de usuários logados, carrinhos e checkouts, páginas de administração e login, solicitações não GET e URLs com strings de consulta sempre ignoram o cache e chegam diretamente ao aplicativo.",
"clearCache": "Limpar cache",
- "clearCachedPagesForEverySite": "Limpar páginas em cache de todos os sites usando o cache compartilhado? As inscrições normalmente expiram em 10 segundos.",
"clearMicroCache": "Limpar micro-cache",
"enableMicroCache": "Habilitar micro-cache",
- "entriesExpireOnTheirOwnWithin": "As inscrições expiram sozinhas em 10 segundos; use isto quando uma alteração precisar ser visível imediatamente. O cache é compartilhado, portanto, ele é limpo para todos os sites que o utilizam.",
"failedToClearTheMicroCache": "Falha ao limpar o microcache",
"failedToUpdateMicroCache": "Falha ao atualizar o microcache",
"meansThePageCameFromThe": "significa que a página veio do cache,",
diff --git a/frontend/src/i18n/locales/ru.json b/frontend/src/i18n/locales/ru.json
index d56ef7c9..80a28f72 100644
--- a/frontend/src/i18n/locales/ru.json
+++ b/frontend/src/i18n/locales/ru.json
@@ -3001,12 +3001,9 @@
"workers": "Рабочие процессы"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "Кэширует полные страницы в nginx в течение 10 секунд, поэтому всплески трафика попадают в кеш, а не в ваше приложение — большая и дешевая победа для сайтов WordPress и PHP. Включать безопасно: запросы от вошедших в систему пользователей, корзин и касс, страниц администрирования и входа, запросы, отличные от GET, а также URL-адреса со строками запросов всегда обходят кеш и достигают приложения напрямую.",
"clearCache": "Очистить кеш",
- "clearCachedPagesForEverySite": "Очистить кешированные страницы для каждого сайта, используя общий кеш? Записи обычно истекают в течение 10 секунд.",
"clearMicroCache": "Очистить микрокэш",
"enableMicroCache": "Включить микрокэш",
- "entriesExpireOnTheirOwnWithin": "Записи истекают самостоятельно в течение 10 секунд; используйте это, когда изменение должно быть видно немедленно. Кэш является общим, поэтому он очищается для каждого сайта, который его использует.",
"failedToClearTheMicroCache": "Не удалось очистить микрокэш",
"failedToUpdateMicroCache": "Не удалось обновить микрокеш.",
"meansThePageCameFromThe": "означает, что страница получена из кеша,",
diff --git a/frontend/src/i18n/locales/th.json b/frontend/src/i18n/locales/th.json
index 0d28c9c5..5b0248e5 100644
--- a/frontend/src/i18n/locales/th.json
+++ b/frontend/src/i18n/locales/th.json
@@ -3001,12 +3001,9 @@
"workers": "คนงาน"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "แคชหน้าเต็มใน nginx เป็นเวลา 10 วินาที ดังนั้นปริมาณการรับส่งข้อมูลพุ่งไปที่แคชแทนที่จะเป็นแอปของคุณ ถือเป็นชัยชนะครั้งใหญ่ในราคาถูกสำหรับไซต์ WordPress และ PHP เปิดใช้งานได้อย่างปลอดภัย: คำขอจากผู้ใช้ที่เข้าสู่ระบบ รถเข็นและการชำระเงิน หน้าผู้ดูแลระบบและเข้าสู่ระบบ คำขอที่ไม่ใช่ GET และ URL ที่มีสตริงการสืบค้นจะข้ามแคชและเข้าถึงแอปโดยตรงเสมอ",
"clearCache": "ล้างแคช",
- "clearCachedPagesForEverySite": "ล้างแคชเพจสำหรับทุกไซต์โดยใช้แคชที่ใช้ร่วมกันหรือไม่ โดยปกติรายการจะหมดอายุภายใน 10 วินาที",
"clearMicroCache": "ล้างไมโครแคช",
"enableMicroCache": "เปิดใช้งานไมโครแคช",
- "entriesExpireOnTheirOwnWithin": "การเข้าร่วมจะหมดอายุภายใน 10 วินาที; ใช้สิ่งนี้เมื่อต้องมองเห็นการเปลี่ยนแปลงทันที แคชถูกแชร์ ดังนั้นจึงเป็นการล้างแคชสำหรับทุกไซต์ที่ใช้งาน",
"failedToClearTheMicroCache": "ไม่สามารถล้างไมโครแคชได้",
"failedToUpdateMicroCache": "อัปเดตไมโครแคชไม่สำเร็จ",
"meansThePageCameFromThe": "หมายถึงเพจมาจากแคช",
diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json
index 523a35d6..b3edfebc 100644
--- a/frontend/src/i18n/locales/tr.json
+++ b/frontend/src/i18n/locales/tr.json
@@ -3001,12 +3001,9 @@
"workers": "İşçiler"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "Tam sayfaları nginx'de 10 saniye boyunca önbelleğe alır, böylece trafikteki ani artışlar uygulamanız yerine önbelleğe çarpar - WordPress ve PHP siteleri için büyük, ucuz bir kazanç. Etkinleştirmek güvenlidir: oturum açmış kullanıcılardan, alışveriş sepetlerinden ve ödemelerden, yönetici ve giriş sayfalarından, GET olmayan isteklerden ve sorgu dizelerine sahip URL'lerden gelen istekler her zaman önbelleği atlar ve uygulamaya doğrudan ulaşır.",
"clearCache": "Önbelleği temizle",
- "clearCachedPagesForEverySite": "Paylaşılan önbelleği kullanan her site için önbelleğe alınmış sayfalar temizlensin mi? Girişler normalde 10 saniye içinde sona erer.",
"clearMicroCache": "Mikro önbelleği temizle",
"enableMicroCache": "Mikro önbelleği etkinleştir",
- "entriesExpireOnTheirOwnWithin": "Girişler 10 saniye içinde kendiliğinden sona erer; Bir değişikliğin hemen görünür olması gerektiğinde bunu kullanın. Önbellek paylaşılır, dolayısıyla onu kullanan her site için temizler.",
"failedToClearTheMicroCache": "Mikro önbellek temizlenemedi",
"failedToUpdateMicroCache": "Mikro önbellek güncellenemedi",
"meansThePageCameFromThe": "sayfanın önbellekten geldiği anlamına gelir,",
diff --git a/frontend/src/i18n/locales/vi.json b/frontend/src/i18n/locales/vi.json
index da64cdff..07aca0a8 100644
--- a/frontend/src/i18n/locales/vi.json
+++ b/frontend/src/i18n/locales/vi.json
@@ -3001,12 +3001,9 @@
"workers": "Công nhân"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "Lưu toàn bộ trang vào bộ nhớ đệm trong nginx trong 10 giây, do đó lưu lượng truy cập tăng đột biến sẽ tác động vào bộ nhớ đệm thay vì ứng dụng của bạn — một chiến thắng lớn, rẻ cho các trang web WordPress và PHP. Việc kích hoạt là an toàn: yêu cầu từ người dùng đã đăng nhập, giỏ hàng và thanh toán, trang quản trị và đăng nhập, yêu cầu không GET và URL có chuỗi truy vấn luôn bỏ qua bộ nhớ đệm và truy cập trực tiếp vào ứng dụng.",
"clearCache": "Xóa bộ nhớ đệm",
- "clearCachedPagesForEverySite": "Xóa các trang được lưu trong bộ nhớ đệm cho mọi trang web bằng bộ nhớ đệm dùng chung? Các mục thường hết hạn trong vòng 10 giây.",
"clearMicroCache": "Xóa bộ nhớ đệm vi mô",
"enableMicroCache": "Kích hoạt bộ nhớ đệm vi mô",
- "entriesExpireOnTheirOwnWithin": "Các mục sẽ tự hết hạn trong vòng 10 giây; sử dụng điều này khi một thay đổi phải được nhìn thấy ngay lập tức. Bộ nhớ đệm được chia sẻ nên việc này sẽ xóa nó đối với mọi trang web sử dụng nó.",
"failedToClearTheMicroCache": "Không thể xóa bộ nhớ đệm vi mô",
"failedToUpdateMicroCache": "Không thể cập nhật bộ đệm vi mô",
"meansThePageCameFromThe": "có nghĩa là trang đến từ bộ nhớ đệm,",
diff --git a/frontend/src/i18n/locales/zh-Hans.json b/frontend/src/i18n/locales/zh-Hans.json
index 58b46474..ce5c9f55 100644
--- a/frontend/src/i18n/locales/zh-Hans.json
+++ b/frontend/src/i18n/locales/zh-Hans.json
@@ -3001,12 +3001,9 @@
"workers": "工作进程"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "在 nginx 中缓存完整页面 10 秒,因此流量峰值会影响缓存而不是您的应用程序 — 这对于 WordPress 和 PHP 网站来说是一个巨大而廉价的胜利。启用是安全的:来自登录用户、购物车和结帐、管理和登录页面、非 GET 请求以及带有查询字符串的 URL 的请求始终绕过缓存并直接到达应用程序。",
"clearCache": "清除缓存",
- "clearCachedPagesForEverySite": "使用共享缓存清除每个站点的缓存页面?条目通常会在 10 秒内过期。",
"clearMicroCache": "清除微缓存",
"enableMicroCache": "启用微缓存",
- "entriesExpireOnTheirOwnWithin": "条目会在 10 秒内自行过期;当更改必须立即可见时使用此选项。缓存是共享的,因此这会清除每个使用它的站点。",
"failedToClearTheMicroCache": "无法清除微缓存",
"failedToUpdateMicroCache": "微缓存更新失败",
"meansThePageCameFromThe": "表示该页面来自缓存,",
diff --git a/frontend/src/i18n/locales/zh-Hant.json b/frontend/src/i18n/locales/zh-Hant.json
index e74c90cc..ccbadf55 100644
--- a/frontend/src/i18n/locales/zh-Hant.json
+++ b/frontend/src/i18n/locales/zh-Hant.json
@@ -3193,12 +3193,9 @@
"workers": "工作程序"
},
"microCachePanel": {
- "cachesFullPagesInNginxFor": "nginx 會將完整頁面快取 10 秒,讓流量高峰優先由快取處理,減輕 WordPress 和 PHP 網站的負擔,且幾乎不增加成本。登入使用者的請求、購物車與結帳頁面、管理與登入頁面、非 GET 請求,以及含查詢字串的網址,都會略過快取並直接送往應用程式。",
"clearCache": "清除快取",
- "clearCachedPagesForEverySite": "使用共享快取清除每個網站的快取頁面?條目通常會在 10 秒內過期。",
"clearMicroCache": "清除微快取",
"enableMicroCache": "啟用微快取",
- "entriesExpireOnTheirOwnWithin": "條目會在 10 秒內自行過期;當變更必須立即可見時使用此選項。快取是共享的,因此這會清除每個使用它的網站。",
"failedToClearTheMicroCache": "無法清除微快取",
"failedToUpdateMicroCache": "微快取更新失敗",
"meansThePageCameFromThe": "表示此頁面來自快取,",
diff --git a/frontend/src/services/api/apps.js b/frontend/src/services/api/apps.js
index 4a41d676..6506eb92 100644
--- a/frontend/src/services/api/apps.js
+++ b/frontend/src/services/api/apps.js
@@ -134,8 +134,10 @@ export async function updateAppResources(id, data) {
}
// Per-site nginx micro-cache (short-TTL page cache with auth/admin/cart bypasses).
-export async function setMicroCache(id, enabled) {
- return this.request(`/apps/${id}/micro-cache`, { method: 'PUT', body: { enabled } });
+// ttl: whole seconds (1-300), null for the 10s default, undefined to leave as is.
+export async function setMicroCache(id, enabled, ttl) {
+ const body = ttl === undefined ? { enabled } : { enabled, ttl };
+ return this.request(`/apps/${id}/micro-cache`, { method: 'PUT', body });
}
export async function purgeMicroCache(id) {
diff --git a/frontend/src/styles/pages/_applications.scss b/frontend/src/styles/pages/_applications.scss
index 146ca2e1..a9b047ad 100644
--- a/frontend/src/styles/pages/_applications.scss
+++ b/frontend/src/styles/pages/_applications.scss
@@ -1708,3 +1708,19 @@
color: var(--text-dim);
}
}
+
+// Micro-cache panel (plan 86 §B3): TTL input + save, hit-ratio readout.
+.micro-cache {
+ &__ttl {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+
+ input { width: 96px; }
+ }
+
+ &__ratio {
+ font-family: var(--mono);
+ color: var(--text);
+ }
+}