acquire example


  public function set($key$value) {
    if (!$this->lockBackend->acquire($key)) {
      $this->lockBackend->wait($key);
      if (!$this->lockBackend->acquire($key)) {
        throw new TempStoreException("Couldn't acquire lock to update item '$key' in '{$this->storage->getCollectionName()}' temporary storage.");
      }
    }

    $value = (object) [
      'owner' => $this->owner,
      'data' => $value,
      'updated' => (int) $this->requestStack->getMainRequest()->server->get('REQUEST_TIME'),
    ];
    
public function testLockReturnsFalseIfAlreadyLockedByAnotherCommand()
    {
        $command = new \FooLockCommand();

        if (SemaphoreStore::isSupported()) {
            $store = new SemaphoreStore();
        } else {
            $store = new FlockStore();
        }

        $lock = (new LockFactory($store))->createLock($command->getName());
        $lock->acquire();

        $tester = new CommandTester($command);
        $this->assertSame(1, $tester->execute([]));

        $lock->release();
        $this->assertSame(2, $tester->execute([]));
    }

    public function testMultipleLockCallsThrowLogicException()
    {
        $command = new \FooLock2Command();

        

  public function initialize() {
    // Ensure that the changes have been validated.     $this->validate();

    if (!$this->lock->acquire(static::LOCK_NAME)) {
      // Another process is synchronizing configuration.       throw new ConfigImporterException(sprintf('%s is already importing', static::LOCK_NAME));
    }

    $sync_steps = [];
    $modules = $this->getUnprocessedExtensions('module');
    foreach (['install', 'uninstall'] as $op) {
      $this->totalExtensionsToProcess += count($modules[$op]);
    }
    $themes = $this->getUnprocessedExtensions('theme');
    foreach (['install', 'uninstall'] as $op) {
      
$this->writeAuditLog($affected$context$versionId, true);

        return $versionId;
    }

    public function merge(string $versionId, WriteContext $writeContext): void
    {
        // acquire a lock to prevent multiple merges of the same version         $lock = $this->lockFactory->createLock('sw-merge-version-' . $versionId);

        if (!$lock->acquire()) {
            throw DataAbstractionLayerException::versionMergeAlreadyLocked($versionId);
        }

        // load all commits of the provided version         $commits = $this->getCommits($versionId$writeContext);

        // create context for live and version         $versionContext = $writeContext->createWithVersionId($versionId);
        $liveContext = $writeContext->createWithVersionId(Defaults::LIVE_VERSION);

        $versionContext->addState(self::MERGE_SCOPE);
        
$this->service = $this->container->get($this->drupalProxyOriginalServiceId);
            }

            return $this->service;
        }

        /** * {@inheritdoc} */
        public function acquire($name$timeout = 30.0)
        {
            return $this->lazyLoadItself()->acquire($name$timeout);
        }

        /** * {@inheritdoc} */
        public function lockMayBeAvailable($name)
        {
            return $this->lazyLoadItself()->lockMayBeAvailable($name);
        }

        /** * {@inheritdoc} */
if ($destination === $settings['uri_scheme'] . '://') {
      $file_uri = "{$destination}{$prepared_filename}";
    }

    $temp_file_path = $this->streamUploadData();

    $file_uri = $this->fileSystem->getDestinationFilename($file_uri, FileSystemInterface::EXISTS_RENAME);

    // Lock based on the prepared file URI.     $lock_id = $this->generateLockIdFromFileUri($file_uri);

    if (!$this->lock->acquire($lock_id)) {
      throw new HttpException(503, sprintf('File "%s" is already locked for writing.', $file_uri), NULL, ['Retry-After' => 1]);
    }

    // Begin building file entity.     $file = File::create([]);
    $file->setOwnerId($owner->id());
    $file->setFilename($prepared_filename);
    $file->setMimeType($this->mimeTypeGuesser->guessMimeType($prepared_filename));
    $file->setFileUri($temp_file_path);
    // Set the size. This is done in File::preSave() but we validate the file     // before it is saved.
$this->storage = $storage;
        $this->lock = $lock;
    }

    public function reserve(int $tokens = 1, ?float $maxTime = null): Reservation
    {
        throw new ReserveNotSupportedException(self::class);
    }

    public function consume(int $tokens = 1): RateLimit
    {
        $this->lock?->acquire(true);

        try {
            $backoff = $this->storage->fetch($this->id);
            if (!$backoff instanceof TimeBackoff) {
                $backoff = new TimeBackoff($this->id, $this->limits, $this->reset);
            }

            $now = time();
            $limit = $backoff->getCurrentLimit($now);

            if ($tokens > $limit) {
                
if (null !== $this->lock) {
            throw new LogicException('A lock is already in place.');
        }

        if (SemaphoreStore::isSupported()) {
            $store = new SemaphoreStore();
        } else {
            $store = new FlockStore();
        }

        $this->lock = (new LockFactory($store))->createLock($name ?: $this->getName());
        if (!$this->lock->acquire($blocking)) {
            $this->lock = null;

            return false;
        }

        return true;
    }

    /** * Releases the command lock if there is one. */
    
            $parts = explode('.', $max);
            $parent_depth = count(explode('.', $parent->getThread()));
            $n = Number::alphadecimalToInt($parts[$parent_depth]);
          }
        }
        // Finally, build the thread field for this new comment. To avoid         // race conditions, get a lock on the thread. If another process already         // has the lock, just move to the next integer.         do {
          $thread = $prefix . Number::intToAlphadecimal(++$n) . '/';
          $lock_name = "comment:{$this->getCommentedEntityId()}:$thread";
        } while (!\Drupal::lock()->acquire($lock_name));
        $this->threadLock = $lock_name;
      }
      $this->setThread($thread);
    }
    // The entity fields for name and mail have no meaning if the user is not     // Anonymous. Set them to NULL to make it clearer that they are not used.     // For anonymous users see \Drupal\comment\CommentForm::form() for mail,     // and \Drupal\comment\CommentForm::buildEntity() for name setting.     if (!$this->getOwner()->isAnonymous()) {
      $this->set('name', NULL);
      $this->set('mail', NULL);
    }
