From e7ffd5d2e795b8896cc853ae3884df92f385ee5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Deruss=C3=A9?= Date: Thu, 15 Oct 2020 10:19:08 +0200 Subject: [PATCH] Reset Key lifetime time in semaphore --- src/Symfony/Component/Semaphore/Key.php | 5 +++++ src/Symfony/Component/Semaphore/Semaphore.php | 2 ++ .../Semaphore/Tests/SemaphoreTest.php | 20 +++++++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/src/Symfony/Component/Semaphore/Key.php b/src/Symfony/Component/Semaphore/Key.php index 741b795f18c01..b2ba8db50acea 100644 --- a/src/Symfony/Component/Semaphore/Key.php +++ b/src/Symfony/Component/Semaphore/Key.php @@ -80,6 +80,11 @@ public function getState(string $stateKey) return $this->state[$stateKey]; } + public function resetLifetime(): void + { + $this->expiringTime = null; + } + public function reduceLifetime(float $ttlInSeconds) { $newTime = microtime(true) + $ttlInSeconds; diff --git a/src/Symfony/Component/Semaphore/Semaphore.php b/src/Symfony/Component/Semaphore/Semaphore.php index 931d675a929cb..a65e2bc289996 100644 --- a/src/Symfony/Component/Semaphore/Semaphore.php +++ b/src/Symfony/Component/Semaphore/Semaphore.php @@ -66,6 +66,7 @@ public function __destruct() public function acquire(): bool { try { + $this->key->resetLifetime(); $this->store->save($this->key, $this->ttlInSecond); $this->key->reduceLifetime($this->ttlInSecond); $this->dirty = true; @@ -97,6 +98,7 @@ public function refresh(?float $ttlInSecond = null) } try { + $this->key->resetLifetime(); $this->store->putOffExpiration($this->key, $ttlInSecond); $this->key->reduceLifetime($ttlInSecond); diff --git a/src/Symfony/Component/Semaphore/Tests/SemaphoreTest.php b/src/Symfony/Component/Semaphore/Tests/SemaphoreTest.php index 9efe71b9c3e65..556c8aad2396b 100644 --- a/src/Symfony/Component/Semaphore/Tests/SemaphoreTest.php +++ b/src/Symfony/Component/Semaphore/Tests/SemaphoreTest.php @@ -252,4 +252,24 @@ public function testExpiration() $semaphore = new Semaphore($key, $store); $this->assertTrue($semaphore->isExpired()); } + + /** + * @group time-sensitive + */ + public function testExpirationResetAfter() + { + $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + + $key = new Key('key', 1); + $semaphore = new Semaphore($key, $store, 1); + + $semaphore->acquire(); + $this->assertFalse($semaphore->isExpired()); + $semaphore->release(); + + sleep(2); + + $semaphore->acquire(); + $this->assertFalse($semaphore->isExpired()); + } }