Add a TTL to refresh lock

This commit is contained in:
Jérémy Derussé 2018-02-19 13:56:49 +01:00
parent 3303355dbf
commit 3b1f3286d8
No known key found for this signature in database
GPG Key ID: 2083FA5758C473D2
3 changed files with 24 additions and 5 deletions

View File

@ -105,22 +105,25 @@ final class Lock implements LockInterface, LoggerAwareInterface
/**
* {@inheritdoc}
*/
public function refresh()
public function refresh($ttl = null)
{
if (!$this->ttl) {
if (null === $ttl) {
$ttl = $this->ttl;
}
if (!$ttl) {
throw new InvalidArgumentException('You have to define an expiration duration.');
}
try {
$this->key->resetLifetime();
$this->store->putOffExpiration($this->key, $this->ttl);
$this->store->putOffExpiration($this->key, $ttl);
$this->dirty = true;
if ($this->key->isExpired()) {
throw new LockExpiredException(sprintf('Failed to put off the expiration of the "%s" lock within the specified time.', $this->key));
}
$this->logger->info('Expiration defined for "{resource}" lock for "{ttl}" seconds.', array('resource' => $this->key, 'ttl' => $this->ttl));
$this->logger->info('Expiration defined for "{resource}" lock for "{ttl}" seconds.', array('resource' => $this->key, 'ttl' => $ttl));
} catch (LockConflictedException $e) {
$this->dirty = false;
$this->logger->notice('Failed to define an expiration for the "{resource}" lock, someone else acquired the lock.', array('resource' => $this->key));

View File

@ -38,10 +38,12 @@ interface LockInterface
/**
* Increase the duration of an acquired lock.
*
* @param float|null $ttl Maximum expected lock duration in seconds
*
* @throws LockConflictedException If the lock is acquired by someone else
* @throws LockAcquiringException If the lock can not be refreshed
*/
public function refresh();
public function refresh(/* $ttl = null */);
/**
* Returns whether or not the lock is acquired.

View File

@ -97,6 +97,20 @@ class LockTest extends TestCase
$lock->refresh();
}
public function testRefreshCustom()
{
$key = new Key(uniqid(__METHOD__, true));
$store = $this->getMockBuilder(StoreInterface::class)->getMock();
$lock = new Lock($key, $store, 10);
$store
->expects($this->once())
->method('putOffExpiration')
->with($key, 20);
$lock->refresh(20);
}
public function testIsAquired()
{
$key = new Key(uniqid(__METHOD__, true));