Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Used blocking operation blPop for locking #45

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 41 additions & 36 deletions src/Kdyby/Redis/ExclusiveLock.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public function setClient(RedisClient $client)
*/
public function calculateTimeout()
{
return time() + abs((int)$this->duration) + 1;
return time() + $this->calculateRelativeTimeout() + 1;
}


Expand All @@ -92,36 +92,27 @@ public function acquireLock($key)
return $this->increaseLockTimeout($key);
}

$start = microtime(TRUE);

$lockKey = $this->formatLock($key);
$maxAttempts = 10;
do {
$sleepTime = 5000;
do {
if ($this->client->setNX($lockKey, $timeout = $this->calculateTimeout())) {
$this->keys[$key] = $timeout;
return TRUE;
}

if ($this->acquireTimeout !== FALSE && (microtime(TRUE) - $start) >= $this->acquireTimeout) {
throw LockException::acquireTimeout();
}

$lockExpiration = $this->client->get($lockKey);
$sleepTime += 2500;

} while (empty($lockExpiration) || ($lockExpiration >= time() && !usleep($sleepTime)));

$oldExpiration = $this->client->getSet($lockKey, $timeout = $this->calculateTimeout());
if ($oldExpiration === $lockExpiration) {
$this->keys[$key] = $timeout;
return TRUE;
}
if ($this->client->sAdd($lockKey . ':control', $lockKey) > 0) {
$this->client->del($lockKey);
$this->client->rPush($lockKey, 1);
}
try {
$result = $this->client->blPop($lockKey, $this->calculateRelativeTimeout());
} catch (Kdyby\Redis\RedisClientException $e) {
LockException::highConcurrency();
}
if (empty($result)) {
throw LockException::acquireTimeout();
}

} while (--$maxAttempts > 0);
$timeout = $this->calculateTimeout();
$this->client->set($lockKey . ':timeout', $timeout);
$this->client->expireAt($lockKey . ':timeout', $timeout);
$this->client->expireAt($lockKey . ':control', $timeout);
$this->keys[$key] = $timeout;

throw LockException::highConcurrency();
return TRUE;
}


Expand All @@ -135,14 +126,15 @@ public function release($key)
return FALSE;
}

if ($this->keys[$key] <= time()) {
unset($this->keys[$key]);
return FALSE;
$timeout = $this->keys[$key];
$lockKey = $this->formatLock($key);
$this->client->del($lockKey . ':timeout');
if ($timeout > time()) {
$this->client->rPush($lockKey, 1);
}

$this->client->del($this->formatLock($key));
unset($this->keys[$key]);
return TRUE;

return $timeout > time();
}


Expand All @@ -161,11 +153,17 @@ public function increaseLockTimeout($key)
throw LockException::durabilityTimedOut();
}

$oldTimeout = $this->client->getSet($this->formatLock($key), $timeout = $this->calculateTimeout());
if ((int)$oldTimeout !== (int)$this->keys[$key]) {
$lockKey = $this->formatLock($key);
$timeout = $this->calculateTimeout();
$oldTimeout = $this->client->getSet($lockKey . ':timeout', $timeout);
if ((int) $oldTimeout !== (int) $this->keys[$key]) {
throw LockException::invalidDuration();
}

$this->client->expireAt($lockKey . ':timeout', $timeout);
$this->client->expireAt($lockKey . ':control', $timeout);
$this->keys[$key] = $timeout;

return TRUE;
}

Expand Down Expand Up @@ -221,6 +219,13 @@ protected function formatLock($key)



protected function calculateRelativeTimeout()
{
return abs((int) ($this->acquireTimeout !== FALSE && $this->acquireTimeout > $this->duration ? $this->acquireTimeout : $this->duration));
}



public function __destruct()
{
$this->releaseAll();
Expand Down
27 changes: 27 additions & 0 deletions tests/KdybyTests/Redis/ExclusiveLock.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,33 @@ class ExclusiveLockTest extends AbstractRedisTestCase
Assert::true($second->acquireLock('foo:bar'));
}



public function testAcquireTimeoutLongerThenLockDuration()
{
$first = new ExclusiveLock($this->client);
$first->acquireTimeout = 4;
$first->duration = 1;
$second = new ExclusiveLock(new RedisClient());
$second->acquireTimeout = 4;
$second->duration = 1;

Assert::true($first->acquireLock('foo:bar'));
sleep(2);

Assert::exception(function () use ($second) {
$second->acquireLock('foo:bar');
}, 'Kdyby\Redis\LockException', 'Lock couldn\'t be acquired. The locking mechanism is giving up. You should kill the request.');
sleep(2);

Assert::true($second->acquireLock('foo:bar'));

Assert::false($first->release('foo:bar'));
Assert::true($second->release('foo:bar'));

Assert::same(1, $this->client->lLen('foo:bar:lock'));
}

}

\run(new ExclusiveLockTest());
18 changes: 9 additions & 9 deletions tests/KdybyTests/Redis/RedisSessionHandler.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ class SessionHandlerTest extends AbstractRedisTestCase

$handler->close(); // unlock

Assert::count(1, $this->client->keys('Nette.Session:*'));
Assert::count(3, $this->client->keys('Nette.Session:*'));
}


Expand Down Expand Up @@ -118,7 +118,7 @@ class SessionHandlerTest extends AbstractRedisTestCase
array('close' => array()),
), $handler->methods);

Assert::count(1, $this->client->keys('Nette.Session:*'));
Assert::count(3, $this->client->keys('Nette.Session:*'));
}


Expand Down Expand Up @@ -178,7 +178,7 @@ class SessionHandlerTest extends AbstractRedisTestCase
array('close' => array()),
), $handler->methods);

Assert::count(1, $this->client->keys('Nette.Session:*'));
Assert::count(5, $this->client->keys('Nette.Session:*'));
}


Expand Down Expand Up @@ -206,7 +206,7 @@ class SessionHandlerTest extends AbstractRedisTestCase
Assert::same(1, $counter->visits);
}, 'Kdyby\Redis\SessionHandlerException', sprintf('Cannot work with non-locked session id %s: Lock couldn\'t be acquired. The locking mechanism is giving up. You should kill the request.', $sessionId));

Assert::count(1, $this->client->keys('Nette.Session:*'));
Assert::count(2, $this->client->keys('Nette.Session:*'));
}


Expand Down Expand Up @@ -265,18 +265,18 @@ class SessionHandlerTest extends AbstractRedisTestCase
$session->close(); // explicit close with unlock
}, 100, 30); // silence, I kill you!

self::assertRange(30, 40, $result[Tester\Runner\Runner::PASSED]);
self::assertRange(30, 45, $result[Tester\Runner\Runner::PASSED]);

// hard unlock
$client->del('Nette.Session:' . $sessionId . ':lock');
// hard unlock
$client->rPush('Nette.Session:' . $sessionId . ':lock', 1);

// open session for visits verify, for second time
$counter = $session->getSection('counter');
self::assertRange(30, 40, $counter->visits);
self::assertRange(30, 45, $counter->visits);

$session->close(); // unlocking drops the key

Assert::count(1, $this->client->keys('Nette.Session:*'));
Assert::count(3, $this->client->keys('Nette.Session:*'));
}


Expand Down