8000 [HttpKernel][HttpCache][RFC] SSI kernel proxy by kingcrunch · Pull Request #6766 · symfony/symfony · GitHub
[go: up one dir, main page]

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 1 commit
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
Next Next commit
SSI-Proxy
- Implement SSI rendering strategy
- Implement SSI kernel proxy
- Implement Listeer
  • Loading branch information
kingcrunch committed Jan 24, 2013
commit 323dc7fc421cef28361c7a02d8efca7422c78128
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
23 changes: 23 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/ssi.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?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="esi_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" />
<call method="setUrlGenerator"><argument type="service" id="router" /></call>
</service>
</services>
</container>
53 changes: 53 additions & 0 deletions src/Symfony/Component/HttpKernel/EventListener/SsiListener.php
E30A
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');
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?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\RenderingStrategy;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ControllerReference;

/**
* Implements the ESI rendering strategy.
*
* @author Sebastian Krebs <krebs.seb@gmail.com>
*/
class SsiRenderingStrategy extends GeneratorAwareRenderingStrategy
{
private $defaultStrategy;

/**
* Constructor.
*
* The "fallback" strategy when ESI is not available should always be an
* instance of DefaultRenderingStrategy (or a class you are using for the
* default strategy).
*
* @param RenderingStrategyInterface $defaultStrategy The default strategy to use when ESI is not supported
*/
public function __construct(RenderingStrategyInterface $defaultStrategy)
{
$this->defaultStrategy = $defaultStrategy;
}

/**
* {@inheritdoc}
*
* Note that if the current Request has no ESI capability, this method
* falls back to use the default rendering strategy.
*
* Additional available options:
*
* * comment: a comment to add when returning an esi:include tag
*/
public function render($uri, Request $request = null, array $options = array())
{
if (null === $request) {
return $this->defaultStrategy->render($uri, $request, $options);
}

if ($uri instanceof ControllerReference) {
$uri = $this->generateProxyUri($uri, $request);
}

$tag = $this->renderIncludeTag($uri, isset($options['ignore_errors']) ? $options['ignore_errors'] : false, isset($options['comment']) ? $options['comment'] : '');

return new Response($tag);
}

/**
* {@inheritdoc}
*/
public function getName()
{
return 'ssi';
}


private function renderIncludeTag ($uri, $ignoreErrors = true, $comment = '') {
$html = sprintf('<!--#include virtual="%s"%s -->',
$uri,
$ignoreErrors ? ' fmt="?"' : ''
);

if (!empty($comment)) {
return sprintf("<!-- %s -->\n%s", $comment, $html);
}

return $html;
}
}
153 changes: 153 additions & 0 deletions src/Symfony/Component/HttpKernel/SsiKernelProxy.php
E13E
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
<?php
namespace Symfony\Component\HttpKernel;

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

/**
* Kernel proxy handling SSI-responses
*
* @author Sebastian Krebs <krebs.seb@gmail.com>
*/
class SsiKernelProxy implements HttpKernelInterface, TerminableInterface
{
private $kernel;
private $options = array(
'pass_through' => false
);

public function __construct (HttpKernelInterface $kernel, array $options = array())
{
$this->kernel = $kernel;
$this->options = array_merge($this->options, $options);
}

/**
* Handles a Request to convert it to a Response.
*
* When $catch is true, the implementation must catch all exceptions
* and do its best to convert them to a Response instance.
*
* @param Request $request A Request instance
* @param integer $type The type of the request
* (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
* @param Boolean $catch Whether to catch exceptions or not
*
* @return Response A Response instance
*
* @throws \Exception When an Exception occurs during processing
*
* @api
*/
public function handle (Request $request, $type = self::MASTER_REQUEST, $catch = true)
{
$response = $this->kernel->handle($request, $type, $catch);

if (!$this->options['pass_through'] && !$this->serverHasCapability($request) && $this->hasControlHeader($response)) {
$this->parse($request, $response);
}

return $response;
}

/**
* Terminates a request/response cycle.
*
* Should be called after sending the response and before shutting down the kernel.
*
* @param Request $request A Request instance
* @param Response $response A Response instance
*
* @api
*/
public function terminate (Request $request, Response $response)
{
if ($this->kernel instanceof TerminableInterface) {
$this->kernel->terminate($request, $response);
}
}

private function parse (Request $request, Response $response)
{
$this->addCapabilityHeader($request);

$content = preg_replace_callback('#<!--\#include\s+(.*?)\s*-->#', $this->createHandler($this, $request, $response), $response->getContent());
$response->setContent($content);

$this->removeControlHeader($response);
}

private function createHandler (HttpKernelInterface $kernel, Request $request, Response $response)
{
return function ($attributes) use ($kernel, $request, $response) {
$options = array();
preg_match_all('/(virtual|fmt)="([^"]*?)"/', $attributes[1], $matches, PREG_SET_ORDER);
foreach ($matches as $set) {
$options[$set[1]] = $set[2];
}

if (!isset($options['virtual'])) {
throw new \RuntimeException('Unable to process an SSI tag without a "virtual" attribute.');
}


$subRequest = Request::create($options['virtual'], 'GET', array(), $request->cookies->all(), array(), $request->server->all());

try {
$subResponse = $kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);

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

if ($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 {
$response->headers->set('Cache-Control', 'no-cache, must-revalidate');
}

return $subResponse->getContent();
} catch (\Exception $e) {

if (!isset($options['fmt']) || $options['fmt'] != '?') {
throw $e;
}
}

return '';
};
}

private function serverHasCapability (Request $request)
{
$value = $request->headers->get('Surrogate-Capability');
return $value && strpos($value, 'SSI/1.0') !== false;
}

private function hasControlHeader (Response $response) {
$value = $response->headers->get('Surrogate-Control');
return $value && strpos($value, 'SSI/1.0') !== false;
}

private function addCapabilityHeader (Request $request)
{
$current = $request->headers->get('Surrogate-Capability');
$request->headers->set('Surrogate-Capability', ($current ? $current . ', ' : '') . 'symfony2="SSI/1.0"');
}

private function removeControlHeader (Response $response)
{
$current = $response->headers->get('Surrogate-Control');
$new = array_filter(explode(',', $current), function ($control) {
return strpos($control, 'SSI/1.0') === false;
});
if ($new) {
$response->headers->set('Surrogate-Control', implode(', ', $new));
} else {
$response->headers->remove('Surrogate-Control');
}
}
}
0