annotate vendor/symfony/http-kernel/HttpCache/HttpCache.php @ 16:c2387f117808

Routine composer update
author Chris Cannam
date Tue, 10 Jul 2018 15:07:59 +0100
parents 1fec387a4317
children 129ea1e6d783
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 public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = array())
Chris@0 74 {
Chris@0 75 $this->store = $store;
Chris@0 76 $this->kernel = $kernel;
Chris@0 77 $this->surrogate = $surrogate;
Chris@0 78
Chris@0 79 // needed in case there is a fatal error because the backend is too slow to respond
Chris@0 80 register_shutdown_function(array($this->store, 'cleanup'));
Chris@0 81
Chris@0 82 $this->options = array_merge(array(
Chris@0 83 'debug' => false,
Chris@0 84 'default_ttl' => 0,
Chris@0 85 'private_headers' => array('Authorization', 'Cookie'),
Chris@0 86 'allow_reload' => false,
Chris@0 87 'allow_revalidate' => false,
Chris@0 88 'stale_while_revalidate' => 2,
Chris@0 89 'stale_if_error' => 60,
Chris@0 90 ), $options);
Chris@0 91 }
Chris@0 92
Chris@0 93 /**
Chris@0 94 * Gets the current store.
Chris@0 95 *
Chris@0 96 * @return StoreInterface $store A StoreInterface instance
Chris@0 97 */
Chris@0 98 public function getStore()
Chris@0 99 {
Chris@0 100 return $this->store;
Chris@0 101 }
Chris@0 102
Chris@0 103 /**
Chris@0 104 * Returns an array of events that took place during processing of the last request.
Chris@0 105 *
Chris@0 106 * @return array An array of events
Chris@0 107 */
Chris@0 108 public function getTraces()
Chris@0 109 {
Chris@0 110 return $this->traces;
Chris@0 111 }
Chris@0 112
Chris@0 113 /**
Chris@0 114 * Returns a log message for the events of the last request processing.
Chris@0 115 *
Chris@0 116 * @return string A log message
Chris@0 117 */
Chris@0 118 public function getLog()
Chris@0 119 {
Chris@0 120 $log = array();
Chris@0 121 foreach ($this->traces as $request => $traces) {
Chris@0 122 $log[] = sprintf('%s: %s', $request, implode(', ', $traces));
Chris@0 123 }
Chris@0 124
Chris@0 125 return implode('; ', $log);
Chris@0 126 }
Chris@0 127
Chris@0 128 /**
Chris@0 129 * Gets the Request instance associated with the master request.
Chris@0 130 *
Chris@0 131 * @return Request A Request instance
Chris@0 132 */
Chris@0 133 public function getRequest()
Chris@0 134 {
Chris@0 135 return $this->request;
Chris@0 136 }
Chris@0 137
Chris@0 138 /**
Chris@0 139 * Gets the Kernel instance.
Chris@0 140 *
Chris@0 141 * @return HttpKernelInterface An HttpKernelInterface instance
Chris@0 142 */
Chris@0 143 public function getKernel()
Chris@0 144 {
Chris@0 145 return $this->kernel;
Chris@0 146 }
Chris@0 147
Chris@0 148 /**
Chris@0 149 * Gets the Surrogate instance.
Chris@0 150 *
Chris@0 151 * @return SurrogateInterface A Surrogate instance
Chris@0 152 *
Chris@0 153 * @throws \LogicException
Chris@0 154 */
Chris@0 155 public function getSurrogate()
Chris@0 156 {
Chris@0 157 return $this->surrogate;
Chris@0 158 }
Chris@0 159
Chris@0 160 /**
Chris@0 161 * {@inheritdoc}
Chris@0 162 */
Chris@0 163 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
Chris@0 164 {
Chris@0 165 // FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism
Chris@0 166 if (HttpKernelInterface::MASTER_REQUEST === $type) {
Chris@0 167 $this->traces = array();
Chris@16 168 // Keep a clone of the original request for surrogates so they can access it.
Chris@16 169 // We must clone here to get a separate instance because the application will modify the request during
Chris@16 170 // the application flow (we know it always does because we do ourselves by setting REMOTE_ADDR to 127.0.0.1
Chris@16 171 // and adding the X-Forwarded-For header, see HttpCache::forward()).
Chris@16 172 $this->request = clone $request;
Chris@0 173 if (null !== $this->surrogate) {
Chris@0 174 $this->surrogateCacheStrategy = $this->surrogate->createCacheStrategy();
Chris@0 175 }
Chris@0 176 }
Chris@0 177
Chris@14 178 $this->traces[$this->getTraceKey($request)] = array();
Chris@0 179
Chris@0 180 if (!$request->isMethodSafe(false)) {
Chris@0 181 $response = $this->invalidate($request, $catch);
Chris@0 182 } elseif ($request->headers->has('expect') || !$request->isMethodCacheable()) {
Chris@0 183 $response = $this->pass($request, $catch);
Chris@14 184 } elseif ($this->options['allow_reload'] && $request->isNoCache()) {
Chris@14 185 /*
Chris@14 186 If allow_reload is configured and the client requests "Cache-Control: no-cache",
Chris@14 187 reload the cache by fetching a fresh response and caching it (if possible).
Chris@14 188 */
Chris@14 189 $this->record($request, 'reload');
Chris@14 190 $response = $this->fetch($request, $catch);
Chris@0 191 } else {
Chris@0 192 $response = $this->lookup($request, $catch);
Chris@0 193 }
Chris@0 194
Chris@0 195 $this->restoreResponseBody($request, $response);
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@14 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 try {
Chris@0 303 $entry = $this->store->lookup($request);
Chris@0 304 } catch (\Exception $e) {
Chris@0 305 $this->record($request, 'lookup-failed');
Chris@0 306
Chris@0 307 if ($this->options['debug']) {
Chris@0 308 throw $e;
Chris@0 309 }
Chris@0 310
Chris@0 311 return $this->pass($request, $catch);
Chris@0 312 }
Chris@0 313
Chris@0 314 if (null === $entry) {
Chris@0 315 $this->record($request, 'miss');
Chris@0 316
Chris@0 317 return $this->fetch($request, $catch);
Chris@0 318 }
Chris@0 319
Chris@0 320 if (!$this->isFreshEnough($request, $entry)) {
Chris@0 321 $this->record($request, 'stale');
Chris@0 322
Chris@0 323 return $this->validate($request, $entry, $catch);
Chris@0 324 }
Chris@0 325
Chris@0 326 $this->record($request, 'fresh');
Chris@0 327
Chris@0 328 $entry->headers->set('Age', $entry->getAge());
Chris@0 329
Chris@0 330 return $entry;
Chris@0 331 }
Chris@0 332
Chris@0 333 /**
Chris@0 334 * Validates that a cache entry is fresh.
Chris@0 335 *
Chris@0 336 * The original request is used as a template for a conditional
Chris@0 337 * GET request with the backend.
Chris@0 338 *
Chris@0 339 * @param Request $request A Request instance
Chris@0 340 * @param Response $entry A Response instance to validate
Chris@0 341 * @param bool $catch Whether to process exceptions
Chris@0 342 *
Chris@0 343 * @return Response A Response instance
Chris@0 344 */
Chris@0 345 protected function validate(Request $request, Response $entry, $catch = false)
Chris@0 346 {
Chris@0 347 $subRequest = clone $request;
Chris@0 348
Chris@0 349 // send no head requests because we want content
Chris@0 350 if ('HEAD' === $request->getMethod()) {
Chris@0 351 $subRequest->setMethod('GET');
Chris@0 352 }
Chris@0 353
Chris@0 354 // add our cached last-modified validator
Chris@0 355 $subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
Chris@0 356
Chris@0 357 // Add our cached etag validator to the environment.
Chris@0 358 // We keep the etags from the client to handle the case when the client
Chris@0 359 // has a different private valid entry which is not cached here.
Chris@0 360 $cachedEtags = $entry->getEtag() ? array($entry->getEtag()) : array();
Chris@0 361 $requestEtags = $request->getETags();
Chris@0 362 if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) {
Chris@0 363 $subRequest->headers->set('if_none_match', implode(', ', $etags));
Chris@0 364 }
Chris@0 365
Chris@0 366 $response = $this->forward($subRequest, $catch, $entry);
Chris@0 367
Chris@0 368 if (304 == $response->getStatusCode()) {
Chris@0 369 $this->record($request, 'valid');
Chris@0 370
Chris@0 371 // return the response and not the cache entry if the response is valid but not cached
Chris@0 372 $etag = $response->getEtag();
Chris@0 373 if ($etag && in_array($etag, $requestEtags) && !in_array($etag, $cachedEtags)) {
Chris@0 374 return $response;
Chris@0 375 }
Chris@0 376
Chris@0 377 $entry = clone $entry;
Chris@0 378 $entry->headers->remove('Date');
Chris@0 379
Chris@0 380 foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
Chris@0 381 if ($response->headers->has($name)) {
Chris@0 382 $entry->headers->set($name, $response->headers->get($name));
Chris@0 383 }
Chris@0 384 }
Chris@0 385
Chris@0 386 $response = $entry;
Chris@0 387 } else {
Chris@0 388 $this->record($request, 'invalid');
Chris@0 389 }
Chris@0 390
Chris@0 391 if ($response->isCacheable()) {
Chris@0 392 $this->store($request, $response);
Chris@0 393 }
Chris@0 394
Chris@0 395 return $response;
Chris@0 396 }
Chris@0 397
Chris@0 398 /**
Chris@14 399 * Unconditionally fetches a fresh response from the backend and
Chris@14 400 * stores it in the cache if is cacheable.
Chris@0 401 *
Chris@0 402 * @param Request $request A Request instance
Chris@14 403 * @param bool $catch Whether to process exceptions
Chris@0 404 *
Chris@0 405 * @return Response A Response instance
Chris@0 406 */
Chris@0 407 protected function fetch(Request $request, $catch = false)
Chris@0 408 {
Chris@0 409 $subRequest = clone $request;
Chris@0 410
Chris@0 411 // send no head requests because we want content
Chris@0 412 if ('HEAD' === $request->getMethod()) {
Chris@0 413 $subRequest->setMethod('GET');
Chris@0 414 }
Chris@0 415
Chris@0 416 // avoid that the backend sends no content
Chris@0 417 $subRequest->headers->remove('if_modified_since');
Chris@0 418 $subRequest->headers->remove('if_none_match');
Chris@0 419
Chris@0 420 $response = $this->forward($subRequest, $catch);
Chris@0 421
Chris@0 422 if ($response->isCacheable()) {
Chris@0 423 $this->store($request, $response);
Chris@0 424 }
Chris@0 425
Chris@0 426 return $response;
Chris@0 427 }
Chris@0 428
Chris@0 429 /**
Chris@0 430 * Forwards the Request to the backend and returns the Response.
Chris@0 431 *
Chris@14 432 * All backend requests (cache passes, fetches, cache validations)
Chris@14 433 * run through this method.
Chris@14 434 *
Chris@0 435 * @param Request $request A Request instance
Chris@0 436 * @param bool $catch Whether to catch exceptions or not
Chris@0 437 * @param Response $entry A Response instance (the stale entry if present, null otherwise)
Chris@0 438 *
Chris@0 439 * @return Response A Response instance
Chris@0 440 */
Chris@0 441 protected function forward(Request $request, $catch = false, Response $entry = null)
Chris@0 442 {
Chris@0 443 if ($this->surrogate) {
Chris@0 444 $this->surrogate->addSurrogateCapability($request);
Chris@0 445 }
Chris@0 446
Chris@0 447 // modify the X-Forwarded-For header if needed
Chris@0 448 $forwardedFor = $request->headers->get('X-Forwarded-For');
Chris@0 449 if ($forwardedFor) {
Chris@0 450 $request->headers->set('X-Forwarded-For', $forwardedFor.', '.$request->server->get('REMOTE_ADDR'));
Chris@0 451 } else {
Chris@0 452 $request->headers->set('X-Forwarded-For', $request->server->get('REMOTE_ADDR'));
Chris@0 453 }
Chris@0 454
Chris@0 455 // fix the client IP address by setting it to 127.0.0.1 as HttpCache
Chris@0 456 // is always called from the same process as the backend.
Chris@0 457 $request->server->set('REMOTE_ADDR', '127.0.0.1');
Chris@0 458
Chris@0 459 // make sure HttpCache is a trusted proxy
Chris@0 460 if (!in_array('127.0.0.1', $trustedProxies = Request::getTrustedProxies())) {
Chris@0 461 $trustedProxies[] = '127.0.0.1';
Chris@14 462 Request::setTrustedProxies($trustedProxies, Request::HEADER_X_FORWARDED_ALL);
Chris@0 463 }
Chris@0 464
Chris@0 465 // always a "master" request (as the real master request can be in cache)
Chris@0 466 $response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch);
Chris@0 467 // FIXME: we probably need to also catch exceptions if raw === true
Chris@0 468
Chris@0 469 // we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
Chris@0 470 if (null !== $entry && in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
Chris@0 471 if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
Chris@0 472 $age = $this->options['stale_if_error'];
Chris@0 473 }
Chris@0 474
Chris@0 475 if (abs($entry->getTtl()) < $age) {
Chris@0 476 $this->record($request, 'stale-if-error');
Chris@0 477
Chris@0 478 return $entry;
Chris@0 479 }
Chris@0 480 }
Chris@0 481
Chris@14 482 /*
Chris@14 483 RFC 7231 Sect. 7.1.1.2 says that a server that does not have a reasonably accurate
Chris@14 484 clock MUST NOT send a "Date" header, although it MUST send one in most other cases
Chris@14 485 except for 1xx or 5xx responses where it MAY do so.
Chris@14 486
Chris@14 487 Anyway, a client that received a message without a "Date" header MUST add it.
Chris@14 488 */
Chris@14 489 if (!$response->headers->has('Date')) {
Chris@14 490 $response->setDate(\DateTime::createFromFormat('U', time()));
Chris@14 491 }
Chris@14 492
Chris@0 493 $this->processResponseBody($request, $response);
Chris@0 494
Chris@0 495 if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
Chris@0 496 $response->setPrivate();
Chris@0 497 } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) {
Chris@0 498 $response->setTtl($this->options['default_ttl']);
Chris@0 499 }
Chris@0 500
Chris@0 501 return $response;
Chris@0 502 }
Chris@0 503
Chris@0 504 /**
Chris@0 505 * Checks whether the cache entry is "fresh enough" to satisfy the Request.
Chris@0 506 *
Chris@0 507 * @return bool true if the cache entry if fresh enough, false otherwise
Chris@0 508 */
Chris@0 509 protected function isFreshEnough(Request $request, Response $entry)
Chris@0 510 {
Chris@0 511 if (!$entry->isFresh()) {
Chris@0 512 return $this->lock($request, $entry);
Chris@0 513 }
Chris@0 514
Chris@0 515 if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
Chris@0 516 return $maxAge > 0 && $maxAge >= $entry->getAge();
Chris@0 517 }
Chris@0 518
Chris@0 519 return true;
Chris@0 520 }
Chris@0 521
Chris@0 522 /**
Chris@0 523 * Locks a Request during the call to the backend.
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@14 532 if (true === $lock) {
Chris@14 533 // we have the lock, call the backend
Chris@14 534 return false;
Chris@14 535 }
Chris@14 536
Chris@0 537 // there is already another process calling the backend
Chris@0 538
Chris@14 539 // May we serve a stale response?
Chris@14 540 if ($this->mayServeStaleWhileRevalidate($entry)) {
Chris@14 541 $this->record($request, 'stale-while-revalidate');
Chris@0 542
Chris@0 543 return true;
Chris@0 544 }
Chris@0 545
Chris@14 546 // wait for the lock to be released
Chris@14 547 if ($this->waitForLock($request)) {
Chris@14 548 // replace the current entry with the fresh one
Chris@14 549 $new = $this->lookup($request);
Chris@14 550 $entry->headers = $new->headers;
Chris@14 551 $entry->setContent($new->getContent());
Chris@14 552 $entry->setStatusCode($new->getStatusCode());
Chris@14 553 $entry->setProtocolVersion($new->getProtocolVersion());
Chris@14 554 foreach ($new->headers->getCookies() as $cookie) {
Chris@14 555 $entry->headers->setCookie($cookie);
Chris@14 556 }
Chris@14 557 } else {
Chris@14 558 // backend is slow as hell, send a 503 response (to avoid the dog pile effect)
Chris@14 559 $entry->setStatusCode(503);
Chris@14 560 $entry->setContent('503 Service Unavailable');
Chris@14 561 $entry->headers->set('Retry-After', 10);
Chris@14 562 }
Chris@14 563
Chris@14 564 return true;
Chris@0 565 }
Chris@0 566
Chris@0 567 /**
Chris@0 568 * Writes the Response to the cache.
Chris@0 569 *
Chris@0 570 * @throws \Exception
Chris@0 571 */
Chris@0 572 protected function store(Request $request, Response $response)
Chris@0 573 {
Chris@0 574 try {
Chris@0 575 $this->store->write($request, $response);
Chris@0 576
Chris@0 577 $this->record($request, 'store');
Chris@0 578
Chris@0 579 $response->headers->set('Age', $response->getAge());
Chris@0 580 } catch (\Exception $e) {
Chris@0 581 $this->record($request, 'store-failed');
Chris@0 582
Chris@0 583 if ($this->options['debug']) {
Chris@0 584 throw $e;
Chris@0 585 }
Chris@0 586 }
Chris@0 587
Chris@0 588 // now that the response is cached, release the lock
Chris@0 589 $this->store->unlock($request);
Chris@0 590 }
Chris@0 591
Chris@0 592 /**
Chris@0 593 * Restores the Response body.
Chris@0 594 */
Chris@0 595 private function restoreResponseBody(Request $request, Response $response)
Chris@0 596 {
Chris@0 597 if ($response->headers->has('X-Body-Eval')) {
Chris@0 598 ob_start();
Chris@0 599
Chris@0 600 if ($response->headers->has('X-Body-File')) {
Chris@0 601 include $response->headers->get('X-Body-File');
Chris@0 602 } else {
Chris@0 603 eval('; ?>'.$response->getContent().'<?php ;');
Chris@0 604 }
Chris@0 605
Chris@0 606 $response->setContent(ob_get_clean());
Chris@0 607 $response->headers->remove('X-Body-Eval');
Chris@0 608 if (!$response->headers->has('Transfer-Encoding')) {
Chris@0 609 $response->headers->set('Content-Length', strlen($response->getContent()));
Chris@0 610 }
Chris@0 611 } elseif ($response->headers->has('X-Body-File')) {
Chris@14 612 // Response does not include possibly dynamic content (ESI, SSI), so we need
Chris@14 613 // not handle the content for HEAD requests
Chris@14 614 if (!$request->isMethod('HEAD')) {
Chris@14 615 $response->setContent(file_get_contents($response->headers->get('X-Body-File')));
Chris@14 616 }
Chris@0 617 } else {
Chris@0 618 return;
Chris@0 619 }
Chris@0 620
Chris@0 621 $response->headers->remove('X-Body-File');
Chris@0 622 }
Chris@0 623
Chris@0 624 protected function processResponseBody(Request $request, Response $response)
Chris@0 625 {
Chris@0 626 if (null !== $this->surrogate && $this->surrogate->needsParsing($response)) {
Chris@0 627 $this->surrogate->process($request, $response);
Chris@0 628 }
Chris@0 629 }
Chris@0 630
Chris@0 631 /**
Chris@0 632 * Checks if the Request includes authorization or other sensitive information
Chris@0 633 * that should cause the Response to be considered private by default.
Chris@0 634 *
Chris@0 635 * @return bool true if the Request is private, false otherwise
Chris@0 636 */
Chris@0 637 private function isPrivateRequest(Request $request)
Chris@0 638 {
Chris@0 639 foreach ($this->options['private_headers'] as $key) {
Chris@0 640 $key = strtolower(str_replace('HTTP_', '', $key));
Chris@0 641
Chris@0 642 if ('cookie' === $key) {
Chris@0 643 if (count($request->cookies->all())) {
Chris@0 644 return true;
Chris@0 645 }
Chris@0 646 } elseif ($request->headers->has($key)) {
Chris@0 647 return true;
Chris@0 648 }
Chris@0 649 }
Chris@0 650
Chris@0 651 return false;
Chris@0 652 }
Chris@0 653
Chris@0 654 /**
Chris@0 655 * Records that an event took place.
Chris@0 656 *
Chris@0 657 * @param Request $request A Request instance
Chris@0 658 * @param string $event The event name
Chris@0 659 */
Chris@0 660 private function record(Request $request, $event)
Chris@0 661 {
Chris@14 662 $this->traces[$this->getTraceKey($request)][] = $event;
Chris@14 663 }
Chris@14 664
Chris@14 665 /**
Chris@14 666 * Calculates the key we use in the "trace" array for a given request.
Chris@14 667 *
Chris@14 668 * @param Request $request
Chris@14 669 *
Chris@14 670 * @return string
Chris@14 671 */
Chris@14 672 private function getTraceKey(Request $request)
Chris@14 673 {
Chris@0 674 $path = $request->getPathInfo();
Chris@0 675 if ($qs = $request->getQueryString()) {
Chris@0 676 $path .= '?'.$qs;
Chris@0 677 }
Chris@14 678
Chris@14 679 return $request->getMethod().' '.$path;
Chris@14 680 }
Chris@14 681
Chris@14 682 /**
Chris@14 683 * Checks whether the given (cached) response may be served as "stale" when a revalidation
Chris@14 684 * is currently in progress.
Chris@14 685 *
Chris@14 686 * @param Response $entry
Chris@14 687 *
Chris@14 688 * @return bool true when the stale response may be served, false otherwise
Chris@14 689 */
Chris@14 690 private function mayServeStaleWhileRevalidate(Response $entry)
Chris@14 691 {
Chris@14 692 $timeout = $entry->headers->getCacheControlDirective('stale-while-revalidate');
Chris@14 693
Chris@14 694 if (null === $timeout) {
Chris@14 695 $timeout = $this->options['stale_while_revalidate'];
Chris@14 696 }
Chris@14 697
Chris@14 698 return abs($entry->getTtl()) < $timeout;
Chris@14 699 }
Chris@14 700
Chris@14 701 /**
Chris@14 702 * Waits for the store to release a locked entry.
Chris@14 703 *
Chris@14 704 * @param Request $request The request to wait for
Chris@14 705 *
Chris@14 706 * @return bool true if the lock was released before the internal timeout was hit; false if the wait timeout was exceeded
Chris@14 707 */
Chris@14 708 private function waitForLock(Request $request)
Chris@14 709 {
Chris@14 710 $wait = 0;
Chris@14 711 while ($this->store->isLocked($request) && $wait < 100) {
Chris@14 712 usleep(50000);
Chris@14 713 ++$wait;
Chris@14 714 }
Chris@14 715
Chris@14 716 return $wait < 100;
Chris@0 717 }
Chris@0 718 }