Skip to content

[HttpKernel][HttpCache][RFC] SSI kernel proxy #6766

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

Closed
wants to merge 6 commits into from
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
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ public function getConfigTreeBuilder()

$this->addFormSection($rootNode);
$this->addEsiSection($rootNode);
$this->addSsiSection($rootNode);
$this->addRouterProxySection($rootNode);
$this->addProfilerSection($rootNode);
$this->addRouterSection($rootNode);
Expand Down Expand Up @@ -130,6 +131,16 @@ private function addRouterProxySection(ArrayNodeDefinition $rootNode)
;
}

private function addSsiSection (ArrayNodeDefinition $rootNode) {
$rootNode
->children()
->arrayNode('ssi')
->info('ssi configuration')
->canBeDisabled()
->end()
->end();
}

private function addProfilerSection(ArrayNodeDefinition $rootNode)
{
$rootNode
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ public function load(array $configs, ContainerBuilder $container)
$this->registerEsiConfiguration($config['esi'], $loader);
}

if (isset($config['ssi'])) {
$this->registerSsiConfiguration($config['ssi'], $loader);
}

if (isset($config['router_proxy'])) {
$this->registerRouterProxyConfiguration($config['router_proxy'], $container, $loader);
}
Expand Down Expand Up @@ -188,6 +192,18 @@ private function registerEsiConfiguration(array $config, XmlFileLoader $loader)
}
}

/**
* Loads the SSI configuration.
*
* @param array $config An SSI configuration array
* @param XmlFileLoader $loader An XmlFileLoader instance
*/
private function registerSsiConfiguration (array $config, XmlFileLoader $loader) {
Copy link
Contributor

Choose a reason for hiding this comment

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

minor issue .. { needs to be on the next line

if (!empty($config['enabled'])) {
$loader->load('ssi.xml');
}
}

/**
* Loads the router proxy configuration.
*
Expand Down
7 changes: 1 addition & 6 deletions src/Symfony/Bundle/FrameworkBundle/HttpCache/HttpCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function __construct(HttpKernelInterface $kernel, $cacheDir = null)
$this->kernel = $kernel;
$this->cacheDir = $cacheDir;

parent::__construct($kernel, $this->createStore(), $this->createEsi(), array_merge(array('debug' => $kernel->isDebug()), $this->getOptions()));
parent::__construct($kernel, $this->createStore(), array_merge(array('debug' => $kernel->isDebug()), $this->getOptions()));
}

/**
Expand Down Expand Up @@ -70,11 +70,6 @@ protected function getOptions()
return array();
}

protected function createEsi()
{
return new Esi();
}

protected function createStore()
{
return new Store($this->cacheDir ?: $this->kernel->getCacheDir().'/http_cache');
Expand Down
24 changes: 24 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/ssi.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<parameters>
<parameter key="ssi_listener.class">Symfony\Component\HttpKernel\EventListener\SsiListener</parameter>
<parameter key="http_content_renderer.strategy.ssi.class">Symfony\Component\HttpKernel\RenderingStrategy\SsiRenderingStrategy</parameter>
</parameters>

<services>
<service id="ssi_listener" class="%ssi_listener.class%">
<tag name="kernel.event_subscriber"/>
</service>

<service id="http_content_renderer.strategy.ssi" class="%http_content_renderer.strategy.ssi.class%">
<tag name="kernel.content_renderer_strategy" />
<argument type="service" id="http_content_renderer.strategy.default" />
<argument type="service" id="http_content_renderer.strategy.default"/>
<call method="setProxyPath"><argument>%http_content_renderer.proxy_path%</argument></call>
</service>
</services>
</container>
53 changes: 53 additions & 0 deletions src/Symfony/Component/HttpKernel/EventListener/SsiListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpKernel\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
* SsiListener adds a Surrogate-Control HTTP header when the Response needs to be parsed for SSI.
*
* @author Sebastian Krebs <krebs.seb@gmail.com>
*/
class SsiListener implements EventSubscriberInterface
{
/**
* Filters the Response.
*
* @param FilterResponseEvent $event A FilterResponseEvent instance
*/
public function onKernelResponse(FilterResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$this->updateResponseHeader($event->getResponse());
}
}

public static function getSubscribedEvents()
{
return array(
KernelEvents::RESPONSE => 'onKernelResponse',
);
}

private function updateResponseHeader (Response $response)
{
if (false !== strpos($response->getContent(), '<!--#include')) {
$header = $response->headers->get('Surrogate-Control');
$response->headers->set('Surrogate-Control', ($header ? $header . ', ' : '') . 'content=SSI/1.0');
}
}
}
41 changes: 1 addition & 40 deletions src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
private $kernel;
private $store;
private $request;
private $esi;
private $esiCacheStrategy;
private $traces;

/**
Expand Down Expand Up @@ -74,10 +72,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
*
* @param HttpKernelInterface $kernel An HttpKernelInterface instance
* @param StoreInterface $store A Store instance
* @param Esi $esi An Esi instance
* @param array $options An array of options
*/
public function __construct(HttpKernelInterface $kernel, StoreInterface $store, Esi $esi = null, array $options = array())
public function __construct(HttpKernelInterface $kernel, StoreInterface $store, array $options = array())
{
$this->store = $store;
$this->kernel = $kernel;
Expand All @@ -94,7 +91,6 @@ public function __construct(HttpKernelInterface $kernel, StoreInterface $store,
'stale_while_revalidate' => 2,
'stale_if_error' => 60,
), $options);
$this->esi = $esi;
$this->traces = array();
}

