annotate vendor/symfony/http-kernel/HttpCache/HttpCache.php @ 2:92f882872392

Trusted hosts, + remove migration modules
author Chris Cannam
date Tue, 05 Dec 2017 09:26:43 +0000
parents 4c8ae668cc8c
children 1fec387a4317
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /*
Chris@0 4 * This file is part of the Symfony package.
Chris@0 5 *
Chris@0 6 * (c) Fabien Potencier <fabien@symfony.com>
Chris@0 7 *
Chris@0 8 * This code is partially based on the Rack-Cache library by Ryan Tomayko,
Chris@0 9 * which is released under the MIT license.
Chris@0 10 * (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801)
Chris@0 11 *
Chris@0 12 * For the full copyright and license information, please view the LICENSE
Chris@0 13 * file that was distributed with this source code.
Chris@0 14 */
Chris@0 15
Chris@0 16 namespace Symfony\Component\HttpKernel\HttpCache;
Chris@0 17
Chris@0 18 use Symfony\Component\HttpKernel\HttpKernelInterface;
Chris@0 19 use Symfony\Component\HttpKernel\TerminableInterface;
Chris@0 20 use Symfony\Component\HttpFoundation\Request;
Chris@0 21 use Symfony\Component\HttpFoundation\Response;
Chris@0 22
Chris@0 23 /**
Chris@0 24 * Cache provides HTTP caching.
Chris@0 25 *
Chris@0 26 * @author Fabien Potencier <fabien@symfony.com>
Chris@0 27 */
Chris@0 28 class HttpCache implements HttpKernelInterface, TerminableInterface
Chris@0 29 {
Chris@0 30 private $kernel;
Chris@0 31 private $store;
Chris@0 32 private $request;
Chris@0 33 private $surrogate;
Chris@0 34 private $surrogateCacheStrategy;
Chris@0 35 private $options = array();
Chris@0 36 private $traces = array();
Chris@0 37
Chris@0 38 /**
Chris@0 39 * Constructor.
Chris@0 40 *
Chris@0 41 * The available options are:
Chris@0 42 *
Chris@0 43 * * debug: If true, the traces are added as a HTTP header to ease debugging
Chris@0 44 *
Chris@0 45 * * default_ttl The number of seconds that a cache entry should be considered
Chris@0 46 * fresh when no explicit freshness information is provided in
Chris@0 47 * a response. Explicit Cache-Control or Expires headers
Chris@0 48 * override this value. (default: 0)
Chris@0 49 *
Chris@0 50 * * private_headers Set of request headers that trigger "private" cache-control behavior
Chris@0 51 * on responses that don't explicitly state whether the response is
Chris@0 52 * public or private via a Cache-Control directive. (default: Authorization and Cookie)
Chris@0 53 *
Chris@0 54 * * allow_reload Specifies whether the client can force a cache reload by including a
Chris@0 55 * Cache-Control "no-cache" directive in the request. Set it to ``true``
Chris@0 56 * for compliance with RFC 2616. (default: false)
Chris@0 57 *
Chris@0 58 * * allow_revalidate Specifies whether the client can force a cache revalidate by including
Chris@0 59 * a Cache-Control "max-age=0" directive in the request. Set it to ``true``
Chris@0 60 * for compliance with RFC 2616. (default: false)
Chris@0 61 *
Chris@0 62 * * stale_while_revalidate Specifies the default number of seconds (the granularity is the second as the
Chris@0 63 * Response TTL precision is a second) during which the cache can immediately return
Chris@0 64 * a stale response while it revalidates it in the background (default: 2).
Chris@0 65 * This setting is overridden by the stale-while-revalidate HTTP Cache-Control
Chris@0 66 * extension (see RFC 5861).
Chris@0 67 *
Chris@0 68 * * stale_if_error Specifies the default number of seconds (the granularity is the second) during which
Chris@0 69 * the cache can serve a stale response when an error is encountered (default: 60).
Chris@0 70 * This setting is overridden by the stale-if-error HTTP Cache-Control extension
Chris@0 71 * (see RFC 5861).
Chris@0 72 *
Chris@0 73 * @param HttpKernelInterface $kernel An HttpKernelInterface instance
Chris@0 74 * @param StoreInterface $store A Store instance
Chris@0 75 * @param SurrogateInterface $surrogate A SurrogateInterface instance
Chris@0 76 * @param array $options An array of options
Chris@0 77 */
Chris@0 78 public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = array())
Chris@0 79 {
Chris@0 80 $this->store = $store;
Chris@0 81 $this->kernel = $kernel;
Chris@0 82 $this->surrogate = $surrogate;
Chris@0 83
Chris@0 84 // needed in case there is a fatal error because the backend is too slow to respond
Chris@0 85 register_shutdown_function(array($this->store, 'cleanup'));
Chris@0 86
Chris@0 87 $this->options = array_merge(array(
Chris@0 88 'debug' => false,
Chris@0 89 'default_ttl' => 0,
Chris@0 90 'private_headers' => array('Authorization', 'Cookie'),
Chris@0 91 'allow_reload' => false,
Chris@0 92 'allow_revalidate' => false,
Chris@0 93 'stale_while_revalidate' => 2,
Chris@0 94 'stale_if_error' => 60,
Chris@0 95 ), $options);
Chris@0 96 }
Chris@0 97
Chris@0 98 /**
Chris@0 99 * Gets the current store.
Chris@0 100 *
Chris@0 101 * @return StoreInterface $store A StoreInterface instance
Chris@0 102 */
Chris@0 103 public function getStore()
Chris@0 104 {
Chris@0 105 return $this->store;
Chris@0 106 }
Chris@0 107
Chris@0 108 /**
Chris@0 109 * Returns an array of events that took place during processing of the last request.
Chris@0 110 *
Chris@0 111 * @return array An array of events
Chris@0 112 */
Chris@0 113 public function getTraces()
Chris@0 114 {
Chris@0 115 return $this->traces;
Chris@0 116 }
Chris@0 117
Chris@0 118 /**
Chris@0 119 * Returns a log message for the events of the last request processing.
Chris@0 120 *
Chris@0 121 * @return string A log message
Chris@0 122 */
Chris@0 123 public function getLog()
Chris@0 124 {
Chris@0 125 $log = array();
Chris@0 126 foreach ($this->traces as $request => $traces) {
Chris@0 127 $log[] = sprintf('%s: %s', $request, implode(', ', $traces));
Chris@0 128 }
Chris@0 129
Chris@0 130 return implode('; ', $log);
Chris@0 131 }
Chris@0 132
Chris@0 133 /**
Chris@0 134 * Gets the Request instance associated with the master request.
Chris@0 135 *
Chris@0 136 * @return Request A Request instance
Chris@0 137 */
Chris@0 138 public function getRequest()
Chris@0 139 {
Chris@0 140 return $this->request;
Chris@0 141 }
Chris@0 142
Chris@0 143 /**
Chris@0 144 * Gets the Kernel instance.
Chris@0 145 *
Chris@0 146 * @return HttpKernelInterface An HttpKernelInterface instance
Chris@0 147 */
Chris@0 148 public function getKernel()
Chris@0 149 {
Chris@0 150 return $this->kernel;
Chris@0 151 }
Chris@0 152
Chris@0 153 /**
Chris@0 154 * Gets the Surrogate instance.
Chris@0 155 *
Chris@0 156 * @return SurrogateInterface A Surrogate instance
Chris@0 157 *
Chris@0 158 * @throws \LogicException
Chris@0 159 */
Chris@0 160 public function getSurrogate()
Chris@0 161 {
Chris@0 162 return $this->surrogate;
Chris@0 163 }
Chris@0 164
Chris@0 165 /**
Chris@0 166 * {@inheritdoc}
Chris@0 167 */
Chris@0 168 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
Chris@0 169 {
Chris@0 170 // FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism
Chris@0 171 if (HttpKernelInterface::MASTER_REQUEST === $type) {
Chris@0 172 $this->traces = array();
Chris@0 173 $this->request = $request;
Chris@0 174 if (null !== $this->surrogate) {
Chris@0 175 $this->surrogateCacheStrategy = $this->surrogate->createCacheStrategy();
Chris@0 176 }
Chris@0 177 }
Chris@0 178
Chris@0 179 $path = $request->getPathInfo();
Chris@0 180 if ($qs = $request->getQueryString()) {
Chris@0 181 $path .= '?'.$qs;
Chris@0 182 }
Chris@0 183 $this->traces[$request->getMethod().' '.$path] = array();
Chris@0 184
Chris@0 185 if (!$request->isMethodSafe(false)) {
Chris@0 186 $response = $this->invalidate($request, $catch);
Chris@0 187 } elseif ($request->headers->has('expect') || !$request->isMethodCacheable()) {
Chris@0 188 $response = $this->pass($request, $catch);
Chris@0 189 } else {
Chris@0 190 $response = $this->lookup($request, $catch);
Chris@0 191 }
Chris@0 192
Chris@0 193 $this->restoreResponseBody($request, $response);
Chris@0 194
Chris@0 195 $response->setDate(\DateTime::createFromFormat('U', time(), new \DateTimeZone('UTC')));
Chris@0 196
Chris@0 197 if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) {
Chris@0 198 $response->headers->set('X-Symfony-Cache', $this->getLog());
Chris@0 199 }
Chris@0 200
Chris@0 201 if (null !== $this->surrogate) {
Chris@0 202 if (HttpKernelInterface::MASTER_REQUEST === $type) {
Chris@0 203 $this->surrogateCacheStrategy->update($response);
Chris@0 204 } else {
Chris@0 205 $this->surrogateCacheStrategy->add($response);
Chris@0 206 }
Chris@0 207 }
Chris@0 208
Chris@0 209 $response->prepare($request);
Chris@0 210
Chris@0 211 $response->isNotModified($request);
Chris@0 212
Chris@0 213 return $response;
Chris@0 214 }
Chris@0 215
Chris@0 216 /**
Chris@0 217 * {@inheritdoc}
Chris@0 218 */
Chris@0 219 public function terminate(Request $request, Response $response)
Chris@0 220 {
Chris@0 221 if ($this->getKernel() instanceof TerminableInterface) {
Chris@0 222 $this->getKernel()->terminate($request, $response);
Chris@0 223 }
Chris@0 224 }
Chris@0 225
Chris@0 226 /**
Chris@0 227 * Forwards the Request to the backend without storing the Response in the cache.
Chris@0 228 *
Chris@0 229 * @param Request $request A Request instance
Chris@0 230 * @param bool $catch Whether to process exceptions
Chris@0 231 *
Chris@0 232 * @return Response A Response instance
Chris@0 233 */
Chris@0 234 protected function pass(Request $request, $catch = false)
Chris@0 235 {
Chris@0 236 $this->record($request, 'pass');
Chris@0 237
Chris@0 238 return $this->forward($request, $catch);
Chris@0 239 }
Chris@0 240
Chris@0 241 /**
Chris@0 242 * Invalidates non-safe methods (like POST, PUT, and DELETE).
Chris@0 243 *
Chris@0 244 * @param Request $request A Request instance
Chris@0 245 * @param bool $catch Whether to process exceptions
Chris@0 246 *
Chris@0 247 * @return Response A Response instance
Chris@0 248 *
Chris@0 249 * @throws \Exception
Chris@0 250 *
Chris@0 251 * @see RFC2616 13.10
Chris@0 252 */
Chris@0 253 protected function invalidate(Request $request, $catch = false)
Chris@0 254 {
Chris@0 255 $response = $this->pass($request, $catch);
Chris@0 256
Chris@0 257 // invalidate only when the response is successful
Chris@0 258 if ($response->isSuccessful() || $response->isRedirect()) {
Chris@0 259 try {
Chris@0 260 $this->store->invalidate($request);
Chris@0 261
Chris@0 262 // As per the RFC, invalidate Location and Content-Location URLs if present
Chris@0 263 foreach (array('Location', 'Content-Location') as $header) {
Chris@0 264 if ($uri = $response->headers->get($header)) {
Chris@0 265 $subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all());
Chris@0 266
Chris@0 267 $this->store->invalidate($subRequest);
Chris@0 268 }
Chris@0 269 }
Chris@0 270
Chris@0 271 $this->record($request, 'invalidate');
Chris@0 272 } catch (\Exception $e) {
Chris@0 273 $this->record($request, 'invalidate-failed');
Chris@0 274
Chris@0 275 if ($this->options['debug']) {
Chris@0 276 throw $e;
Chris@0 277 }
Chris@0 278 }
Chris@0 279 }
Chris@0 280
Chris@0 281 return $response;
Chris@0 282 }
Chris@0 283
Chris@0 284 /**
Chris@0 285 * Lookups a Response from the cache for the given Request.
Chris@0 286 *
Chris@0 287 * When a matching cache entry is found and is fresh, it uses it as the
Chris@0 288 * response without forwarding any request to the backend. When a matching
Chris@0 289 * cache entry is found but is stale, it attempts to "validate" the entry with
Chris@0 290 * the backend using conditional GET. When no matching cache entry is found,
Chris@0 291 * it triggers "miss" processing.
Chris@0 292 *
Chris@0 293 * @param Request $request A Request instance
Chris@0 294 * @param bool $catch whether to process exceptions
Chris@0 295 *
Chris@0 296 * @return Response A Response instance
Chris@0 297 *
Chris@0 298 * @throws \Exception
Chris@0 299 */
Chris@0 300 protected function lookup(Request $request, $catch = false)
Chris@0 301 {
Chris@0 302 // if allow_reload and no-cache Cache-Control, allow a cache reload
Chris@0 303 if ($this->options['allow_reload'] && $request->isNoCache()) {
Chris@0 304 $this->record($request, 'reload');
Chris@0 305
Chris@0 306 return $this->fetch($request, $catch);
Chris@0 307 }
Chris@0 308
Chris@0 309 try {
Chris@0 310 $entry = $this->store->lookup($request);
Chris@0 311 } catch (\Exception $e) {
Chris@0 312 $this->record($request, 'lookup-failed');
Chris@0 313
Chris@0 314 if ($this->options['debug']) {
Chris@0 315 throw $e;
Chris@0 316 }
Chris@0 317
Chris@0 318 return $this->pass($request, $catch);
Chris@0 319 }
Chris@0 320
Chris@0 321 if (null === $entry) {
Chris@0 322 $this->record($request, 'miss');
Chris@0 323
Chris@0 324 return $this->fetch($request, $catch);
Chris@0 325 }
Chris@0 326
Chris@0 327 if (!$this->isFreshEnough($request, $entry)) {
Chris@0 328 $this->record($request, 'stale');
Chris@0 329
Chris@0 330 return $this->validate($request, $entry, $catch);
Chris@0 331 }
Chris@0 332
Chris@0 333 $this->record($request, 'fresh');
Chris@0 334
Chris@0 335 $entry->headers->set('Age', $entry->getAge());
Chris@0 336
Chris@0 337 return $entry;
Chris@0 338 }
Chris@0 339
Chris@0 340 /**
Chris@0 341 * Validates that a cache entry is fresh.
Chris@0 342 *
Chris@0 343 * The original request is used as a template for a conditional
Chris@0 344 * GET request with the backend.
Chris@0 345 *
Chris@0 346 * @param Request $request A Request instance
Chris@0 347 * @param Response $entry A Response instance to validate
Chris@0 348 * @param bool $catch Whether to process exceptions
Chris@0 349 *
Chris@0 350 * @return Response A Response instance
Chris@0 351 */
Chris@0 352 protected function validate(Request $request, Response $entry, $catch = false)
Chris@0 353 {
Chris@0 354 $subRequest = clone $request;
Chris@0 355
Chris@0 356 // send no head requests because we want content
Chris@0 357 if ('HEAD' === $request->getMethod()) {
Chris@0 358 $subRequest->setMethod('GET');
Chris@0 359 }
Chris@0 360
Chris@0 361 // add our cached last-modified validator
Chris@0 362 $subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
Chris@0 363
Chris@0 364 // Add our cached etag validator to the environment.
Chris@0 365 // We keep the etags from the client to handle the case when the client
Chris@0 366 // has a different private valid entry which is not cached here.
Chris@0 367 $cachedEtags = $entry->getEtag() ? array($entry->getEtag()) : array();
Chris@0 368 $requestEtags = $request->getETags();
Chris@0 369 if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) {
Chris@0 370 $subRequest->headers->set('if_none_match', implode(', ', $etags));
Chris@0 371 }
Chris@0 372
Chris@0 373 $response = $this->forward($subRequest, $catch, $entry);
Chris@0 374
Chris@0 375 if (304 == $response->getStatusCode()) {
Chris@0 376 $this->record($request, 'valid');
Chris@0 377
Chris@0 378 // return the response and not the cache entry if the response is valid but not cached
Chris@0 379 $etag = $response->getEtag();
Chris@0 380 if ($etag && in_array($etag, $requestEtags) && !in_array($etag, $cachedEtags)) {
Chris@0 381 return $response;
Chris@0 382 }
Chris@0 383
Chris@0 384 $entry = clone $entry;
Chris@0 385 $entry->headers->remove('Date');
Chris@0 386
Chris@0 387 foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
Chris@0 388 if ($response->headers->has($name)) {
Chris@0 389 $entry->headers->set($name, $response->headers->get($name));
Chris@0 390 }
Chris@0 391 }
Chris@0 392
Chris@0 393 $response = $entry;
Chris@0 394 } else {
Chris@0 395 $this->record($request, 'invalid');
Chris@0 396 }
Chris@0 397
Chris@0 398 if ($response->isCacheable()) {
Chris@0 399 $this->store($request, $response);
Chris@0 400 }
Chris@0 401
Chris@0 402 return $response;
Chris@0 403 }
Chris@0 404
Chris@0 405 /**
Chris@0 406 * Forwards the Request to the backend and determines whether the response should be stored.
Chris@0 407 *
Chris@0 408 * This methods is triggered when the cache missed or a reload is required.
Chris@0 409 *
Chris@0 410 * @param Request $request A Request instance
Chris@0 411 * @param bool $catch whether to process exceptions
Chris@0 412 *
Chris@0 413 * @return Response A Response instance
Chris@0 414 */
Chris@0 415 protected function fetch(Request $request, $catch = false)
Chris@0 416 {
Chris@0 417 $subRequest = clone $request;
Chris@0 418
Chris@0 419 // send no head requests because we want content
Chris@0 420 if ('HEAD' === $request->getMethod()) {
Chris@0 421 $subRequest->setMethod('GET');
Chris@0 422 }
Chris@0 423
Chris@0 424 // avoid that the backend sends no content
Chris@0 425 $subRequest->headers->remove('if_modified_since');
Chris@0 426 $subRequest->headers->remove('if_none_match');
Chris@0 427
Chris@0 428 $response = $this->forward($subRequest, $catch);
Chris@0 429
Chris@0 430 if ($response->isCacheable()) {
Chris@0 431 $this->store($request, $response);
Chris@0 432 }
Chris@0 433
Chris@0 434 return $response;
Chris@0 435 }
Chris@0 436
Chris@0 437 /**
Chris@0 438 * Forwards the Request to the backend and returns the Response.
Chris@0 439 *
Chris@0 440 * @param Request $request A Request instance
Chris@0 441 * @param bool $catch Whether to catch exceptions or not
Chris@0 442 * @param Response $entry A Response instance (the stale entry if present, null otherwise)
Chris@0 443 *
Chris@0 444 * @return Response A Response instance
Chris@0 445 */
Chris@0 446 protected function forward(Request $request, $catch = false, Response $entry = null)
Chris@0 447 {
Chris@0 448 if ($this->surrogate) {
Chris@0 449 $this->surrogate->addSurrogateCapability($request);
Chris@0 450 }
Chris@0 451
Chris@0 452 // modify the X-Forwarded-For header if needed
Chris@0 453 $forwardedFor = $request->headers->get('X-Forwarded-For');
Chris@0 454 if ($forwardedFor) {
Chris@0 455 $request->headers->set('X-Forwarded-For', $forwardedFor.', '.$request->server->get('REMOTE_ADDR'));
Chris@0 456 } else {
Chris@0 457 $request->headers->set('X-Forwarded-For', $request->server->get('REMOTE_ADDR'));
Chris@0 458 }
Chris@0 459
Chris@0 460 // fix the client IP address by setting it to 127.0.0.1 as HttpCache
Chris@0 461 // is always called from the same process as the backend.
Chris@0 462 $request->server->set('REMOTE_ADDR', '127.0.0.1');
Chris@0 463
Chris@0 464 // make sure HttpCache is a trusted proxy
Chris@0 465 if (!in_array('127.0.0.1', $trustedProxies = Request::getTrustedProxies())) {
Chris@0 466 $trustedProxies[] = '127.0.0.1';
Chris@0 467 Request::setTrustedProxies($trustedProxies, method_exists('Request', 'getTrustedHeaderSet') ? Request::getTrustedHeaderSet() : -1);
Chris@0 468 }
Chris@0 469
Chris@0 470 // always a "master" request (as the real master request can be in cache)
Chris@0 471 $response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch);
Chris@0 472 // FIXME: we probably need to also catch exceptions if raw === true
Chris@0 473
Chris@0 474 // we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
Chris@0 475 if (null !== $entry && in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
Chris@0 476 if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
Chris@0 477 $age = $this->options['stale_if_error'];
Chris@0 478 }
Chris@0 479
Chris@0 480 if (abs($entry->getTtl()) < $age) {
Chris@0 481 $this->record($request, 'stale-if-error');
Chris@0 482
Chris@0 483 return $entry;
Chris@0 484 }
Chris@0 485 }
Chris@0 486
Chris@0 487 $this->processResponseBody($request, $response);
Chris@0 488
Chris@0 489 if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
Chris@0 490 $response->setPrivate();
Chris@0 491 } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) {
Chris@0 492 $response->setTtl($this->options['default_ttl']);
Chris@0 493 }
Chris@0 494
Chris@0 495 return $response;
Chris@0 496 }
Chris@0 497
Chris@0 498 /**
Chris@0 499 * Checks whether the cache entry is "fresh enough" to satisfy the Request.
Chris@0 500 *
Chris@0 501 * @param Request $request A Request instance
Chris@0 502 * @param Response $entry A Response instance
Chris@0 503 *
Chris@0 504 * @return bool true if the cache entry if fresh enough, false otherwise
Chris@0 505 */
Chris@0 506 protected function isFreshEnough(Request $request, Response $entry)
Chris@0 507 {
Chris@0 508 if (!$entry->isFresh()) {
Chris@0 509 return $this->lock($request, $entry);
Chris@0 510 }
Chris@0 511
Chris@0 512 if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
Chris@0 513 return $maxAge > 0 && $maxAge >= $entry->getAge();
Chris@0 514 }
Chris@0 515
Chris@0 516 return true;
Chris@0 517 }
Chris@0 518
Chris@0 519 /**
Chris@0 520 * Locks a Request during the call to the backend.
Chris@0 521 *
Chris@0 522 * @param Request $request A Request instance
Chris@0 523 * @param Response $entry A Response instance
Chris@0 524 *
Chris@0 525 * @return bool true if the cache entry can be returned even if it is staled, false otherwise
Chris@0 526 */
Chris@0 527 protected function lock(Request $request, Response $entry)
Chris@0 528 {
Chris@0 529 // try to acquire a lock to call the backend
Chris@0 530 $lock = $this->store->lock($request);
Chris@0 531
Chris@0 532 // there is already another process calling the backend
Chris@0 533 if (true !== $lock) {
Chris@0 534 // check if we can serve the stale entry
Chris@0 535 if (null === $age = $entry->headers->getCacheControlDirective('stale-while-revalidate')) {
Chris@0 536 $age = $this->options['stale_while_revalidate'];
Chris@0 537 }
Chris@0 538
Chris@0 539 if (abs($entry->getTtl()) < $age) {
Chris@0 540 $this->record($request, 'stale-while-revalidate');
Chris@0 541
Chris@0 542 // server the stale response while there is a revalidation
Chris@0 543 return true;
Chris@0 544 }
Chris@0 545
Chris@0 546 // wait for the lock to be released
Chris@0 547 $wait = 0;
Chris@0 548 while ($this->store->isLocked($request) && $wait < 5000000) {
Chris@0 549 usleep(50000);
Chris@0 550 $wait += 50000;
Chris@0 551 }
Chris@0 552
Chris@0 553 if ($wait < 5000000) {
Chris@0 554 // replace the current entry with the fresh one
Chris@0 555 $new = $this->lookup($request);
Chris@0 556 $entry->headers = $new->headers;
Chris@0 557 $entry->setContent($new->getContent());
Chris@0 558 $entry->setStatusCode($new->getStatusCode());
Chris@0 559 $entry->setProtocolVersion($new->getProtocolVersion());
Chris@0 560 foreach ($new->headers->getCookies() as $cookie) {
Chris@0 561 $entry->headers->setCookie($cookie);
Chris@0 562 }
Chris@0 563 } else {
Chris@0 564 // backend is slow as hell, send a 503 response (to avoid the dog pile effect)
Chris@0 565 $entry->setStatusCode(503);
Chris@0 566 $entry->setContent('503 Service Unavailable');
Chris@0 567 $entry->headers->set('Retry-After', 10);
Chris@0 568 }
Chris@0 569
Chris@0 570 return true;
Chris@0 571 }
Chris@0 572
Chris@0 573 // we have the lock, call the backend
Chris@0 574 return false;
Chris@0 575 }
Chris@0 576
Chris@0 577 /**
Chris@0 578 * Writes the Response to the cache.
Chris@0 579 *
Chris@0 580 * @param Request $request A Request instance
Chris@0 581 * @param Response $response A Response instance
Chris@0 582 *
Chris@0 583 * @throws \Exception
Chris@0 584 */
Chris@0 585 protected function store(Request $request, Response $response)
Chris@0 586 {
Chris@0 587 if (!$response->headers->has('Date')) {
Chris@0 588 $response->setDate(\DateTime::createFromFormat('U', time()));
Chris@0 589 }
Chris@0 590 try {
Chris@0 591 $this->store->write($request, $response);
Chris@0 592
Chris@0 593 $this->record($request, 'store');
Chris@0 594
Chris@0 595 $response->headers->set('Age', $response->getAge());
Chris@0 596 } catch (\Exception $e) {
Chris@0 597 $this->record($request, 'store-failed');
Chris@0 598
Chris@0 599 if ($this->options['debug']) {
Chris@0 600 throw $e;
Chris@0 601 }
Chris@0 602 }
Chris@0 603
Chris@0 604 // now that the response is cached, release the lock
Chris@0 605 $this->store->unlock($request);
Chris@0 606 }
Chris@0 607
Chris@0 608 /**
Chris@0 609 * Restores the Response body.
Chris@0 610 *
Chris@0 611 * @param Request $request A Request instance
Chris@0 612 * @param Response $response A Response instance
Chris@0 613 */
Chris@0 614 private function restoreResponseBody(Request $request, Response $response)
Chris@0 615 {
Chris@0 616 if ($request->isMethod('HEAD') || 304 === $response->getStatusCode()) {
Chris@0 617 $response->setContent(null);
Chris@0 618 $response->headers->remove('X-Body-Eval');
Chris@0 619 $response->headers->remove('X-Body-File');
Chris@0 620
Chris@0 621 return;
Chris@0 622 }
Chris@0 623
Chris@0 624 if ($response->headers->has('X-Body-Eval')) {
Chris@0 625 ob_start();
Chris@0 626
Chris@0 627 if ($response->headers->has('X-Body-File')) {
Chris@0 628 include $response->headers->get('X-Body-File');
Chris@0 629 } else {
Chris@0 630 eval('; ?>'.$response->getContent().'<?php ;');
Chris@0 631 }
Chris@0 632
Chris@0 633 $response->setContent(ob_get_clean());
Chris@0 634 $response->headers->remove('X-Body-Eval');
Chris@0 635 if (!$response->headers->has('Transfer-Encoding')) {
Chris@0 636 $response->headers->set('Content-Length', strlen($response->getContent()));
Chris@0 637 }
Chris@0 638 } elseif ($response->headers->has('X-Body-File')) {
Chris@0 639 $response->setContent(file_get_contents($response->headers->get('X-Body-File')));
Chris@0 640 } else {
Chris@0 641 return;
Chris@0 642 }
Chris@0 643
Chris@0 644 $response->headers->remove('X-Body-File');
Chris@0 645 }
Chris@0 646
Chris@0 647 protected function processResponseBody(Request $request, Response $response)
Chris@0 648 {
Chris@0 649 if (null !== $this->surrogate && $this->surrogate->needsParsing($response)) {
Chris@0 650 $this->surrogate->process($request, $response);
Chris@0 651 }
Chris@0 652 }
Chris@0 653
Chris@0 654 /**
Chris@0 655 * Checks if the Request includes authorization or other sensitive information
Chris@0 656 * that should cause the Response to be considered private by default.
Chris@0 657 *
Chris@0 658 * @param Request $request A Request instance
Chris@0 659 *
Chris@0 660 * @return bool true if the Request is private, false otherwise
Chris@0 661 */
Chris@0 662 private function isPrivateRequest(Request $request)
Chris@0 663 {
Chris@0 664 foreach ($this->options['private_headers'] as $key) {
Chris@0 665 $key = strtolower(str_replace('HTTP_', '', $key));
Chris@0 666
Chris@0 667 if ('cookie' === $key) {
Chris@0 668 if (count($request->cookies->all())) {
Chris@0 669 return true;
Chris@0 670 }
Chris@0 671 } elseif ($request->headers->has($key)) {
Chris@0 672 return true;
Chris@0 673 }
Chris@0 674 }
Chris@0 675
Chris@0 676 return false;
Chris@0 677 }
Chris@0 678
Chris@0 679 /**
Chris@0 680 * Records that an event took place.
Chris@0 681 *
Chris@0 682 * @param Request $request A Request instance
Chris@0 683 * @param string $event The event name
Chris@0 684 */
Chris@0 685 private function record(Request $request, $event)
Chris@0 686 {
Chris@0 687 $path = $request->getPathInfo();
Chris@0 688 if ($qs = $request->getQueryString()) {
Chris@0 689 $path .= '?'.$qs;
Chris@0 690 }
Chris@0 691 $this->traces[$request->getMethod().' '.$path][] = $event;
Chris@0 692 }
Chris@0 693 }