Dashboard sipadu mbip
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

HttpCache.php 24KB

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