Cache.php 20 KB

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