vendor/symfony/http-kernel/HttpCache/HttpCache.php line 215

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