3 namespace MediaWiki\Tests\Storage
;
8 use MediaWiki\MediaWikiServices
;
9 use MediaWiki\Storage\NameTableAccessException
;
10 use MediaWiki\Storage\NameTableStore
;
11 use MediaWikiTestCase
;
12 use PHPUnit\Framework\MockObject\MockObject
;
13 use Psr\Log\NullLogger
;
16 use Wikimedia\Rdbms\IDatabase
;
17 use Wikimedia\Rdbms\LoadBalancer
;
18 use Wikimedia\Rdbms\MaintainableDBConnRef
;
19 use Wikimedia\TestingAccessWrapper
;
24 * @covers \MediaWiki\Storage\NameTableStore
26 class NameTableStoreTest
extends MediaWikiTestCase
{
28 public function setUp() {
29 $this->tablesUsed
[] = 'slot_roles';
33 protected function addCoreDBData() {
34 // The default implementation causes the slot_roles to already have content. Skip that.
37 private function populateTable( $values ) {
39 foreach ( $values as $name ) {
40 $insertValues[] = [ 'role_name' => $name ];
42 $this->db
->insert( 'slot_roles', $insertValues );
45 private function getHashWANObjectCache( $cacheBag ) {
46 return new WANObjectCache( [ 'cache' => $cacheBag ] );
51 * @return \PHPUnit_Framework_MockObject_MockObject|LoadBalancer
53 private function getMockLoadBalancer( $db ) {
54 $mock = $this->getMockBuilder( LoadBalancer
::class )
55 ->disableOriginalConstructor()
57 $mock->expects( $this->any() )
58 ->method( 'getConnectionRef' )
59 ->willReturnCallback( function ( $i ) use ( $mock, $db ) {
60 return new MaintainableDBConnRef( $mock, $db, $i );
66 * @param null $insertCalls
67 * @param null $selectCalls
69 * @return MockObject|IDatabase
71 private function getProxyDb( $insertCalls = null, $selectCalls = null ) {
73 'select' => $selectCalls,
74 'insert' => $insertCalls,
75 'affectedRows' => null,
77 'getSessionLagStatus' => null,
78 'writesPending' => null,
79 'onTransactionPreCommitOrIdle' => null,
80 'onAtomicSectionCancel' => null,
81 'doAtomicSection' => null,
86 $mock = $this->getMockBuilder( IDatabase
::class )
87 ->disableOriginalConstructor()
89 foreach ( $proxiedMethods as $method => $count ) {
90 $mock->expects( is_int( $count ) ?
$this->exactly( $count ) : $this->any() )
92 ->willReturnCallback( function ( ...$args ) use ( $method ) {
93 return call_user_func_array( [ $this->db
, $method ], $args );
99 private function getNameTableSqlStore(
103 $normalizationCallback = null,
104 $insertCallback = null
106 return new NameTableStore(
107 $this->getMockLoadBalancer( $this->getProxyDb( $insertCalls, $selectCalls ) ),
108 $this->getHashWANObjectCache( $cacheBag ),
110 'slot_roles', 'role_id', 'role_name',
111 $normalizationCallback,
117 public function provideGetAndAcquireId() {
119 'no wancache, empty table' =>
120 [ new EmptyBagOStuff(), true, 1, [], 'foo', 1 ],
121 'no wancache, one matching value' =>
122 [ new EmptyBagOStuff(), false, 1, [ 'foo' ], 'foo', 1 ],
123 'no wancache, one not matching value' =>
124 [ new EmptyBagOStuff(), true, 1, [ 'bar' ], 'foo', 2 ],
125 'no wancache, multiple, one matching value' =>
126 [ new EmptyBagOStuff(), false, 1, [ 'foo', 'bar' ], 'bar', 2 ],
127 'no wancache, multiple, no matching value' =>
128 [ new EmptyBagOStuff(), true, 1, [ 'foo', 'bar' ], 'baz', 3 ],
129 'wancache, empty table' =>
130 [ new HashBagOStuff(), true, 1, [], 'foo', 1 ],
131 'wancache, one matching value' =>
132 [ new HashBagOStuff(), false, 1, [ 'foo' ], 'foo', 1 ],
133 'wancache, one not matching value' =>
134 [ new HashBagOStuff(), true, 1, [ 'bar' ], 'foo', 2 ],
135 'wancache, multiple, one matching value' =>
136 [ new HashBagOStuff(), false, 1, [ 'foo', 'bar' ], 'bar', 2 ],
137 'wancache, multiple, no matching value' =>
138 [ new HashBagOStuff(), true, 1, [ 'foo', 'bar' ], 'baz', 3 ],
143 * @dataProvider provideGetAndAcquireId
144 * @param BagOStuff $cacheBag to use in the WANObjectCache service
145 * @param bool $needsInsert Does the value we are testing need to be inserted?
146 * @param int $selectCalls Number of times the select DB method will be called
147 * @param string[] $existingValues to be added to the db table
148 * @param string $name name to acquire
149 * @param int $expectedId the id we expect the name to have
151 public function testGetAndAcquireId(
159 // Make sure the table is empty!
160 $this->truncateTable( 'slot_roles' );
162 $this->populateTable( $existingValues );
163 $store = $this->getNameTableSqlStore( $cacheBag, (int)$needsInsert, $selectCalls );
165 // Some names will not initially exist
167 $result = $store->getId( $name );
168 $this->assertSame( $expectedId, $result );
169 } catch ( NameTableAccessException
$e ) {
170 if ( $needsInsert ) {
171 $this->assertTrue( true ); // Expected exception
173 $this->fail( 'Did not expect an exception, but got one: ' . $e->getMessage() );
177 // All names should return their id here
178 $this->assertSame( $expectedId, $store->acquireId( $name ) );
180 // acquireId inserted these names, so now everything should exist with getId
181 $this->assertSame( $expectedId, $store->getId( $name ) );
183 // calling getId again will also still work, and not result in more selects
184 $this->assertSame( $expectedId, $store->getId( $name ) );
187 public function provideTestGetAndAcquireIdNameNormalization() {
188 yield
[ 'A', 'a', 'strtolower' ];
189 yield
[ 'b', 'B', 'strtoupper' ];
197 yield
[ 'ZZ', 'ZZ-a', __CLASS__
. '::appendDashAToString' ];
200 public static function appendDashAToString( $string ) {
201 return $string . '-a';
205 * @dataProvider provideTestGetAndAcquireIdNameNormalization
207 public function testGetAndAcquireIdNameNormalization(
210 $normalizationCallback
212 $store = $this->getNameTableSqlStore(
213 new EmptyBagOStuff(),
216 $normalizationCallback
218 $acquiredId = $store->acquireId( $nameIn );
219 $this->assertSame( $nameOut, $store->getName( $acquiredId ) );
222 public function provideGetName() {
224 [ new HashBagOStuff(), 3, 2 ],
225 [ new EmptyBagOStuff(), 3, 3 ],
230 * @dataProvider provideGetName
232 public function testGetName( BagOStuff
$cacheBag, $insertCalls, $selectCalls ) {
233 $now = microtime( true );
234 $cacheBag->setMockTime( $now );
235 // Check for operations to in-memory cache (IMC) and persistent cache (PC)
236 $store = $this->getNameTableSqlStore( $cacheBag, $insertCalls, $selectCalls );
238 // Get 1 ID and make sure getName returns correctly
239 $fooId = $store->acquireId( 'foo' ); // regen PC, set IMC, update IMC, tombstone PC
241 $this->assertSame( 'foo', $store->getName( $fooId ) ); // use IMC
244 // Get another ID and make sure getName returns correctly
245 $barId = $store->acquireId( 'bar' ); // update IMC, tombstone PC
247 $this->assertSame( 'bar', $store->getName( $barId ) ); // use IMC
250 // Blitz the cache and make sure it still returns
251 TestingAccessWrapper
::newFromObject( $store )->tableCache
= null; // clear IMC
252 $this->assertSame( 'foo', $store->getName( $fooId ) ); // regen interim PC, set IMC
253 $this->assertSame( 'bar', $store->getName( $barId ) ); // use IMC
255 // Blitz the cache again and get another ID and make sure getName returns correctly
256 TestingAccessWrapper
::newFromObject( $store )->tableCache
= null; // clear IMC
257 $bazId = $store->acquireId( 'baz' ); // set IMC using interim PC, update IMC, tombstone PC
259 $this->assertSame( 'baz', $store->getName( $bazId ) ); // uses IMC
260 $this->assertSame( 'baz', $store->getName( $bazId ) ); // uses IMC
263 public function testGetName_masterFallback() {
264 $store = $this->getNameTableSqlStore( new EmptyBagOStuff(), 1, 2 );
267 $fooId = $store->acquireId( 'foo' );
269 // Empty the process cache, getCachedTable() will now return this empty array
270 TestingAccessWrapper
::newFromObject( $store )->tableCache
= [];
272 // getName should fallback to master, which is why we assert 2 selectCalls above
273 $this->assertSame( 'foo', $store->getName( $fooId ) );
276 public function testGetMap_empty() {
277 $this->populateTable( [] );
278 $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 1 );
279 $table = $store->getMap();
280 $this->assertSame( [], $table );
283 public function testGetMap_twoValues() {
284 $this->populateTable( [ 'foo', 'bar' ] );
285 $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 1 );
287 // We are using a cache, so 2 calls should only result in 1 select on the db
289 $table = $store->getMap();
291 $expected = [ 1 => 'foo', 2 => 'bar' ];
292 $this->assertSame( $expected, $table );
293 // Make sure the table returned is the same as the cached table
294 $this->assertSame( $expected, TestingAccessWrapper
::newFromObject( $store )->tableCache
);
297 public function testReloadMap() {
298 $this->populateTable( [ 'foo' ] );
299 $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 2 );
302 $this->assertCount( 1, $store->getMap() );
304 // add more stuff to the table, so the cache gets out of sync
305 $this->populateTable( [ 'bar' ] );
307 $expected = [ 1 => 'foo', 2 => 'bar' ];
308 $this->assertSame( $expected, $store->reloadMap() );
309 $this->assertSame( $expected, $store->getMap() );
312 public function testCacheRaceCondition() {
313 $wanHashBag = new HashBagOStuff();
314 $store1 = $this->getNameTableSqlStore( $wanHashBag, 1, 1 );
315 $store2 = $this->getNameTableSqlStore( $wanHashBag, 1, 0 );
316 $store3 = $this->getNameTableSqlStore( $wanHashBag, 1, 1 );
318 // Cache the current table in the instances we will use
319 // This simulates multiple requests running simultaneously
324 // Store 2 separate names using different instances
325 $fooId = $store1->acquireId( 'foo' );
326 $barId = $store2->acquireId( 'bar' );
328 // Each of these instances should be aware of what they have inserted
329 $this->assertSame( $fooId, $store1->acquireId( 'foo' ) );
330 $this->assertSame( $barId, $store2->acquireId( 'bar' ) );
332 // A new store should be able to get both of these new Ids
333 // Note: before there was a race condition here where acquireId( 'bar' ) would update the
334 // cache with data missing the 'foo' key that it was not aware of
335 $store4 = $this->getNameTableSqlStore( $wanHashBag, 0, 1 );
336 $this->assertSame( $fooId, $store4->getId( 'foo' ) );
337 $this->assertSame( $barId, $store4->getId( 'bar' ) );
339 // If a store with old cached data tries to acquire these we will get the same ids.
340 $this->assertSame( $fooId, $store3->acquireId( 'foo' ) );
341 $this->assertSame( $barId, $store3->acquireId( 'bar' ) );
344 public function testGetAndAcquireIdInsertCallback() {
345 // FIXME: fails under postgres
346 $this->markTestSkippedIfDbType( 'postgres' );
348 $store = $this->getNameTableSqlStore(
349 new EmptyBagOStuff(),
353 function ( $insertFields ) {
354 $insertFields['role_id'] = 7251;
355 return $insertFields;
358 $this->assertSame( 7251, $store->acquireId( 'A' ) );
361 public function testTransactionRollback() {
362 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
364 // Two instances hitting the real database using separate caches.
365 $store1 = new NameTableStore(
367 $this->getHashWANObjectCache( new HashBagOStuff() ),
369 'slot_roles', 'role_id', 'role_name'
371 $store2 = new NameTableStore(
373 $this->getHashWANObjectCache( new HashBagOStuff() ),
375 'slot_roles', 'role_id', 'role_name'
378 $this->db
->begin( __METHOD__
);
379 $fooId = $store1->acquireId( 'foo' );
380 $this->db
->rollback( __METHOD__
);
382 $this->assertSame( $fooId, $store2->getId( 'foo' ) );
383 $this->assertSame( $fooId, $store1->getId( 'foo' ) );
386 public function testTransactionRollbackWithFailedRedo() {
389 $db = $this->getProxyDb( 2 );
390 $db->method( 'insert' )
391 ->willReturnCallback( function () use ( &$insertCalls, $db ) {
393 switch ( $insertCalls ) {
397 throw new RuntimeException( 'Testing' );
403 $lb = $this->getMockBuilder( LoadBalancer
::class )
404 ->disableOriginalConstructor()
406 $lb->method( 'getConnectionRef' )
408 $lb->method( 'resolveDomainID' )
409 ->willReturnArgument( 0 );
411 // Two instances hitting the real database using separate caches.
412 $store1 = new NameTableStore(
414 $this->getHashWANObjectCache( new HashBagOStuff() ),
416 'slot_roles', 'role_id', 'role_name'
419 $this->db
->begin( __METHOD__
);
420 $store1->acquireId( 'foo' );
421 $this->db
->rollback( __METHOD__
);
423 $this->assertArrayNotHasKey( 'foo', $store1->getMap() );
426 public function testTransactionRollbackWithInterference() {
427 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
429 // Two instances hitting the real database using separate caches.
430 $store1 = new NameTableStore(
432 $this->getHashWANObjectCache( new HashBagOStuff() ),
434 'slot_roles', 'role_id', 'role_name'
436 $store2 = new NameTableStore(
438 $this->getHashWANObjectCache( new HashBagOStuff() ),
440 'slot_roles', 'role_id', 'role_name'
443 $this->db
->begin( __METHOD__
);
446 $this->db
->onTransactionResolution(
447 function () use ( $store1, &$quuxId ) {
448 $quuxId = $store1->acquireId( 'quux' );
452 $store1->acquireId( 'foo' );
453 $this->db
->rollback( __METHOD__
);
455 // $store2 should know about the insert by $store1
456 $this->assertSame( $quuxId, $store2->getId( 'quux' ) );
458 // A "best effort" attempt was made to restore the entry for 'foo'
459 // after the transaction failed. This may succeed on some databases like MySQL,
460 // while it fails on others. Since we are giving no guarantee about this,
461 // the only thing we can test here is that acquireId( 'foo' ) returns an
462 // ID that is distinct from the ID of quux (but might be different from the
463 // value returned by the original call to acquireId( 'foo' ).
464 // Note that $store2 will not know about the ID for 'foo' acquired by $store1,
465 // because it's using a separate cache, and getId() does not fall back to
466 // checking the database.
467 $this->assertNotSame( $quuxId, $store1->acquireId( 'foo' ) );
470 public function testTransactionDoubleRollback() {
473 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
474 $store = new NameTableStore(
476 $this->getHashWANObjectCache( new HashBagOStuff() ),
478 'slot_roles', 'role_id', 'role_name'
481 // Nested atomic sections
482 $atomic1 = $this->db
->startAtomic( $fname, $this->db
::ATOMIC_CANCELABLE
);
483 $atomic2 = $this->db
->startAtomic( $fname, $this->db
::ATOMIC_CANCELABLE
);
486 $id = $store->acquireId( 'foo' );
489 $this->db
->cancelAtomic( $fname, $atomic2 );
491 // Should have been re-inserted
493 $this->assertSame( $id, $store->getId( 'foo' ) );
495 // Oops, re-insert was rolled back too.
496 $this->db
->cancelAtomic( $fname, $atomic1 );
498 // This time, no re-insertion happened.
500 $id2 = $store->getId( 'foo' );
501 $this->fail( "Expected NameTableAccessException, got $id2 (originally was $id)" );
502 } catch ( NameTableAccessException
$ex ) {