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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(wordpress): page cache + per-site Redis object cache (Docker-correct)
Juan Denis6b67271677c1
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.pyindex 0b3de9f8..5998da7a 100644--- a/backend/app/api/wordpress.py+++ b/backend/app/api/wordpress.py@@ -1,3 +1,4 @@+import jsonfrom flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required, get_jwt_identityfrom app.models import User, Application, WordPressSite@@ -674,6 +675,88 @@ def optimize_database(app_id):return jsonify(result), 200 if result['success'] else 400+@wordpress_bp.route('/sites/<int:app_id>/page-cache', methods=['GET'])+@jwt_required()+def get_page_cache(app_id):+ """Report full-page cache plugin status for a site."""+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ return jsonify(WordPressService.get_page_cache_status(app.root_path)), 200+++@wordpress_bp.route('/sites/<int:app_id>/page-cache', methods=['POST'])+@jwt_required()+@admin_required+def enable_page_cache(app_id):+ """Enable the full-page cache for a site."""+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ result = WordPressService.enable_page_cache(app.root_path)+ if result.get('success'):+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()+ if wp_site:+ cfg = json.loads(wp_site.sync_config) if wp_site.sync_config else {}+ cfg['page_cache_enabled'] = True+ wp_site.sync_config = json.dumps(cfg)+ db.session.commit()+ return jsonify(result), 200 if result.get('success') else 400+++@wordpress_bp.route('/sites/<int:app_id>/page-cache', methods=['DELETE'])+@jwt_required()+@admin_required+def disable_page_cache(app_id):+ """Disable the full-page cache for a site."""+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ result = WordPressService.disable_page_cache(app.root_path)+ if result.get('success'):+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()+ if wp_site:+ cfg = json.loads(wp_site.sync_config) if wp_site.sync_config else {}+ cfg['page_cache_enabled'] = False+ wp_site.sync_config = json.dumps(cfg)+ db.session.commit()+ return jsonify(result), 200 if result.get('success') else 400+++@wordpress_bp.route('/sites/<int:app_id>/object-cache', methods=['GET'])+@jwt_required()+def object_cache_status(app_id):+ """Report Redis object-cache state for a site."""+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ return jsonify(WordPressService.object_cache_status(app.root_path)), 200+++@wordpress_bp.route('/sites/<int:app_id>/object-cache', methods=['POST'])+@jwt_required()+@admin_required+def enable_object_cache(app_id):+ """Enable Redis object cache (adds a redis container if needed, activates plugin)."""+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ result = WordPressService.enable_object_cache(app.root_path)+ return jsonify(result), 200 if result.get('success') else 400+++@wordpress_bp.route('/sites/<int:app_id>/object-cache', methods=['DELETE'])+@jwt_required()+@admin_required+def disable_object_cache(app_id):+ """Disable Redis object cache (keeps the container + plugin)."""+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ result = WordPressService.disable_object_cache(app.root_path)+ return jsonify(result), 200 if result.get('success') else 400++@wordpress_bp.route('/sites/<int:app_id>/flush-cache', methods=['POST'])@jwt_required()@admin_requireddiff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.pyindex acaca23f..50ad1a9c 100644--- a/backend/app/services/wordpress_service.py+++ b/backend/app/services/wordpress_service.py@@ -681,6 +681,144 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]result = cls.wp_cli(path, ['db', 'optimize'])return result+ PAGE_CACHE_PLUGIN = 'cache-enabler'++ @classmethod+ def get_page_cache_status(cls, path: str) -> Dict:+ """Report whether the full-page cache plugin is installed/active."""+ res = cls.wp_cli(path, ['plugin', 'get', cls.PAGE_CACHE_PLUGIN, '--field=status'])+ status = (res.get('output') or '').strip() if res.get('success') else ''+ return {+ 'success': True,+ 'plugin': cls.PAGE_CACHE_PLUGIN,+ 'installed': res.get('success', False),+ 'active': status == 'active',+ 'status': status,+ }++ @classmethod+ def enable_page_cache(cls, path: str) -> Dict:+ """Install + activate a full-page disk cache plugin with WP-aware skip rules."""+ inst = cls.install_plugin(path, cls.PAGE_CACHE_PLUGIN, activate=True)+ if not inst.get('success'):+ return {'success': False, 'error': 'Failed to install page-cache plugin: ' + (inst.get('error') or '')}+ opts = {+ 'cache_expires': 1,+ 'clear_on_upgrade': 1,+ 'excl_regexp': '/(wp-admin|wp-login|cart|checkout|my-account)/',+ 'excl_cookies': 'comment_author|wordpress_logged_in|wp-postpass|woocommerce_cart_hash|woocommerce_items_in_cart',+ }+ cls.wp_cli(path, ['option', 'update', cls.PAGE_CACHE_PLUGIN, json.dumps(opts), '--format=json'])+ cls.wp_cli(path, ['rewrite', 'flush'])+ return {'success': True, 'message': 'Page cache enabled', 'plugin': cls.PAGE_CACHE_PLUGIN}++ @classmethod+ def disable_page_cache(cls, path: str) -> Dict:+ """Purge then deactivate the page-cache plugin."""+ cls.purge_page_cache(path)+ res = cls.deactivate_plugin(path, cls.PAGE_CACHE_PLUGIN)+ if res.get('success'):+ return {'success': True, 'message': 'Page cache disabled'}+ return {'success': False, 'error': res.get('error') or 'Failed to disable page cache'}++ @classmethod+ def purge_page_cache(cls, path: str) -> bool:+ """Best-effort full-page cache purge. Never raises."""+ try:+ res = cls.wp_cli(path, ['cache-enabler', 'clear'])+ if res.get('success'):+ return True+ res = cls.wp_cli(path, ['eval', 'if (function_exists("cache_enabler_clear_complete_cache")) cache_enabler_clear_complete_cache();'])+ return bool(res.get('success'))+ except Exception:+ return False++ @classmethod+ def _ensure_redis_in_stack(cls, path: str) -> Dict:+ """Ensure the site's compose stack has a redis service, recreating the+ stack (additive compose up -d, no downtime) if one had to be injected.+ Idempotent — short-circuits when redis already present.+ """+ import yaml+ compose_file = os.path.join(path, 'docker-compose.yml')+ if not os.path.exists(compose_file):+ return {'success': False, 'error': 'Not a Docker-stack site (no docker-compose.yml)'}+ try:+ with open(compose_file, 'r') as f:+ compose = yaml.safe_load(f) or {}+ services = compose.setdefault('services', {})+ if 'redis' in services:+ return {'success': True, 'created': False}+ app_name = os.path.basename(path)+ from app.models import Application+ app = Application.query.filter_by(root_path=path).first()+ if app:+ app_name = app.name+ services['redis'] = {+ 'image': 'redis:7-alpine',+ 'container_name': f'{app_name}-redis',+ 'restart': 'unless-stopped',+ }+ wp = services.get('wordpress')+ if isinstance(wp, dict):+ deps = wp.get('depends_on') or []+ if isinstance(deps, list) and 'redis' not in deps:+ deps.append('redis')+ wp['depends_on'] = deps+ with open(compose_file, 'w') as f:+ yaml.dump(compose, f, default_flow_style=False, sort_keys=False)+ from app.services.docker_service import DockerService+ up = DockerService.compose_up(path, detach=True)+ if not up.get('success'):+ return {'success': False, 'error': 'Failed to recreate stack with redis: ' + (up.get('error') or '')}+ cls._wait_for_wp_ready(path)+ return {'success': True, 'created': True}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def enable_object_cache(cls, path: str) -> Dict:+ """Enable a Redis object cache: ensure a redis container, install+activate+ the redis-cache plugin, point WP at redis, and turn the drop-in on.+ """+ ensure = cls._ensure_redis_in_stack(path)+ if not ensure.get('success'):+ return ensure+ actions = []+ if ensure.get('created'):+ actions.append('Added redis container to stack')+ inst = cls.wp_cli(path, ['plugin', 'install', 'redis-cache', '--activate'])+ if not inst.get('success'):+ return {'success': False, 'error': 'Failed to install redis-cache plugin: ' + (inst.get('error') or '')}+ actions.append('Installed redis-cache plugin')+ cls.wp_cli(path, ['config', 'set', 'WP_REDIS_HOST', 'redis'])+ cls.wp_cli(path, ['config', 'set', 'WP_REDIS_PORT', '6379', '--raw'])+ enable = cls.wp_cli(path, ['redis', 'enable'])+ if not enable.get('success'):+ return {'success': False, 'error': 'Plugin installed but enabling the drop-in failed: ' + (enable.get('error') or ''), 'actions': actions}+ actions.append('Enabled Redis object cache drop-in')+ return {'success': True, 'message': 'Redis object cache enabled', 'actions': actions, 'status': cls.object_cache_status(path)}++ @classmethod+ def disable_object_cache(cls, path: str) -> Dict:+ """Turn the Redis object-cache drop-in off (keeps the container + plugin)."""+ res = cls.wp_cli(path, ['redis', 'disable'])+ if res.get('success'):+ return {'success': True, 'message': 'Redis object cache disabled'}+ return {'success': False, 'error': res.get('error') or 'Failed to disable object cache'}++ @classmethod+ def object_cache_status(cls, path: str) -> Dict:+ """Report object-cache state via `wp redis status`. Never raises."""+ compose_file = os.path.join(path, 'docker-compose.yml')+ if not os.path.exists(compose_file):+ return {'enabled': False, 'available': False, 'reason': 'not a Docker-stack site'}+ res = cls.wp_cli(path, ['redis', 'status'])+ if not res.get('success'):+ return {'enabled': False, 'available': False}+ out = (res.get('output') or '').lower()+ return {'enabled': 'connected' in out, 'available': True, 'raw': res.get('output', '').strip()}+@classmethoddef flush_cache(cls, path: str) -> Dict:"""Flush WordPress cache."""@@ -699,6 +837,15 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]if cache_result['success']:results.append('Flushed object cache')+ # Flush the Redis object-cache drop-in if the plugin is active (Roadmap #23)+ redis_flush = cls.wp_cli(path, ['redis', 'flush'])+ if redis_flush.get('success'):+ results.append('Flushed Redis object cache')++ # Purge the full-page cache plugin if present (Roadmap #22)+ if cls.purge_page_cache(path):+ results.append('Purged page cache')+return {'success': True, 'message': 'Cache flushed', 'actions': results}@classmethoddiff --git a/backend/templates/wordpress.yaml b/backend/templates/wordpress.yamlindex ec5c1136..ad6b55a5 100644--- a/backend/templates/wordpress.yaml+++ b/backend/templates/wordpress.yaml@@ -57,6 +57,12 @@ compose:- "${HTTP_PORT}:80"depends_on:- db+ - redis++ redis:+ image: redis:7-alpine+ container_name: ${APP_NAME}-redis+ restart: unless-stoppeddb:image: mysql:8.0diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.mdindex 6d304263..0c680ede 100644--- a/docs/WORDPRESS_ROADMAP.md+++ b/docs/WORDPRESS_ROADMAP.md@@ -210,13 +210,13 @@ These are the features that make a user say "this is a managed platform, not a fThe headline value of a managed platform, and the most net-new — but it leans on existing nginx/cache/health/metrics/notification primitives. **Estimated cluster: 4–7 days.**-### #22 — Page cache with WP-aware skip rules `[L]` ❌+### #22 — Page cache with WP-aware skip rules `[L]` ❌ — ✅ Done (Docker-correct: in-container cache-enabler plugin, NOT nginx fastcgi_cache which doesn't apply to the apache-container model)- **Today:** `nginx_advanced_service` can emit `proxy_cache_path`/`proxy_cache`/`proxy_cache_bypass` zones with config-test + diff, but the WP location template (`services/nginx_service.py:215-237`) has **no** cache and the WP UI has no cache controls.- **Do:** Add `fastcgi_cache`/`proxy_cache` to the per-site vhost with skip rules (`wp-admin`/`wp-login`/preview, auth/cart/checkout cookies, query strings) + a single-URL purge action wired to the existing `flush-cache` (#5).- **Reuse:** `nginx_advanced_service`, `nginx_service` WP template.- **Done when:** Anonymous hits are cached; logged-in/cart paths bypass; purge works.-### #23 — Per-site Redis object cache `[L]` ❌+### #23 — Per-site Redis object cache `[L]` ❌ — ✅ Done (adds a redis service to the compose stack + redis-cache plugin via wp_cli; new sites ship redis, existing sites get it injected on enable)- **Today:** Only a blind `wp cache flush` with nothing behind it.- **Do:** Add a Redis service to the compose stack (or a shared Redis DB index per env); `wp plugin install redis-cache --activate`; write `WP_REDIS_HOST`/`WP_REDIS_DATABASE` into `wp-config`; surface enable/status/flush on the site.- **Reuse:** `wp_cli`, `wordpress.yaml` compose template, `flush_cache`.diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsxindex e8de656b..3fdd60a5 100644--- a/frontend/src/pages/WordPressDetail.jsx+++ b/frontend/src/pages/WordPressDetail.jsx@@ -1,6 +1,6 @@import React, { useState, useEffect } from 'react';import { useParams, useNavigate, Link } from 'react-router-dom';-import { ExternalLink, Settings, RefreshCw, Plus, Database, GitBranch, Package, Palette, Archive, Trash2, Replace, ShieldCheck, FolderOpen, FileText, Lock, Copy } from 'lucide-react';+import { ExternalLink, Settings, RefreshCw, Plus, Database, GitBranch, Package, Palette, Archive, Trash2, Replace, ShieldCheck, FolderOpen, FileText, Lock, Copy, Zap } from 'lucide-react';import useTabParam from '../hooks/useTabParam';import wordpressApi from '../services/wordpress';import api from '../services/api';@@ -397,6 +397,10 @@ const OverviewTab = ({ site, onUpdate }) => {const [syncingAll, setSyncingAll] = useState(false);const [flushingCache, setFlushingCache] = useState(false);const [hardening, setHardening] = useState(false);+ const [pageCacheActive, setPageCacheActive] = useState(false);+ const [togglingPageCache, setTogglingPageCache] = useState(false);+ const [objectCache, setObjectCache] = useState(null);+ const [togglingCache, setTogglingCache] = useState(false);const [showSearchReplace, setShowSearchReplace] = useState(false);const [health, setHealth] = useState(null);const [diskUsage, setDiskUsage] = useState(null);@@ -510,6 +514,60 @@ const OverviewTab = ({ site, onUpdate }) => {}}+ useEffect(() => {+ let active = true;+ wordpressApi.getPageCache(site.id)+ .then(r => { if (active) setPageCacheActive(Boolean(r?.active)); })+ .catch(() => { /* best-effort; control just shows Enable */ });+ wordpressApi.getObjectCacheStatus(site.id)+ .then(s => { if (active) setObjectCache(s); })+ .catch(() => {});+ return () => { active = false; };+ }, [site.id]);++ async function handleTogglePageCache() {+ setTogglingPageCache(true);+ const enabling = !pageCacheActive;+ toast.info(enabling ? 'Enabling page cache...' : 'Disabling page cache...', { duration: 4000 });+ try {+ const res = enabling+ ? await wordpressApi.enablePageCache(site.id)+ : await wordpressApi.disablePageCache(site.id);+ if (res.success === false) {+ toast.error(res.error || 'Page cache change failed');+ } else {+ toast.success(res.message || (enabling ? 'Page cache enabled' : 'Page cache disabled'));+ setPageCacheActive(enabling);+ }+ } catch (err) {+ toast.error(err.message || 'Page cache change failed');+ } finally {+ setTogglingPageCache(false);+ }+ }++ async function handleToggleObjectCache() {+ setTogglingCache(true);+ const enabling = !objectCache?.enabled;+ toast.info(enabling ? 'Enabling Redis object cache...' : 'Disabling object cache...', { duration: 4000 });+ try {+ const res = enabling+ ? await wordpressApi.enableObjectCache(site.id)+ : await wordpressApi.disableObjectCache(site.id);+ if (res.success === false) {+ toast.error(res.error || 'Object cache change failed');+ } else {+ toast.success(res.message || (enabling ? 'Object cache enabled' : 'Object cache disabled'));+ const fresh = await wordpressApi.getObjectCacheStatus(site.id).catch(() => null);+ if (fresh) setObjectCache(fresh);+ }+ } catch (err) {+ toast.error(err.message || 'Object cache change failed');+ } finally {+ setTogglingCache(false);+ }+ }+async function handleFlushCache() {setFlushingCache(true);toast.info('Flushing cache...', { duration: 2000 });@@ -876,6 +934,17 @@ const OverviewTab = ({ site, onUpdate }) => {<Trash2 size={16} />{flushingCache ? 'Flushing...' : 'Purge Cache'}</button>+ <button+ className="quick-action-btn"+ onClick={handleTogglePageCache}+ disabled={togglingPageCache}+ title={pageCacheActive ? 'Full-page cache is active' : 'Enable a full-page cache for this site'}+ >+ <Zap size={16} />+ {togglingPageCache+ ? 'Working...'+ : (pageCacheActive ? 'Page Cache: On' : 'Enable Page Cache')}+ </button><buttonclassName="quick-action-btn"onClick={() => setShowSearchReplace(true)}@@ -891,6 +960,17 @@ const OverviewTab = ({ site, onUpdate }) => {<ShieldCheck size={16} />{hardening ? 'Hardening...' : 'Harden'}</button>+ <button+ className="quick-action-btn"+ onClick={handleToggleObjectCache}+ disabled={togglingCache}+ title={objectCache?.enabled ? 'Redis object cache is active' : 'Enable a Redis object cache for this site'}+ >+ <Database size={16} />+ {togglingCache+ ? (objectCache?.enabled ? 'Disabling...' : 'Enabling...')+ : (objectCache?.enabled ? 'Object Cache: On' : 'Enable Object Cache')}+ </button></div></div></div>diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.jsindex 12e01111..d74b64a1 100644--- a/frontend/src/services/wordpress.js+++ b/frontend/src/services/wordpress.js@@ -149,6 +149,11 @@ const wordpressApi = {method: 'POST'}),+ // Full-page cache (plugin-backed) — status / enable / disable+ getPageCache: (siteId) => api.request(`${BASE_PATH}/${siteId}/page-cache`),+ enablePageCache: (siteId) => api.request(`${BASE_PATH}/${siteId}/page-cache`, { method: 'POST' }),+ disablePageCache: (siteId) => api.request(`${BASE_PATH}/${siteId}/page-cache`, { method: 'DELETE' }),+searchReplace: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/search-replace`, {method: 'POST',body: data@@ -158,6 +163,11 @@ const wordpressApi = {method: 'POST'}),+ // Object cache (Redis) — status / enable / disable+ getObjectCacheStatus: (siteId) => api.request(`${BASE_PATH}/${siteId}/object-cache`),+ enableObjectCache: (siteId) => api.request(`${BASE_PATH}/${siteId}/object-cache`, { method: 'POST' }),+ disableObjectCache: (siteId) => api.request(`${BASE_PATH}/${siteId}/object-cache`, { method: 'DELETE' }),+// Mint a one-time passwordless wp-admin login URL for the current operator.autoLogin: (siteId) => api.request(`${BASE_PATH}/${siteId}/login`, {method: 'POST'