HttpCache.php 26 KB

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