Debian Codegraph @

tests/phpunit/includes/Storage/NameTableStoreTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Storage;
4
5 use MediaWiki\Storage\NameTableAccessException;
6 use MediaWiki\Storage\NameTableStore;
7 use MediaWikiIntegrationTestCase;
8 use PHPUnit\Framework\MockObject\MockObject;
9 use Psr\Log\NullLogger;
10 use Wikimedia\ObjectCache\BagOStuff;
11 use Wikimedia\ObjectCache\EmptyBagOStuff;
12 use Wikimedia\ObjectCache\HashBagOStuff;
13 use Wikimedia\ObjectCache\WANObjectCache;
14 use Wikimedia\Rdbms\IDatabase;
15 use Wikimedia\Rdbms\InsertQueryBuilder;
16 use Wikimedia\Rdbms\LoadBalancer;
17 use Wikimedia\Rdbms\SelectQueryBuilder;
18 use Wikimedia\TestingAccessWrapper;
19
20 /**
21 * @author Addshore
22 * @group Database
23 * @covers \MediaWiki\Storage\NameTableStore
24 */
25 class NameTableStoreTest extends MediaWikiIntegrationTestCase {
26
27 private function populateTable( $values ) {
28 if ( !$values ) {
29 return;
30 }
31 $insertValues = [];
32 foreach ( $values as $name ) {
33 $insertValues[] = [ 'role_name' => $name ];
34 }
35 $this->getDb()->newInsertQueryBuilder()
36 ->insertInto( 'slot_roles' )
37 ->rows( $insertValues )
38 ->caller( __METHOD__ )
39 ->execute();
40 }
41
42 private function getHashWANObjectCache( $cacheBag ) {
43 return new WANObjectCache( [ 'cache' => $cacheBag ] );
44 }
45
46 /**
47 * @param IDatabase $db
48 * @return LoadBalancer
49 */
50 private function getMockLoadBalancer( $db ) {
51 $mock = $this->createMock( LoadBalancer::class );
52 $mock->method( 'getConnection' )->willReturn( $db );
53 return $mock;
54 }
55
56 /**
57 * @param int $insertCalls
58 * @param int $selectCalls
59 * @param int $selectFieldCalls
60 *
61 * @return MockObject&IDatabase
62 */
63 private function getProxyDb( $insertCalls, $selectCalls, $selectFieldCalls ) {
64 $proxiedMethods = [
65 'select' => $selectCalls,
66 'insert' => $insertCalls,
67 'selectField' => $selectFieldCalls,
68 'affectedRows' => null,
69 'insertId' => null,
70 'getSessionLagStatus' => null,
71 'onTransactionPreCommitOrIdle' => null,
72 'doAtomicSection' => null,
73 'begin' => null,
74 'rollback' => null,
75 'commit' => null,
76 ];
77 $mock = $this->createMock( IDatabase::class );
78 foreach ( $proxiedMethods as $method => $count ) {
79 $mock->expects( is_int( $count ) ? $this->exactly( $count ) : $this->any() )
80 ->method( $method )
81 ->willReturnCallback( function ( ...$args ) use ( $method ) {
82 return $this->getDb()->$method( ...$args );
83 } );
84 }
85 $mock->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $mock ) );
86 $mock->method( 'newInsertQueryBuilder' )->willReturnCallback( static fn () => new InsertQueryBuilder( $mock ) );
87 return $mock;
88 }
89
90 private function getNameTableSqlStore(
91 BagOStuff $cacheBag,
92 $insertCalls,
93 $selectCalls,
94 $selectFieldCalls,
95 $normalizationCallback = null,
96 $insertCallback = null
97 ) {
98 return new NameTableStore(
99 $this->getMockLoadBalancer(
100 $this->getProxyDb( $insertCalls, $selectCalls, $selectFieldCalls )
101 ),
102 $this->getHashWANObjectCache( $cacheBag ),
103 new NullLogger(),
104 'slot_roles', 'role_id', 'role_name',
105 $normalizationCallback,
106 false,
107 $insertCallback
108 );
109 }
110
111 public static function provideGetAndAcquireId() {
112 return [
113 'no wancache, empty table' =>
114 [ new EmptyBagOStuff(), true, 1, [], 'foo', 1 ],
115 'no wancache, one matching value' =>
116 [ new EmptyBagOStuff(), false, 1, [ 'foo' ], 'foo', 1 ],
117 'no wancache, one not matching value' =>
118 [ new EmptyBagOStuff(), true, 1, [ 'bar' ], 'foo', 2 ],
119 'no wancache, multiple, one matching value' =>
120 [ new EmptyBagOStuff(), false, 1, [ 'foo', 'bar' ], 'bar', 2 ],
121 'no wancache, multiple, no matching value' =>
122 [ new EmptyBagOStuff(), true, 1, [ 'foo', 'bar' ], 'baz', 3 ],
123 'wancache, empty table' =>
124 [ new HashBagOStuff(), true, 1, [], 'foo', 1 ],
125 'wancache, one matching value' =>
126 [ new HashBagOStuff(), false, 1, [ 'foo' ], 'foo', 1 ],
127 'wancache, one not matching value' =>
128 [ new HashBagOStuff(), true, 1, [ 'bar' ], 'foo', 2 ],
129 'wancache, multiple, one matching value' =>
130 [ new HashBagOStuff(), false, 1, [ 'foo', 'bar' ], 'bar', 2 ],
131 'wancache, multiple, no matching value' =>
132 [ new HashBagOStuff(), true, 1, [ 'foo', 'bar' ], 'baz', 3 ],
133 ];
134 }
135
136 /**
137 * @dataProvider provideGetAndAcquireId
138 * @param BagOStuff $cacheBag to use in the WANObjectCache service
139 * @param bool $needsInsert Does the value we are testing need to be inserted?
140 * @param int $selectCalls Number of times the select DB method will be called
141 * @param string[] $existingValues to be added to the db table
142 * @param string $name name to acquire
143 * @param int $expectedId the id we expect the name to have
144 */
145 public function testGetAndAcquireId(
146 $cacheBag,
147 $needsInsert,
148 $selectCalls,
149 $existingValues,
150 $name,
151 $expectedId
152 ) {
153 $this->populateTable( $existingValues );
154 $store = $this->getNameTableSqlStore( $cacheBag, (int)$needsInsert, $selectCalls, 0 );
155
156 // Some names will not initially exist
157 try {
158 $result = $store->getId( $name );
159 $this->assertSame( $expectedId, $result );
160 } catch ( NameTableAccessException $e ) {
161 if ( $needsInsert ) {
162 $this->assertTrue( true ); // Expected exception
163 } else {
164 $this->fail( 'Did not expect an exception, but got one: ' . $e->getMessage() );
165 }
166 }
167
168 // All names should return their id here
169 $this->assertSame( $expectedId, $store->acquireId( $name ) );
170
171 // acquireId inserted these names, so now everything should exist with getId
172 $this->assertSame( $expectedId, $store->getId( $name ) );
173
174 // calling getId again will also still work, and not result in more selects
175 $this->assertSame( $expectedId, $store->getId( $name ) );
176 }
177
178 public static function provideTestGetAndAcquireIdNameNormalization() {
179 yield [ 'A', 'a', 'strtolower' ];
180 yield [ 'b', 'B', 'strtoupper' ];
181 yield [ 'X', 'X', static fn ( $name ) => $name ];
182 yield [ 'ZZ', 'ZZ-a', static fn ( $name ) => "$name-a" ];
183 }
184
185 /**
186 * @dataProvider provideTestGetAndAcquireIdNameNormalization
187 */
188 public function testGetAndAcquireIdNameNormalization(
189 $nameIn,
190 $nameOut,
191 $normalizationCallback
192 ) {
193 $store = $this->getNameTableSqlStore(
194 new EmptyBagOStuff(),
195 1,
196 1,
197 0,
198 $normalizationCallback
199 );
200 $acquiredId = $store->acquireId( $nameIn );
201 $this->assertSame( $nameOut, $store->getName( $acquiredId ) );
202 }
203
204 public static function provideGetName() {
205 return [
206 [ new HashBagOStuff(), 3, 2 ],
207 [ new EmptyBagOStuff(), 3, 3 ],
208 ];
209 }
210
211 /**
212 * @dataProvider provideGetName
213 */
214 public function testGetName( BagOStuff $cacheBag, $insertCalls, $selectCalls ) {
215 $now = microtime( true );
216 $cacheBag->setMockTime( $now );
217 // Check for operations to in-memory cache (IMC) and persistent cache (PC)
218 $store = $this->getNameTableSqlStore( $cacheBag, $insertCalls, $selectCalls, 0 );
219
220 // Get 1 ID and make sure getName returns correctly
221 $fooId = $store->acquireId( 'foo' ); // regen PC, set IMC, update IMC, tombstone PC
222 $now += 0.01;
223 $this->assertSame( 'foo', $store->getName( $fooId ) ); // use IMC
224 $now += 0.01;
225
226 // Get another ID and make sure getName returns correctly
227 $barId = $store->acquireId( 'bar' ); // update IMC, tombstone PC
228 $now += 0.01;
229 $this->assertSame( 'bar', $store->getName( $barId ) ); // use IMC
230 $now += 0.01;
231
232 // Blitz the cache and make sure it still returns
233 TestingAccessWrapper::newFromObject( $store )->tableCache = null; // clear IMC
234 $this->assertSame( 'foo', $store->getName( $fooId ) ); // regen interim PC, set IMC
235 $this->assertSame( 'bar', $store->getName( $barId ) ); // use IMC
236
237 // Blitz the cache again and get another ID and make sure getName returns correctly
238 TestingAccessWrapper::newFromObject( $store )->tableCache = null; // clear IMC
239 $bazId = $store->acquireId( 'baz' ); // set IMC using interim PC, update IMC, tombstone PC
240 $now += 0.01;
241 $this->assertSame( 'baz', $store->getName( $bazId ) ); // uses IMC
242 $this->assertSame( 'baz', $store->getName( $bazId ) ); // uses IMC
243 }
244
245 public function testGetName_masterFallback() {
246 $store = $this->getNameTableSqlStore( new EmptyBagOStuff(), 1, 2, 0 );
247
248 // Insert a new name
249 $fooId = $store->acquireId( 'foo' );
250
251 // Empty the process cache, getCachedTable() will now return this empty array
252 TestingAccessWrapper::newFromObject( $store )->tableCache = [];
253
254 // getName should fallback to master, which is why we assert 2 selectCalls above
255 $this->assertSame( 'foo', $store->getName( $fooId ) );
256 }
257
258 public function testGetMap_empty() {
259 $this->populateTable( [] );
260 $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 1, 0 );
261 $table = $store->getMap();
262 $this->assertSame( [], $table );
263 }
264
265 public function testGetMap_twoValues() {
266 $this->populateTable( [ 'foo', 'bar' ] );
267 $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 1, 0 );
268
269 // We are using a cache, so 2 calls should only result in 1 select on the db
270 $store->getMap();
271 $table = $store->getMap();
272
273 $expected = [ 1 => 'foo', 2 => 'bar' ];
274 $this->assertSame( $expected, $table );
275 // Make sure the table returned is the same as the cached table
276 $this->assertSame( $expected, TestingAccessWrapper::newFromObject( $store )->tableCache );
277 }
278
279 public function testReloadMap() {
280 $this->populateTable( [ 'foo' ] );
281 $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 2, 0 );
282
283 // force load
284 $this->assertCount( 1, $store->getMap() );
285
286 // add more stuff to the table, so the cache gets out of sync
287 $this->populateTable( [ 'bar' ] );
288
289 $expected = [ 1 => 'foo', 2 => 'bar' ];
290 $this->assertSame( $expected, $store->reloadMap() );
291 $this->assertSame( $expected, $store->getMap() );
292 }
293
294 public function testCacheRaceCondition() {
295 $wanHashBag = new HashBagOStuff();
296 $store1 = $this->getNameTableSqlStore( $wanHashBag, 1, 1, 0 );
297 $store2 = $this->getNameTableSqlStore( $wanHashBag, 1, 0, 0 );
298 $store3 = $this->getNameTableSqlStore( $wanHashBag, 2, 0, 2 );
299
300 // Cache the current table in the instances we will use
301 // This simulates multiple requests running simultaneously
302 $store1->getMap();
303 $store2->getMap();
304 $store3->getMap();
305
306 // Store 2 separate names using different instances
307 $fooId = $store1->acquireId( 'foo' );
308 $barId = $store2->acquireId( 'bar' );
309
310 // Each of these instances should be aware of what they have inserted
311 $this->assertSame( $fooId, $store1->acquireId( 'foo' ) );
312 $this->assertSame( $barId, $store2->acquireId( 'bar' ) );
313
314 // A new store should be able to get both of these new Ids
315 // Note: before there was a race condition here where acquireId( 'bar' ) would update the
316 // cache with data missing the 'foo' key that it was not aware of
317 $store4 = $this->getNameTableSqlStore( $wanHashBag, 0, 1, 0 );
318 $this->assertSame( $fooId, $store4->getId( 'foo' ) );
319 $this->assertSame( $barId, $store4->getId( 'bar' ) );
320
321 // If a store with old cached data tries to acquire these we will get the same ids.
322 $this->assertSame( $fooId, $store3->acquireId( 'foo' ) );
323 $this->assertSame( $barId, $store3->acquireId( 'bar' ) );
324 }
325
326 public function testGetAndAcquireIdInsertCallback() {
327 // Postgres does not allow to specify the SERIAL column on insert to fake an id
328 $this->markTestSkippedIfDbType( 'postgres' );
329
330 $store = $this->getNameTableSqlStore(
331 new EmptyBagOStuff(),
332 1,
333 1,
334 0,
335 null,
336 static function ( $insertFields ) {
337 $insertFields['role_id'] = 7251;
338 return $insertFields;
339 }
340 );
341 $this->assertSame( 7251, $store->acquireId( 'A' ) );
342 }
343 }