Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Facades/HttpCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
/**
* @method static \FOS\HttpCache\ProxyClient\ProxyClient client(?string $name = null)
* @method static \FOS\HttpCache\CacheInvalidator invalidator(?string $name = null)
* @method static int flush()
* @method static HttpCacheManager extend(string $driver, \Closure $callback)
*
* @see HttpCacheManager
Expand Down
6 changes: 3 additions & 3 deletions src/Http/Middleware/SendTagHeader.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
namespace CraftCms\HttpCache\Http\Middleware;

use Closure;
use CraftCms\Cms\HttpCache\ResponseTagger;
use CraftCms\Cms\Http\ResponseCacheInfo;
use FOS\HttpCache\TagHeaderFormatter\TagHeaderFormatter;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
Expand All @@ -19,7 +19,7 @@
readonly class SendTagHeader
{
public function __construct(
private ResponseTagger $tagger,
private ResponseCacheInfo $cacheInfo,
private ?TagHeaderFormatter $formatter = null,
) {}

Expand All @@ -38,7 +38,7 @@ public function handle(Request $request, Closure $next): mixed
return $response;
}

$tags = $this->tagger->getTags();
$tags = $this->cacheInfo->getTags();

if ($tags !== []) {
$response->headers->set(
Expand Down
24 changes: 24 additions & 0 deletions src/HttpCacheManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace CraftCms\HttpCache;

use FOS\HttpCache\CacheInvalidator;
use FOS\HttpCache\Exception\ExceptionCollection;
use FOS\HttpCache\ProxyClient\Cloudflare;
use FOS\HttpCache\ProxyClient\Fastly;
use FOS\HttpCache\ProxyClient\Noop;
Expand Down Expand Up @@ -45,6 +46,29 @@ public function invalidator(?string $name = null): CacheInvalidator
return $this->invalidators[$name] ??= new CacheInvalidator($this->client($name));
}

/**
* Sends every client's queued invalidations. A failed client is reported, not thrown, so one unreachable cache
* doesn't stop the others or fail the request, job or command that queued them.
*
* @return int The number of invalidation requests sent.
*/
public function flush(): int
{
$sent = 0;

foreach ($this->invalidators as $invalidator) {
try {
$sent += $invalidator->flush();
} catch (ExceptionCollection $exceptions) {
foreach ($exceptions as $exception) {
report($exception);
}
}
}

return $sent;
}

