vendor/symfony/cache/LockRegistry.php line 118

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. namespace Symfony\Component\Cache;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Contracts\Cache\CacheInterface;
  13. use Symfony\Contracts\Cache\ItemInterface;
  14. /**
  15.  * LockRegistry is used internally by existing adapters to protect against cache stampede.
  16.  *
  17.  * It does so by wrapping the computation of items in a pool of locks.
  18.  * Foreach each apps, there can be at most 20 concurrent processes that
  19.  * compute items at the same time and only one per cache-key.
  20.  *
  21.  * @author Nicolas Grekas <p@tchwork.com>
  22.  */
  23. final class LockRegistry
  24. {
  25.     private static $openedFiles = [];
  26.     private static $lockedFiles;
  27.     private static $signalingException;
  28.     private static $signalingCallback;
  29.     /**
  30.      * The number of items in this list controls the max number of concurrent processes.
  31.      */
  32.     private static $files = [
  33.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'AbstractAdapter.php',
  34.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'AbstractTagAwareAdapter.php',
  35.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'AdapterInterface.php',
  36.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ApcuAdapter.php',
  37.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ArrayAdapter.php',
  38.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ChainAdapter.php',
  39.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'CouchbaseBucketAdapter.php',
  40.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'CouchbaseCollectionAdapter.php',
  41.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'DoctrineDbalAdapter.php',
  42.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'FilesystemAdapter.php',
  43.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'FilesystemTagAwareAdapter.php',
  44.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'MemcachedAdapter.php',
  45.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'NullAdapter.php',
  46.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ParameterNormalizer.php',
  47.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'PdoAdapter.php',
  48.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'PhpArrayAdapter.php',
  49.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'PhpFilesAdapter.php',
  50.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ProxyAdapter.php',
  51.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'Psr16Adapter.php',
  52.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'RedisAdapter.php',
  53.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'RedisTagAwareAdapter.php',
  54.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TagAwareAdapter.php',
  55.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TagAwareAdapterInterface.php',
  56.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TraceableAdapter.php',
  57.         __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TraceableTagAwareAdapter.php',
  58.     ];
  59.     /**
  60.      * Defines a set of existing files that will be used as keys to acquire locks.
  61.      *
  62.      * @return array The previously defined set of files
  63.      */
  64.     public static function setFiles(array $files): array
  65.     {
  66.         $previousFiles self::$files;
  67.         self::$files $files;
  68.         foreach (self::$openedFiles as $file) {
  69.             if ($file) {
  70.                 flock($file\LOCK_UN);
  71.                 fclose($file);
  72.             }
  73.         }
  74.         self::$openedFiles self::$lockedFiles = [];
  75.         return $previousFiles;
  76.     }
  77.     public static function compute(callable $callbackItemInterface $itembool &$saveCacheInterface $pool\Closure $setMetadata nullLoggerInterface $logger null): mixed
  78.     {
  79.         if ('\\' === \DIRECTORY_SEPARATOR && null === self::$lockedFiles) {
  80.             // disable locking on Windows by default
  81.             self::$files self::$lockedFiles = [];
  82.         }
  83.         $key self::$files abs(crc32($item->getKey())) % \count(self::$files) : -1;
  84.         if ($key || self::$lockedFiles || !$lock self::open($key)) {
  85.             return $callback($item$save);
  86.         }
  87.         self::$signalingException ??= unserialize("O:9:\"Exception\":1:{s:16:\"\0Exception\0trace\";a:0:{}}");
  88.         self::$signalingCallback ??= function () { throw self::$signalingException; };
  89.         while (true) {
  90.             try {
  91.                 // race to get the lock in non-blocking mode
  92.                 $locked flock($lock\LOCK_EX \LOCK_NB$wouldBlock);
  93.                 if ($locked || !$wouldBlock) {
  94.                     $logger?->info(sprintf('Lock %s, now computing item "{key}"'$locked 'acquired' 'not supported'), ['key' => $item->getKey()]);
  95.                     self::$lockedFiles[$key] = true;
  96.                     $value $callback($item$save);
  97.                     if ($save) {
  98.                         if ($setMetadata) {
  99.                             $setMetadata($item);
  100.                         }
  101.                         $pool->save($item->set($value));
  102.                         $save false;
  103.                     }
  104.                     return $value;
  105.                 }
  106.                 // if we failed the race, retry locking in blocking mode to wait for the winner
  107.                 $logger?->info('Item "{key}" is locked, waiting for it to be released', ['key' => $item->getKey()]);
  108.                 flock($lock\LOCK_SH);
  109.             } finally {
  110.                 flock($lock\LOCK_UN);
  111.                 unset(self::$lockedFiles[$key]);
  112.             }
  113.             try {
  114.                 $value $pool->get($item->getKey(), self::$signalingCallback0);
  115.                 $logger?->info('Item "{key}" retrieved after lock was released', ['key' => $item->getKey()]);
  116.                 $save false;
  117.                 return $value;
  118.             } catch (\Exception $e) {
  119.                 if (self::$signalingException !== $e) {
  120.                     throw $e;
  121.                 }
  122.                 $logger?->info('Item "{key}" not found while lock was released, now retrying', ['key' => $item->getKey()]);
  123.             }
  124.         }
  125.         return null;
  126.     }
  127.     /**
  128.      * @return resource|false
  129.      */
  130.     private static function open(int $key)
  131.     {
  132.         if (null !== $h self::$openedFiles[$key] ?? null) {
  133.             return $h;
  134.         }
  135.         set_error_handler(function () {});
  136.         try {
  137.             $h fopen(self::$files[$key], 'r+');
  138.         } finally {
  139.             restore_error_handler();
  140.         }
  141.         return self::$openedFiles[$key] = $h ?: @fopen(self::$files[$key], 'r');
  142.     }
  143. }