Skip to content

[FrameworkBundle] allow enabling the HTTP cache using semantic configuration #37351

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 22, 2020
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
5 changes: 5 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

5.2.0
-----

* Added `framework.http_cache` configuration tree

5.1.0
-----

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ public function getConfigTreeBuilder()

$this->addCsrfSection($rootNode);
$this->addFormSection($rootNode);
$this->addHttpCacheSection($rootNode);
$this->addEsiSection($rootNode);
$this->addSsiSection($rootNode);
$this->addFragmentsSection($rootNode);
Expand Down Expand Up @@ -180,6 +181,36 @@ private function addFormSection(ArrayNodeDefinition $rootNode)
;
}

private function addHttpCacheSection(ArrayNodeDefinition $rootNode)
{
$rootNode
->children()
->arrayNode('http_cache')
->info('HTTP cache configuration')
->canBeEnabled()
->children()
->booleanNode('debug')->defaultValue('%kernel.debug%')->end()
->enumNode('trace_level')
->values(['none', 'short', 'full'])
->end()
->scalarNode('trace_header')->end()
->integerNode('default_ttl')->end()
->arrayNode('private_headers')
->performNoDeepMerging()
->requiresAtLeastOneElement()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why would we require at least one element here ?

->fixXmlConfig('private_header')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this must be on the parent node to work

->scalarPrototype()->end()
->end()
->booleanNode('allow_reload')->end()
->booleanNode('allow_revalidate')->end()
->integerNode('stale_while_revalidate')->end()
->integerNode('stale_if_error')->end()
->end()
->end()
->end()
;
}

private function addEsiSection(ArrayNodeDefinition $rootNode)
{
$rootNode
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,7 @@ public function load(array $configs, ContainerBuilder $container)

$propertyInfoEnabled = $this->isConfigEnabled($container, $config['property_info']);
$this->registerValidationConfiguration($config['validation'], $container, $phpLoader, $propertyInfoEnabled);
$this->registerHttpCacheConfiguration($config['http_cache'], $container);
$this->registerEsiConfiguration($config['esi'], $container, $phpLoader);
$this->registerSsiConfiguration($config['ssi'], $container, $phpLoader);
$this->registerFragmentsConfiguration($config['fragments'], $container, $phpLoader);
Expand Down Expand Up @@ -532,6 +533,20 @@ private function registerFormConfiguration(array $config, ContainerBuilder $cont
}
}

private function registerHttpCacheConfiguration(array $config, ContainerBuilder $container)
{
$options = $config;
unset($options['enabled']);

if (!$options['private_headers']) {
unset($options['private_headers']);
}

$container->getDefinition('http_cache')
->setPublic($config['enabled'])
->replaceArgument(3, $options);
}

