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'; import { toastError } from '@/utils/errorMessage'; import InfoTip from '@/components/InfoTip'; // Must match NginxService.MICROCACHE_TTL_DEFAULT / MICROCACHE_TTL_MAX. const TTL_DEFAULT = 10; const TTL_MAX = 300; // App types whose vhost proxies to the app — the only ones the fingerprinted // asset rule applies to (NginxService._with_immutable_assets). const PROXIED_TYPES = ['docker', 'flask', 'django', 'python', 'remote']; // Micro-cache panel — 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). 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); const [immutable, setImmutable] = useState(!!app.immutable_assets); const proxied = PROXIED_TYPES.includes(app.app_type); 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); try { const data = await api.setMicroCache(app.id, nextEnabled, nextTtl); if (data.warning) toast.warning(data.warning); 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.')); } } catch (err) { setEnabled(!next); toastError(toast, t('app.microCachePanel.failedToUpdateMicroCache', "Couldn't update the micro-cache."), err); } } async function handleSaveTtl() { try { await save(enabled, ttlNumber); toast.success(t('app.microCachePanel.cacheLifetimeSaved', 'Cache lifetime saved')); } catch (err) { toastError(toast, t('app.microCachePanel.failedToUpdateMicroCache', "Couldn't update the micro-cache."), err); } } async function handleImmutable(next) { setImmutable(next); try { const data = await api.setImmutableAssets(app.id, next); if (data.warning) toast.warning(data.warning); else toast.success(t('app.microCachePanel.assetCachingSaved', 'Asset caching saved')); onChanged?.(); } catch (err) { setImmutable(!next); toastError(toast, t('app.microCachePanel.couldntUpdateImmutableAssets', "Couldn't update immutable asset caching."), err); } } async function handlePurge() { if (!await confirm({ title: t('app.microCachePanel.clearMicroCache', 'Clear micro-cache'), message: t('app.microCachePanel.clearCachedPagesForThisSite', 'Clear the cached pages for this service? Other services keep their cache.'), confirmText: t('app.microCachePanel.clearCache', 'Clear cache'), })) return; setPurging(true); try { const data = await api.purgeMicroCache(app.id); toast.success(data.message || t('app.microCachePanel.microCacheCleared', 'Micro-cache cleared')); } catch (err) { toastError(toast, t('app.microCachePanel.failedToClearTheMicroCache', "Couldn't clear the micro-cache."), err); } finally { setPurging(false); } } return (
{t('app.microCachePanel.cachesFullPagesShort', 'Caches pages in nginx for a few seconds.')}
{t('app.microCachePanel.toVerifyItWorksCheckThe', 'To verify it works, check the')} {t('app.microCachePanel.xSkCache', 'X-SK-Cache')} {t('app.microCachePanel.responseHeaderOnTheSite', 'response header on the site:')} HIT {t('app.microCachePanel.meansThePageCameFromThe', 'means the page came from the cache,')}
MISS/EXPIRED {t('app.microCachePanel.thatItWasFetchedFreshAnd', 'that it was fetched fresh, and')}
BYPASS {t('app.microCachePanel.thatABypassRuleApplied', 'that a bypass rule applied.')}