You are here

protected function HttpCache::lock in Zircon Profile 8.0

Same name and namespace in other branches
  1. 8 vendor/symfony/http-kernel/HttpCache/HttpCache.php \Symfony\Component\HttpKernel\HttpCache\HttpCache::lock()

Locks a Request during the call to the backend.

Parameters

Request $request A Request instance:

Response $entry A Response instance:

Return value

bool true if the cache entry can be returned even if it is staled, false otherwise

1 call to HttpCache::lock()
HttpCache::isFreshEnough in vendor/symfony/http-kernel/HttpCache/HttpCache.php
Checks whether the cache entry is "fresh enough" to satisfy the Request.

File

vendor/symfony/http-kernel/HttpCache/HttpCache.php, line 543

Class

HttpCache
Cache provides HTTP caching.

Namespace

Symfony\Component\HttpKernel\HttpCache

Code

protected function lock(Request $request, Response $entry) {

  // try to acquire a lock to call the backend
  $lock = $this->store
    ->lock($request);

  // there is already another process calling the backend
  if (true !== $lock) {

    // check if we can serve the stale entry
    if (null === ($age = $entry->headers
      ->getCacheControlDirective('stale-while-revalidate'))) {
      $age = $this->options['stale_while_revalidate'];
    }
    if (abs($entry
      ->getTtl()) < $age) {
      $this
        ->record($request, 'stale-while-revalidate');

      // server the stale response while there is a revalidation
      return true;
    }

    // wait for the lock to be released
    $wait = 0;
    while ($this->store
      ->isLocked($request) && $wait < 5000000) {
      usleep(50000);
      $wait += 50000;
    }
    if ($wait < 2000000) {

      // replace the current entry with the fresh one
      $new = $this
        ->lookup($request);
      $entry->headers = $new->headers;
      $entry
        ->setContent($new
        ->getContent());
      $entry
        ->setStatusCode($new
        ->getStatusCode());
      $entry
        ->setProtocolVersion($new
        ->getProtocolVersion());
      foreach ($new->headers
        ->getCookies() as $cookie) {
        $entry->headers
          ->setCookie($cookie);
      }
    }
    else {

      // backend is slow as hell, send a 503 response (to avoid the dog pile effect)
      $entry
        ->setStatusCode(503);
      $entry
        ->setContent('503 Service Unavailable');
      $entry->headers
        ->set('Retry-After', 10);
    }
    return true;
  }

  // we have the lock, call the backend
  return false;
}