-
Notifications
You must be signed in to change notification settings - Fork 2
fix(lock): implement Redlock single-instance pattern in LockManagerService #537
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
Open
romanetar
wants to merge
2
commits into
main
Choose a base branch
from
fix/release-on-failed-acquire-and-add-ownership-tokens
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,9 +22,10 @@ | |
| */ | ||
| final class LockManagerService implements ILockManagerService { | ||
|
|
||
| const MaxRetries = 3; | ||
| const MaxRetries = 3; | ||
| const BackOffMultiplier = 2.0; | ||
| const BackOffBaseInterval = 100000; // 1 ms | ||
| const BackOffBaseInterval = 100000; // microseconds | ||
|
|
||
| /** | ||
| * @var ICacheService | ||
| */ | ||
|
|
@@ -41,73 +42,76 @@ public function __construct(ICacheService $cache_service){ | |
| /** | ||
| * @param string $name | ||
| * @param int $lifetime | ||
| * @return LockManagerService | ||
| * @return string ownership token — pass to releaseLock | ||
| * @throws UnacquiredLockException | ||
| */ | ||
| public function acquireLock(string $name, int $lifetime = 3600):LockManagerService | ||
| public function acquireLock(string $name, int $lifetime = 3600): string | ||
| { | ||
| Log::debug(sprintf("LockManagerService::acquireLock name %s lifetime %s",$name, $lifetime)); | ||
| $attempt = 0 ; | ||
| Log::debug(sprintf("LockManagerService::acquireLock name %s lifetime %s", $name, $lifetime)); | ||
| if ($lifetime <= 0) { | ||
| throw new \InvalidArgumentException("Lock lifetime must be greater than zero seconds."); | ||
| } | ||
| $token = bin2hex(random_bytes(16)); | ||
| $attempt = 0; | ||
| do { | ||
| $time = time() + $lifetime + 1; | ||
| $success = $this->cache_service->addSingleValue($name, $time, $time); | ||
| if($success) return $this; | ||
| $wait_interval = self::BackOffBaseInterval * ( self::BackOffMultiplier ^ $attempt ); | ||
| Log::debug(sprintf("LockManagerService::acquireLock name %s retrying in %s microseconds (%s).", $name, $wait_interval, $attempt)); | ||
| $success = $this->cache_service->addSingleValue($name, $token, $lifetime); | ||
| if ($success) { | ||
| return $token; | ||
| } | ||
| $wait_interval = (int)(self::BackOffBaseInterval * (self::BackOffMultiplier ** $attempt)); | ||
| Log::debug(sprintf("LockManagerService::acquireLock name %s retrying in %s µs (attempt %s)", $name, $wait_interval, $attempt)); | ||
| usleep($wait_interval); | ||
| if($attempt >= (self::MaxRetries - 1 )) { | ||
| // only one time we could use this handle | ||
| if ($attempt >= (self::MaxRetries - 1)) { | ||
| Log::error(sprintf("LockManagerService::acquireLock name %s lifetime %s ERROR MAX RETRIES attempt %s", $name, $lifetime, $attempt)); | ||
| throw new UnacquiredLockException(sprintf("lock name %s", $name)); | ||
| } | ||
| ++$attempt; | ||
| } while(1); | ||
| } while (1); | ||
| } | ||
|
|
||
| /** | ||
| * @param string $name | ||
| * @return $this | ||
| * @param string $token ownership token returned by acquireLock | ||
| */ | ||
| public function releaseLock(string $name):LockManagerService | ||
| public function releaseLock(string $name, string $token): void | ||
| { | ||
| Log::debug(sprintf("LockManagerService::releaseLock name %s",$name)); | ||
| $this->cache_service->delete($name); | ||
| return $this; | ||
| Log::debug(sprintf("LockManagerService::releaseLock name %s", $name)); | ||
| $this->cache_service->deleteIfValueMatches($name, $token); | ||
|
Comment on lines
+76
to
+79
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Surface failed ownership-aware releases.
Proposed fix public function releaseLock(string $name, string $token): void
{
Log::debug(sprintf("LockManagerService::releaseLock name %s", $name));
- $this->cache_service->deleteIfValueMatches($name, $token);
+ $released = $this->cache_service->deleteIfValueMatches($name, $token);
+ if (!$released) {
+ Log::warning(sprintf(
+ "LockManagerService::releaseLock name %s was not released; token may have expired, been reacquired, or Redis delete failed",
+ $name
+ ));
+ }
}🤖 Prompt for AI Agents |
||
| } | ||
|
|
||
| /** | ||
| * @param string $name | ||
| * @param Closure $callback | ||
| * @param int $lifetime | ||
| * @return null | ||
| * @return mixed | ||
| * @throws UnacquiredLockException | ||
| * @throws Exception | ||
| */ | ||
| public function lock(string $name, Closure $callback, int $lifetime = 3600) | ||
| public function lock(string $name, Closure $callback, int $lifetime = 3600): mixed | ||
| { | ||
| $token = null; | ||
| $result = null; | ||
| Log::debug(sprintf("LockManagerService::lock name %s lifetime %s", $name, $lifetime)); | ||
|
|
||
| try | ||
| { | ||
| $this->acquireLock($name, $lifetime); | ||
| try { | ||
| $token = $this->acquireLock($name, $lifetime); | ||
| Log::debug(sprintf("LockManagerService::lock name %s calling callback", $name)); | ||
| $result = $callback($this); | ||
| } | ||
| catch(UnacquiredLockException $ex) | ||
| { | ||
| catch(UnacquiredLockException $ex) { | ||
| Log::warning($ex); | ||
| throw $ex; | ||
| } | ||
| catch(Exception $ex) | ||
| { | ||
| catch(Exception $ex) { | ||
| Log::error($ex); | ||
| throw $ex; | ||
| } | ||
| finally { | ||
| $this->releaseLock($name); | ||
| if ($token !== null) { | ||
| $this->releaseLock($name, $token); | ||
| } | ||
| } | ||
| return $result; | ||
| } | ||
|
|
||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| <?php namespace Tests\Integration; | ||
| /** | ||
| * Copyright 2026 OpenStack Foundation | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| **/ | ||
|
|
||
| use Illuminate\Support\Facades\Redis; | ||
| use PHPUnit\Framework\Attributes\Group; | ||
| use services\utils\RedisCacheService; | ||
| use Tests\CreatesApplication; | ||
| use Tests\TestCase; | ||
|
|
||
| /** | ||
| * Integration tests for RedisCacheService::addSingleValue. | ||
| * | ||
| * These tests require a live Redis instance and verify two properties that | ||
| * mocks cannot exercise: | ||
| * | ||
| * 1. Driver compatibility — the variadic SET NX EX form works with the | ||
| * configured Predis/PhpRedis driver. If the driver is switched to | ||
| * PhpRedis, set() returns false on an NX-miss (not null), which would | ||
| * silently break the `!== null` check; this test catches that regression. | ||
| * | ||
| * 2. Atomicity — key and TTL are written in a single command; there is no | ||
| * window where the key exists without a TTL. Verified by reading TTL | ||
| * immediately after addSingleValue returns. | ||
| * | ||
| */ | ||
| #[Group("integration")] | ||
| final class RedisCacheServiceAddSingleValueTest extends TestCase | ||
| { | ||
| use CreatesApplication; | ||
|
|
||
| private const TEST_KEY = 'test:add_single_value:lock'; | ||
| private const TTL = 30; | ||
|
|
||
| private RedisCacheService $service; | ||
| private mixed $redis; | ||
|
|
||
| protected function setUp(): void | ||
| { | ||
| parent::setUp(); | ||
| $this->redis = Redis::connection(); | ||
| $this->service = new RedisCacheService(); | ||
| // Start clean regardless of any leftover from a previous failed run. | ||
| $this->redis->del(self::TEST_KEY); | ||
| } | ||
|
|
||
| protected function tearDown(): void | ||
| { | ||
| $this->redis->del(self::TEST_KEY); | ||
| parent::tearDown(); | ||
| } | ||
|
|
||
| /** | ||
| * First call must succeed and leave a TTL on the key. | ||
| * Second call on the same key must return false (NX semantics). | ||
| */ | ||
| public function testAddSingleValueSetsKeyWithTtlAndNxSemanticsHold(): void | ||
| { | ||
| $token = bin2hex(random_bytes(16)); | ||
|
|
||
| $acquired = $this->service->addSingleValue(self::TEST_KEY, $token, self::TTL); | ||
| $this->assertTrue($acquired, 'first addSingleValue must return true'); | ||
|
|
||
| // Atomicity: TTL must already be set — no gap between key write and expire. | ||
| $ttl = (int)$this->redis->ttl(self::TEST_KEY); | ||
| $this->assertGreaterThanOrEqual(1, $ttl, 'key must have a positive TTL immediately after addSingleValue'); | ||
| $this->assertLessThanOrEqual(self::TTL, $ttl, 'TTL must not exceed the requested lifetime'); | ||
|
|
||
| // NX semantics: a second call while the key still exists must fail. | ||
| $again = $this->service->addSingleValue(self::TEST_KEY, bin2hex(random_bytes(16)), self::TTL); | ||
| $this->assertFalse($again, 'addSingleValue must return false when key already exists (NX)'); | ||
| } | ||
|
|
||
| /** | ||
| * After the key is deleted the lock can be re-acquired, confirming the | ||
| * return-value contract holds across both the true and false branches. | ||
| */ | ||
| public function testAddSingleValueReturnsTrueAfterKeyIsDeleted(): void | ||
| { | ||
| $token = bin2hex(random_bytes(16)); | ||
|
|
||
| $this->assertTrue($this->service->addSingleValue(self::TEST_KEY, $token, self::TTL)); | ||
| $this->redis->del(self::TEST_KEY); | ||
| $this->assertTrue( | ||
| $this->service->addSingleValue(self::TEST_KEY, bin2hex(random_bytes(16)), self::TTL), | ||
| 'addSingleValue must return true once the key has been removed' | ||
| ); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.