public function getDefaultInstance(): string
{
return $this->config->get('http-cache.default');
Expand Down
13 changes: 13 additions & 0 deletions src/HttpCacheServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@

namespace CraftCms\HttpCache;

use CraftCms\Cms\Element\Events\ElementCachesInvalidated;
use CraftCms\HttpCache\Http\Middleware\SendTagHeader;
use CraftCms\HttpCache\Listeners\InvalidateElementTags;
use FOS\HttpCache\TagHeaderFormatter\TagHeaderFormatter;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Illuminate\Queue\Events\JobExceptionOccurred;
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use Override;

Expand All @@ -31,6 +36,14 @@ public function boot(): void
{
$this->publishes([__DIR__.'/../config/http-cache.php' => config_path('http-cache.php')], 'http-cache-config');

Event::listen(ElementCachesInvalidated::class, InvalidateElementTags::class);

// Purges are queued and sent once, after the response, command or job that queued them.
$flush = fn () => $this->app->make(HttpCacheManager::class)->flush();
$this->app->terminating($flush);
// Queue workers don't terminate between jobs.
Event::listen([JobProcessed::class, JobExceptionOccurred::class], $flush);

/** @var HttpKernel $kernel */
$kernel = $this->app->make(Kernel::class);

Expand Down
37 changes: 37 additions & 0 deletions src/Listeners/InvalidateElementTags.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

declare(strict_types=1);

namespace CraftCms\HttpCache\Listeners;

use CraftCms\Cms\Element\ElementHelper;
use CraftCms\Cms\Element\Events\ElementCachesInvalidated;
use CraftCms\HttpCache\HttpCacheManager;
use FOS\HttpCache\CacheInvalidator;

/**
* Invalidates the default client's cached pages tagged with the elements whose caches Craft invalidated.
*
* The tags are the same ones Craft collects from element queries, so a page is invalidated when an element it showed,
* or could have shown, changes. Drafts and revisions are skipped, because visitors never see them. Clients that can't
* invalidate by tag are skipped too; a driver without tags handles element changes itself.
*/
readonly class InvalidateElementTags
{
public function __construct(
private HttpCacheManager $httpCache,
) {}

public function handle(ElementCachesInvalidated $event): void
{
if ($event->element !== null && ElementHelper::isDraftOrRevision($event->element)) {
return;
}

$invalidator = $this->httpCache->invalidator();

if ($event->tags !== [] && $invalidator->supports(CacheInvalidator::TAGS)) {
$invalidator->invalidateTags(array_values($event->tags));
}
}
}
70 changes: 70 additions & 0 deletions tests/Feature/InvalidateElementTagsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

declare(strict_types=1);

use CraftCms\Cms\Element\Events\ElementCachesInvalidated;
use CraftCms\Cms\Entry\Elements\Entry;
use CraftCms\HttpCache\Facades\HttpCache;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\Facades\Http;

beforeEach(function () {
config([
'http-cache.default' => 'cloudflare',
'http-cache.clients.cloudflare' => [
'driver' => 'cloudflare',
'authentication_token' => 'secret',
'zone_identifier' => 'zone',
],
]);
});

function purgedTags(): array
{
return Http::recorded()->flatMap(fn (array $pair) => $pair[0]->data()['tags'] ?? [])->all();
}

it('purges invalidated element tags once the request ends', function () {
Http::fake();
event(new ElementCachesInvalidated(['element::5', 'element::'.Entry::class.'::*'], new Entry(['id' => 5])));

Http::assertNothingSent();

app()->terminate();

expect(purgedTags())->toBe(['element::5', 'element::'.Entry::class.'::*']);
});

it('purges after each queued job', function () {
Http::fake();
config(['queue.default' => 'sync']);

dispatch(fn () => event(new ElementCachesInvalidated(['element::5'])));

expect(purgedTags())->toContain('element::5');
});

it('skips drafts and revisions', function (array $attributes) {
Http::fake();
event(new ElementCachesInvalidated(['element::5'], new Entry(['id' => 5, ...$attributes])));

app()->terminate();

Http::assertNothingSent();
})->with([
'draft' => [['draftId' => 3]],
'revision' => [['revisionId' => 3]],
]);

it('reports a failed purge instead of throwing', function () {
Http::fake(['*' => Http::response(status: 503)]);
$reported = [];
app(ExceptionHandler::class)->reportable(function (Throwable $e) use (&$reported) {
$reported[] = $e;
});

event(new ElementCachesInvalidated(['element::5']));

expect(HttpCache::flush())->toBe(0)
->and($reported)->not->toBeEmpty();
});
14 changes: 7 additions & 7 deletions tests/Feature/SendTagHeaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use CraftCms\Cms\Cms;
use CraftCms\Cms\Entry\Elements\Entry;
use CraftCms\Cms\Support\Facades\ResponseTagger;
use CraftCms\Cms\Support\Facades\ResponseCacheInfo;
use FOS\HttpCache\TagHeaderFormatter\CommaSeparatedTagHeaderFormatter;
use Illuminate\Support\Facades\Route;

Expand All @@ -20,9 +20,9 @@
it('sends element tags and tags added in PHP and Twig', function () {
Route::get('/page', function () {
Entry::find()->id(123)->one();
ResponseTagger::addTags(['from-php']);
ResponseCacheInfo::addTags(['from-php']);

return response(renderString("{% do ResponseTagger.addTags(['from-twig']) %}ok"));
return response(renderString("{% do ResponseCacheInfo.addTags(['from-twig']) %}ok"));
});

$tags = explode(',', (string) $this->get('/page')->headers->get('Cache-Tag'));
Expand All @@ -34,7 +34,7 @@
config(['http-cache.tags.formatter_options' => ['headerName' => 'Surrogate-Key', 'glue' => ' ']]);

Route::get('/page', function () {
ResponseTagger::addTags(['a', 'b']);
ResponseCacheInfo::addTags(['a', 'b']);

return response('ok', headers: ['Surrogate-Key' => 'existing']);
});
Expand All @@ -46,7 +46,7 @@
$uri = $uri === 'cp' ? '/'.Cms::config()->cpTrigger.'/page' : $uri;

Route::match(['GET', 'HEAD', 'POST'], $uri, function () use ($status) {
ResponseTagger::addTags(['page']);
ResponseCacheInfo::addTags(['page']);

return response('ok', $status);
});
Expand All @@ -64,11 +64,11 @@
config(['http-cache.tags.formatter' => null]);

Route::get('/page', function () {
ResponseTagger::addTags(['page']);
ResponseCacheInfo::addTags(['page']);

return response('ok');
});

expect($this->get('/page')->headers->has('Cache-Tag'))->toBeFalse()
->and(ResponseTagger::getTags())->toBe(['page']);
->and(ResponseCacheInfo::getTags())->toBe(['page']);
});
Loading