Cache.php 20 KB

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