private function registerEsiConfiguration(array $config, ContainerBuilder $container, PhpFileLoader $loader)
{
if (!$this->isConfigEnabled($container, $config)) {
Expand Down
36 changes: 26 additions & 10 deletions src/Symfony/Bundle/FrameworkBundle/HttpCache/HttpCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpKernel\HttpCache\HttpCache as BaseHttpCache;
use Symfony\Component\HttpKernel\HttpCache\Store;
use Symfony\Component\HttpKernel\HttpCache\StoreInterface;
use Symfony\Component\HttpKernel\HttpCache\SurrogateInterface;
use Symfony\Component\HttpKernel\KernelInterface;

/**
Expand All @@ -28,22 +30,36 @@ class HttpCache extends BaseHttpCache
protected $cacheDir;
protected $kernel;

private $store;
private $surrogate;
private $options;

/**
* @param string $cacheDir The cache directory (default used if null)
* @param string|StoreInterface $cache The cache directory (default used if null) or the storage instance
*/
public function __construct(KernelInterface $kernel, string $cacheDir = null)
public function __construct(KernelInterface $kernel, $cache = null, SurrogateInterface $surrogate = null, array $options = null)
{
$this->kernel = $kernel;
$this->cacheDir = $cacheDir;
$this->surrogate = $surrogate;
$this->options = $options ?? [];

if ($cache instanceof StoreInterface) {
$this->store = $cache;
} elseif (null !== $cache && !\is_string($cache)) {
throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be a string or a SurrogateInterface, "%s" given.', __METHOD__, get_debug_type($cache)));
} else {
$this->cacheDir = $cache;
}

$isDebug = $kernel->isDebug();
$options = ['debug' => $isDebug];
if (null === $options && $kernel->isDebug()) {
$this->options = ['debug' => true];
}

if ($isDebug) {
$options['stale_if_error'] = 0;
if ($this->options['debug'] ?? false) {
$this->options += ['stale_if_error' => 0];
}

parent::__construct($kernel, $this->createStore(), $this->createSurrogate(), array_merge($options, $this->getOptions()));
parent::__construct($kernel, $this->createStore(), $this->createSurrogate(), array_merge($this->options, $this->getOptions()));
}

/**
Expand All @@ -69,11 +85,11 @@ protected function getOptions()

protected function createSurrogate()
{
return new Esi();
return $this->surrogate ?? new Esi();
}

protected function createStore()
{
return new Store($this->cacheDir ?: $this->kernel->getCacheDir().'/http_cache');
return $this->store ?? new Store($this->cacheDir ?: $this->kernel->getCacheDir().'/http_cache');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
<xsd:element name="messenger" type="messenger" minOccurs="0" maxOccurs="1" />
<xsd:element name="http-client" type="http_client" minOccurs="0" maxOccurs="1" />
<xsd:element name="mailer" type="mailer" minOccurs="0" maxOccurs="1" />
<xsd:element name="http-cache" type="http_cache" minOccurs="0" maxOccurs="1" />
</xsd:choice>

<xsd:attribute name="http-method-override" type="xsd:boolean" />
Expand Down Expand Up @@ -576,4 +577,28 @@
<xsd:element name="recipients" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>

<xsd:complexType name="http_cache">
<xsd:sequence>
<xsd:element name="private-header" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>

<xsd:attribute name="enabled" type="xsd:boolean" />
<xsd:attribute name="debug" type="xsd:boolean" />
<xsd:attribute name="trace-level" type="http_cache_trace_levels" />
<xsd:attribute name="trace-header" type="xsd:string" />
<xsd:attribute name="default-ttl" type="xsd:integer" />
<xsd:attribute name="allow-reload" type="xsd:boolean" />
<xsd:attribute name="allow-revalidate" type="xsd:boolean" />
<xsd:attribute name="stale-while-revalidate" type="xsd:integer" />
<xsd:attribute name="stale-if-error" type="xsd:integer" />
</xsd:complexType>

<xsd:simpleType name="http_cache_trace_levels">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="none" />
<xsd:enumeration value="short" />
<xsd:enumeration value="full" />
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
16 changes: 16 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Closure;
use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;
use Symfony\Component\Config\Resource\SelfCheckingResourceChecker;
use Symfony\Component\Config\ResourceCheckerConfigCacheFactory;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
Expand Down Expand Up @@ -46,6 +47,7 @@
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\EventListener\LocaleAwareListener;
use Symfony\Component\HttpKernel\HttpCache\Store;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelInterface;
Expand Down Expand Up @@ -120,6 +122,20 @@
->public()
->alias(RequestStack::class, 'request_stack')

->set('http_cache', HttpCache::class)
->args([
service('kernel'),
service('http_cache.store'),
service('esi')->nullOnInvalid(),
abstract_arg('options'),
])
->tag('container.hot_path')

->set('http_cache.store', Store::class)
->args([
param('kernel.cache_dir').'/http_cache',
])

->set('url_helper', UrlHelper::class)
->args([
service('request_stack'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,11 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
'local_dotenv_file' => '%kernel.project_dir%/.env.%kernel.environment%.local',
'decryption_env_var' => 'base64:default::SYMFONY_DECRYPTION_SECRET',
],
'http_cache' => [
'enabled' => false,
'debug' => '%kernel.debug%',
'private_headers' => [],
],
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Kernel;
Expand Down Expand Up @@ -74,12 +73,6 @@ public function __wakeup()
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}

public function __destruct()
{
$fs = new Filesystem();
$fs->remove($this->cacheDir);
}

protected function configureRoutes(RoutingConfigurator $routes): void
{
$routes->add('halloween', '/')->controller('kernel::halloweenAction');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
Expand All @@ -29,9 +30,21 @@

class MicroKernelTraitTest extends TestCase
{
private $kernel;

protected function tearDown(): void
{
if ($this->kernel) {
$kernel = $this->kernel;
$this->kernel = null;
$fs = new Filesystem();
$fs->remove($kernel->getCacheDir());
}
}

public function test()
{
$kernel = new ConcreteMicroKernel('test', false);
$kernel = $this->kernel = new ConcreteMicroKernel('test', false);
$kernel->boot();

$request = Request::create('/');
Expand All @@ -44,7 +57,7 @@ public function test()

public function testAsEventSubscriber()
{
$kernel = new ConcreteMicroKernel('test', false);
$kernel = $this->kernel = new ConcreteMicroKernel('test', false);
$kernel->boot();

$request = Request::create('/danger');
Expand All @@ -62,7 +75,7 @@ public function testRoutingRouteLoaderTagIsAdded()
->willReturn('framework');
$container = new ContainerBuilder();
$container->registerExtension($frameworkExtension);
$kernel = new ConcreteMicroKernel('test', false);
$kernel = $this->kernel = new ConcreteMicroKernel('test', false);
$kernel->registerContainerConfiguration(new ClosureLoader($container));
$this->assertTrue($container->getDefinition('kernel')->hasTag('routing.route_loader'));
}
Expand All @@ -80,7 +93,7 @@ public function testFlexStyle()

public function testSecretLoadedFromExtension()
{
$kernel = new ConcreteMicroKernel('test', false);
$kernel = $this->kernel = new ConcreteMicroKernel('test', false);
$kernel->boot();

self::assertSame('$ecret', $kernel->getContainer()->getParameter('kernel.secret'));
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"symfony/event-dispatcher": "^5.1",
"symfony/error-handler": "^4.4.1|^5.0.1",
"symfony/http-foundation": "^4.4|^5.0",
"symfony/http-kernel": "^5.0",
"symfony/http-kernel": "^5.2",
"symfony/polyfill-mbstring": "~1.0",
"symfony/polyfill-php80": "^1.15",
"symfony/filesystem": "^4.4|^5.0",
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/HttpKernel/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

5.2.0
-----

* made the public `http_cache` service handle requests when available

5.1.0
-----

Expand Down
Loading