Expand Down Expand Up @@ -153,17 +149,6 @@ public function getKernel()
return $this->kernel;
}


/**
* Gets the Esi instance
*
* @return Esi An Esi instance
*/
public function getEsi()
{
return $this->esi;
}

/**
* {@inheritdoc}
*
Expand All @@ -175,9 +160,6 @@ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQ
if (HttpKernelInterface::MASTER_REQUEST === $type) {
$this->traces = array();
$this->request = $request;
if (null !== $this->esi) {
$this->esiCacheStrategy = $this->esi->createCacheStrategy();
}
}

$path = $request->getPathInfo();
Expand All @@ -204,14 +186,6 @@ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQ
$response->headers->set('X-Symfony-Cache', $this->getLog());
}

if (null !== $this->esi) {
$this->esiCacheStrategy->add($response);

if (HttpKernelInterface::MASTER_REQUEST === $type) {
$this->esiCacheStrategy->update($response);
}
}

$response->prepare($request);

return $response;
Expand Down Expand Up @@ -444,10 +418,6 @@ protected function fetch(Request $request, $catch = false)
*/
protected function forward(Request $request, $catch = false, Response $entry = null)
{
if ($this->esi) {
$this->esi->addSurrogateEsiCapability($request);
}

// always a "master" request (as the real master request can be in cache)
$response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch);
// FIXME: we probably need to also catch exceptions if raw === true
Expand All @@ -465,8 +435,6 @@ protected function forward(Request $request, $catch = false, Response $entry = n
}
}

$this->processResponseBody($request, $response);

return $response;
}

Expand Down Expand Up @@ -618,13 +586,6 @@ private function restoreResponseBody(Request $request, Response $response)
$response->headers->remove('X-Body-File');
}

protected function processResponseBody(Request $request, Response $response)
{
if (null !== $this->esi && $this->esi->needsEsiParsing($response)) {
$this->esi->process($request, $response);
}
}

/**
* Checks if the Request includes authorization or other sensitive information
* that should cause the Response to be considered private by default.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php
namespace Symfony\Component\HttpKernel\IncludeProxy;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
* @author Sebastian Krebs <krebs.seb@gmail.com>
*/
class EsiIncludeStrategy implements IncludeStrategyInterface
{
public function getName ()
{
return 'ESI/1.0';
}

public function handle (HttpKernelInterface $kernel, Request $request, Response $response)
{
$extractor = function ($attributes) {
$options = array();
preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $attributes[1], $matches, PREG_SET_ORDER);
foreach ($matches as $set) {
$options[$set[1]] = $set[2];
}

return array(
isset($options['src']) ? $options['virtual'] : null,
isset($options['alt']) ? $options['alt'] : null,
isset($options['onerror']) && $options['onerror'] == 'continue'
);

};
return preg_replace_callback('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', new IncludeHandler($kernel, $request, $response, $extractor), $response->getContent());
}
}
83 changes: 83 additions & 0 deletions src/Symfony/Component/HttpKernel/IncludeProxy/IncludeHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php
namespace Symfony\Component\HttpKernel\IncludeProxy;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
* Sebastian Krebs <krebs.seb@gmail.com>
*
* This is a helper class, that act as and replace the closure of the
* IncludeStrategy-implementations.
*
* @internal
*/
class IncludeHandler
{
private $kernel;
private $request;
private $response;
private $extractor;

public function __construct (HttpKernelInterface $kernel, Request $request, Response $response, $extractor)
{
$this->kernel = $kernel;
$this->request = $request;
$this->response = $response;
$this->extractor = $extractor;
}

public function __invoke ($attributes)
{
list($source, $alternative, $ignoreErrors) = call_user_func($this->extractor, $attributes);
return $this->handle($source, $alternative, $ignoreErrors);
}

private function handle ($source, $alternative, $ignoreErrors)
{
if (!$source) {
throw new \RuntimeException('Unable to process an include tag without a source attribute.');
}

try {
$subResponse = $this->request($source);
$this->updateHeaders($this->response, $subResponse);
return $subResponse->getContent();
} catch (\Exception $e) {
if ($alternative) {
return $this->handle($alternative, null, $ignoreErrors);
}

if ($ignoreErrors) {
throw $e;
}
}

return '';
}

private function request ($source)
{
$subRequest = Request::create($source, 'GET', array(), $this->request->cookies->all(), array(), $this->request->server->all());

$response = $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);

if (!$response->isSuccessful()) {
throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
}
return $response;
}

private function updateHeaders (Response $response, Response $subResponse)
{
if ($this->response->isCacheable() && $subResponse->isCacheable()) {
$maxAge = min($response->headers->getCacheControlDirective('max-age'), $subResponse->headers->getCacheControlDirective('max-age'));
$sMaxAge = min($response->headers->getCacheControlDirective('s-maxage'), $subResponse->headers->getCacheControlDirective('s-maxage'));
$response->setSharedMaxAge($sMaxAge);
$response->setMaxAge($maxAge);
} else {
$this->response->headers->set('Cache-Control', 'no-cache, must-revalidate');
}
}
}
Loading