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 a73a114d15a..4ebfd4529ea 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\StaticFileBackend; use SFC\Staticfilecache\Event\PreGenerateEvent; use SFC\Staticfilecache\Service\CacheService; use SFC\Staticfilecache\Service\ConfigurationService; @@ -98,6 +99,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 +115,21 @@ 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 the static file of the given $uri exists. + * + * Other backends than the StaticFileBackend know nothing about files, so + * the entry alone decides there. + */ + protected function hasStaticFile(string $uri): bool + { + $backend = $this->cache->getBackend(); + + 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 6e253887de3..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; @@ -125,6 +126,32 @@ public function testValidCacheEntryIsNotStoredAgain(): void self::assertSame('TYPO3 - already in cache', $response->getHeaderLine('X-SFC-State')); } + 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); + + $response = $this->getMiddleware()->process($this->getRequest(), $this->getHandler($this->getCachableResponse())); + + self::assertSame('TYPO3 - already in cache', $response->getHeaderLine('X-SFC-State')); + } + + 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); + + $response = $this->getMiddleware()->process($this->getRequest(), $this->getHandler($this->getCachableResponse())); + + self::assertSame('TYPO3 - add to cache', $response->getHeaderLine('X-SFC-State')); + } + /** * @return array, expires: int}, bool}> */ @@ -170,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, [