HttpCache.php 23 KB

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