Skip to content

[Cache] Add hierarchical invalidation with ContextAwareAdapterInterface #19521

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

Closed
wants to merge 1 commit into from
Closed
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
39 changes: 36 additions & 3 deletions src/Symfony/Component/Cache/Adapter/AbstractAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\CacheException;
use Symfony\Component\Cache\Exception\InvalidArgumentException;

/**
* @author Nicolas Grekas <p@tchwork.com>
*/
abstract class AbstractAdapter implements AdapterInterface, LoggerAwareInterface
abstract class AbstractAdapter implements ContextAwareAdapterInterface, LoggerAwareInterface
{
use LoggerAwareTrait;

Expand All @@ -32,9 +34,17 @@ abstract class AbstractAdapter implements AdapterInterface, LoggerAwareInterface
private $createCacheItem;
private $mergeByLifetime;

/**
* @var int|null The maximum length to enforce for identifiers or null when no limit applies
*/
protected $maxIdLength;

protected function __construct($namespace = '', $defaultLifetime = 0)
{
$this->namespace = '' === $namespace ? '' : $this->getId($namespace);
$this->namespace = '' === $namespace ? '' : $this->getId($namespace).':';
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));
}
$this->createCacheItem = \Closure::bind(
function ($key, $value, $isHit) use ($defaultLifetime) {
$item = new CacheItem();
Expand Down Expand Up @@ -363,6 +373,22 @@ public function commit()
return $ok;
}

/**
* {@inheritdoc}
*/
public function withContext($context)
{
$fork = clone $this;
$fork->deferred = array();
$fork->namespace .= $this->getId($context).':';

if (null !== $this->maxIdLength && strlen($fork->namespace) > $this->maxIdLength - 23) {
throw new CacheException(sprintf('Full namespace must be %d chars max, %d reached ("%s")', $this->maxIdLength - 24, strlen($fork->namespace), substr($fork->namespace, 0, -1)));
}

return $fork;
}

public function __destruct()
{
if ($this->deferred) {
Expand Down Expand Up @@ -401,7 +427,14 @@ private function getId($key)
{
CacheItem::validateKey($key);

return $this->namespace.$key;
if (null === $this->maxIdLength) {
return $this->namespace.$key;
}
if (strlen($id = $this->namespace.$key) > $this->maxIdLength) {
$id = $this->namespace.substr_replace(base64_encode(md5($key, true)), ':', -2);
}

return $id;
}

private function generateItems($items, &$keys)
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/Cache/Adapter/ApcuAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ public function __construct($namespace = '', $defaultLifetime = 0, $version = nu
if (null !== $version) {
CacheItem::validateKey($version);

if (!apcu_exists($version.':'.$namespace)) {
if (!apcu_exists($version.'@'.$namespace)) {
$this->clear($namespace);
apcu_add($version.':'.$namespace, null);
apcu_add($version.'@'.$namespace, null);
}
}
}
Expand Down
24 changes: 23 additions & 1 deletion src/Symfony/Component/Cache/Adapter/ArrayAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@
/**
* @author Nicolas Grekas <p@tchwork.com>
*/
class ArrayAdapter implements AdapterInterface, LoggerAwareInterface
class ArrayAdapter implements ContextAwareAdapterInterface, LoggerAwareInterface
{
use LoggerAwareTrait;

private $storeSerialized;
private $values = array();
private $expiries = array();
private $createCacheItem;
private $forks = array();

/**
* @param int $defaultLifetime
Expand Down Expand Up @@ -115,6 +116,9 @@ public function hasItem($key)
public function clear()
{
$this->values = $this->expiries = array();
foreach ($this->forks as $fork) {
$fork->clear();
}

return true;
}
Expand Down Expand Up @@ -197,6 +201,24 @@ public function commit()
return true;
}

/**
* {@inheritdoc}
*/
public function withContext($context)
{
CacheItem::validateKey($context);

if (isset($this->forks[$context])) {
return $this->forks[$context];
}

$fork = clone $this;
$fork->values = $fork->expiries = array();
$this->forks[$context] = $fork;

return $fork;
}

private function generateItems(array $keys, $now)
{
$f = $this->createCacheItem;
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,6 +14,7 @@
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\CacheException;
use Symfony\Component\Cache\Exception\InvalidArgumentException;

/**
Expand All @@ -24,7 +25,7 @@
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class ChainAdapter implements AdapterInterface
class ChainAdapter implements ContextAwareAdapterInterface
{
private $adapters = array();
private $saveUp;
Expand Down Expand Up @@ -223,4 +224,22 @@ public function commit()

return $committed;
}

/**
* {@inheritdoc}
*/
public function withContext($context)
{
$fork = clone $this;
$fork->adapters = array();

foreach ($this->adapters as $adapter) {
if (!$adapter instanceof ContextAwareAdapterInterface) {
throw new CacheException(sprintf('%s does not implement ContextAwareAdapterInterface.', get_class($adapter)));
}
$fork->adapters[] = $adapter->withContext($context);
}

return $fork;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Cache\Adapter;

use Psr\Cache\CacheException;
use Psr\Cache\InvalidArgumentException;

/**
* Interface for creating contextualized key spaces from existing pools.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface ContextAwareAdapterInterface extends AdapterInterface
{
/**
* Derivates a new cache pool from an existing one by contextualizing its key space.
*
* Contexts add to each others.
* Clearing a parent also clears all its derivated
* pools (but not necessarily their deferred items).
*
* @param string $context A context identifier.
*
* @return self A clone of the current instance, where cache keys are isolated from its parent
*
* @throws InvalidArgumentException When $context contains invalid characters
* @throws CacheException When the adapter can't be forked
*/
public function withContext($context);
}
9 changes: 9 additions & 0 deletions src/Symfony/Component/Cache/Adapter/DoctrineAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Cache\Adapter;

use Doctrine\Common\Cache\CacheProvider;
use Symfony\Component\Cache\Exception\CacheException;

/**
* @author Nicolas Grekas <p@tchwork.com>
Expand All @@ -27,6 +28,14 @@ public function __construct(CacheProvider $provider, $namespace = '', $defaultLi
$provider->setNamespace($namespace);
}

/**
* @inheritdoc}
*/
public function withContext($context)
{
throw new CacheException(sprintf('%s does not implement ContextAwareAdapterInterface.', get_class($this)));
}

/**
* {@inheritdoc}
*/
Expand Down
14 changes: 14 additions & 0 deletions src/Symfony/Component/Cache/Adapter/FilesystemAdapterTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\Cache\Adapter;

use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\InvalidArgumentException;

/**
Expand Down Expand Up @@ -79,6 +80,19 @@ protected function doDelete(array $ids)
return $ok;
}

/**
* {@inheritdoc}
*/
public function withContext($context)
{
CacheItem::validateKey($context);

$fork = clone $this;
$fork->init($context, $this->directory);

return $fork;
}

private function write($file, $data, $expiresAt = null)
{
if (false === @file_put_contents($this->tmp, $data)) {
Expand Down
10 changes: 9 additions & 1 deletion src/Symfony/Component/Cache/Adapter/NullAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
/**
* @author Titouan Galopin <galopintitouan@gmail.com>
*/
class NullAdapter implements AdapterInterface
class NullAdapter implements ContextAwareAdapterInterface
{
private $createCacheItem;

Expand Down Expand Up @@ -110,6 +110,14 @@ public function commit()
return false;
}

/**
* {@inheritdoc}
*/
public function withContext($context)
{
return clone $this;
}

private function generateItems(array $keys)
{
$f = $this->createCacheItem;
Expand Down
19 changes: 18 additions & 1 deletion src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
use Psr\Cache\CacheItemInterface;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\CacheException;

/**
* @author Nicolas Grekas <p@tchwork.com>
*/
class TagAwareAdapter implements TagAwareAdapterInterface
class TagAwareAdapter implements ContextAwareAdapterInterface, TagAwareAdapterInterface
{
const TAGS_PREFIX = "\0tags\0";

Expand Down Expand Up @@ -242,6 +243,22 @@ public function commit()
return $this->itemsAdapter->commit() && $ok;
}

/**
* {@inheritdoc}
*/
public function withContext($context)
{
if (!$this->itemsAdapter instanceof ContextAwareAdapterInterface) {
throw new CacheException(sprintf('%s does not implement ContextAwareAdapterInterface.', get_class($this->itemsAdapter)));
}

$fork = clone $this;
$fork->itemsAdapter = $this->itemsAdapter->withContext($context);
$fork->deferred = array();

return $fork;
}

public function __destruct()
{
$this->commit();
Expand Down
54 changes: 54 additions & 0 deletions src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Cache\Tests\Adapter;

use Cache\IntegrationTests\CachePoolTest;
use Symfony\Component\Cache\Adapter\ContextAwareAdapterInterface;

abstract class AdapterTestCase extends CachePoolTest
{
Expand Down Expand Up @@ -71,6 +72,59 @@ public function testNotUnserializable()
}
$this->assertFalse($item->isHit());
}

public function testContext()
{
if (isset($this->skippedTests[__FUNCTION__])) {
$this->markTestSkipped($this->skippedTests[__FUNCTION__]);

return;
}
$cache = $this->createCachePool();

if (!$cache instanceof ContextAwareAdapterInterface) {
$this->markTestSkipped('ContextAwareAdapterInterface not implemented.');
}

$item = $cache->getItem('foo');
$cache->save($item->set('foo'));

$fork = $cache->withContext('ns');
$item = $fork->getItem('foo');
$this->assertFalse($item->isHit());

$fork->save($item->set('bar'));
$item = $cache->getItem('bar');
$this->assertFalse($item->isHit());

$fork = $cache->withContext('ns');
$item = $fork->getItem('foo');
$this->assertTrue($item->isHit());

$cache->clear();
$item = $fork->getItem('foo');
$this->assertFalse($item->isHit());
}

/**
* @expectedException \Psr\Cache\InvalidArgumentException
* @dataProvider invalidKeys
*/
public function testBadContext($context)
{
if (isset($this->skippedTests[__FUNCTION__])) {
$this->markTestSkipped($this->skippedTests[__FUNCTION__]);

return;
}
$cache = $this->createCachePool();

if (!$cache instanceof ContextAwareAdapterInterface) {
$this->markTestSkipped('ContextAwareAdapterInterface not implemented.');
}

$cache->withContext($context);
}
}

class NotUnserializable implements \Serializable
Expand Down
Loading