From 55ad70225a819fa1f2d09c1d4aa77a28b0a6e749 Mon Sep 17 00:00:00 2001 From: Nyholm Date: Tue, 13 Oct 2020 18:10:46 +0200 Subject: [PATCH] [Lock] Reset Key lifetime time before we acquire it --- src/Symfony/Component/Lock/Lock.php | 1 + src/Symfony/Component/Lock/Tests/LockTest.php | 47 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/Symfony/Component/Lock/Lock.php b/src/Symfony/Component/Lock/Lock.php index 41af54727a..1271100550 100644 --- a/src/Symfony/Component/Lock/Lock.php +++ b/src/Symfony/Component/Lock/Lock.php @@ -67,6 +67,7 @@ final class Lock implements LockInterface, LoggerAwareInterface */ public function acquire($blocking = false): bool { + $this->key->resetLifetime(); try { if ($blocking) { if (!$this->store instanceof StoreInterface && !$this->store instanceof BlockingStoreInterface) { diff --git a/src/Symfony/Component/Lock/Tests/LockTest.php b/src/Symfony/Component/Lock/Tests/LockTest.php index d31a6d58aa..acf0a33977 100644 --- a/src/Symfony/Component/Lock/Tests/LockTest.php +++ b/src/Symfony/Component/Lock/Tests/LockTest.php @@ -18,6 +18,7 @@ use Symfony\Component\Lock\Exception\LockConflictedException; use Symfony\Component\Lock\Key; use Symfony\Component\Lock\Lock; use Symfony\Component\Lock\PersistingStoreInterface; +use Symfony\Component\Lock\Store\ExpiringStoreTrait; use Symfony\Component\Lock\StoreInterface; /** @@ -392,4 +393,50 @@ class LockTest extends TestCase yield [[0.1], false]; yield [[-0.1, null], false]; } + + /** + * @group time-sensitive + */ + public function testAcquireTwiceWithExpiration() + { + $key = new Key(uniqid(__METHOD__, true)); + $store = new class() implements PersistingStoreInterface { + use ExpiringStoreTrait; + private $keys = []; + private $initialTtl = 30; + + public function save(Key $key) + { + $key->reduceLifetime($this->initialTtl); + $this->keys[spl_object_hash($key)] = $key; + $this->checkNotExpired($key); + + return true; + } + + public function delete(Key $key) + { + unset($this->keys[spl_object_hash($key)]); + } + + public function exists(Key $key) + { + return isset($this->keys[spl_object_hash($key)]); + } + + public function putOffExpiration(Key $key, $ttl) + { + $key->reduceLifetime($ttl); + $this->checkNotExpired($key); + } + }; + $ttl = 1; + $lock = new Lock($key, $store, $ttl); + + $this->assertTrue($lock->acquire()); + $lock->release(); + sleep($ttl + 1); + $this->assertTrue($lock->acquire()); + $lock->release(); + } }