Skip to content

[Cache] Enable namespace-based invalidation by prefixing keys with backend-native namespace separators #59813

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

Merged
merged 1 commit into from
Mar 23, 2025
Merged
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
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"psr/http-message": "^1.0|^2.0",
"psr/link": "^1.1|^2.0",
"psr/log": "^1|^2|^3",
"symfony/contracts": "^3.5",
"symfony/contracts": "^3.6",
"symfony/polyfill-ctype": "~1.8",
"symfony/polyfill-intl-grapheme": "~1.0",
"symfony/polyfill-intl-icu": "~1.0",
Expand Down Expand Up @@ -218,7 +218,7 @@
"url": "src/Symfony/Contracts",
"options": {
"versions": {
"symfony/contracts": "3.5.x-dev"
"symfony/contracts": "3.6.x-dev"
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@
use Symfony\Component\Yaml\Yaml;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\CallbackInterface;
use Symfony\Contracts\Cache\NamespacedPoolInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
Expand Down Expand Up @@ -2576,6 +2577,10 @@ private function registerCacheConfiguration(array $config, ContainerBuilder $con
$container->registerAliasForArgument($tagAwareId, TagAwareCacheInterface::class, $pool['name'] ?? $name);
$container->registerAliasForArgument($name, CacheInterface::class, $pool['name'] ?? $name);
$container->registerAliasForArgument($name, CacheItemPoolInterface::class, $pool['name'] ?? $name);

if (interface_exists(NamespacedPoolInterface::class)) {
$container->registerAliasForArgument($name, NamespacedPoolInterface::class, $pool['name'] ?? $name);
}
}

$definition->setPublic($pool['public']);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
<tr>
<td class="font-normal text-small text-muted nowrap">{{ loop.index }}</td>
<td class="nowrap">{{ '%0.2f'|format((call.end - call.start) * 1000) }} ms</td>
<td class="nowrap">{{ call.name }}()</td>
<td class="nowrap">{{ call.name }}({{ call.namespace|default('') }})</td>
<td>{{ profiler_dump(call.value.result, maxDepth=2) }}</td>
</tr>
{% endfor %}
Expand Down
23 changes: 18 additions & 5 deletions src/Symfony/Component/Cache/Adapter/AbstractAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@
use Symfony\Component\Cache\Traits\AbstractAdapterTrait;
use Symfony\Component\Cache\Traits\ContractsTrait;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\NamespacedPoolInterface;

/**
* @author Nicolas Grekas <p@tchwork.com>
*/
abstract class AbstractAdapter implements AdapterInterface, CacheInterface, LoggerAwareInterface, ResettableInterface
abstract class AbstractAdapter implements AdapterInterface, CacheInterface, NamespacedPoolInterface, LoggerAwareInterface, ResettableInterface
{
use AbstractAdapterTrait;
use ContractsTrait;
Expand All @@ -37,7 +38,19 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg

protected function __construct(string $namespace = '', int $defaultLifetime = 0)
{
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).static::NS_SEPARATOR;
if ('' !== $namespace) {
if (str_contains($namespace, static::NS_SEPARATOR)) {
if (str_contains($namespace, static::NS_SEPARATOR.static::NS_SEPARATOR)) {
throw new InvalidArgumentException(\sprintf('Cache namespace "%s" contains empty sub-namespace.', $namespace));
}
CacheItem::validateKey(str_replace(static::NS_SEPARATOR, '', $namespace));
} else {
CacheItem::validateKey($namespace);
}
$this->namespace = $namespace.static::NS_SEPARATOR;
}
$this->rootNamespace = $this->namespace;

$this->defaultLifetime = $defaultLifetime;
if (null !== $this->maxIdLength && \strlen($namespace) > $this->maxIdLength - 24) {
throw new InvalidArgumentException(\sprintf('Namespace must be %d chars max, %d given ("%s").', $this->maxIdLength - 24, \strlen($namespace), $namespace));
Expand Down Expand Up @@ -118,7 +131,7 @@ public static function createConnection(#[\SensitiveParameter] string $dsn, arra
return MemcachedAdapter::createConnection($dsn, $options);
}
if (str_starts_with($dsn, 'couchbase:')) {
if (class_exists('CouchbaseBucket') && CouchbaseBucketAdapter::isSupported()) {
if (class_exists(\CouchbaseBucket::class) && CouchbaseBucketAdapter::isSupported()) {
return CouchbaseBucketAdapter::createConnection($dsn, $options);
}

Expand Down Expand Up @@ -159,7 +172,7 @@ public function commit(): bool
$v = $values[$id];
$type = get_debug_type($v);
$message = \sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->namespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->rootNamespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
}
} else {
foreach ($values as $id => $v) {
Expand All @@ -182,7 +195,7 @@ public function commit(): bool
$ok = false;
$type = get_debug_type($v);
$message = \sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->namespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->rootNamespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
}
}

Expand Down
38 changes: 28 additions & 10 deletions src/Symfony/Component/Cache/Adapter/AbstractTagAwareAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\Cache\Traits\AbstractAdapterTrait;
use Symfony\Component\Cache\Traits\ContractsTrait;
use Symfony\Contracts\Cache\NamespacedPoolInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;

/**
Expand All @@ -30,16 +31,33 @@
*
* @internal
*/
abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterface, LoggerAwareInterface, ResettableInterface
abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterface, AdapterInterface, NamespacedPoolInterface, LoggerAwareInterface, ResettableInterface
{
use AbstractAdapterTrait;
use ContractsTrait;

/**
* @internal
*/
protected const NS_SEPARATOR = ':';

private const TAGS_PREFIX = "\1tags\1";

protected function __construct(string $namespace = '', int $defaultLifetime = 0)
{
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).':';
if ('' !== $namespace) {
if (str_contains($namespace, static::NS_SEPARATOR)) {
if (str_contains($namespace, static::NS_SEPARATOR.static::NS_SEPARATOR)) {
throw new InvalidArgumentException(\sprintf('Cache namespace "%s" contains empty sub-namespace.', $namespace));
}
CacheItem::validateKey(str_replace(static::NS_SEPARATOR, '', $namespace));
} else {
CacheItem::validateKey($namespace);
}
$this->namespace = $namespace.static::NS_SEPARATOR;
}
$this->rootNamespace = $this->namespace;

$this->defaultLifetime = $defaultLifetime;
if (null !== $this->maxIdLength && \strlen($namespace) > $this->maxIdLength - 24) {
throw new InvalidArgumentException(\sprintf('Namespace must be %d chars max, %d given ("%s").', $this->maxIdLength - 24, \strlen($namespace), $namespace));
Expand Down Expand Up @@ -70,7 +88,7 @@ static function ($key, $value, $isHit) {
CacheItem::class
);
self::$mergeByLifetime ??= \Closure::bind(
static function ($deferred, &$expiredIds, $getId, $tagPrefix, $defaultLifetime) {
static function ($deferred, &$expiredIds, $getId, $tagPrefix, $defaultLifetime, $rootNamespace) {
$byLifetime = [];
$now = microtime(true);
$expiredIds = [];
Expand Down Expand Up @@ -102,10 +120,10 @@ static function ($deferred, &$expiredIds, $getId, $tagPrefix, $defaultLifetime)
$value['tag-operations'] = ['add' => [], 'remove' => []];
$oldTags = $item->metadata[CacheItem::METADATA_TAGS] ?? [];
foreach (array_diff_key($value['tags'], $oldTags) as $addedTag) {
$value['tag-operations']['add'][] = $getId($tagPrefix.$addedTag);
$value['tag-operations']['add'][] = $getId($tagPrefix.$addedTag, $rootNamespace);
}
foreach (array_diff_key($oldTags, $value['tags']) as $removedTag) {
$value['tag-operations']['remove'][] = $getId($tagPrefix.$removedTag);
$value['tag-operations']['remove'][] = $getId($tagPrefix.$removedTag, $rootNamespace);
}
$value['tags'] = array_keys($value['tags']);

Expand Down Expand Up @@ -168,7 +186,7 @@ protected function doDeleteYieldTags(array $ids): iterable
public function commit(): bool
{
$ok = true;
$byLifetime = (self::$mergeByLifetime)($this->deferred, $expiredIds, $this->getId(...), self::TAGS_PREFIX, $this->defaultLifetime);
$byLifetime = (self::$mergeByLifetime)($this->deferred, $expiredIds, $this->getId(...), self::TAGS_PREFIX, $this->defaultLifetime, $this->rootNamespace);
$retry = $this->deferred = [];

if ($expiredIds) {
Expand All @@ -195,7 +213,7 @@ public function commit(): bool
$v = $values[$id];
$type = get_debug_type($v);
$message = \sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->namespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->rootNamespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
}
} else {
foreach ($values as $id => $v) {
Expand All @@ -219,7 +237,7 @@ public function commit(): bool
$ok = false;
$type = get_debug_type($v);
$message = \sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->namespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->rootNamespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
}
}

Expand All @@ -244,7 +262,7 @@ public function deleteItems(array $keys): bool
try {
foreach ($this->doDeleteYieldTags(array_values($ids)) as $id => $tags) {
foreach ($tags as $tag) {
$tagData[$this->getId(self::TAGS_PREFIX.$tag)][] = $id;
$tagData[$this->getId(self::TAGS_PREFIX.$tag, $this->rootNamespace)][] = $id;
}
}
} catch (\Exception) {
Expand Down Expand Up @@ -283,7 +301,7 @@ public function invalidateTags(array $tags): bool

$tagIds = [];
foreach (array_unique($tags) as $tag) {
$tagIds[] = $this->getId(self::TAGS_PREFIX.$tag);
$tagIds[] = $this->getId(self::TAGS_PREFIX.$tag, $this->rootNamespace);
}

try {
Expand Down
41 changes: 36 additions & 5 deletions src/Symfony/Component/Cache/Adapter/ArrayAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\NamespacedPoolInterface;

/**
* An in-memory cache storage.
Expand All @@ -27,13 +28,14 @@
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInterface, ResettableInterface
class ArrayAdapter implements AdapterInterface, CacheInterface, NamespacedPoolInterface, LoggerAwareInterface, ResettableInterface
{
use LoggerAwareTrait;

private array $values = [];
private array $tags = [];
private array $expiries = [];
private array $subPools = [];

private static \Closure $createCacheItem;

Expand Down Expand Up @@ -226,16 +228,38 @@ public function clear(string $prefix = ''): bool
}
}

if ($this->values) {
return true;
}
return true;
}

foreach ($this->subPools as $pool) {
$pool->clear();
}

$this->values = $this->tags = $this->expiries = [];
$this->subPools = $this->values = $this->tags = $this->expiries = [];

return true;
}

public function withSubNamespace(string $namespace): static
{
CacheItem::validateKey($namespace);

$subPools = $this->subPools;

if (isset($subPools[$namespace])) {
return $subPools[$namespace];
}

$this->subPools = [];
$clone = clone $this;
$clone->clear();

$subPools[$namespace] = $clone;
$this->subPools = $subPools;

return $clone;
}

/**
* Returns all cached values, with cache miss as null.
*/
Expand Down Expand Up @@ -263,6 +287,13 @@ public function reset(): void
$this->clear();
}

public function __clone()
{
foreach ($this->subPools as $i => $pool) {
$this->subPools[$i] = clone $pool;
}
}

private function generateItems(array $keys, float $now, \Closure $f): \Generator
{
foreach ($keys as $i => $key) {
Expand Down
21 changes: 20 additions & 1 deletion src/Symfony/Component/Cache/Adapter/ChainAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\BadMethodCallException;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\Cache\Traits\ContractsTrait;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\NamespacedPoolInterface;
use Symfony\Contracts\Service\ResetInterface;

/**
Expand All @@ -29,7 +31,7 @@
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterface, ResettableInterface
class ChainAdapter implements AdapterInterface, CacheInterface, NamespacedPoolInterface, PruneableInterface, ResettableInterface
{
use ContractsTrait;

Expand Down Expand Up @@ -280,6 +282,23 @@ public function prune(): bool
return $pruned;
}

public function withSubNamespace(string $namespace): static
{
$clone = clone $this;
$adapters = [];

foreach ($this->adapters as $adapter) {
if (!$adapter instanceof NamespacedPoolInterface) {
throw new BadMethodCallException('All adapters must implement NamespacedPoolInterface to support namespaces.');
}

$adapters[] = $adapter->withSubNamespace($namespace);
}
$clone->adapters = $adapters;

return $clone;
}

public function reset(): void
{
foreach ($this->adapters as $adapter) {
Expand Down
6 changes: 3 additions & 3 deletions src/Symfony/Component/Cache/Adapter/DoctrineDbalAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -335,17 +335,17 @@ protected function doSave(array $values, int $lifetime): array|bool
/**
* @internal
*/
protected function getId(mixed $key): string
protected function getId(mixed $key, ?string $namespace = null): string
{
if ('pgsql' !== $this->platformName ??= $this->getPlatformName()) {
return parent::getId($key);
return parent::getId($key, $namespace);
}

if (str_contains($key, "\0") || str_contains($key, '%') || !preg_match('//u', $key)) {
$key = rawurlencode($key);
}

return parent::getId($key);
return parent::getId($key, $namespace);
}

private function getPlatformName(): string
Expand Down
8 changes: 7 additions & 1 deletion src/Symfony/Component/Cache/Adapter/NullAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
use Psr\Cache\CacheItemInterface;
use Symfony\Component\Cache\CacheItem;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\NamespacedPoolInterface;

/**
* @author Titouan Galopin <galopintitouan@gmail.com>
*/
class NullAdapter implements AdapterInterface, CacheInterface
class NullAdapter implements AdapterInterface, CacheInterface, NamespacedPoolInterface
{
private static \Closure $createCacheItem;

Expand Down Expand Up @@ -94,6 +95,11 @@ public function delete(string $key): bool
return $this->deleteItem($key);
}

public function withSubNamespace(string $namespace): static
{
return clone $this;
}

private function generateItems(array $keys): \Generator
{
$f = self::$createCacheItem;
Expand Down
Loading
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy