Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Lock] Add namespace support to Redis & Memcache lock stores #60227

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
wants to merge 5 commits into
base: 7.4
Choose a base branch
Loading
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
[Lock] Add namespace support to Redis & Memcache lock stores
  • Loading branch information
WaylandAce committed May 16, 2025
commit e674445f832a15130d6e7309cee9725d1908a3b6
1 change: 1 addition & 0 deletions 1 src/Symfony/Component/Lock/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Add support for `valkey:` / `valkeys:` schemes
* RedisStore and MemcacheStore namespace support
WaylandAce marked this conversation as resolved.
Show resolved Hide resolved

7.2
---
Expand Down
27 changes: 19 additions & 8 deletions 27 src/Symfony/Component/Lock/Store/MemcachedStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,16 @@ class MemcachedStore implements PersistingStoreInterface
{
use ExpiringStoreTrait;

/**
* @internal
*/
WaylandAce marked this conversation as resolved.
Show resolved Hide resolved
private const NS_SEPARATOR = ':';

private bool $useExtendedReturn;

WaylandAce marked this conversation as resolved.
Show resolved Hide resolved
private string $namespace = '';


WaylandAce marked this conversation as resolved.
Show resolved Hide resolved
public static function isSupported(): bool
{
return \extension_loaded('memcached');
Expand All @@ -39,6 +47,7 @@ public static function isSupported(): bool
public function __construct(
private \Memcached $memcached,
private int $initialTtl = 300,
private array $options = [],
) {
if (!static::isSupported()) {
throw new InvalidArgumentException('Memcached extension is required.');
Expand All @@ -47,13 +56,15 @@ public function __construct(
if ($initialTtl < 1) {
throw new InvalidArgumentException(\sprintf('"%s()" expects a strictly positive TTL. Got %d.', __METHOD__, $initialTtl));
}

$this->namespace = isset($this->options['namespace']) ? $this->options['namespace'] . static::NS_SEPARATOR : '';
}

public function save(Key $key): void
{
$token = $this->getUniqueToken($key);
$key->reduceLifetime($this->initialTtl);
if (!$this->memcached->add((string) $key, $token, (int) ceil($this->initialTtl))) {
if (!$this->memcached->add($this->namespace . $key, $token, (int) ceil($this->initialTtl))) {
WaylandAce marked this conversation as resolved.
Show resolved Hide resolved
// the lock is already acquired. It could be us. Let's try to put off.
$this->putOffExpiration($key, $this->initialTtl);
}
Expand All @@ -77,7 +88,7 @@ public function putOffExpiration(Key $key, float $ttl): void
$key->reduceLifetime($ttl);
// Could happens when we ask a putOff after a timeout but in luck nobody steal the lock
if (\Memcached::RES_NOTFOUND === $this->memcached->getResultCode()) {
if ($this->memcached->add((string) $key, $token, $ttl)) {
if ($this->memcached->add($this->namespace . $key, $token, $ttl)) {
return;
}

Expand All @@ -90,7 +101,7 @@ public function putOffExpiration(Key $key, float $ttl): void
throw new LockConflictedException();
}

if (!$this->memcached->cas($cas, (string) $key, $token, $ttl)) {
if (!$this->memcached->cas($cas, $this->namespace . $key, $token, $ttl)) {
throw new LockConflictedException();
}

Expand All @@ -109,18 +120,18 @@ public function delete(Key $key): void
}

// To avoid concurrency in deletion, the trick is to extends the TTL then deleting the key
if (!$this->memcached->cas($cas, (string) $key, $token, 2)) {
if (!$this->memcached->cas($cas, $this->namespace . $key, $token, 2)) {
// Someone steal our lock. It does not belongs to us anymore. Nothing to do.
return;
}

// Now, we are the owner of the lock for 2 more seconds, we can delete it.
$this->memcached->delete((string) $key);
$this->memcached->delete($this->namespace . $key);
}

public function exists(Key $key): bool
{
return $this->memcached->get((string) $key) === $this->getUniqueToken($key);
return $this->memcached->get($this->namespace . $key) === $this->getUniqueToken($key);
}

private function getUniqueToken(Key $key): string
Expand All @@ -136,7 +147,7 @@ private function getUniqueToken(Key $key): string
private function getValueAndCas(Key $key): array
{
if ($this->useExtendedReturn ??= version_compare(phpversion('memcached'), '2.9.9', '>')) {
$extendedReturn = $this->memcached->get((string) $key, null, \Memcached::GET_EXTENDED);
$extendedReturn = $this->memcached->get($this->namespace . $key, null, \Memcached::GET_EXTENDED);
if (\Memcached::GET_ERROR_RETURN_VALUE === $extendedReturn) {
return [$extendedReturn, 0.0];
}
Expand All @@ -145,7 +156,7 @@ private function getValueAndCas(Key $key): array
}

$cas = 0.0;
$value = $this->memcached->get((string) $key, null, $cas);
$value = $this->memcached->get($this->namespace . $key, null, $cas);

return [$value, $cas];
}
Expand Down
23 changes: 18 additions & 5 deletions 23 src/Symfony/Component/Lock/Store/RedisStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,32 @@ class RedisStore implements SharedLockStoreInterface
use ExpiringStoreTrait;

private const NO_SCRIPT_ERROR_MESSAGE_PREFIX = 'NOSCRIPT';
/**
* @internal
*/
WaylandAce marked this conversation as resolved.
Show resolved Hide resolved
private const NS_SEPARATOR = ':';

private bool $supportTime;

private string $namespace = '';

/**
* @param float $initialTtl The expiration delay of locks in seconds
* @param array $options See below
*
* Options:
* namespace: Prefix used for keys
*/
public function __construct(
private \Redis|Relay|RelayCluster|\RedisArray|\RedisCluster|\Predis\ClientInterface $redis,
private float $initialTtl = 300.0,
private array $options = [],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why use an array of options rather than give the namespace directly?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to use namespace parameter directly, but I tried to keep style similar to other stores (DoctrineDbalStore, MongoDbStore, PdoStore, PostgreSqlStore)

) {
if ($initialTtl <= 0) {
throw new InvalidTtlException(\sprintf('"%s()" expects a strictly positive TTL. Got %d.', __METHOD__, $initialTtl));
}

$this->namespace = isset($this->options['namespace']) ? $this->options['namespace'] . static::NS_SEPARATOR : '';
}

public function save(Key $key): void
Expand Down Expand Up @@ -85,7 +98,7 @@ public function save(Key $key): void
';

$key->reduceLifetime($this->initialTtl);
if (!$this->evaluate($script, (string) $key, [microtime(true), $this->getUniqueToken($key), (int) ceil($this->initialTtl * 1000)])) {
if (!$this->evaluate($script, $this->namespace . $key, [microtime(true), $this->getUniqueToken($key), (int) ceil($this->initialTtl * 1000)])) {
throw new LockConflictedException();
}

Expand Down Expand Up @@ -125,7 +138,7 @@ public function saveRead(Key $key): void
';

$key->reduceLifetime($this->initialTtl);
if (!$this->evaluate($script, (string) $key, [microtime(true), $this->getUniqueToken($key), (int) ceil($this->initialTtl * 1000)])) {
if (!$this->evaluate($script, $this->namespace . $key, [microtime(true), $this->getUniqueToken($key), (int) ceil($this->initialTtl * 1000)])) {
throw new LockConflictedException();
}

Expand Down Expand Up @@ -165,7 +178,7 @@ public function putOffExpiration(Key $key, float $ttl): void
';

$key->reduceLifetime($ttl);
if (!$this->evaluate($script, (string) $key, [microtime(true), $this->getUniqueToken($key), (int) ceil($ttl * 1000)])) {
if (!$this->evaluate($script, $this->namespace . $key, [microtime(true), $this->getUniqueToken($key), (int) ceil($ttl * 1000)])) {
throw new LockConflictedException();
}

Expand Down Expand Up @@ -199,7 +212,7 @@ public function delete(Key $key): void
return true
';

$this->evaluate($script, (string) $key, [$this->getUniqueToken($key)]);
$this->evaluate($script, $this->namespace . $key, [$this->getUniqueToken($key)]);
}

public function exists(Key $key): bool
Expand All @@ -225,7 +238,7 @@ public function exists(Key $key): bool
return false
';

return (bool) $this->evaluate($script, (string) $key, [microtime(true), $this->getUniqueToken($key)]);
return (bool) $this->evaluate($script, $this->namespace . $key, [microtime(true), $this->getUniqueToken($key)]);
}

private function evaluate(string $script, string $resource, array $args): mixed
Expand Down
14 changes: 13 additions & 1 deletion 14 src/Symfony/Component/Lock/Store/StoreFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,21 @@ public static function createStore(#[\SensitiveParameter] object|string $connect
throw new InvalidArgumentException('Unsupported Redis or Memcached DSN. Try running "composer require symfony/cache".');
}
$storeClass = str_starts_with($connection, 'memcached:') ? MemcachedStore::class : RedisStore::class;

$matches = [];
$namespace = '';
if (preg_match('/^(.*[\?&])namespace=([^&#]*)&?(([^#]*).*)$/', $connection, $matches)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can't we use parse_url instead of this logic?

also, don't we need something similar on MemcachedStore?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's general to both stores (StoreFactory class).
parse_url cant be used here, because redis dsn string is not always URL format compatible. Also this approach is used in MongoDbStore (collection paramerer), with "options" array as well.

$prefix = $matches[1];
$namespace = $matches[2];
if (empty($matches[4])) {
$prefix = substr($prefix, 0, -1);
}
$connection = $prefix.$matches[3];
}

$connection = AbstractAdapter::createConnection($connection, ['lazy' => true]);

return new $storeClass($connection);
return new $storeClass($connection, ['namespace' => $namespace]);

case str_starts_with($connection, 'mongodb'):
return new MongoDbStore($connection);
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.