HttpCache.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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() ? -1 : $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 (-1 === $ttl) {
  174. $response->headers->set('Cache-Control', 'no-cache, must-revalidate');
  175. } else {
  176. $response->setSharedMaxAge($ttl);
  177. $response->setMaxAge(0);
  178. }
  179. }
  180. /**
  181. * Forwards the Request to the backend without storing the Response in the cache.
  182. *
  183. * @param Request $request A Request instance
  184. * @param Boolean $catch whether to process exceptions
  185. *
  186. * @return Response A Response instance
  187. */
  188. protected function pass(Request $request, $catch = false)
  189. {
  190. $this->record($request, 'pass');
  191. return $this->forward($request, $catch);
  192. }
  193. /**
  194. * Invalidates non-safe methods (like POST, PUT, and DELETE).
  195. *
  196. * @param Request $request A Request instance
  197. * @param Boolean $catch whether to process exceptions
  198. *
  199. * @return Response A Response instance
  200. *
  201. * @see RFC2616 13.10
  202. */
  203. protected function invalidate(Request $request, $catch = false)
  204. {
  205. $response = $this->pass($request, $catch);
  206. // invalidate only when the response is successful
  207. if ($response->isSuccessful() || $response->isRedirect()) {
  208. try {
  209. $this->store->invalidate($request, $catch);
  210. $this->record($request, 'invalidate');
  211. } catch (\Exception $e) {
  212. $this->record($request, 'invalidate-failed');
  213. if ($this->options['debug']) {
  214. throw $e;
  215. }
  216. }
  217. }
  218. return $response;
  219. }
  220. /**
  221. * Lookups a Response from the cache for the given Request.
  222. *
  223. * When a matching cache entry is found and is fresh, it uses it as the
  224. * response without forwarding any request to the backend. When a matching
  225. * cache entry is found but is stale, it attempts to "validate" the entry with
  226. * the backend using conditional GET. When no matching cache entry is found,
  227. * it triggers "miss" processing.
  228. *
  229. * @param Request $request A Request instance
  230. * @param Boolean $catch whether to process exceptions
  231. *
  232. * @return Response A Response instance
  233. */
  234. protected function lookup(Request $request, $catch = false)
  235. {
  236. // if allow_reload and no-cache Cache-Control, allow a cache reload
  237. if ($this->options['allow_reload'] && $request->isNoCache()) {
  238. $this->record($request, 'reload');
  239. return $this->fetch($request);
  240. }
  241. try {
  242. $entry = $this->store->lookup($request);
  243. } catch (\Exception $e) {
  244. $this->record($request, 'lookup-failed');
  245. if ($this->options['debug']) {
  246. throw $e;
  247. }
  248. return $this->pass($request, $catch);
  249. }
  250. if (null === $entry) {
  251. $this->record($request, 'miss');
  252. return $this->fetch($request, $catch);
  253. }
  254. if (!$this->isFreshEnough($request, $entry)) {
  255. $this->record($request, 'stale');
  256. return $this->validate($request, $entry);
  257. }
  258. $this->record($request, 'fresh');
  259. $entry->headers->set('Age', $entry->getAge());
  260. return $entry;
  261. }
  262. /**
  263. * Validates that a cache entry is fresh.
  264. *
  265. * The original request is used as a template for a conditional
  266. * GET request with the backend.
  267. *
  268. * @param Request $request A Request instance
  269. * @param Response $entry A Response instance to validate
  270. *
  271. * @return Response A Response instance
  272. */
  273. protected function validate(Request $request, Response $entry)
  274. {
  275. $subRequest = clone $request;
  276. // send no head requests because we want content
  277. $subRequest->setMethod('get');
  278. // add our cached last-modified validator
  279. $subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
  280. // Add our cached etag validator to the environment.
  281. // We keep the etags from the client to handle the case when the client
  282. // has a different private valid entry which is not cached here.
  283. $cachedEtags = array($entry->getEtag());
  284. $requestEtags = $request->getEtags();
  285. $etags = array_unique(array_merge($cachedEtags, $requestEtags));
  286. $subRequest->headers->set('if_none_match', $etags ? implode(', ', $etags) : '');
  287. $response = $this->forward($subRequest, false, $entry);
  288. if (304 == $response->getStatusCode()) {
  289. $this->record($request, 'valid');
  290. // return the response and not the cache entry if the response is valid but not cached
  291. $etag = $response->getEtag();
  292. if ($etag && in_array($etag, $requestEtags) && !in_array($etag, $cachedEtags)) {
  293. return $response;
  294. }
  295. $entry = clone $entry;
  296. $entry->headers->remove('Date');
  297. foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
  298. if ($response->headers->has($name)) {
  299. $entry->headers->set($name, $response->headers->get($name));
  300. }
  301. }
  302. $response = $entry;
  303. } else {
  304. $this->record($request, 'invalid');
  305. }
  306. if ($response->isCacheable()) {
  307. $this->store($request, $response);
  308. }
  309. return $response;
  310. }
  311. /**
  312. * Forwards the Request to the backend and determines whether the response should be stored.
  313. *
  314. * This methods is trigered when the cache missed or a reload is required.
  315. *
  316. * @param Request $request A Request instance
  317. * @param Boolean $catch whether to process exceptions
  318. *
  319. * @return Response A Response instance
  320. */
  321. protected function fetch(Request $request, $catch = false)
  322. {
  323. $subRequest = clone $request;
  324. // send no head requests because we want content
  325. $subRequest->setMethod('get');
  326. // avoid that the backend sends no content
  327. $subRequest->headers->remove('if_modified_since');
  328. $subRequest->headers->remove('if_none_match');
  329. $response = $this->forward($subRequest, $catch);
  330. if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
  331. $response->setPrivate(true);
  332. } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) {
  333. $response->setTtl($this->options['default_ttl']);
  334. }
  335. if ($response->isCacheable()) {
  336. $this->store($request, $response);
  337. }
  338. return $response;
  339. }
  340. /**
  341. * Forwards the Request to the backend and returns the Response.
  342. *
  343. * @param Request $request A Request instance
  344. * @param Boolean $catch Whether to catch exceptions or not
  345. * @param Response $response A Response instance (the stale entry if present, null otherwise)
  346. *
  347. * @return Response A Response instance
  348. */
  349. protected function forward(Request $request, $catch = false, Response $entry = null)
  350. {
  351. if ($this->esi) {
  352. $this->esi->addSurrogateEsiCapability($request);
  353. }
  354. // always a "master" request (as the real master request can be in cache)
  355. $response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch);
  356. // FIXME: we probably need to also catch exceptions if raw === true
  357. // we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
  358. if (null !== $entry && in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
  359. if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
  360. $age = $this->options['stale_if_error'];
  361. }
  362. if (abs($entry->getTtl()) < $age) {
  363. $this->record($request, 'stale-if-error');
  364. return $entry;
  365. }
  366. }
  367. $this->processResponseBody($request, $response);
  368. return $response;
  369. }
  370. /**
  371. * Checks whether the cache entry is "fresh enough" to satisfy the Request.
  372. *
  373. * @param Request $request A Request instance
  374. * @param Response $entry A Response instance
  375. *
  376. * @return Boolean true if the cache entry if fresh enough, false otherwise
  377. */
  378. protected function isFreshEnough(Request $request, Response $entry)
  379. {
  380. if (!$entry->isFresh()) {
  381. return $this->lock($request, $entry);
  382. }
  383. if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
  384. return $maxAge > 0 && $maxAge >= $entry->getAge();
  385. }
  386. return true;
  387. }
  388. /**
  389. * Locks a Request during the call to the backend.
  390. *
  391. * @param Request $request A Request instance
  392. * @param Response $entry A Response instance
  393. *
  394. * @return Boolean true if the cache entry can be returned even if it is staled, false otherwise
  395. */
  396. protected function lock(Request $request, Response $entry)
  397. {
  398. // try to acquire a lock to call the backend
  399. $lock = $this->store->lock($request, $entry);
  400. // there is already another process calling the backend
  401. if (true !== $lock) {
  402. // check if we can serve the stale entry
  403. if (null === $age = $entry->headers->getCacheControlDirective('stale-while-revalidate')) {
  404. $age = $this->options['stale_while_revalidate'];
  405. }
  406. if (abs($entry->getTtl()) < $age) {
  407. $this->record($request, 'stale-while-revalidate');
  408. // server the stale response while there is a revalidation
  409. return true;
  410. } else {
  411. // wait for the lock to be released
  412. $wait = 0;
  413. while (file_exists($lock) && $wait < 5000000) {
  414. usleep($wait += 50000);
  415. }
  416. if ($wait < 2000000) {
  417. // replace the current entry with the fresh one
  418. $new = $this->lookup($request);
  419. $entry->headers = $new->headers;
  420. $entry->setContent($new->getContent());
  421. $entry->setStatusCode($new->getStatusCode());
  422. $entry->setProtocolVersion($new->getProtocolVersion());
  423. $entry->setCookies($new->getCookies());
  424. return true;
  425. } else {
  426. // backend is slow as hell, send a 503 response (to avoid the dog pile effect)
  427. $entry->setStatusCode(503);
  428. $entry->setContent('503 Service Unavailable');
  429. $entry->headers->set('Retry-After', 10);
  430. return true;
  431. }
  432. }
  433. }
  434. // we have the lock, call the backend
  435. return false;
  436. }
  437. /**
  438. * Writes the Response to the cache.
  439. *
  440. * @param Request $request A Request instance
  441. * @param Response $response A Response instance
  442. */
  443. protected function store(Request $request, Response $response)
  444. {
  445. try {
  446. $this->store->write($request, $response);
  447. $this->record($request, 'store');
  448. $response->headers->set('Age', $response->getAge());
  449. } catch (\Exception $e) {
  450. $this->record($request, 'store-failed');
  451. if ($this->options['debug']) {
  452. throw $e;
  453. }
  454. }
  455. // now that the response is cached, release the lock
  456. $this->store->unlock($request);
  457. }
  458. /**
  459. * Restores the Response body.
  460. *
  461. * @param Response $response A Response instance
  462. *
  463. * @return Response A Response instance
  464. */
  465. protected function restoreResponseBody(Request $request, Response $response)
  466. {
  467. if ('head' === strtolower($request->getMethod())) {
  468. $response->setContent('');
  469. $response->headers->remove('X-Body-Eval');
  470. $response->headers->remove('X-Body-File');
  471. return;
  472. }
  473. if ($response->headers->has('X-Body-Eval')) {
  474. ob_start();
  475. if ($response->headers->has('X-Body-File')) {
  476. include $response->headers->get('X-Body-File');
  477. } else {
  478. eval('; ?>'.$response->getContent().'<?php ;');
  479. }
  480. $response->setContent(ob_get_clean());
  481. $response->headers->remove('X-Body-Eval');
  482. } elseif ($response->headers->has('X-Body-File')) {
  483. $response->setContent(file_get_contents($response->headers->get('X-Body-File')));
  484. } else {
  485. return;
  486. }
  487. $response->headers->remove('X-Body-File');
  488. if (!$response->headers->has('Transfer-Encoding')) {
  489. $response->headers->set('Content-Length', strlen($response->getContent()));
  490. }
  491. }
  492. protected function processResponseBody(Request $request, Response $response)
  493. {
  494. if (null !== $this->esi && $this->esi->needsEsiParsing($response)) {
  495. $this->esi->process($request, $response);
  496. }
  497. }
  498. /**
  499. * Checks if the Request includes authorization or other sensitive information
  500. * that should cause the Response to be considered private by default.
  501. *
  502. * @param Request $request A Request instance
  503. *
  504. * @return Boolean true if the Request is private, false otherwise
  505. */
  506. protected function isPrivateRequest(Request $request)
  507. {
  508. foreach ($this->options['private_headers'] as $key) {
  509. $key = strtolower(str_replace('HTTP_', '', $key));
  510. if ('cookie' === $key) {
  511. if (count($request->cookies->all())) {
  512. return true;
  513. }
  514. } elseif ($request->headers->has($key)) {
  515. return true;
  516. }
  517. }
  518. return false;
  519. }
  520. /**
  521. * Records that an event took place.
  522. *
  523. * @param string $event The event name
  524. */
  525. protected function record(Request $request, $event)
  526. {
  527. $path = $request->getPathInfo();
  528. if ($qs = $request->getQueryString()) {
  529. $path .= '?'.$qs;
  530. }
  531. $this->traces[$request->getMethod().' '.$path][] = $event;
  532. }
  533. }