Implement server status caching and automatic refresh for improved performance

This commit is contained in:
Fabian Schieder 2026-03-01 14:51:10 +01:00
parent 4ebb0bc9c1
commit bcea63dcb8

View File

@ -15,14 +15,65 @@ require_once __DIR__ . '/includes/lib/server_status.php';
require_once __DIR__ . '/includes/lib/view_helpers.php'; require_once __DIR__ . '/includes/lib/view_helpers.php';
// ── Serverstatus ───────────────────────────────────────────────────────── // ── Serverstatus ─────────────────────────────────────────────────────────
// Wichtig für Performance: Beim initialen Rendern NICHT blockierend live prüfen. // Performance: Beim ersten Rendern sofort antworten (=> Unbekannt).
// Die Badges starten als „Unbekannt“ und werden clientseitig über /server_status.php aktualisiert. // Nach ~1s lädt die Seite einmal neu mit ?status=1 und rendert dann serverseitig Online/Offline.
$shouldComputeStatus = isset($_GET['status']) && $_GET['status'] === '1';
$serverStatusByUrl = []; $serverStatusByUrl = [];
if ($shouldComputeStatus) {
$cacheTtlSeconds = 30;
$cacheKey = 'server_status_v5';
$cacheFile = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $cacheKey . '.json';
$serverStatus = null;
if (is_file($cacheFile)) {
$raw = @file_get_contents($cacheFile);
if ($raw !== false) {
$decoded = json_decode($raw, true);
if (is_array($decoded) && isset($decoded['ts'], $decoded['data']) && is_array($decoded['data'])) {
$age = time() - (int)$decoded['ts'];
if ($age >= 0 && $age <= $cacheTtlSeconds) {
$serverStatus = $decoded['data'];
}
}
}
}
if (!is_array($serverStatus)) {
$serverStatus = build_server_status($serverStatusTargets);
@file_put_contents($cacheFile, json_encode(['ts' => time(), 'data' => $serverStatus], JSON_UNESCAPED_SLASHES));
}
foreach ($serverStatus as $svc) {
if (!empty($svc['url']) && is_string($svc['url'])) {
$serverStatusByUrl[$svc['url']] = $svc;
}
}
}
require __DIR__ . '/includes/views/layout_head.php'; require __DIR__ . '/includes/views/layout_head.php';
require __DIR__ . '/includes/views/header.php'; require __DIR__ . '/includes/views/header.php';
?> ?>
<?php if (!$shouldComputeStatus): ?>
<script>
// Einmaliger Reload nach ~1 Sekunde, um dann serverseitig den Status zu laden.
setTimeout(function () {
try {
const url = new URL(window.location.href);
if (url.searchParams.get('status') === '1') return;
url.searchParams.set('status', '1');
window.location.replace(url.toString());
} catch (e) {
// Fallback
if (window.location.search.indexOf('status=1') === -1) {
window.location.replace(window.location.pathname + '?status=1');
}
}
}, 1000);
</script>
<?php endif; ?>
<main> <main>
<?php foreach ($projects as $category => $items): ?> <?php foreach ($projects as $category => $items): ?>
<?php require __DIR__ . '/includes/views/projects_section.php'; ?> <?php require __DIR__ . '/includes/views/projects_section.php'; ?>