HttpCache.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  6. *
  7. * This code is partially based on the Rack-Cache library by Ryan Tomayko,
  8. * which is released under the MIT license.
  9. * (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801)
  10. *
  11. * For the full copyright and license information, please view the LICENSE
  12. * file that was distributed with this source code.
  13. */
  14. namespace Symfony\Component\HttpKernel\HttpCache;
  15. use Symfony\Component\HttpKernel\HttpKernelInterface;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. /**
  19. * Cache provides HTTP caching.
  20. *
  21. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  22. */
  23. class HttpCache implements HttpKernelInterface
  24. {
  25. protected $kernel;
  26. protected $traces;
  27. protected $store;
  28. protected $request;
  29. protected $esi;
  30. protected $esiTtls;
  31. /**
  32. * Constructor.
  33. *
  34. * The available options are:
  35. *
  36. * * debug: If true, the traces are added as a HTTP header to ease debugging
  37. *
  38. * * default_ttl The number of seconds that a cache entry should be considered
  39. * fresh when no explicit freshness information is provided in
  40. * a response. Explicit Cache-Control or Expires headers
  41. * override this value. (default: 0)
  42. *
  43. * * private_headers Set of request headers that trigger "private" cache-control behavior
  44. * on responses that don't explicitly state whether the response is
  45. * public or private via a Cache-Control directive. (default: Authorization and Cookie)
  46. *
  47. * * allow_reload Specifies whether the client can force a cache reload by including a
  48. * Cache-Control "no-cache" directive in the request. Set it to ``true``
  49. * for compliance with RFC 2616. (default: false)
  50. *
  51. * * allow_revalidate Specifies whether the client can force a cache revalidate by including
  52. * a Cache-Control "max-age=0" directive in the request. Set it to ``true``
  53. * for compliance with RFC 2616. (default: false)
  54. *
  55. * * stale_while_revalidate Specifies the default number of seconds (the granularity is the second as the
  56. * Response TTL precision is a second) during which the cache can immediately return
  57. * a stale response while it revalidates it in the background (default: 2).
  58. * This setting is overridden by the stale-while-revalidate HTTP Cache-Control
  59. * extension (see RFC 5861).
  60. *
  61. * * stale_if_error Specifies the default number of seconds (the granularity is the second) during which
  62. * the cache can serve a stale response when an error is encountered (default: 60).
  63. * This setting is overridden by the stale-if-error HTTP Cache-Control extension
  64. * (see RFC 5861).
  65. *
  66. * @param HttpKernelInterface $kernel An HttpKernelInterface instance
  67. * @param StoreInterface $store A Store instance
  68. * @param Esi $esi An Esi instance
  69. * @param array $options An array of options
  70. */
  71. public function __construct(HttpKernelInterface $kernel, StoreInterface $store, Esi $esi = null, array $options = array())
  72. {
  73. $this->store = $store;
  74. $this->kernel = $kernel;
  75. // needed in case there is a fatal error because the backend is too slow to respond
  76. register_shutdown_function(array($this->store, 'cleanup'));
  77. $this->options = array_merge(array(
  78. 'debug' => false,
  79. 'default_ttl' => 0,
  80. 'private_headers' => array('Authorization', 'Cookie'),
  81. 'allow_reload' => false,
  82. 'allow_revalidate' => false,
  83. 'stale_while_revalidate' => 2,
  84. 'stale_if_error' => 60,
  85. ), $options);
  86. $this->esi = $esi;
  87. }
  88. /**
  89. * Returns an array of events that took place during processing of the last request.
  90. *
  91. * @return array An array of events
  92. */
  93. public function getTraces()
  94. {
  95. return $this->traces;
  96. }
  97. /**
  98. * Returns a log message for the events of the last request processing.
  99. *
  100. * @return string A log message
  101. */
  102. public function getLog()
  103. {
  104. $log = array();
  105. foreach ($this->traces as $request => $traces) {
  106. $log[] = sprintf('%s: %s', $request, implode(', ', $traces));
  107. }
  108. return implode('; ', $log);
  109. }
  110. /**
  111. * Gets the Request instance associated with the master request.
  112. *
  113. * @return Symfony\Component\HttpFoundation\Request A Request instance
  114. */
  115. public function getRequest()
  116. {
  117. return $this->request;
  118. }
  119. /**
  120. * {@inheritdoc}
  121. */
  122. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  123. {
  124. // FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism
  125. if (HttpKernelInterface::MASTER_REQUEST === $type) {
  126. $this->traces = array();
  127. $this->request = $request;
  128. $this->esiTtls = array();
  129. }
  130. $path = $request->getPathInfo();
  131. if ($qs = $request->getQueryString()) {
  132. $path .= '?'.$qs;
  133. }
  134. $this->traces[$request->getMethod().' '.$path] = array();
  135. if (!$request->isMethodSafe($request)) {
  136. $response = $this->invalidate($request, $catch);
  137. } elseif ($request->headers->has('expect')) {
  138. $response = $this->pass($request, $catch);
  139. } else {
  140. $response = $this->lookup($request, $catch);
  141. }
  142. $response->isNotModified($request);
  143. $this->restoreResponseBody($request, $response);
  144. if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) {
  145. $response->headers->set('X-Symfony-Cache', $this->getLog());
  146. }
  147. if (null !== $this->esi) {
  148. $this->addEsiTtl($response);
  149. if ($request === $this->request) {
  150. $this->updateResponseCacheControl($response);
  151. }
  152. }
  153. return $response;
  154. }
  155. /**
  156. * Stores the response's TTL locally.
  157. *
  158. * @param Response $response
  159. */
  160. protected function addEsiTtl(Response $response)
  161. {
  162. $this->esiTtls[] = $response->isValidateable() ? 0 : $response->getTtl();
  163. }
  164. /**
  165. * Changes the master response TTL to the smallest TTL received or force validation if
  166. * one of the ESI has validation cache strategy.
  167. *
  168. * @param Response $response
  169. */
  170. protected function updateResponseCacheControl(Response $response)
  171. {
  172. $ttl = min($this->esiTtls);
  173. if (0 === $ttl) {
  174. $response->headers->set('Cache-Control', 'no-cache, must-revalidate');
  175. } else {
  176. $response->setSharedMaxAge($ttl);
  177. }
  178. }
  179. /**
  180. * Forwards the Request to the backend without storing the Response in the cache.
  181. *
  182. * @param Request $request A Request instance
  183. * @param Boolean $catch whether to process exceptions
  184. *
  185. * @return Response A Response instance
  186. */
  187. protected function pass(Request $request, $catch = false)
  188. {
  189. $this->record($request, 'pass');
  190. return $this->forward($request, $catch);
  191. }
  192. /**
  193. * Invalidates non-safe methods (like POST, PUT, and DELETE).
  194. *
  195. * @param Request $request A Request instance
  196. * @param Boolean $catch whether to process exceptions
  197. *
  198. * @return Response A Response instance
  199. *
  200. * @see RFC2616 13.10
  201. */
  202. protected function invalidate(Request $request, $catch = false)
  203. {
  204. $response = $this->pass($request, $catch);
  205. // invalidate only when the response is successful
  206. if ($response->isSuccessful() || $response->isRedirect()) {
  207. try {
  208. $this->store->invalidate($request, $catch);
  209. $this->record($request, 'invalidate');
  210. } catch (\Exception $e) {
  211. $this->record($request, 'invalidate-failed');
  212. if ($this->options['debug']) {
  213. throw $e;
  214. }
  215. }
  216. }
  217. return $response;
  218. }
  219. /**
  220. * Lookups a Response from the cache for the given Request.
  221. *
  222. * When a matching cache entry is found and is fresh, it uses it as the
  223. * response without forwarding any request to the backend. When a matching
  224. * cache entry is found but is stale, it attempts to "validate" the entry with
  225. * the backend using conditional GET. When no matching cache entry is found,
  226. * it triggers "miss" processing.
  227. *
  228. * @param Request $request A Request instance
  229. * @param Boolean $catch whether to process exceptions
  230. *
  231. * @return Response A Response instance
  232. */
  233. protected function lookup(Request $request, $catch = false)
  234. {
  235. // if allow_reload and no-cache Cache-Control, allow a cache reload
  236. if ($this->options['allow_reload'] && $request->isNoCache()) {
  237. $this->record($request, 'reload');
  238. return $this->fetch($request);
  239. }
  240. try {
  241. $entry = $this->store->lookup($request);
  242. } catch (\Exception $e) {
  243. $this->record($request, 'lookup-failed');
  244. if ($this->options['debug']) {
  245. throw $e;
  246. }
  247. return $this->pass($request, $catch);
  248. }
  249. if (null === $entry) {
  250. $this->record($request, 'miss');
  251. return $this->fetch($request, $catch);
  252. }
  253. if (!$this->isFreshEnough($request, $entry)) {
  254. $this->record($request, 'stale');
  255. return $this->validate($request, $entry);
  256. }
  257. $this->record($request, 'fresh');
  258. $entry->headers->set('Age', $entry->getAge());
  259. return $entry;
  260. }
  261. /**
  262. * Validates that a cache entry is fresh.
  263. *
  264. * The original request is used as a template for a conditional
  265. * GET request with the backend.
  266. *
  267. * @param Request $request A Request instance
  268. * @param Response $entry A Response instance to validate
  269. *
  270. * @return Response A Response instance
  271. */
  272. protected function validate(Request $request, Response $entry)
  273. {
  274. $subRequest = clone $request;
  275. // send no head requests because we want content
  276. $subRequest->setMethod('get');
  277. // add our cached last-modified validator
  278. $subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
  279. // Add our cached etag validator to the environment.
  280. // We keep the etags from the client to handle the case when the client
  281. // has a different private valid entry which is not cached here.
  282. $cachedEtags = array($entry->getEtag());
  283. $requestEtags = $request->getEtags();
  284. $etags = array_unique(array_merge($cachedEtags, $requestEtags));
  285. $subRequest->headers->set('if_none_match', $etags ? implode(', ', $etags) : '');
  286. $response = $this->forward($subRequest, false, $entry);
  287. if (304 == $response->getStatusCode()) {
  288. $this->record($request, 'valid');
  289. // return the response and not the cache entry if the response is valid but not cached
  290. $etag = $response->getEtag();
  291. if ($etag && in_array($etag, $requestEtags) && !in_array($etag, $cachedEtags)) {
  292. return $response;
  293. }
  294. $entry = clone $entry;
  295. $entry->headers->remove('Date');
  296. foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
  297. if ($response->headers->has($name)) {
  298. $entry->headers->set($name, $response->headers->get($name));
  299. }
  300. }
  301. $response = $entry;
  302. } else {
  303. $this->record($request, 'invalid');
  304. }
  305. if ($response->isCacheable()) {
  306. $this->store($request, $response);
  307. }
  308. return $response;
  309. }
  310. /**
  311. * Forwards the Request to the backend and determines whether the response should be stored.
  312. *
  313. * This methods is trigered when the cache missed or a reload is required.
  314. *
  315. * @param Request $request A Request instance
  316. * @param Boolean $catch whether to process exceptions
  317. *
  318. * @return Response A Response instance
  319. */
  320. protected function fetch(Request $request, $catch = false)
  321. {
  322. $subRequest = clone $request;
  323. // send no head requests because we want content
  324. $subRequest->setMethod('get');
  325. // avoid that the backend sends no content
  326. $subRequest->headers->remove('if_modified_since');
  327. $subRequest->headers->remove('if_none_match');
  328. $response = $this->forward($subRequest, $catch);
  329. if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
  330. $response->setPrivate(true);
  331. } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) {
  332. $response->setTtl($this->options['default_ttl']);
  333. }
  334. if ($response->isCacheable()) {
  335. $this->store($request, $response);
  336. }
  337. return $response;
  338. }
  339. /**
  340. * Forwards the Request to the backend and returns the Response.
  341. *
  342. * @param Request $request A Request instance
  343. * @param Boolean $catch Whether to catch exceptions or not
  344. * @param Response $response A Response instance (the stale entry if present, null otherwise)
  345. *
  346. * @return Response A Response instance
  347. */
  348. protected function forward(Request $request, $catch = false, Response $entry = null)
  349. {
  350. if ($this->esi) {
  351. $this->esi->addSurrogateEsiCapability($request);
  352. }
  353. // always a "master" request (as the real master request can be in cache)
  354. $response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch);
  355. // FIXME: we probably need to also catch exceptions if raw === true
  356. // we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
  357. if (null !== $entry && in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
  358. if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
  359. $age = $this->options['stale_if_error'];
  360. }
  361. if (abs($entry->getTtl()) < $age) {
  362. $this->record($request, 'stale-if-error');
  363. return $entry;
  364. }
  365. }
  366. $this->processResponseBody($request, $response);
  367. return $response;
  368. }
  369. /**
  370. * Checks whether the cache entry is "fresh enough" to satisfy the Request.
  371. *
  372. * @param Request $request A Request instance
  373. * @param Response $entry A Response instance
  374. *
  375. * @return Boolean true if the cache entry if fresh enough, false otherwise
  376. */
  377. protected function isFreshEnough(Request $request, Response $entry)
  378. {
  379. if (!$entry->isFresh()) {
  380. return $this->lock($request, $entry);
  381. }
  382. if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
  383. return $maxAge > 0 && $maxAge >= $entry->getAge();
  384. }
  385. return true;
  386. }
  387. /**
  388. * Locks a Request during the call to the backend.
  389. *
  390. * @param Request $request A Request instance
  391. * @param Response $entry A Response instance
  392. *
  393. * @return Boolean true if the cache entry can be returned even if it is staled, false otherwise
  394. */
  395. protected function lock(Request $request, Response $entry)
  396. {
  397. // try to acquire a lock to call the backend
  398. $lock = $this->store->lock($request, $entry);
  399. // there is already another process calling the backend
  400. if (true !== $lock) {
  401. // check if we can serve the stale entry
  402. if (null === $age = $entry->headers->getCacheControlDirective('stale-while-revalidate')) {
  403. $age = $this->options['stale_while_revalidate'];
  404. }
  405. if (abs($entry->getTtl()) < $age) {
  406. $this->record($request, 'stale-while-revalidate');
  407. // server the stale response while there is a revalidation
  408. return true;
  409. } else {
  410. // wait for the lock to be released
  411. $wait = 0;
  412. while (file_exists($lock) && $wait < 5000000) {
  413. usleep($wait += 50000);
  414. }
  415. if ($wait < 2000000) {
  416. // replace the current entry with the fresh one
  417. $new = $this->lookup($request);
  418. $entry->headers = $new->headers;
  419. $entry->setContent($new->getContent());
  420. $entry->setStatusCode($new->getStatusCode());
  421. $entry->setProtocolVersion($new->getProtocolVersion());
  422. $entry->setCookies($new->getCookies());
  423. return true;
  424. } else {
  425. // backend is slow as hell, send a 503 response (to avoid the dog pile effect)
  426. $entry->setStatusCode(503);
  427. $entry->setContent('503 Service Unavailable');
  428. $entry->headers->set('Retry-After', 10);
  429. return true;
  430. }
  431. }
  432. }
  433. // we have the lock, call the backend
  434. return false;
  435. }
  436. /**
  437. * Writes the Response to the cache.
  438. *
  439. * @param Request $request A Request instance
  440. * @param Response $response A Response instance
  441. */
  442. protected function store(Request $request, Response $response)
  443. {
  444. try {
  445. $this->store->write($request, $response);
  446. $this->record($request, 'store');
  447. $response->headers->set('Age', $response->getAge());
  448. } catch (\Exception $e) {
  449. $this->record($request, 'store-failed');
  450. if ($this->options['debug']) {
  451. throw $e;
  452. }
  453. }
  454. // now that the response is cached, release the lock
  455. $this->store->unlock($request);
  456. }
  457. /**
  458. * Restores the Response body.
  459. *
  460. * @param Response $response A Response instance
  461. *
  462. * @return Response A Response instance
  463. */
  464. protected function restoreResponseBody(Request $request, Response $response)
  465. {
  466. if ('head' === strtolower($request->getMethod())) {
  467. $response->setContent('');
  468. $response->headers->remove('X-Body-Eval');
  469. $response->headers->remove('X-Body-File');
  470. return;
  471. }
  472. if ($response->headers->has('X-Body-Eval')) {
  473. ob_start();
  474. if ($response->headers->has('X-Body-File')) {
  475. include $response->headers->get('X-Body-File');
  476. } else {
  477. eval('; ?>'.$response->getContent().'<?php ;');
  478. }
  479. $response->setContent(ob_get_clean());
  480. $response->headers->remove('X-Body-Eval');
  481. } elseif ($response->headers->has('X-Body-File')) {
  482. $response->setContent(file_get_contents($response->headers->get('X-Body-File')));
  483. } else {
  484. return;
  485. }
  486. $response->headers->remove('X-Body-File');
  487. if (!$response->headers->has('Transfer-Encoding')) {
  488. $response->headers->set('Content-Length', strlen($response->getContent()));
  489. }
  490. }
  491. protected function processResponseBody(Request $request, Response $response)
  492. {
  493. if (null !== $this->esi && $this->esi->needsEsiParsing($response)) {
  494. $this->esi->process($request, $response);
  495. }
  496. }
  497. /**
  498. * Checks if the Request includes authorization or other sensitive information
  499. * that should cause the Response to be considered private by default.
  500. *
  501. * @param Request $request A Request instance
  502. *
  503. * @return Boolean true if the Request is private, false otherwise
  504. */
  505. protected function isPrivateRequest(Request $request)
  506. {
  507. foreach ($this->options['private_headers'] as $key) {
  508. $key = strtolower(str_replace('HTTP_', '', $key));
  509. if ('cookie' === $key) {
  510. if (count($request->cookies->all())) {
  511. return true;
  512. }
  513. } elseif ($request->headers->has($key)) {
  514. return true;
  515. }
  516. }
  517. return false;
  518. }
  519. /**
  520. * Records that an event took place.
  521. *
  522. * @param string $event The event name
  523. */
  524. protected function record(Request $request, $event)
  525. {
  526. $path = $request->getPathInfo();
  527. if ($qs = $request->getQueryString()) {
  528. $path .= '?'.$qs;
  529. }
  530. $this->traces[$request->getMethod().' '.$path][] = $event;
  531. }
  532. }