Skip to content

Commit f8a7518

Browse files
[Cache] Use namespace versioning for backends that dont support clearing by keys
1 parent ebd14ee commit f8a7518

File tree

8 files changed

+57
-12
lines changed

8 files changed

+57
-12
lines changed

src/Symfony/Component/Cache/Adapter/AbstractAdapter.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ abstract class AbstractAdapter implements AdapterInterface, LoggerAwareInterface
3838
*/
3939
protected function __construct($namespace = '', $defaultLifetime = 0)
4040
{
41-
$this->namespace = '' === $namespace ? '' : $this->getId($namespace).':';
41+
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).':';
4242
if (null !== $this->maxIdLength && strlen($namespace) > $this->maxIdLength - 24) {
4343
throw new InvalidArgumentException(sprintf('Namespace must be %d chars max, %d given ("%s")', $this->maxIdLength - 24, strlen($namespace), $namespace));
4444
}

src/Symfony/Component/Cache/Adapter/ProxyAdapter.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public function __construct(CacheItemPoolInterface $pool, $namespace = '', $defa
3535
{
3636
$this->pool = $pool;
3737
$this->poolHash = $poolHash = spl_object_hash($pool);
38-
$this->namespace = '' === $namespace ? '' : $this->getId($namespace);
38+
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace);
3939
$this->namespaceLen = strlen($namespace);
4040
$this->createCacheItem = \Closure::bind(
4141
function ($key, $innerItem) use ($defaultLifetime, $poolHash) {

src/Symfony/Component/Cache/CacheItem.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,8 @@ public function getPreviousTags()
148148
*
149149
* @param string $key The key to validate
150150
*
151+
* @return string
152+
*
151153
* @throws InvalidArgumentException When $key is not valid
152154
*/
153155
public static function validateKey($key)
@@ -161,6 +163,8 @@ public static function validateKey($key)
161163
if (false !== strpbrk($key, '{}()/\@:')) {
162164
throw new InvalidArgumentException(sprintf('Cache key "%s" contains reserved characters {}()/\@:', $key));
163165
}
166+
167+
return $key;
164168
}
165169

166170
/**

src/Symfony/Component/Cache/Simple/AbstractCache.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ abstract class AbstractCache implements CacheInterface, LoggerAwareInterface
3737
protected function __construct($namespace = '', $defaultLifetime = 0)
3838
{
3939
$this->defaultLifetime = max(0, (int) $defaultLifetime);
40-
$this->namespace = '' === $namespace ? '' : $this->getId($namespace).':';
40+
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).':';
4141
if (null !== $this->maxIdLength && strlen($namespace) > $this->maxIdLength - 24) {
4242
throw new InvalidArgumentException(sprintf('Namespace must be %d chars max, %d given ("%s")', $this->maxIdLength - 24, strlen($namespace), $namespace));
4343
}

src/Symfony/Component/Cache/Tests/CacheItemTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class CacheItemTest extends TestCase
1818
{
1919
public function testValidKey()
2020
{
21-
$this->assertNull(CacheItem::validateKey('foo'));
21+
$this->assertSame('foo', CacheItem::validateKey('foo'));
2222
}
2323

2424
/**

src/Symfony/Component/Cache/Traits/AbstractTrait.php

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ trait AbstractTrait
2424
use LoggerAwareTrait;
2525

2626
private $namespace;
27+
private $namespaceVersion = '';
28+
private $versioningIsEnabled = false;
2729
private $deferred = array();
2830

2931
/**
@@ -102,10 +104,18 @@ public function hasItem($key)
102104
*/
103105
public function clear()
104106
{
107+
if ($cleared = $this->versioningIsEnabled) {
108+
$this->namespaceVersion = 2;
109+
foreach ($this->doFetch(array('@'.$this->namespace)) as $v) {
110+
$this->namespaceVersion = 1 + (int) $v;
111+
}
112+
$this->namespaceVersion .= ':';
113+
$cleared = $this->doSave(array('@'.$this->namespace => $this->namespaceVersion), 0);
114+
}
105115
$this->deferred = array();
106116

107117
try {
108-
return $this->doClear($this->namespace);
118+
return $this->doClear($this->namespace) || $cleared;
109119
} catch (\Exception $e) {
110120
CacheItem::log($this->logger, 'Failed to clear the cache', array('exception' => $e));
111121

@@ -158,6 +168,27 @@ public function deleteItems(array $keys)
158168
return $ok;
159169
}
160170

171+
/**
172+
* Enables/disables versioning of items.
173+
*
174+
* When versioning is enabled, clearing the cache is atomic and doesn't require listing existing keys to proceed,
175+
* but old keys may need garbage collection and extra round-trips to the back-end are required.
176+
*
177+
* Calling this method also clears the memoized namespace version and thus forces a resynchonization of it.
178+
*
179+
* @param bool $enable
180+
*
181+
* @return bool the previous state of versioning
182+
*/
183+
public function enableVersioning($enable = true)
184+
{
185+
$wasEnabled = $this->versioningIsEnabled;
186+
$this->versioningIsEnabled = (bool) $enable;
187+
$this->namespaceVersion = '';
188+
189+
return $wasEnabled;
190+
}
191+
161192
/**
162193
* Like the native unserialize() function but throws an exception if anything goes wrong.
163194
*
@@ -189,11 +220,18 @@ private function getId($key)
189220
{
190221
CacheItem::validateKey($key);
191222

223+
if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
224+
$this->namespaceVersion = '1:';
225+
foreach ($this->doFetch(array('@'.$this->namespace)) as $v) {
226+
$this->namespaceVersion = $v;
227+
}
228+
}
229+
192230
if (null === $this->maxIdLength) {
193-
return $this->namespace.$key;
231+
return $this->namespace.$this->namespaceVersion.$key;
194232
}
195-
if (strlen($id = $this->namespace.$key) > $this->maxIdLength) {
196-
$id = $this->namespace.substr_replace(base64_encode(hash('sha256', $key, true)), ':', -22);
233+
if (strlen($id = $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
234+
$id = $this->namespace.$this->namespaceVersion.substr_replace(base64_encode(hash('sha256', $key, true)), ':', -22);
197235
}
198236

199237
return $id;

src/Symfony/Component/Cache/Traits/MemcachedTrait.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ private function init(\Memcached $client, $namespace, $defaultLifetime)
5454
}
5555

5656
parent::__construct($namespace, $defaultLifetime);
57+
$this->enableVersioning();
5758
}
5859

5960
/**
@@ -242,7 +243,7 @@ protected function doDelete(array $ids)
242243
*/
243244
protected function doClear($namespace)
244245
{
245-
return $this->checkResultCode($this->getClient()->flush());
246+
return false;
246247
}
247248

248249
private function checkResultCode($result)

src/Symfony/Component/Cache/Traits/RedisTrait.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,9 @@ public function init($redisClient, $namespace = '', $defaultLifetime = 0)
4646
if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
4747
throw new InvalidArgumentException(sprintf('RedisAdapter namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
4848
}
49-
if (!$redisClient instanceof \Redis && !$redisClient instanceof \RedisArray && !$redisClient instanceof \RedisCluster && !$redisClient instanceof \Predis\Client) {
49+
if ($redisClient instanceof \RedisCluster) {
50+
$this->enableversioning();
51+
} elseif (!$redisClient instanceof \Redis && !$redisClient instanceof \RedisArray && !$redisClient instanceof \Predis\Client) {
5052
throw new InvalidArgumentException(sprintf('%s() expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\Client, %s given', __METHOD__, is_object($redisClient) ? get_class($redisClient) : gettype($redisClient)));
5153
}
5254
$this->redis = $redisClient;
@@ -171,8 +173,8 @@ protected function doHave($id)
171173
*/
172174
protected function doClear($namespace)
173175
{
174-
// When using a native Redis cluster, clearing the cache cannot work and always returns false.
175-
// Clearing the cache should then be done by any other means (e.g. by restarting the cluster).
176+
// When using a native Redis cluster, clearing the cache is done by versioning in AbstractTrait::clear().
177+
// This means old keys are not really removed until they expire and may need gargage collection.
176178

177179
$cleared = true;
178180
$hosts = array($this->redis);

0 commit comments

Comments
 (0)