HttpCache.php 21 KB

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