Merge "Make DBAccessBase use DBConnRef, rename $wiki, and hide getLoadBalancer()"
[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->getConnectionRef( $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 $table = $this->reloadMap( ILoadBalancer::CONN_TRX_AUTOCOMMIT );
164
165 $searchResult = array_search( $name, $table, true );
166 if ( $searchResult === false ) {
167 // Insert failed due to IGNORE flag, but DB_MASTER didn't give us the data
168 $m = "No insert possible but master didn't give us a record for " .
169 "'{$name}' in '{$this->table}'";
170 $this->logger->error( $m );
171 throw new NameTableAccessException( $m );
172 }
173 } elseif ( isset( $table[$id] ) ) {
174 throw new NameTableAccessException(
175 "Expected unused ID from database insert for '$name' "
176 . " into '{$this->table}', but ID $id is already associated with"
177 . " the name '{$table[$id]}'! This may indicate database corruption!" );
178 } else {
179 $table[$id] = $name;
180 $searchResult = $id;
181
182 // As store returned an ID we know we inserted so delete from WAN cache
183 $dbw = $this->getDBConnection( DB_MASTER );
184 $dbw->onTransactionPreCommitOrIdle( function () {
185 $this->cache->delete( $this->getCacheKey() );
186 } );
187 }
188 $this->tableCache = $table;
189 }
190
191 return $searchResult;
192 }
193
194 /**
195 * Reloads the name table from the master database, and purges the WAN cache entry.
196 *
197 * @note This should only be called in situations where the local cache has been detected
198 * to be out of sync with the database. There should be no reason to call this method
199 * from outside the NameTabelStore during normal operation. This method may however be
200 * useful in unit tests.
201 *
202 * @param int $connFlags ILoadBalancer::CONN_XXX flags. Optional.
203 *
204 * @return string[] The freshly reloaded name map
205 */
206 public function reloadMap( $connFlags = 0 ) {
207 $dbw = $this->getDBConnection( DB_MASTER, $connFlags );
208 $this->tableCache = $this->loadTable( $dbw );
209 $dbw->onTransactionPreCommitOrIdle( function () {
210 $this->cache->reap( $this->getCacheKey(), INF );
211 } );
212
213 return $this->tableCache;
214 }
215
216 /**
217 * Get the id of the given name.
218 * If the name doesn't exist this will throw.
219 * This should be used in cases where we believe the name already exists or want to check for
220 * existence.
221 *
222 * @param string $name
223 * @throws NameTableAccessException The name does not exist
224 * @return int Id
225 */
226 public function getId( $name ) {
227 Assert::parameterType( 'string', $name, '$name' );
228 $name = $this->normalizeName( $name );
229
230 $table = $this->getTableFromCachesOrReplica();
231 $searchResult = array_search( $name, $table, true );
232
233 if ( $searchResult !== false ) {
234 return $searchResult;
235 }
236
237 throw NameTableAccessException::newFromDetails( $this->table, 'name', $name );
238 }
239
240 /**
241 * Get the name of the given id.
242 * If the id doesn't exist this will throw.
243 * This should be used in cases where we believe the id already exists.
244 *
245 * Note: Calls to this method will result in a master select for non existing IDs.
246 *
247 * @param int $id
248 * @throws NameTableAccessException The id does not exist
249 * @return string name
250 */
251 public function getName( $id ) {
252 Assert::parameterType( 'integer', $id, '$id' );
253
254 $table = $this->getTableFromCachesOrReplica();
255 if ( array_key_exists( $id, $table ) ) {
256 return $table[$id];
257 }
258 $fname = __METHOD__;
259
260 $table = $this->cache->getWithSetCallback(
261 $this->getCacheKey(),
262 $this->cacheTTL,
263 function ( $oldValue, &$ttl, &$setOpts ) use ( $id, $fname ) {
264 // Check if cached value is up-to-date enough to have $id
265 if ( is_array( $oldValue ) && array_key_exists( $id, $oldValue ) ) {
266 // Completely leave the cache key alone
267 $ttl = WANObjectCache::TTL_UNCACHEABLE;
268 // Use the old value
269 return $oldValue;
270 }
271 // Regenerate from replica DB, and master DB if needed
272 foreach ( [ DB_REPLICA, DB_MASTER ] as $source ) {
273 // Log a fallback to master
274 if ( $source === DB_MASTER ) {
275 $this->logger->info(
276 $fname . ' falling back to master select from ' .
277 $this->table . ' with id ' . $id
278 );
279 }
280 $db = $this->getDBConnection( $source );
281 $cacheSetOpts = Database::getCacheSetOptions( $db );
282 $table = $this->loadTable( $db );
283 if ( array_key_exists( $id, $table ) ) {
284 break; // found it
285 }
286 }
287 // Use the value from last source checked
288 $setOpts += $cacheSetOpts;
289
290 return $table;
291 },
292 [ 'minAsOf' => INF ] // force callback run
293 );
294
295 $this->tableCache = $table;
296
297 if ( array_key_exists( $id, $table ) ) {
298 return $table[$id];
299 }
300
301 throw NameTableAccessException::newFromDetails( $this->table, 'id', $id );
302 }
303
304 /**
305 * Get the whole table, in no particular order as a map of ids to names.
306 * This method could be subject to DB or cache lag.
307 *
308 * @return string[] keys are the name ids, values are the names themselves
309 * Example: [ 1 => 'foo', 3 => 'bar' ]
310 */
311 public function getMap() {
312 return $this->getTableFromCachesOrReplica();
313 }
314
315 /**
316 * @return string[]
317 */
318 private function getTableFromCachesOrReplica() {
319 if ( $this->tableCache !== null ) {
320 return $this->tableCache;
321 }
322
323 $table = $this->cache->getWithSetCallback(
324 $this->getCacheKey(),
325 $this->cacheTTL,
326 function ( $oldValue, &$ttl, &$setOpts ) {
327 $dbr = $this->getDBConnection( DB_REPLICA );
328 $setOpts += Database::getCacheSetOptions( $dbr );
329 return $this->loadTable( $dbr );
330 }
331 );
332
333 $this->tableCache = $table;
334
335 return $table;
336 }
337
338 /**
339 * Gets the table from the db
340 *
341 * @param IDatabase $db
342 *
343 * @return string[]
344 */
345 private function loadTable( IDatabase $db ) {
346 $result = $db->select(
347 $this->table,
348 [
349 'id' => $this->idField,
350 'name' => $this->nameField
351 ],
352 [],
353 __METHOD__,
354 [ 'ORDER BY' => 'id' ]
355 );
356
357 $assocArray = [];
358 foreach ( $result as $row ) {
359 $assocArray[$row->id] = $row->name;
360 }
361
362 return $assocArray;
363 }
364
365 /**
366 * Stores the given name in the DB, returning the ID when an insert occurs.
367 *
368 * @param string $name
369 * @return int|null int if we know the ID, null if we don't
370 */
371 private function store( $name ) {
372 Assert::parameterType( 'string', $name, '$name' );
373 Assert::parameter( $name !== '', '$name', 'should not be an empty string' );
374 // Note: this is only called internally so normalization of $name has already occurred.
375
376 $dbw = $this->getDBConnection( DB_MASTER );
377
378 $dbw->insert(
379 $this->table,
380 $this->getFieldsToStore( $name ),
381 __METHOD__,
382 [ 'IGNORE' ]
383 );
384
385 if ( $dbw->affectedRows() === 0 ) {
386 $this->logger->info(
387 'Tried to insert name into table ' . $this->table . ', but value already existed.'
388 );
389 return null;
390 }
391
392 return $dbw->insertId();
393 }
394
395 /**
396 * @param string $name
397 * @return array
398 */
399 private function getFieldsToStore( $name ) {
400 $fields = [ $this->nameField => $name ];
401 if ( $this->insertCallback !== null ) {
402 $fields = call_user_func( $this->insertCallback, $fields );
403 }
404 return $fields;
405 }
406
407 }