Files
VITEC-website/packages/vitec/Classes/Controller/Backend/SsrController.php
T
orascheandClaude Fable 5.1 5121eaa000 Client-Error-Endpoint POST /api/vitec/client-error (0072-FE / 0077-BE)
Neue PSR-15-Middleware ClientErrorMiddleware: nimmt Browser-Fehler des
React-Frontends als JSON {url, message, stack, release, userAgent}
entgegen und antwortet 204 ohne Body. Schutz: 30 Meldungen pro Minute
und IP (Sliding Window ueber TYPO3-RateLimiter, 429 + Retry-After),
8-KB-Body-Limit (413, Content-Length und tatsaechliche Bytes), kein
JSON-Objekt oder leere message = 400, GET = 405. Keine Session, keine
Cookies; der /_json-Praefix funktioniert ebenfalls.

Speicherung in der neuen Tabelle tx_vitec_clienterrorlog mit
anonymisierter IP (IPv4 letztes Oktett 0, IPv6 /48). Sichtbar als
Tabelle "Client errors (last 24 h)" im Modul VITEC SSR (mit Stack als
Aufklapper) und als Zeile "Client errors reported (24 h / 7 d)" in der
Dashboard-Kachel VITEC: SSR statistics.

CLI vitec:client-error-cleanup [--days=30] loescht Eintraege aelter als
30 Tage (taeglich per Cron).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-10 17:25:23 +01:00

