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

Open in your IDE?
  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.     public const BODY_EVAL_BOUNDARY_LENGTH 24;
  28.     private $kernel;
  29.     private $store;
  30.     private $request;
  31.     private $surrogate;
  32.     private $surrogateCacheStrategy;
  33.     private $options = [];
  34.     private $traces = [];
  35.     /**
  36.      * Constructor.
  37.      *
  38.      * The available options are:
  39.      *
  40.      *   * debug                  If true, exceptions are thrown when things go wrong. Otherwise, the cache
  41.      *                            will try to carry on and deliver a meaningful response.
  42.      *
  43.      *   * trace_level            May be one of 'none', 'short' and 'full'. For 'short', a concise trace of the
  44.      *                            main request will be added as an HTTP header. 'full' will add traces for all
  45.      *                            requests (including ESI subrequests). (default: 'full' if in debug; 'none' otherwise)
  46.      *
  47.      *   * trace_header           Header name to use for traces. (default: X-Symfony-Cache)
  48.      *
  49.      *   * default_ttl            The number of seconds that a cache entry should be considered
  50.      *                            fresh when no explicit freshness information is provided in
  51.      *                            a response. Explicit Cache-Control or Expires headers
  52.      *                            override this value. (default: 0)
  53.      *
  54.      *   * private_headers        Set of request headers that trigger "private" cache-control behavior
  55.      *                            on responses that don't explicitly state whether the response is
  56.      *                            public or private via a Cache-Control directive. (default: Authorization and 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(HttpKernelInterface $kernelStoreInterface $store, ?SurrogateInterface $surrogate null, array $options = [])
  78.     {
  79.         $this->store $store;
  80.         $this->kernel $kernel;
  81.         $this->surrogate $surrogate;
  82.         // needed in case there is a fatal error because the backend is too slow to respond
  83.         register_shutdown_function([$this->store'cleanup']);
  84.         $this->options array_merge([
  85.             'debug' => false,
  86.             'default_ttl' => 0,
  87.             'private_headers' => ['Authorization''Cookie'],
  88.             'allow_reload' => false,
  89.             'allow_revalidate' => false,
  90.             'stale_while_revalidate' => 2,
  91.             'stale_if_error' => 60,
  92.             'trace_level' => 'none',
  93.             'trace_header' => 'X-Symfony-Cache',
  94.         ], $options);
  95.         if (!isset($options['trace_level'])) {
  96.             $this->options['trace_level'] = $this->options['debug'] ? 'full' 'none';
  97.         }
  98.     }
  99.     /**
  100.      * Gets the current store.
  101.      *
  102.      * @return StoreInterface
  103.      */
  104.     public function getStore()
  105.     {
  106.         return $this->store;
  107.     }
  108.     /**
  109.      * Returns an array of events that took place during processing of the last request.
  110.      *
  111.      * @return array
  112.      */
  113.     public function getTraces()
  114.     {
  115.         return $this->traces;
  116.     }
  117.     private function addTraces(Response $response)
  118.     {
  119.         $traceString null;
  120.         if ('full' === $this->options['trace_level']) {
  121.             $traceString $this->getLog();
  122.         }
  123.         if ('short' === $this->options['trace_level'] && $masterId array_key_first($this->traces)) {
  124.             $traceString implode('/'$this->traces[$masterId]);
  125.         }
  126.         if (null !== $traceString) {
  127.             $response->headers->add([$this->options['trace_header'] => $traceString]);
  128.         }
  129.     }
  130.     /**
  131.      * Returns a log message for the events of the last request processing.
  132.      *
  133.      * @return string
  134.      */
  135.     public function getLog()
  136.     {
  137.         $log = [];
  138.         foreach ($this->traces as $request => $traces) {
  139.             $log[] = sprintf('%s: %s'$requestimplode(', '$traces));
  140.         }
  141.         return implode('; '$log);
  142.     }
  143.     /**
  144.      * Gets the Request instance associated with the main request.
  145.      *
  146.      * @return Request
  147.      */
  148.     public function getRequest()
  149.     {
  150.         return $this->request;
  151.     }
  152.     /**
  153.      * Gets the Kernel instance.
  154.      *
  155.      * @return HttpKernelInterface
  156.      */
  157.     public function getKernel()
  158.     {
  159.         return $this->kernel;
  160.     }
  161.     /**
  162.      * Gets the Surrogate instance.
  163.      *
  164.      * @return SurrogateInterface
  165.      *
  166.      * @throws \LogicException
  167.      */
  168.     public function getSurrogate()
  169.     {
  170.         return $this->surrogate;
  171.     }
  172.     /**
  173.      * {@inheritdoc}
  174.      */
  175.     public function handle(Request $requestint $type HttpKernelInterface::MAIN_REQUESTbool $catch true)
  176.     {
  177.         // FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism
  178.         if (HttpKernelInterface::MAIN_REQUEST === $type) {
  179.             $this->traces = [];
  180.             // Keep a clone of the original request for surrogates so they can access it.
  181.             // We must clone here to get a separate instance because the application will modify the request during
  182.             // the application flow (we know it always does because we do ourselves by setting REMOTE_ADDR to 127.0.0.1
  183.             // and adding the X-Forwarded-For header, see HttpCache::forward()).
  184.             $this->request = clone $request;
  185.             if (null !== $this->surrogate) {
  186.                 $this->surrogateCacheStrategy $this->surrogate->createCacheStrategy();
  187.             }
  188.         }
  189.         $this->traces[$this->getTraceKey($request)] = [];
  190.         if (!$request->isMethodSafe()) {
  191.             $response $this->invalidate($request$catch);
  192.         } elseif ($request->headers->has('expect') || !$request->isMethodCacheable()) {
  193.             $response $this->pass($request$catch);
  194.         } elseif ($this->options['allow_reload'] && $request->isNoCache()) {
  195.             /*
  196.                 If allow_reload is configured and the client requests "Cache-Control: no-cache",
  197.                 reload the cache by fetching a fresh response and caching it (if possible).
  198.             */
  199.             $this->record($request'reload');
  200.             $response $this->fetch($request$catch);
  201.         } else {
  202.             $response $this->lookup($request$catch);
  203.         }
  204.         $this->restoreResponseBody($request$response);
  205.         if (HttpKernelInterface::MAIN_REQUEST === $type) {
  206.             $this->addTraces($response);
  207.         }
  208.         if (null !== $this->surrogate) {
  209.             if (HttpKernelInterface::MAIN_REQUEST === $type) {
  210.                 $this->surrogateCacheStrategy->update($response);
  211.             } else {
  212.                 $this->surrogateCacheStrategy->add($response);
  213.             }
  214.         }
  215.         $response->prepare($request);
  216.         $response->isNotModified($request);
  217.         return $response;
  218.     }
  219.     /**
  220.      * {@inheritdoc}
  221.      */
  222.     public function terminate(Request $requestResponse $response)
  223.     {
  224.         if ($this->getKernel() instanceof TerminableInterface) {
  225.             $this->getKernel()->terminate($request$response);
  226.         }
  227.     }
  228.     /**
  229.      * Forwards the Request to the backend without storing the Response in the cache.
  230.      *
  231.      * @param bool $catch Whether to process exceptions
  232.      *
  233.      * @return Response
  234.      */
  235.     protected function pass(Request $requestbool $catch false)
  236.     {
  237.         $this->record($request'pass');
  238.         return $this->forward($request$catch);
  239.     }
  240.     /**
  241.      * Invalidates non-safe methods (like POST, PUT, and DELETE).
  242.      *
  243.      * @param bool $catch Whether to process exceptions
  244.      *
  245.      * @return Response
  246.      *
  247.      * @throws \Exception
  248.      *
  249.      * @see RFC2616 13.10
  250.      */
  251.     protected function invalidate(Request $requestbool $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 bool $catch Whether to process exceptions
  285.      *
  286.      * @return Response
  287.      *
  288.      * @throws \Exception
  289.      */
  290.     protected function lookup(Request $requestbool $catch false)
  291.     {
  292.         try {
  293.             $entry $this->store->lookup($request);
  294.         } catch (\Exception $e) {
  295.             $this->record($request'lookup-failed');
  296.             if ($this->options['debug']) {
  297.                 throw $e;
  298.             }
  299.             return $this->pass($request$catch);
  300.         }
  301.         if (null === $entry) {
  302.             $this->record($request'miss');
  303.             return $this->fetch($request$catch);
  304.         }
  305.         if (!$this->isFreshEnough($request$entry)) {
  306.             $this->record($request'stale');
  307.             return $this->validate($request$entry$catch);
  308.         }
  309.         if ($entry->headers->hasCacheControlDirective('no-cache')) {
  310.             return $this->validate($request$entry$catch);
  311.         }
  312.         $this->record($request'fresh');
  313.         $entry->headers->set('Age'$entry->getAge());
  314.         return $entry;
  315.     }
  316.     /**
  317.      * Validates that a cache entry is fresh.
  318.      *
  319.      * The original request is used as a template for a conditional
  320.      * GET request with the backend.
  321.      *
  322.      * @param bool $catch Whether to process exceptions
  323.      *
  324.      * @return Response
  325.      */
  326.     protected function validate(Request $requestResponse $entrybool $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.         if ($entry->headers->has('Last-Modified')) {
  335.             $subRequest->headers->set('If-Modified-Since'$entry->headers->get('Last-Modified'));
  336.         }
  337.         // Add our cached etag validator to the environment.
  338.         // We keep the etags from the client to handle the case when the client
  339.         // has a different private valid entry which is not cached here.
  340.         $cachedEtags $entry->getEtag() ? [$entry->getEtag()] : [];
  341.         $requestEtags $request->getETags();
  342.         if ($etags array_unique(array_merge($cachedEtags$requestEtags))) {
  343.             $subRequest->headers->set('If-None-Match'implode(', '$etags));
  344.         }
  345.         $response $this->forward($subRequest$catch$entry);
  346.         if (304 == $response->getStatusCode()) {
  347.             $this->record($request'valid');
  348.             // return the response and not the cache entry if the response is valid but not cached
  349.             $etag $response->getEtag();
  350.             if ($etag && \in_array($etag$requestEtags) && !\in_array($etag$cachedEtags)) {
  351.                 return $response;
  352.             }
  353.             $entry = clone $entry;
  354.             $entry->headers->remove('Date');
  355.             foreach (['Date''Expires''Cache-Control''ETag''Last-Modified'] as $name) {
  356.                 if ($response->headers->has($name)) {
  357.                     $entry->headers->set($name$response->headers->get($name));
  358.                 }
  359.             }
  360.             $response $entry;
  361.         } else {
  362.             $this->record($request'invalid');
  363.         }
  364.         if ($response->isCacheable()) {
  365.             $this->store($request$response);
  366.         }
  367.         return $response;
  368.     }
  369.     /**
  370.      * Unconditionally fetches a fresh response from the backend and
  371.      * stores it in the cache if is cacheable.
  372.      *
  373.      * @param bool $catch Whether to process exceptions
  374.      *
  375.      * @return Response
  376.      */
  377.     protected function fetch(Request $requestbool $catch false)
  378.     {
  379.         $subRequest = clone $request;
  380.         // send no head requests because we want content
  381.         if ('HEAD' === $request->getMethod()) {
  382.             $subRequest->setMethod('GET');
  383.         }
  384.         // avoid that the backend sends no content
  385.         $subRequest->headers->remove('If-Modified-Since');
  386.         $subRequest->headers->remove('If-None-Match');
  387.         $response $this->forward($subRequest$catch);
  388.         if ($response->isCacheable()) {
  389.             $this->store($request$response);
  390.         }
  391.         return $response;
  392.     }
  393.     /**
  394.      * Forwards the Request to the backend and returns the Response.
  395.      *
  396.      * All backend requests (cache passes, fetches, cache validations)
  397.      * run through this method.
  398.      *
  399.      * @param bool          $catch Whether to catch exceptions or not
  400.      * @param Response|null $entry A Response instance (the stale entry if present, null otherwise)
  401.      *
  402.      * @return Response
  403.      */
  404.     protected function forward(Request $requestbool $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$requestHttpKernelInterface::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(), [500502503504])
  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(\DateTime::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'] > && 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.      * @return bool
  466.      */
  467.     protected function isFreshEnough(Request $requestResponse $entry)
  468.     {
  469.         if (!$entry->isFresh()) {
  470.             return $this->lock($request$entry);
  471.         }
  472.         if ($this->options['allow_revalidate'] && null !== $maxAge $request->headers->getCacheControlDirective('max-age')) {
  473.             return $maxAge && $maxAge >= $entry->getAge();
  474.         }
  475.         return true;
  476.     }
  477.     /**
  478.      * Locks a Request during the call to the backend.
  479.      *
  480.      * @return bool true if the cache entry can be returned even if it is staled, false otherwise
  481.      */
  482.     protected function lock(Request $requestResponse $entry)
  483.     {
  484.         // try to acquire a lock to call the backend
  485.         $lock $this->store->lock($request);
  486.         if (true === $lock) {
  487.             // we have the lock, call the backend
  488.             return false;
  489.         }
  490.         // there is already another process calling the backend
  491.         // May we serve a stale response?
  492.         if ($this->mayServeStaleWhileRevalidate($entry)) {
  493.             $this->record($request'stale-while-revalidate');
  494.             return true;
  495.         }
  496.         // wait for the lock to be released
  497.         if ($this->waitForLock($request)) {
  498.             // replace the current entry with the fresh one
  499.             $new $this->lookup($request);
  500.             $entry->headers $new->headers;
  501.             $entry->setContent($new->getContent());
  502.             $entry->setStatusCode($new->getStatusCode());
  503.             $entry->setProtocolVersion($new->getProtocolVersion());
  504.             foreach ($new->headers->getCookies() as $cookie) {
  505.                 $entry->headers->setCookie($cookie);
  506.             }
  507.         } else {
  508.             // backend is slow as hell, send a 503 response (to avoid the dog pile effect)
  509.             $entry->setStatusCode(503);
  510.             $entry->setContent('503 Service Unavailable');
  511.             $entry->headers->set('Retry-After'10);
  512.         }
  513.         return true;
  514.     }
  515.     /**
  516.      * Writes the Response to the cache.
  517.      *
  518.      * @throws \Exception
  519.      */
  520.     protected function store(Request $requestResponse $response)
  521.     {
  522.         try {
  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.         }
  532.         // now that the response is cached, release the lock
  533.         $this->store->unlock($request);
  534.     }
  535.     /**
  536.      * Restores the Response body.
  537.      */
  538.     private function restoreResponseBody(Request $requestResponse $response)
  539.     {
  540.         if ($response->headers->has('X-Body-Eval')) {
  541.             \assert(self::BODY_EVAL_BOUNDARY_LENGTH === 24);
  542.             ob_start();
  543.             $content $response->getContent();
  544.             $boundary substr($content024);
  545.             $j strpos($content$boundary24);
  546.             echo substr($content24$j 24);
  547.             $i $j 24;
  548.             while (false !== $j strpos($content$boundary$i)) {
  549.                 [$uri$alt$ignoreErrors$part] = explode("\n"substr($content$i$j $i), 4);
  550.                 $i $j 24;
  551.                 echo $this->surrogate->handle($this$uri$alt$ignoreErrors);
  552.                 echo $part;
  553.             }
  554.             $response->setContent(ob_get_clean());
  555.             $response->headers->remove('X-Body-Eval');
  556.             if (!$response->headers->has('Transfer-Encoding')) {
  557.                 $response->headers->set('Content-Length'\strlen($response->getContent()));
  558.             }
  559.         } elseif ($response->headers->has('X-Body-File')) {
  560.             // Response does not include possibly dynamic content (ESI, SSI), so we need
  561.             // not handle the content for HEAD requests
  562.             if (!$request->isMethod('HEAD')) {
  563.                 $response->setContent(file_get_contents($response->headers->get('X-Body-File')));
  564.             }
  565.         } else {
  566.             return;
  567.         }
  568.         $response->headers->remove('X-Body-File');
  569.     }
  570.     protected function processResponseBody(Request $requestResponse $response)
  571.     {
  572.         if (null !== $this->surrogate && $this->surrogate->needsParsing($response)) {
  573.             $this->surrogate->process($request$response);
  574.         }
  575.     }
  576.     /**
  577.      * Checks if the Request includes authorization or other sensitive information
  578.      * that should cause the Response to be considered private by default.
  579.      */
  580.     private function isPrivateRequest(Request $request): bool
  581.     {
  582.         foreach ($this->options['private_headers'] as $key) {
  583.             $key strtolower(str_replace('HTTP_'''$key));
  584.             if ('cookie' === $key) {
  585.                 if (\count($request->cookies->all())) {
  586.                     return true;
  587.                 }
  588.             } elseif ($request->headers->has($key)) {
  589.                 return true;
  590.             }
  591.         }
  592.         return false;
  593.     }
  594.     /**
  595.      * Records that an event took place.
  596.      */
  597.     private function record(Request $requeststring $event)
  598.     {
  599.         $this->traces[$this->getTraceKey($request)][] = $event;
  600.     }
  601.     /**
  602.      * Calculates the key we use in the "trace" array for a given request.
  603.      */
  604.     private function getTraceKey(Request $request): string
  605.     {
  606.         $path $request->getPathInfo();
  607.         if ($qs $request->getQueryString()) {
  608.             $path .= '?'.$qs;
  609.         }
  610.         return $request->getMethod().' '.$path;
  611.     }
  612.     /**
  613.      * Checks whether the given (cached) response may be served as "stale" when a revalidation
  614.      * is currently in progress.
  615.      */
  616.     private function mayServeStaleWhileRevalidate(Response $entry): bool
  617.     {
  618.         $timeout $entry->headers->getCacheControlDirective('stale-while-revalidate');
  619.         if (null === $timeout) {
  620.             $timeout $this->options['stale_while_revalidate'];
  621.         }
  622.         $age $entry->getAge();
  623.         $maxAge $entry->getMaxAge() ?? 0;
  624.         $ttl $maxAge $age;
  625.         return abs($ttl) < $timeout;
  626.     }
  627.     /**
  628.      * Waits for the store to release a locked entry.
  629.      */
  630.     private function waitForLock(Request $request): bool
  631.     {
  632.         $wait 0;
  633.         while ($this->store->isLocked($request) && $wait 100) {
  634.             usleep(50000);
  635.             ++$wait;
  636.         }
  637.         return $wait 100;
  638.     }
  639. }