bug #38581 [Semaphore] Reset Key lifetime time before we acquire it (jderusse)

This PR was merged into the 5.x branch.

Discussion
----------

[Semaphore] Reset Key lifetime time before we acquire it

| Q             | A
| ------------- | ---
| Branch?       | 5.x
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | /
| License       | MIT
| Doc PR        | /

This is the same issue fixed by #38553 but for Semaphore component.

Commits
-------

e7ffd5d2e7 Reset Key lifetime time in semaphore
This commit is contained in:
Nyholm 2020-10-15 19:46:28 +02:00
commit 1e8916904e
No known key found for this signature in database
GPG Key ID: 1187B6F70C4F519E
3 changed files with 27 additions and 0 deletions

View File

@ -80,6 +80,11 @@ final class Key
return $this->state[$stateKey];
}
public function resetLifetime(): void
{
$this->expiringTime = null;
}
public function reduceLifetime(float $ttlInSeconds)
{
$newTime = microtime(true) + $ttlInSeconds;

View File

@ -66,6 +66,7 @@ final class Semaphore implements SemaphoreInterface, LoggerAwareInterface
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 @@ final class Semaphore implements SemaphoreInterface, LoggerAwareInterface
}
try {
$this->key->resetLifetime();
$this->store->putOffExpiration($this->key, $ttlInSecond);
$this->key->reduceLifetime($ttlInSecond);

View File

@ -252,4 +252,24 @@ class SemaphoreTest extends TestCase
$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());
}
}