213 lines
8.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Evomedien\Vitec\Controller\Backend;
use Evomedien\Vitec\Service\SsrPurgeService;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Backend\Attribute\AsController;
use TYPO3\CMS\Backend\Routing\UriBuilder;
use TYPO3\CMS\Backend\Template\ModuleTemplateFactory;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Http\JsonResponse;
use TYPO3\CMS\Core\Http\RedirectResponse;
use TYPO3\CMS\Core\Http\RequestFactory;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Site\SiteFinder;
use TYPO3\CMS\Core\Messaging\FlashMessageService;
use TYPO3\CMS\Core\Type\ContextualFeedbackSeverity;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* Backend module "VITEC SSR": live state of the SSR node, manual purge
* (single paths or everything) and the purge/health protocol.
*/
#[AsController]
final class SsrController
{
public function __construct(
private readonly ModuleTemplateFactory $moduleTemplateFactory,
private readonly SsrPurgeService $purgeService,
private readonly RequestFactory $requestFactory,
private readonly ConnectionPool $connectionPool,
private readonly FlashMessageService $flashMessageService,
private readonly UriBuilder $uriBuilder,
) {}
public function indexAction(ServerRequestInterface $request): ResponseInterface
{
$view = $this->moduleTemplateFactory->create($request);
$view->setTitle('VITEC SSR');
$health = null;
$healthError = '';
$endpoint = $this->purgeService->getHealthEndpoint();
if ($endpoint === '') {
$healthError = 'var/vitec-ssr-purge.env fehlt oder ist unvollständig.';
} else {
$start = microtime(true);
try {
$response = $this->requestFactory->request($endpoint, 'GET', [
'timeout' => 3, 'connect_timeout' => 2, 'http_errors' => false,
]);
if ($response->getStatusCode() === 200) {
$health = json_decode((string)$response->getBody(), true) ?: null;
if ($health !== null) {
$health['responseMs'] = (int)round((microtime(true) - $start) * 1000);
}
} else {
$healthError = 'HTTP ' . $response->getStatusCode();
}
} catch (\Throwable $e) {
$healthError = $e->getMessage();
}
}
$view->assignMultiple([
'flagOn' => file_exists(Environment::getVarPath() . '/vitec-ssr-on.flag'),
'configured' => $this->purgeService->isConfigured(),
'health' => $health,
'healthError' => $healthError,
'purgeLog' => $this->rows('tx_vitec_ssrpurgelog', 30),
'healthLog' => $this->rows('tx_vitec_ssrhealthlog', 10),
'clientErrors' => $this->clientErrors(50),
'clientErrorCount24h' => $this->clientErrorCount24h(),
]);
return $view->renderResponse('Ssr/Index');
}
/**
* Client error reports of the last 24 hours (POST /api/vitec/client-error,
* ClientErrorMiddleware), newest first. Rows carry a "host" (URL without
* scheme/query) and a shortened user agent for the table; the full
* values stay in the row for the details toggle.
*/
private function clientErrors(int $limit): array
{
try {
$qb = $this->connectionPool->getQueryBuilderForTable('tx_vitec_clienterrorlog');
$rows = $qb->select('*')->from('tx_vitec_clienterrorlog')
->where($qb->expr()->gt('crdate', $qb->createNamedParameter(time() - 86400, Connection::PARAM_INT)))
->orderBy('uid', 'DESC')->setMaxResults($limit)
->executeQuery()->fetchAllAssociative();
} catch (\Throwable) {
return [];
}
foreach ($rows as &$row) {
$path = (string)(parse_url((string)$row['url'], PHP_URL_PATH) ?? '');
$row['path'] = $path !== '' ? $path : (string)$row['url'];
$ua = (string)$row['user_agent'];
$row['ua_short'] = mb_strlen($ua) > 60 ? mb_substr($ua, 0, 57) . '...' : $ua;
$row['is_chunk_reload'] = str_contains(strtolower((string)$row['message']), 'chunk reload');
}
unset($row);
return $rows;
}
private function clientErrorCount24h(): int
{
try {
return (int)$this->connectionPool->getConnectionForTable('tx_vitec_clienterrorlog')
->executeQuery('SELECT COUNT(*) FROM tx_vitec_clienterrorlog WHERE crdate > ?', [time() - 86400])
->fetchOne();
} catch (\Throwable) {
return 0;
}
}
public function purgeAction(ServerRequestInterface $request): ResponseInterface
{
$body = (array)$request->getParsedBody();
$mode = (string)($body['mode'] ?? 'paths');
$user = (string)($GLOBALS['BE_USER']->user['username'] ?? '?');
if ($mode === 'all') {
$paths = ['*'];
} else {
$paths = preg_split('/[\s,]+/', (string)($body['paths'] ?? ''), -1, PREG_SPLIT_NO_EMPTY) ?: [];
}
if ($paths === []) {
$this->flash('No paths given.', 'Purge', false);
} else {
$result = $this->purgeService->purge($paths, 'module:' . $user);
$this->flash(
sprintf('HTTP %d — %s', $result['httpCode'], $result['message']),
$result['success'] ? 'Purge successful' : 'Purge failed',
$result['success']
);
}
return new RedirectResponse((string)$this->uriBuilder->buildUriFromRoute('web_vitecssr'), 303);
}
/**
* "Warm cache" button: asks the node to render every page of the
* sitemap in the background (0066-FE). Returns at once; progress is
* the "Cache warming" row of the status table.
*/
public function warmAction(ServerRequestInterface $request): ResponseInterface
{
$result = $this->purgeService->warm();
$this->flash(
$result['message'],
$result['success'] ? 'Cache warming' : 'Cache warming failed',
$result['success']
);
return new RedirectResponse((string)$this->uriBuilder->buildUriFromRoute('web_vitecssr'), 303);
}
/**
* Ajax route vitec_ssr_purge_page: purge exactly one page, called by
* the page tree context menu item (ssr-context-menu.js).
*/
public function purgePage(ServerRequestInterface $request): ResponseInterface
{
$body = (array)($request->getParsedBody() ?? []);
$pageUid = (int)($body['pageUid'] ?? ($request->getQueryParams()['pageUid'] ?? 0));
if ($pageUid <= 0) {
return new JsonResponse(['success' => false, 'message' => 'No page uid given'], 400);
}
try {
$site = GeneralUtility::makeInstance(SiteFinder::class)->getSiteByPageId($pageUid);
$path = $site->getRouter()->generateUri($pageUid)->getPath() ?: '/';
} catch (\Throwable) {
return new JsonResponse(['success' => false, 'message' => 'Page has no routable URL (folder?)']);
}
$user = (string)($GLOBALS['BE_USER']->user['username'] ?? '?');
$result = $this->purgeService->purge([$path], 'contextmenu:' . $user);
return new JsonResponse([
'success' => $result['success'],
'path' => $path,
'message' => 'HTTP ' . $result['httpCode'] . ' - ' . $result['message'],
]);
}
private function rows(string $table, int $limit): array
{
try {
$qb = $this->connectionPool->getQueryBuilderForTable($table);
return $qb->select('*')->from($table)
->orderBy('uid', 'DESC')->setMaxResults($limit)
->executeQuery()->fetchAllAssociative();
} catch (\Throwable) {
return [];
}
}
private function flash(string $message, string $title, bool $ok): void
{
$flash = GeneralUtility::makeInstance(
FlashMessage::class,
$message,
$title,
$ok ? ContextualFeedbackSeverity::OK : ContextualFeedbackSeverity::ERROR,
true
);
$this->flashMessageService->getMessageQueueByIdentifier()->addMessage($flash);
}
}