HttpCache.php 27 KB

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