From 318fea659836ca4f24a0dd5326470f5be4ecf822 Mon Sep 17 00:00:00 2001 From: contemas-tschmidt <14309291+contemas-tschmidt@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:27:10 +0100 Subject: [PATCH 1/2] [BUGFIX] Treat a cache entry without generated file as missing GenerateMiddleware reported a page as "already in cache" as soon as the database entry was valid, without looking at the file system. If the generated files are gone while the entry is still there, the page is not written again until the entry expires, and every request is handled by PHP in the meantime. That happens whenever the cache directory is emptied without the database table, e.g. a deployment step like "find -delete" right after a cache flush: a page requested between the flush and the delete keeps a valid entry but loses its file. The entry now only counts as valid if at least one generated file exists (plain, .gz, .br or .php, depending on the enabled generators). Otherwise the page is stored again, which rewrites entry and file. Co-Authored-By: Claude Sonnet 5.5 --- Classes/Middleware/GenerateMiddleware.php | 44 ++++++++- .../Middleware/GenerateMiddlewareTest.php | 91 ++++++++++++++++++- 2 files changed, 132 insertions(+), 3 deletions(-) diff --git a/Classes/Middleware/GenerateMiddleware.php b/Classes/Middleware/GenerateMiddleware.php index a73a114d15a..a2f1fa7c29f 100644 --- a/Classes/Middleware/GenerateMiddleware.php +++ b/Classes/Middleware/GenerateMiddleware.php @@ -12,6 +12,7 @@ use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; +use SFC\Staticfilecache\Cache\IdentifierBuilder; use SFC\Staticfilecache\Event\PreGenerateEvent; use SFC\Staticfilecache\Service\CacheService; use SFC\Staticfilecache\Service\ConfigurationService; @@ -19,6 +20,7 @@ use SFC\Staticfilecache\Service\DateTimeService; use TYPO3\CMS\Core\Http\ServerRequest; use TYPO3\CMS\Core\Information\Typo3Version; +use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Utility\DebuggerUtility; class GenerateMiddleware implements MiddlewareInterface @@ -98,6 +100,12 @@ protected function calculateLifetime(RequestInterface $request, ResponseInterfac /** * Determines whether the given $uri has a valid cache entry. * + * The entry (database) is only valid together with the generated file. An + * entry without a file (e.g. the cache directory was emptied while the + * database table was not) would otherwise be reported as "already in cache" + * until it expires, and every request would be handled by PHP in the + * meantime, because nobody writes the file again. + * * @param string $uri * * @return bool is available and valid @@ -108,7 +116,41 @@ protected function hasValidCacheEntry($uri): bool return false !== $entry && empty($entry['explanation']) - && $entry['expires'] >= (new DateTimeService())->getCurrentTime(); + && $entry['expires'] >= (new DateTimeService())->getCurrentTime() + && $this->hasStaticFile((string) $uri); + } + + /** + * Determines whether at least one generated file exists for the given $uri. + * + * Which file is written depends on the enabled generators (plain, gzip, + * brotli, php), so every variant counts. + */ + protected function hasStaticFile(string $uri): bool + { + try { + $fileName = $this->getStaticFileName($uri); + } catch (\Throwable) { + return false; + } + + foreach (['', '.gz', '.br', '.php'] as $suffix) { + if (is_file($fileName . $suffix)) { + return true; + } + } + + return false; + } + + /** + * Absolute path of the (plain) cache file for the given $uri. + * + * @throws \Exception + */ + protected function getStaticFileName(string $uri): string + { + return GeneralUtility::makeInstance(IdentifierBuilder::class)->getFilepath($uri); } /** diff --git a/Tests/Unit/Middleware/GenerateMiddlewareTest.php b/Tests/Unit/Middleware/GenerateMiddlewareTest.php index 6e253887de3..28cf42df4b1 100644 --- a/Tests/Unit/Middleware/GenerateMiddlewareTest.php +++ b/Tests/Unit/Middleware/GenerateMiddlewareTest.php @@ -30,9 +30,13 @@ final class GenerateMiddlewareTest extends AbstractMiddlewareTest protected CookieService&MockObject $cookieService; + protected string $cacheDirectory = ''; + protected function setUp(): void { parent::setUp(); + $this->cacheDirectory = sys_get_temp_dir() . '/sfc-generate-middleware-' . bin2hex(random_bytes(6)); + mkdir($this->cacheDirectory); $this->cache = $this->createMock(FrontendInterface::class); $this->cacheService = $this->createMock(CacheService::class); $this->cacheService->method('get')->willReturn($this->cache); @@ -40,6 +44,15 @@ protected function setUp(): void $this->setExtensionConfiguration(); } + protected function tearDown(): void + { + foreach (glob($this->cacheDirectory . '/*') ?: [] as $file) { + unlink($file); + } + rmdir($this->cacheDirectory); + parent::tearDown(); + } + public function testNotCachableResponseIsNotCached(): void { $this->cacheService->expects(self::never())->method('get'); @@ -119,12 +132,60 @@ public function testValidCacheEntryIsNotStoredAgain(): void $this->cache->method('get')->willReturn(['explanation' => [], 'expires' => PHP_INT_MAX]); $this->cache->expects(self::never())->method('set'); $this->cookieService->method('hasCookie')->willReturn(false); + touch($this->cacheDirectory . '/index'); $response = $this->getMiddleware()->process($this->getRequest(), $this->getHandler($this->getCachableResponse())); self::assertSame('TYPO3 - already in cache', $response->getHeaderLine('X-SFC-State')); } + /** + * @return array + */ + public static function generatedFileProvider(): array + { + return [ + 'plain' => ['index'], + 'gzip' => ['index.gz'], + 'brotli' => ['index.br'], + 'php' => ['index.php'], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('generatedFileProvider')] + public function testValidCacheEntryWithAnyGeneratedFileIsNotStoredAgain(string $file): void + { + $this->cache->method('get')->willReturn(['explanation' => [], 'expires' => PHP_INT_MAX]); + $this->cache->expects(self::never())->method('set'); + $this->cookieService->method('hasCookie')->willReturn(false); + touch($this->cacheDirectory . '/' . $file); + + $this->getMiddleware()->process($this->getRequest(), $this->getHandler($this->getCachableResponse())); + } + + public function testValidCacheEntryWithoutFileIsStoredAgain(): void + { + $this->setExtensionConfiguration(['debugHeaders' => '1']); + $this->cache->method('get')->willReturn(['explanation' => [], 'expires' => PHP_INT_MAX]); + $this->cache->expects(self::once())->method('set'); + $this->cookieService->method('hasCookie')->willReturn(false); + + $response = $this->getMiddleware()->process($this->getRequest(), $this->getHandler($this->getCachableResponse())); + + self::assertSame('TYPO3 - add to cache', $response->getHeaderLine('X-SFC-State')); + } + + public function testValidCacheEntryWithUnresolvableFileNameIsStoredAgain(): void + { + $this->cache->method('get')->willReturn(['explanation' => [], 'expires' => PHP_INT_MAX]); + $this->cache->expects(self::once())->method('set'); + $this->cookieService->method('hasCookie')->willReturn(false); + + $middleware = $this->getMiddleware(); + $middleware->failToResolveFileName = true; + $middleware->process($this->getRequest(), $this->getHandler($this->getCachableResponse())); + } + /** * @return array, expires: int}, bool}> */ @@ -146,6 +207,8 @@ public function testInvalidCacheEntryIsRegenerated(array $entry, bool $hasCookie $this->cache->method('get')->willReturn($entry); $this->cache->expects(self::once())->method('set'); $this->cookieService->method('hasCookie')->willReturn($hasCookie); + // The file exists: only the entry (or the cookie) decides here. + touch($this->cacheDirectory . '/index'); $this->getMiddleware()->process($this->getRequest(), $this->getHandler($this->getCachableResponse())); } @@ -186,14 +249,38 @@ protected function getRequest(int $lifetime = 86400): ServerRequest return (new ServerRequest('https://example.com/page/'))->withAttribute('frontend.cache.collector', $collector); } - protected function getMiddleware(): GenerateMiddleware + protected function getMiddleware(): GenerateMiddlewareWithFixedFileName { - return new GenerateMiddleware( + $middleware = new GenerateMiddlewareWithFixedFileName( $this->getEventDispatcher(), $this->cookieService, new Typo3Version(), $this->cacheService, $this->setExtensionConfiguration($GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['staticfilecache'] ?? []), ); + $middleware->fileName = $this->cacheDirectory . '/index'; + + return $middleware; + } +} + +/** + * Middleware that does not resolve the cache file via the identifier builder, so the tests do not need a TYPO3 environment. + * + * @internal + */ +final class GenerateMiddlewareWithFixedFileName extends GenerateMiddleware +{ + public string $fileName = ''; + + public bool $failToResolveFileName = false; + + protected function getStaticFileName(string $uri): string + { + if ($this->failToResolveFileName) { + throw new \Exception('Invalid RequestUri as cache identifier: ' . $uri, 2346782); + } + + return $this->fileName; } } From 214962f5805ad6cf5acbd2fc0d7b9f81f3e3e981 Mon Sep 17 00:00:00 2001 From: contemas-tschmidt <14309291+contemas-tschmidt@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:43:07 +0100 Subject: [PATCH 2/2] [TASK] Move the static file check into StaticFileBackend Review feedback: the middleware should not depend on the IdentifierBuilder. StaticFileBackend::has() cannot be used for this, it is true when either the file or the database entry exists. A new hasStaticFile() checks the files only (plain, .gz, .br, .php) and reuses getFilepath(), so hashed identifiers are handled as well. The middleware asks the backend of its cache; other backends keep the old behaviour (the entry decides). Co-Authored-By: Claude Sonnet 5.5 --- Classes/Cache/StaticFileBackend.php | 30 +++++++ Classes/Middleware/GenerateMiddleware.php | 33 ++----- Tests/Unit/Cache/StaticFileBackendTest.php | 43 +++++++++ .../Middleware/GenerateMiddlewareTest.php | 90 ++++--------------- 4 files changed, 98 insertions(+), 98 deletions(-) diff --git a/Classes/Cache/StaticFileBackend.php b/Classes/Cache/StaticFileBackend.php index 2785ac6c329..26f274bd275 100644 --- a/Classes/Cache/StaticFileBackend.php +++ b/Classes/Cache/StaticFileBackend.php @@ -140,6 +140,36 @@ public function has(string $entryIdentifier): bool return is_file($this->getFilepath($entryIdentifier)) || parent::has($entryIdentifier); } + /** + * Checks whether a generated file exists for the given entry identifier. + * + * In contrast to has(), the database entry does not count: has() is also + * true for an entry without file (e.g. after the cache directory was + * emptied), but only the file makes Apache deliver the page statically. + * Which file is written depends on the enabled generators (plain, gzip, + * brotli, php), so every variant counts. + */ + public function hasStaticFile(string $entryIdentifier): bool + { + try { + $fileName = $this->getFilepath($entryIdentifier); + } catch (\Throwable) { + return false; + } + + if ('' === $fileName) { + return false; + } + + foreach (['', '.gz', '.br', '.php'] as $suffix) { + if (is_file($fileName . $suffix)) { + return true; + } + } + + return false; + } + /** * Removes all cache entries matching the specified identifier. * Usually this only affects one entry but if - for what reason ever - diff --git a/Classes/Middleware/GenerateMiddleware.php b/Classes/Middleware/GenerateMiddleware.php index a2f1fa7c29f..4ebfd4529ea 100644 --- a/Classes/Middleware/GenerateMiddleware.php +++ b/Classes/Middleware/GenerateMiddleware.php @@ -12,7 +12,7 @@ use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; -use SFC\Staticfilecache\Cache\IdentifierBuilder; +use SFC\Staticfilecache\Cache\StaticFileBackend; use SFC\Staticfilecache\Event\PreGenerateEvent; use SFC\Staticfilecache\Service\CacheService; use SFC\Staticfilecache\Service\ConfigurationService; @@ -20,7 +20,6 @@ use SFC\Staticfilecache\Service\DateTimeService; use TYPO3\CMS\Core\Http\ServerRequest; use TYPO3\CMS\Core\Information\Typo3Version; -use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Utility\DebuggerUtility; class GenerateMiddleware implements MiddlewareInterface @@ -121,36 +120,16 @@ protected function hasValidCacheEntry($uri): bool } /** - * Determines whether at least one generated file exists for the given $uri. + * Determines whether the static file of the given $uri exists. * - * Which file is written depends on the enabled generators (plain, gzip, - * brotli, php), so every variant counts. + * Other backends than the StaticFileBackend know nothing about files, so + * the entry alone decides there. */ protected function hasStaticFile(string $uri): bool { - try { - $fileName = $this->getStaticFileName($uri); - } catch (\Throwable) { - return false; - } - - foreach (['', '.gz', '.br', '.php'] as $suffix) { - if (is_file($fileName . $suffix)) { - return true; - } - } + $backend = $this->cache->getBackend(); - return false; - } - - /** - * Absolute path of the (plain) cache file for the given $uri. - * - * @throws \Exception - */ - protected function getStaticFileName(string $uri): string - { - return GeneralUtility::makeInstance(IdentifierBuilder::class)->getFilepath($uri); + return !$backend instanceof StaticFileBackend || $backend->hasStaticFile($uri); } /** diff --git a/Tests/Unit/Cache/StaticFileBackendTest.php b/Tests/Unit/Cache/StaticFileBackendTest.php index 407b73d2750..a3a7224a9cc 100644 --- a/Tests/Unit/Cache/StaticFileBackendTest.php +++ b/Tests/Unit/Cache/StaticFileBackendTest.php @@ -94,6 +94,49 @@ public function testSetStoreEntryAndDispatchGeneratorEvents(): void self::assertSame([self::URI], array_values($backend->findIdentifiersByTag('pageId_1'))); } + public function testHasStaticFileIsFalseForEntryWithoutFile(): void + { + $this->configure(); + $backend = $this->getBackend(); + $this->frontend->set(self::URI, new Response(), ['pageId_1'], 3600); + + // The entry alone makes has() true, but there is nothing Apache could deliver. + self::assertTrue($backend->has(self::URI)); + self::assertFalse($backend->hasStaticFile(self::URI)); + } + + /** + * @return array + */ + public static function generatedFileProvider(): array + { + return [ + 'plain' => ['index'], + 'gzip' => ['index.gz'], + 'brotli' => ['index.br'], + 'php' => ['index.php'], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('generatedFileProvider')] + public function testHasStaticFileIsTrueForAnyGeneratedFile(string $file): void + { + $this->configure(); + $backend = $this->getBackend(); + $this->frontend->set(self::URI, new Response(), ['pageId_1'], 3600); + touch($this->cacheDirectory . 'https_www.example.com_443/page/' . $file); + + self::assertTrue($backend->hasStaticFile(self::URI)); + } + + public function testHasStaticFileIsFalseForUnknownIdentifier(): void + { + $this->configure(); + + self::assertFalse($this->getBackend()->hasStaticFile('https://www.example.com/unknown/')); + self::assertFalse($this->getBackend()->hasStaticFile('invalid')); + } + public function testSetExplanationOnlyStoresDetails(): void { $this->configure(); diff --git a/Tests/Unit/Middleware/GenerateMiddlewareTest.php b/Tests/Unit/Middleware/GenerateMiddlewareTest.php index 28cf42df4b1..76adf859fcd 100644 --- a/Tests/Unit/Middleware/GenerateMiddlewareTest.php +++ b/Tests/Unit/Middleware/GenerateMiddlewareTest.php @@ -5,6 +5,7 @@ namespace SFC\Staticfilecache\Tests\Unit\Middleware; use PHPUnit\Framework\MockObject\MockObject; +use SFC\Staticfilecache\Cache\StaticFileBackend; use SFC\Staticfilecache\Event\PreGenerateEvent; use SFC\Staticfilecache\Middleware\GenerateMiddleware; use SFC\Staticfilecache\Service\CacheService; @@ -30,13 +31,9 @@ final class GenerateMiddlewareTest extends AbstractMiddlewareTest protected CookieService&MockObject $cookieService; - protected string $cacheDirectory = ''; - protected function setUp(): void { parent::setUp(); - $this->cacheDirectory = sys_get_temp_dir() . '/sfc-generate-middleware-' . bin2hex(random_bytes(6)); - mkdir($this->cacheDirectory); $this->cache = $this->createMock(FrontendInterface::class); $this->cacheService = $this->createMock(CacheService::class); $this->cacheService->method('get')->willReturn($this->cache); @@ -44,15 +41,6 @@ protected function setUp(): void $this->setExtensionConfiguration(); } - protected function tearDown(): void - { - foreach (glob($this->cacheDirectory . '/*') ?: [] as $file) { - unlink($file); - } - rmdir($this->cacheDirectory); - parent::tearDown(); - } - public function testNotCachableResponseIsNotCached(): void { $this->cacheService->expects(self::never())->method('get'); @@ -132,41 +120,30 @@ public function testValidCacheEntryIsNotStoredAgain(): void $this->cache->method('get')->willReturn(['explanation' => [], 'expires' => PHP_INT_MAX]); $this->cache->expects(self::never())->method('set'); $this->cookieService->method('hasCookie')->willReturn(false); - touch($this->cacheDirectory . '/index'); $response = $this->getMiddleware()->process($this->getRequest(), $this->getHandler($this->getCachableResponse())); self::assertSame('TYPO3 - already in cache', $response->getHeaderLine('X-SFC-State')); } - /** - * @return array - */ - public static function generatedFileProvider(): array - { - return [ - 'plain' => ['index'], - 'gzip' => ['index.gz'], - 'brotli' => ['index.br'], - 'php' => ['index.php'], - ]; - } - - #[\PHPUnit\Framework\Attributes\DataProvider('generatedFileProvider')] - public function testValidCacheEntryWithAnyGeneratedFileIsNotStoredAgain(string $file): void + public function testValidCacheEntryWithStaticFileIsNotStoredAgain(): void { + $this->setExtensionConfiguration(['debugHeaders' => '1']); $this->cache->method('get')->willReturn(['explanation' => [], 'expires' => PHP_INT_MAX]); + $this->cache->method('getBackend')->willReturn($this->getStaticFileBackend(true)); $this->cache->expects(self::never())->method('set'); $this->cookieService->method('hasCookie')->willReturn(false); - touch($this->cacheDirectory . '/' . $file); - $this->getMiddleware()->process($this->getRequest(), $this->getHandler($this->getCachableResponse())); + $response = $this->getMiddleware()->process($this->getRequest(), $this->getHandler($this->getCachableResponse())); + + self::assertSame('TYPO3 - already in cache', $response->getHeaderLine('X-SFC-State')); } - public function testValidCacheEntryWithoutFileIsStoredAgain(): void + public function testValidCacheEntryWithoutStaticFileIsStoredAgain(): void { $this->setExtensionConfiguration(['debugHeaders' => '1']); $this->cache->method('get')->willReturn(['explanation' => [], 'expires' => PHP_INT_MAX]); + $this->cache->method('getBackend')->willReturn($this->getStaticFileBackend(false)); $this->cache->expects(self::once())->method('set'); $this->cookieService->method('hasCookie')->willReturn(false); @@ -175,17 +152,6 @@ public function testValidCacheEntryWithoutFileIsStoredAgain(): void self::assertSame('TYPO3 - add to cache', $response->getHeaderLine('X-SFC-State')); } - public function testValidCacheEntryWithUnresolvableFileNameIsStoredAgain(): void - { - $this->cache->method('get')->willReturn(['explanation' => [], 'expires' => PHP_INT_MAX]); - $this->cache->expects(self::once())->method('set'); - $this->cookieService->method('hasCookie')->willReturn(false); - - $middleware = $this->getMiddleware(); - $middleware->failToResolveFileName = true; - $middleware->process($this->getRequest(), $this->getHandler($this->getCachableResponse())); - } - /** * @return array, expires: int}, bool}> */ @@ -207,8 +173,6 @@ public function testInvalidCacheEntryIsRegenerated(array $entry, bool $hasCookie $this->cache->method('get')->willReturn($entry); $this->cache->expects(self::once())->method('set'); $this->cookieService->method('hasCookie')->willReturn($hasCookie); - // The file exists: only the entry (or the cookie) decides here. - touch($this->cacheDirectory . '/index'); $this->getMiddleware()->process($this->getRequest(), $this->getHandler($this->getCachableResponse())); } @@ -233,6 +197,14 @@ public function testEventCanChangeUriAndResponse(): void self::assertSame('yes', $response->getHeaderLine('X-Changed')); } + protected function getStaticFileBackend(bool $hasStaticFile): StaticFileBackend&MockObject + { + $backend = $this->createMock(StaticFileBackend::class); + $backend->expects(self::once())->method('hasStaticFile')->with('https://example.com/page/')->willReturn($hasStaticFile); + + return $backend; + } + protected function getCachableResponse(int $status = 200): HtmlResponse { return new HtmlResponse('', $status, [ @@ -249,38 +221,14 @@ protected function getRequest(int $lifetime = 86400): ServerRequest return (new ServerRequest('https://example.com/page/'))->withAttribute('frontend.cache.collector', $collector); } - protected function getMiddleware(): GenerateMiddlewareWithFixedFileName + protected function getMiddleware(): GenerateMiddleware { - $middleware = new GenerateMiddlewareWithFixedFileName( + return new GenerateMiddleware( $this->getEventDispatcher(), $this->cookieService, new Typo3Version(), $this->cacheService, $this->setExtensionConfiguration($GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['staticfilecache'] ?? []), ); - $middleware->fileName = $this->cacheDirectory . '/index'; - - return $middleware; - } -} - -/** - * Middleware that does not resolve the cache file via the identifier builder, so the tests do not need a TYPO3 environment. - * - * @internal - */ -final class GenerateMiddlewareWithFixedFileName extends GenerateMiddleware -{ - public string $fileName = ''; - - public bool $failToResolveFileName = false; - - protected function getStaticFileName(string $uri): string - { - if ($this->failToResolveFileName) { - throw new \Exception('Invalid RequestUri as cache identifier: ' . $uri, 2346782); - } - - return $this->fileName; } }