Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[lhc/web/wiklou.git] / includes / Storage / NameTableStore.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Storage;
22
23 use IExpiringStore;
24 use Psr\Log\LoggerInterface;
25 use WANObjectCache;
26 use Wikimedia\Assert\Assert;
27 use Wikimedia\Rdbms\Database;
28 use Wikimedia\Rdbms\IDatabase;
29 use Wikimedia\Rdbms\ILoadBalancer;
30
31 /**
32 * @author Addshore
33 * @since 1.31
34 */
35 class NameTableStore {
36
37 /** @var ILoadBalancer */
38 private $loadBalancer;
39
40 /** @var WANObjectCache */
41 private $cache;
42
43 /** @var LoggerInterface */
44 private $logger;
45
46 /** @var string[] */
47 private $tableCache = null;
48
49 /** @var bool|string */
50 private $domain = false;
51
52 /** @var int */
53 private $cacheTTL;
54
55 /** @var string */
56 private $table;
57 /** @var string */
58 private $idField;
59 /** @var string */
60 private $nameField;
61 /** @var null|callable */
62 private $normalizationCallback = null;
63 /** @var null|callable */
64 private $insertCallback = null;
65
66 /**
67 * @param ILoadBalancer $dbLoadBalancer A load balancer for acquiring database connections
68 * @param WANObjectCache $cache A cache manager for caching data. This can be the local
69 * wiki's default instance even if $dbDomain refers to a different wiki, since
70 * makeGlobalKey() is used to constructed a key that allows cached names from
71 * the same database to be re-used between wikis. For example, enwiki and frwiki will
72 * use the same cache keys for names from the wikidatawiki database, regardless
73 * of the cache's default key space.
74 * @param LoggerInterface $logger
75 * @param string $table
76 * @param string $idField
77 * @param string $nameField
78 * @param callable|null $normalizationCallback Normalization to be applied to names before being
79 * saved or queried. This should be a callback that accepts and returns a single string.
80 * @param bool|string $dbDomain Database domain ID. Use false for the local database domain.
81 * @param callable|null $insertCallback Callback to change insert fields accordingly.
82 * This parameter was introduced in 1.32
83 */
84 public function __construct(
85 ILoadBalancer $dbLoadBalancer,
86 WANObjectCache $cache,
87 LoggerInterface $logger,
88 $table,
89 $idField,
90 $nameField,
91 callable $normalizationCallback = null,
92 $dbDomain = false,
93 callable $insertCallback = null
94 ) {
95 $this->loadBalancer = $dbLoadBalancer;
96 $this->cache = $cache;
97 $this->logger = $logger;
98 $this->table = $table;
99 $this->idField = $idField;
100 $this->nameField = $nameField;
101 $this->normalizationCallback = $normalizationCallback;
102 $this->domain = $dbDomain;
103 $this->cacheTTL = IExpiringStore::TTL_MONTH;
104 $this->insertCallback = $insertCallback;
105 }
106
107 /**
108 * @param int $index A database index, like DB_MASTER or DB_REPLICA
109 * @param int $flags Database connection flags
110 *
111 * @return IDatabase
112 */
113 private function getDBConnection( $index, $flags = 0 ) {
114 return $this->loadBalancer->getConnection( $index, [], $this->domain, $flags );
115 }
116
117 /**
118 * Gets the cache key for names.
119 *
120 * The cache key is constructed based on the wiki ID passed to the constructor, and allows
121 * sharing of name tables cached for a specific database between wikis.
122 *
123 * @return string
124 */
125 private function getCacheKey() {
126 return $this->cache->makeGlobalKey(
127 'NameTableSqlStore',
128 $this->table,
129 $this->loadBalancer->resolveDomainID( $this->domain )
130 );
131 }
132
133 /**
134 * @param string $name
135 * @return string
136 */
137 private function normalizeName( $name ) {
138 if ( $this->normalizationCallback === null ) {
139 return $name;
140 }
141 return call_user_func( $this->normalizationCallback, $name );
142 }
143
144 /**
145 * Acquire the id of the given name.
146 * This creates a row in the table if it doesn't already exist.
147 *
148 * @param string $name
149 * @throws NameTableAccessException
150 * @return int
151 */
152 public function acquireId( $name ) {
153 Assert::parameterType( 'string', $name, '$name' );
154 $name = $this->normalizeName( $name );
155
156 $table = $this->getTableFromCachesOrReplica();
157 $searchResult = array_search( $name, $table, true );
158 if ( $searchResult === false ) {
159 $id = $this->store( $name );
160 if ( $id === null ) {
161 // RACE: $name was already in the db, probably just inserted, so load from master.
162 // Use DBO_TRX to avoid missing inserts due to other threads or REPEATABLE-READs.
163 // ...but not during unit tests, because we need the fake DB tables of the default
164 // connection.
165 $connFlags = defined( 'MW_PHPUNIT_TEST' ) ? 0 : ILoadBalancer::CONN_TRX_AUTOCOMMIT;
166 $table = $this->reloadMap( $connFlags );
167
168 $searchResult = array_search( $name, $table, true );
169 if ( $searchResult === false ) {
170 // Insert failed due to IGNORE flag, but DB_MASTER didn't give us the data
171 $m = "No insert possible but master didn't give us a record for " .
172 "'{$name}' in '{$this->table}'";
173 $this->logger->error( $m );
174 throw new NameTableAccessException( $m );
175 }
176 } elseif ( isset( $table[$id] ) ) {
177 throw new NameTableAccessException(
178 "Expected unused ID from database insert for '$name' "
179 . " into '{$this->table}', but ID $id is already associated with"
180 . " the name '{$table[$id]}'! This may indicate database corruption!" );
181 } else {
182 $table[$id] = $name;
183 $searchResult = $id;
184
185 // As store returned an ID we know we inserted so delete from WAN cache
186 $dbw = $this->getDBConnection( DB_MASTER );
187 $dbw->onTransactionPreCommitOrIdle( function () {
188 $this->cache->delete( $this->getCacheKey() );
189 } );
190 }
191 $this->tableCache = $table;
192 }
193
194 return $searchResult;
195 }
196
197 /**
198 * Reloads the name table from the master database, and purges the WAN cache entry.
199 *
200 * @note This should only be called in situations where the local cache has been detected
201 * to be out of sync with the database. There should be no reason to call this method
202 * from outside the NameTabelStore during normal operation. This method may however be
203 * useful in unit tests.
204 *
205 * @param int $connFlags ILoadBalancer::CONN_XXX flags. Optional.
206 *
207 * @return string[] The freshly reloaded name map
208 */
209 public function reloadMap( $connFlags = 0 ) {
210 $dbw = $this->getDBConnection( DB_MASTER, $connFlags );
211 $this->tableCache = $this->loadTable( $dbw );
212 $dbw->onTransactionPreCommitOrIdle( function () {
213 $this->cache->reap( $this->getCacheKey(), INF );
214 } );
215
216 return $this->tableCache;
217 }
218
219 /**
220 * Get the id of the given name.
221 * If the name doesn't exist this will throw.
222 * This should be used in cases where we believe the name already exists or want to check for
223 * existence.
224 *
225 * @param string $name
226 * @throws NameTableAccessException The name does not exist
227 * @return int Id
228 */
229 public function getId( $name ) {
230 Assert::parameterType( 'string', $name, '$name' );
231 $name = $this->normalizeName( $name );
232
233 $table = $this->getTableFromCachesOrReplica();
234 $searchResult = array_search( $name, $table, true );
235
236 if ( $searchResult !== false ) {
237 return $searchResult;
238 }
239
240 throw NameTableAccessException::newFromDetails( $this->table, 'name', $name );
241 }
242
243 /**
244 * Get the name of the given id.
245 * If the id doesn't exist this will throw.
246 * This should be used in cases where we believe the id already exists.
247 *
248 * Note: Calls to this method will result in a master select for non existing IDs.
249 *
250 * @param int $id
251 * @throws NameTableAccessException The id does not exist
252 * @return string name
253 */
254 public function getName( $id ) {
255 Assert::parameterType( 'integer', $id, '$id' );
256
257 $table = $this->getTableFromCachesOrReplica();
258 if ( array_key_exists( $id, $table ) ) {
259 return $table[$id];
260 }
261 $fname = __METHOD__;
262
263 $table = $this->cache->getWithSetCallback(
264 $this->getCacheKey(),
265 $this->cacheTTL,
266 function ( $oldValue, &$ttl, &$setOpts ) use ( $id, $fname ) {
267 // Check if cached value is up-to-date enough to have $id
268 if ( is_array( $oldValue ) && array_key_exists( $id, $oldValue ) ) {
269 // Completely leave the cache key alone
270 $ttl = WANObjectCache::TTL_UNCACHEABLE;
271 // Use the old value
272 return $oldValue;
273 }
274 // Regenerate from replica DB, and master DB if needed
275 foreach ( [ DB_REPLICA, DB_MASTER ] as $source ) {
276 // Log a fallback to master
277 if ( $source === DB_MASTER ) {
278 $this->logger->info(
279 $fname . ' falling back to master select from ' .
280 $this->table . ' with id ' . $id
281 );
282 }
283 $db = $this->getDBConnection( $source );
284 $cacheSetOpts = Database::getCacheSetOptions( $db );
285 $table = $this->loadTable( $db );
286 if ( array_key_exists( $id, $table ) ) {
287 break; // found it
288 }
289 }
290 // Use the value from last source checked
291 $setOpts += $cacheSetOpts;
292
293 return $table;
294 },
295 [ 'minAsOf' => INF ] // force callback run
296 );
297
298 $this->tableCache = $table;
299
300 if ( array_key_exists( $id, $table ) ) {
301 return $table[$id];
302 }
303
304 throw NameTableAccessException::newFromDetails( $this->table, 'id', $id );
305 }
306
307 /**
308 * Get the whole table, in no particular order as a map of ids to names.
309 * This method could be subject to DB or cache lag.
310 *
311 * @return string[] keys are the name ids, values are the names themselves
312 * Example: [ 1 => 'foo', 3 => 'bar' ]
313 */
314 public function getMap() {
315 return $this->getTableFromCachesOrReplica();
316 }
317
318 /**
319 * @return string[]
320 */
321 private function getTableFromCachesOrReplica() {
322 if ( $this->tableCache !== null ) {
323 return $this->tableCache;
324 }
325
326 $table = $this->cache->getWithSetCallback(
327 $this->getCacheKey(),
328 $this->cacheTTL,
329 function ( $oldValue, &$ttl, &$setOpts ) {
330 $dbr = $this->getDBConnection( DB_REPLICA );
331 $setOpts += Database::getCacheSetOptions( $dbr );
332 return $this->loadTable( $dbr );
333 }
334 );
335
336 $this->tableCache = $table;
337
338 return $table;
339 }
340
341 /**
342 * Gets the table from the db
343 *
344 * @param IDatabase $db
345 *
346 * @return string[]
347 */
348 private function loadTable( IDatabase $db ) {
349 $result = $db->select(
350 $this->table,
351 [
352 'id' => $this->idField,
353 'name' => $this->nameField
354 ],
355 [],
356 __METHOD__,
357 [ 'ORDER BY' => 'id' ]
358 );
359
360 $assocArray = [];
361 foreach ( $result as $row ) {
362 $assocArray[$row->id] = $row->name;
363 }
364
365 return $assocArray;
366 }
367
368 /**
369 * Stores the given name in the DB, returning the ID when an insert occurs.
370 *
371 * @param string $name
372 * @return int|null int if we know the ID, null if we don't
373 */
374 private function store( $name ) {
375 Assert::parameterType( 'string', $name, '$name' );
376 Assert::parameter( $name !== '', '$name', 'should not be an empty string' );
377 // Note: this is only called internally so normalization of $name has already occurred.
378
379 $dbw = $this->getDBConnection( DB_MASTER );
380
381 $dbw->insert(
382 $this->table,
383 $this->getFieldsToStore( $name ),
384 __METHOD__,
385 [ 'IGNORE' ]
386 );
387
388 if ( $dbw->affectedRows() === 0 ) {
389 $this->logger->info(
390 'Tried to insert name into table ' . $this->table . ', but value already existed.'
391 );
392 return null;
393 }
394
395 return $dbw->insertId();
396 }
397
398 /**
399 * @param string $name
400 * @return array
401 */
402 private function getFieldsToStore( $name ) {
403 $fields = [ $this->nameField => $name ];
404 if ( $this->insertCallback !== null ) {
405 $fields = call_user_func( $this->insertCallback, $fields );
406 }
407 return $fields;
408 }
409
410 }