From 2bcf34421a11f891c08c13922ae6b5386f0c9fa2 Mon Sep 17 00:00:00 2001 From: Bryan Davis Date: Mon, 22 Feb 2016 18:45:20 -0700 Subject: [PATCH] CachedBagOStuff: cache backend misses Cache misses from the backend cache the same as hits. Bug: T127772 Change-Id: If2fe1920411b24862acea888c627db13717da8bd --- includes/libs/objectcache/CachedBagOStuff.php | 6 ++---- includes/libs/objectcache/HashBagOStuff.php | 13 ++++++++++++- .../libs/objectcache/CachedBagOStuffTest.php | 18 ++++++++++++++++++ 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/includes/libs/objectcache/CachedBagOStuff.php b/includes/libs/objectcache/CachedBagOStuff.php index 798357d596..3d5d383e42 100644 --- a/includes/libs/objectcache/CachedBagOStuff.php +++ b/includes/libs/objectcache/CachedBagOStuff.php @@ -50,11 +50,9 @@ class CachedBagOStuff extends HashBagOStuff { protected function doGet( $key, $flags = 0 ) { $ret = parent::doGet( $key, $flags ); - if ( $ret === false ) { + if ( $ret === false && !$this->hasKey( $key ) ) { $ret = $this->backend->doGet( $key, $flags ); - if ( $ret !== false ) { - $this->set( $key, $ret, 0, self::WRITE_CACHE_ONLY ); - } + $this->set( $key, $ret, 0, self::WRITE_CACHE_ONLY ); } return $ret; } diff --git a/includes/libs/objectcache/HashBagOStuff.php b/includes/libs/objectcache/HashBagOStuff.php index 6e7fb0cae0..e03cec6a2f 100644 --- a/includes/libs/objectcache/HashBagOStuff.php +++ b/includes/libs/objectcache/HashBagOStuff.php @@ -60,8 +60,19 @@ class HashBagOStuff extends BagOStuff { return true; } + /** + * Does this bag have a non-null value for the given key? + * + * @param string $key + * @return bool + * @since 1.27 + */ + protected function hasKey( $key ) { + return isset( $this->bag[$key] ); + } + protected function doGet( $key, $flags = 0 ) { - if ( !isset( $this->bag[$key] ) ) { + if ( !$this->hasKey( $key ) ) { return false; } diff --git a/tests/phpunit/includes/libs/objectcache/CachedBagOStuffTest.php b/tests/phpunit/includes/libs/objectcache/CachedBagOStuffTest.php index 3b19c9a88e..7fe8055444 100644 --- a/tests/phpunit/includes/libs/objectcache/CachedBagOStuffTest.php +++ b/tests/phpunit/includes/libs/objectcache/CachedBagOStuffTest.php @@ -49,4 +49,22 @@ class CachedBagOStuffTest extends PHPUnit_Framework_TestCase { $cache->delete( 'foo', CachedBagOStuff::WRITE_CACHE_ONLY ); $this->assertEquals( 'old', $cache->get( 'foo' ) ); // Reloaded from backend } + + public function testCacheBackendMisses() { + $backend = new HashBagOStuff; + $cache = new CachedBagOStuff( $backend ); + + // First hit primes the cache with miss from the backend + $this->assertEquals( false, $cache->get( 'foo' ) ); + + // Change the value in the backend + $backend->set( 'foo', true ); + + // Second hit returns the cached miss + $this->assertEquals( false, $cache->get( 'foo' ) ); + + // But a fresh value is read from the backend + $backend->set( 'bar', true ); + $this->assertEquals( true, $cache->get( 'bar' ) ); + } } -- 2.20.1