diff --git a/src/StaticCaching/Cachers/FileCacher.php b/src/StaticCaching/Cachers/FileCacher.php index 66630c2ebf1..73c663dd0e9 100644 --- a/src/StaticCaching/Cachers/FileCacher.php +++ b/src/StaticCaching/Cachers/FileCacher.php @@ -128,13 +128,15 @@ public function getGeneratedAt(string $url): ?int */ public function flush() { - foreach ($this->getCachePaths() as $path) { - $this->writer->flush($path); - } - + // Wipe the store before the files, so any page written while the + // files are being deleted keeps the nocache regions it just stored. $this->flushUrls(); $this->flushDedicatedStore(); + + foreach ($this->getCachePaths() as $path) { + $this->writer->flush($path); + } } /** diff --git a/tests/StaticCaching/FileCacherTest.php b/tests/StaticCaching/FileCacherTest.php index d5679b37ed5..c25805544b1 100644 --- a/tests/StaticCaching/FileCacherTest.php +++ b/tests/StaticCaching/FileCacherTest.php @@ -14,6 +14,8 @@ use Statamic\StaticCaching\Cacher; use Statamic\StaticCaching\Cachers\FileCacher; use Statamic\StaticCaching\Cachers\Writer; +use Statamic\StaticCaching\NoCache\Region; +use Statamic\StaticCaching\NoCache\Session; use Tests\TestCase; class FileCacherTest extends TestCase @@ -181,6 +183,49 @@ public function flushing_wipes_the_dedicated_static_cache_store() $this->assertNull($cache->get('untracked')); } + #[Test] + public function a_page_cached_while_flushing_keeps_its_nocache_regions() + { + config(['cache.stores.static_cache' => ['driver' => 'array']]); + $cache = Cache::store('static_cache'); + $path = sys_get_temp_dir().'/statamic-file-cacher-'.uniqid(); + $url = 'http://example.com/one'; + $regionKey = null; + + // Stands in for a request that finishes rendering while the flush is deleting files. + $writer = new class extends Writer + { + public $concurrentRequest; + + public function flush($path) + { + parent::flush($path); + + ($this->concurrentRequest)(); + } + }; + + $cacher = $this->fileCacher(['path' => $path, 'base_url' => 'http://example.com', 'lock_hold_length' => 0], $writer, $cache); + + $writer->concurrentRequest = function () use ($cacher, $url, &$regionKey) { + $session = new Session($url); + $regionKey = $session->pushRegion('Log in', [], 'antlers.html')->key(); + + $cacher->cachePage(Request::create($url), 'html'); + $session->write(); + }; + + try { + $cacher->flush(); + + $this->assertFileExists($path.'/one_.html'); + $this->assertEquals(['/one'], $cacher->getUrls()->values()->all()); + $this->assertInstanceOf(Region::class, (new Session($url))->restore()->region($regionKey)); + } finally { + File::delete($path); + } + } + #[Test] public function invalidating_a_url_thats_not_cached_will_do_nothing() {