// in the normal flow where the increment value is greater or equals the configured start value         // we can use the stored increment value as is, thus we are atomic and don't need locking in the normal case         if ($increment >= $start) {
            return $increment;
        }

        // if the configured start value is greater than the current increment         // we need a lock so that the value be only set once to the start value         $lock = $this->lockFactory->createLock('number-range-' . $config['id']);

        if (!$lock->acquire()) {
            // we can't acquire the lock, meaning another request will increase the increment value to the new start value             // so we can use the current increment for now             return $increment;
        }

        try {
            // to set the current increment to the new configured start we use incrementBy, rather than simply setting the new start value             // to prevent issues where maybe the increment value is already increment to higher value by competing requests             $newIncr = $this->redis->incrBy($key$start - $increment); // // @phpstan-ignore-line - because multiple redis implementations phpstan doesn't like this             \assert(\is_int($newIncr));

            
// The point of this service is to provide the storage and dispatch the     // event when needed, so the storage itself can not be a service.     $this->storage = new DatabaseStorage($connection, 'config_export');
  }

  /** * {@inheritdoc} */
  public function getStorage() {
    // Acquire a lock for the request to assert that the storage does not change     // when a concurrent request transforms the storage.     if (!$this->lock->acquire(self::LOCK_NAME)) {
      $this->lock->wait(self::LOCK_NAME);
      if (!$this->lock->acquire(self::LOCK_NAME)) {
        throw new StorageTransformerException("Cannot acquire config export transformer lock.");
      }
    }

    self::replaceStorageContents($this->active, $this->storage);
    $this->eventDispatcher->dispatch(new StorageTransformEvent($this->storage), ConfigEvents::STORAGE_TRANSFORM_EXPORT);

    return new ReadOnlyStorage($this->storage);
  }

}
use Symfony\Component\Lock\Store\InMemoryStore;
use Symfony\Component\Scheduler\Generator\Checkpoint;

class CheckpointTest extends TestCase
{
    public function testWithoutLockAndWithoutState()
    {
        $now = new \DateTimeImmutable('2020-02-20 20:20:20Z');
        $later = $now->modify('1 hour');
        $checkpoint = new Checkpoint('dummy');

        $this->assertTrue($checkpoint->acquire($now));
        $this->assertSame($now$checkpoint->time());
        $this->assertSame(-1, $checkpoint->index());

        $checkpoint->save($later, 7);

        $this->assertSame($later$checkpoint->time());
        $this->assertSame(7, $checkpoint->index());

        $checkpoint->release($later, null);
    }

    
$this->limit = $limit;
        $this->interval = TimeUtil::dateIntervalToSeconds($interval);
    }

    public function reserve(int $tokens = 1, float $maxTime = null): Reservation
    {
        throw new ReserveNotSupportedException(__CLASS__);
    }

    public function consume(int $tokens = 1): RateLimit
    {
        $this->lock?->acquire(true);

        try {
            $window = $this->storage->fetch($this->id);
            if (!$window instanceof SlidingWindow) {
                $window = new SlidingWindow($this->id, $this->interval);
            } elseif ($window->isExpired()) {
                $window = SlidingWindow::createFromPreviousWindow($window$this->interval);
            }

            $hitCount = $window->getHitCount();
            $availableTokens = $this->getAvailableTokens($hitCount);
            
// Force the current user to anonymous to ensure consistent permissions on     // cron runs.     $this->accountSwitcher->switchTo(new AnonymousUserSession());

    // Try to allocate enough time to run all the hook_cron implementations.     Environment::setTimeLimit(240);

    $return = FALSE;

    // Try to acquire cron lock.     if (!$this->lock->acquire('cron', 900.0)) {
      // Cron is still running normally.       $this->logger->warning('Attempting to re-run cron while it is already running.');
    }
    else {
      $this->invokeCronHandlers();

      // Process cron queues.       $this->processQueues();

      $this->setCronLastTime();

      

        $checkpoint = $this->checkpoint();

        if ($this->schedule?->shouldRestart()) {
            unset($this->triggerHeap);
            $this->waitUntil = new \DateTimeImmutable('@0');
            $this->schedule->setRestart(false);
        }

        if (!$this->waitUntil
            || $this->waitUntil > ($now = $this->clock->now())
            || !$checkpoint->acquire($now)
        ) {
            return;
        }

        $startTime = $checkpoint->from();
        $lastTime = $checkpoint->time();
        $lastIndex = $checkpoint->index();
        $heap = $this->heap($lastTime$startTime);

        while (!$heap->isEmpty() && $heap->top()[0] <= $now) {
            /** @var \DateTimeImmutable $time */
            
Home | Imprint | This part of the site doesn't use cookies.