Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[HttpCache] Do not call terminate() on cache hit #46763

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 27, 2022
Merged
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
15 changes: 15 additions & 0 deletions src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* the cache can serve a stale response when an error is encountered (default: 60).
* This setting is overridden by the stale-if-error HTTP Cache-Control extension
* (see RFC 5861).
*
* * terminate_on_cache_hit Specifies if the kernel.terminate event should be dispatched even when the cache
* was hit (default: true).
* Unless your application needs to process events on cache hits, it is recommended
* to set this to false to avoid having to bootstrap the Symfony framework on a cache hit.
*/
public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = [])
{
Expand All @@ -98,6 +103,7 @@ public function __construct(HttpKernelInterface $kernel, StoreInterface $store,
'stale_if_error' => 60,
'trace_level' => 'none',
'trace_header' => 'X-Symfony-Cache',
'terminate_on_cache_hit' => true,
], $options);

if (!isset($options['trace_level'])) {
Expand Down Expand Up @@ -238,6 +244,15 @@ public function handle(Request $request, int $type = HttpKernelInterface::MAIN_R
*/
public function terminate(Request $request, Response $response)
{
// Do not call any listeners in case of a cache hit.
// This ensures identical behavior as if you had a separate
// reverse caching proxy such as Varnish and the like.
if ($this->options['terminate_on_cache_hit']) {
trigger_deprecation('symfony/http-kernel', '6.2', 'Setting "terminate_on_cache_hit" to "true" is deprecated and will be changed to "false" in Symfony 7.0.');
} elseif (\in_array('fresh', $this->traces[$this->getTraceKey($request)] ?? [], true)) {
return;
}

if ($this->getKernel() instanceof TerminableInterface) {
$this->getKernel()->terminate($request, $response);
}
Expand Down
108 changes: 105 additions & 3 deletions src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@

namespace Symfony\Component\HttpKernel\Tests\HttpCache;

use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpKernel\HttpCache\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\Store;
use Symfony\Component\HttpKernel\HttpCache\StoreInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Kernel;
Expand All @@ -25,6 +27,8 @@
*/
class HttpCacheTest extends HttpCacheTestCase
{
use ExpectDeprecationTrait;

public function testTerminateDelegatesTerminationOnlyForTerminableInterface()
{
$storeMock = $this->getMockBuilder(StoreInterface::class)
Expand All @@ -33,7 +37,7 @@ public function testTerminateDelegatesTerminationOnlyForTerminableInterface()

// does not implement TerminableInterface
$kernel = new TestKernel();
$httpCache = new HttpCache($kernel, $storeMock);
$httpCache = new HttpCache($kernel, $storeMock, null, ['terminate_on_cache_hit' => false]);
$httpCache->terminate(Request::create('/'), new Response());

$this->assertFalse($kernel->terminateCalled, 'terminate() is never called if the kernel class does not implement TerminableInterface');
Expand All @@ -47,10 +51,108 @@ public function testTerminateDelegatesTerminationOnlyForTerminableInterface()
$kernelMock->expects($this->once())
->method('terminate');

$kernel = new HttpCache($kernelMock, $storeMock);
$kernel = new HttpCache($kernelMock, $storeMock, null, ['terminate_on_cache_hit' => false]);
$kernel->terminate(Request::create('/'), new Response());
}

public function testDoesNotCallTerminateOnFreshResponse()
{
$terminateEvents = [];

$eventDispatcher = $this->createMock(EventDispatcher::class);
$eventDispatcher
->expects($this->any())
->method('dispatch')
->with($this->callback(function ($event) use (&$terminateEvents) {
if ($event instanceof TerminateEvent) {
$terminateEvents[] = $event;
}

return true;
}));

$this->setNextResponse(
200,
[
'ETag' => '1234',
'Cache-Control' => 'public, s-maxage=60',
],
'Hello World',
null,
$eventDispatcher
);

$this->request('GET', '/');
$this->assertHttpKernelIsCalled();
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertTraceContains('miss');
$this->assertTraceContains('store');
$this->cache->terminate($this->request, $this->response);

sleep(2);

$this->request('GET', '/');
$this->assertHttpKernelIsNotCalled();
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertTraceContains('fresh');
$this->assertEquals(2, $this->response->headers->get('Age'));
$this->cache->terminate($this->request, $this->response);

$this->assertCount(1, $terminateEvents);
}

/**
* @group legacy
*/
public function testDoesCallTerminateOnFreshResponseIfConfigured()
{
$this->expectDeprecation('Since symfony/http-kernel 6.2: Setting "terminate_on_cache_hit" to "true" is deprecated and will be changed to "false" in Symfony 7.0.');

$terminateEvents = [];

$eventDispatcher = $this->createMock(EventDispatcher::class);
$eventDispatcher
->expects($this->any())
->method('dispatch')
->with($this->callback(function ($event) use (&$terminateEvents) {
if ($event instanceof TerminateEvent) {
$terminateEvents[] = $event;
}

return true;
}));

$this->setNextResponse(
200,
[
'ETag' => '1234',
'Cache-Control' => 'public, s-maxage=60',
],
'Hello World',
null,
$eventDispatcher
);
$this->cacheConfig['terminate_on_cache_hit'] = true;

$this->request('GET', '/');
$this->assertHttpKernelIsCalled();
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertTraceContains('miss');
$this->assertTraceContains('store');
$this->cache->terminate($this->request, $this->response);

sleep(2);

$this->request('GET', '/');
$this->assertHttpKernelIsNotCalled();
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertTraceContains('fresh');
$this->assertEquals(2, $this->response->headers->get('Age'));
$this->cache->terminate($this->request, $this->response);

$this->assertCount(2, $terminateEvents);
}

public function testPassesOnNonGetHeadRequests()
{
$this->setNextResponse(200);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\HttpKernel\Tests\HttpCache;

use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpKernel\HttpCache\HttpCache;
Expand Down Expand Up @@ -124,6 +125,10 @@ public function request($method, $uri = '/', $server = [], $cookies = [], $esi =
$this->cacheConfig['debug'] = true;
}

if (!isset($this->cacheConfig['terminate_on_cache_hit'])) {
$this->cacheConfig['terminate_on_cache_hit'] = false;
}

$this->esi = $esi ? new Esi() : null;
$this->cache = new HttpCache($this->kernel, $this->store, $this->esi, $this->cacheConfig);
$this->request = Request::create($uri, $method, [], $cookies, [], $server);
Expand All @@ -145,9 +150,9 @@ public function getMetaStorageValues()
}

// A basic response with 200 status code and a tiny body.
public function setNextResponse($statusCode = 200, array $headers = [], $body = 'Hello World', \Closure $customizer = null)
public function setNextResponse($statusCode = 200, array $headers = [], $body = 'Hello World', \Closure $customizer = null, EventDispatcher $eventDispatcher = null)
{
$this->kernel = new TestHttpKernel($body, $statusCode, $headers, $customizer);
$this->kernel = new TestHttpKernel($body, $statusCode, $headers, $customizer, $eventDispatcher);
}

public function setNextResponses($responses)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ class TestHttpKernel extends HttpKernel implements ControllerResolverInterface,
protected $catch = false;
protected $backendRequest;

public function __construct($body, $status, $headers, \Closure $customizer = null)
public function __construct($body, $status, $headers, \Closure $customizer = null, EventDispatcher $eventDispatcher = null)
{
$this->body = $body;
$this->status = $status;
$this->headers = $headers;
$this->customizer = $customizer;

parent::__construct(new EventDispatcher(), $this, null, $this, true);
parent::__construct($eventDispatcher ?? new EventDispatcher(), $this, null, $this, true);
}

public function assert(\Closure $callback)
Expand Down