Merge "Add comments to ApiBase::isWriteMode()"
[lhc/web/wiklou.git] / includes / cache / BacklinkCache.php
1 <?php
2 /**
3 * Class for fetching backlink lists, approximate backlink counts and
4 * partitions.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @author Tim Starling
23 * @author Aaron Schulz
24 * @copyright © 2009, Tim Starling, Domas Mituzas
25 * @copyright © 2010, Max Sem
26 * @copyright © 2011, Antoine Musso
27 */
28
29 use Wikimedia\Rdbms\ResultWrapper;
30 use Wikimedia\Rdbms\FakeResultWrapper;
31 use Wikimedia\Rdbms\IDatabase;
32
33 /**
34 * Class for fetching backlink lists, approximate backlink counts and
35 * partitions. This is a shared cache.
36 *
37 * Instances of this class should typically be fetched with the method
38 * $title->getBacklinkCache().
39 *
40 * Ideally you should only get your backlinks from here when you think
41 * there is some advantage in caching them. Otherwise it's just a waste
42 * of memory.
43 *
44 * Introduced by r47317
45 */
46 class BacklinkCache {
47 /** @var BacklinkCache */
48 protected static $instance;
49
50 /**
51 * Multi dimensions array representing batches. Keys are:
52 * > (string) links table name
53 * > (int) batch size
54 * > 'numRows' : Number of rows for this link table
55 * > 'batches' : [ $start, $end ]
56 *
57 * @see BacklinkCache::partitionResult()
58 *
59 * Cleared with BacklinkCache::clear()
60 * @var array[]
61 */
62 protected $partitionCache = [];
63
64 /**
65 * Contains the whole links from a database result.
66 * This is raw data that will be partitioned in $partitionCache
67 *
68 * Initialized with BacklinkCache::getLinks()
69 * Cleared with BacklinkCache::clear()
70 * @var ResultWrapper[]
71 */
72 protected $fullResultCache = [];
73
74 /**
75 * Local copy of a database object.
76 *
77 * Accessor: BacklinkCache::getDB()
78 * Mutator : BacklinkCache::setDB()
79 * Cleared with BacklinkCache::clear()
80 */
81 protected $db;
82
83 /**
84 * Local copy of a Title object
85 */
86 protected $title;
87
88 const CACHE_EXPIRY = 3600;
89
90 /**
91 * Create a new BacklinkCache
92 *
93 * @param Title $title : Title object to create a backlink cache for
94 */
95 public function __construct( Title $title ) {
96 $this->title = $title;
97 }
98
99 /**
100 * Create a new BacklinkCache or reuse any existing one.
101 * Currently, only one cache instance can exist; callers that
102 * need multiple backlink cache objects should keep them in scope.
103 *
104 * @param Title $title Title object to get a backlink cache for
105 * @return BacklinkCache
106 */
107 public static function get( Title $title ) {
108 if ( !self::$instance || !self::$instance->title->equals( $title ) ) {
109 self::$instance = new self( $title );
110 }
111 return self::$instance;
112 }
113
114 /**
115 * Serialization handler, diasallows to serialize the database to prevent
116 * failures after this class is deserialized from cache with dead DB
117 * connection.
118 *
119 * @return array
120 */
121 function __sleep() {
122 return [ 'partitionCache', 'fullResultCache', 'title' ];
123 }
124
125 /**
126 * Clear locally stored data and database object.
127 */
128 public function clear() {
129 $this->partitionCache = [];
130 $this->fullResultCache = [];
131 unset( $this->db );
132 }
133
134 /**
135 * Set the Database object to use
136 *
137 * @param IDatabase $db
138 */
139 public function setDB( $db ) {
140 $this->db = $db;
141 }
142
143 /**
144 * Get the replica DB connection to the database
145 * When non existing, will initialize the connection.
146 * @return IDatabase
147 */
148 protected function getDB() {
149 if ( !isset( $this->db ) ) {
150 $this->db = wfGetDB( DB_REPLICA );
151 }
152
153 return $this->db;
154 }
155
156 /**
157 * Get the backlinks for a given table. Cached in process memory only.
158 * @param string $table
159 * @param int|bool $startId
160 * @param int|bool $endId
161 * @param int $max
162 * @return TitleArrayFromResult
163 */
164 public function getLinks( $table, $startId = false, $endId = false, $max = INF ) {
165 return TitleArray::newFromResult( $this->queryLinks( $table, $startId, $endId, $max ) );
166 }
167
168 /**
169 * Get the backlinks for a given table. Cached in process memory only.
170 * @param string $table
171 * @param int|bool $startId
172 * @param int|bool $endId
173 * @param int $max
174 * @param string $select 'all' or 'ids'
175 * @return ResultWrapper
176 */
177 protected function queryLinks( $table, $startId, $endId, $max, $select = 'all' ) {
178
179 $fromField = $this->getPrefix( $table ) . '_from';
180
181 if ( !$startId && !$endId && is_infinite( $max )
182 && isset( $this->fullResultCache[$table] )
183 ) {
184 wfDebug( __METHOD__ . ": got results from cache\n" );
185 $res = $this->fullResultCache[$table];
186 } else {
187 wfDebug( __METHOD__ . ": got results from DB\n" );
188 $conds = $this->getConditions( $table );
189 // Use the from field in the condition rather than the joined page_id,
190 // because databases are stupid and don't necessarily propagate indexes.
191 if ( $startId ) {
192 $conds[] = "$fromField >= " . intval( $startId );
193 }
194 if ( $endId ) {
195 $conds[] = "$fromField <= " . intval( $endId );
196 }
197 $options = [ 'ORDER BY' => $fromField ];
198 if ( is_finite( $max ) && $max > 0 ) {
199 $options['LIMIT'] = $max;
200 }
201
202 if ( $select === 'ids' ) {
203 // Just select from the backlink table and ignore the page JOIN
204 $res = $this->getDB()->select(
205 $table,
206 [ $this->getPrefix( $table ) . '_from AS page_id' ],
207 array_filter( $conds, function ( $clause ) { // kind of janky
208 return !preg_match( '/(\b|=)page_id(\b|=)/', $clause );
209 } ),
210 __METHOD__,
211 $options
212 );
213 } else {
214 // Select from the backlink table and JOIN with page title information
215 $res = $this->getDB()->select(
216 [ $table, 'page' ],
217 [ 'page_namespace', 'page_title', 'page_id' ],
218 $conds,
219 __METHOD__,
220 array_merge( [ 'STRAIGHT_JOIN' ], $options )
221 );
222 }
223
224 if ( $select === 'all' && !$startId && !$endId && $res->numRows() < $max ) {
225 // The full results fit within the limit, so cache them
226 $this->fullResultCache[$table] = $res;
227 } else {
228 wfDebug( __METHOD__ . ": results from DB were uncacheable\n" );
229 }
230 }
231
232 return $res;
233 }
234
235 /**
236 * Get the field name prefix for a given table
237 * @param string $table
238 * @throws MWException
239 * @return null|string
240 */
241 protected function getPrefix( $table ) {
242 static $prefixes = [
243 'pagelinks' => 'pl',
244 'imagelinks' => 'il',
245 'categorylinks' => 'cl',
246 'templatelinks' => 'tl',
247 'redirect' => 'rd',
248 ];
249
250 if ( isset( $prefixes[$table] ) ) {
251 return $prefixes[$table];
252 } else {
253 $prefix = null;
254 Hooks::run( 'BacklinkCacheGetPrefix', [ $table, &$prefix ] );
255 if ( $prefix ) {
256 return $prefix;
257 } else {
258 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
259 }
260 }
261 }
262
263 /**
264 * Get the SQL condition array for selecting backlinks, with a join
265 * on the page table.
266 * @param string $table
267 * @throws MWException
268 * @return array|null
269 */
270 protected function getConditions( $table ) {
271 $prefix = $this->getPrefix( $table );
272
273 switch ( $table ) {
274 case 'pagelinks':
275 case 'templatelinks':
276 $conds = [
277 "{$prefix}_namespace" => $this->title->getNamespace(),
278 "{$prefix}_title" => $this->title->getDBkey(),
279 "page_id={$prefix}_from"
280 ];
281 break;
282 case 'redirect':
283 $conds = [
284 "{$prefix}_namespace" => $this->title->getNamespace(),
285 "{$prefix}_title" => $this->title->getDBkey(),
286 $this->getDB()->makeList( [
287 "{$prefix}_interwiki" => '',
288 "{$prefix}_interwiki IS NULL",
289 ], LIST_OR ),
290 "page_id={$prefix}_from"
291 ];
292 break;
293 case 'imagelinks':
294 case 'categorylinks':
295 $conds = [
296 "{$prefix}_to" => $this->title->getDBkey(),
297 "page_id={$prefix}_from"
298 ];
299 break;
300 default:
301 $conds = null;
302 Hooks::run( 'BacklinkCacheGetConditions', [ $table, $this->title, &$conds ] );
303 if ( !$conds ) {
304 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
305 }
306 }
307
308 return $conds;
309 }
310
311 /**
312 * Check if there are any backlinks
313 * @param string $table
314 * @return bool
315 */
316 public function hasLinks( $table ) {
317 return ( $this->getNumLinks( $table, 1 ) > 0 );
318 }
319
320 /**
321 * Get the approximate number of backlinks
322 * @param string $table
323 * @param int $max Only count up to this many backlinks
324 * @return int
325 */
326 public function getNumLinks( $table, $max = INF ) {
327 global $wgUpdateRowsPerJob;
328
329 $cache = ObjectCache::getMainWANInstance();
330 // 1) try partition cache ...
331 if ( isset( $this->partitionCache[$table] ) ) {
332 $entry = reset( $this->partitionCache[$table] );
333
334 return min( $max, $entry['numRows'] );
335 }
336
337 // 2) ... then try full result cache ...
338 if ( isset( $this->fullResultCache[$table] ) ) {
339 return min( $max, $this->fullResultCache[$table]->numRows() );
340 }
341
342 $memcKey = wfMemcKey( 'numbacklinks', md5( $this->title->getPrefixedDBkey() ), $table );
343
344 // 3) ... fallback to memcached ...
345 $count = $cache->get( $memcKey );
346 if ( $count ) {
347 return min( $max, $count );
348 }
349
350 // 4) fetch from the database ...
351 if ( is_infinite( $max ) ) { // no limit at all
352 // Use partition() since it will batch the query and skip the JOIN.
353 // Use $wgUpdateRowsPerJob just to encourage cache reuse for jobs.
354 $this->partition( $table, $wgUpdateRowsPerJob ); // updates $this->partitionCache
355 return $this->partitionCache[$table][$wgUpdateRowsPerJob]['numRows'];
356 } else { // probably some sane limit
357 // Fetch the full title info, since the caller will likely need it next
358 $count = $this->getLinks( $table, false, false, $max )->count();
359 if ( $count < $max ) { // full count
360 $cache->set( $memcKey, $count, self::CACHE_EXPIRY );
361 }
362 }
363
364 return min( $max, $count );
365 }
366
367 /**
368 * Partition the backlinks into batches.
369 * Returns an array giving the start and end of each range. The first
370 * batch has a start of false, and the last batch has an end of false.
371 *
372 * @param string $table The links table name
373 * @param int $batchSize
374 * @return array
375 */
376 public function partition( $table, $batchSize ) {
377 // 1) try partition cache ...
378 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
379 wfDebug( __METHOD__ . ": got from partition cache\n" );
380
381 return $this->partitionCache[$table][$batchSize]['batches'];
382 }
383
384 $cache = ObjectCache::getMainWANInstance();
385 $this->partitionCache[$table][$batchSize] = false;
386 $cacheEntry =& $this->partitionCache[$table][$batchSize];
387
388 // 2) ... then try full result cache ...
389 if ( isset( $this->fullResultCache[$table] ) ) {
390 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
391 wfDebug( __METHOD__ . ": got from full result cache\n" );
392
393 return $cacheEntry['batches'];
394 }
395
396 $memcKey = wfMemcKey(
397 'backlinks',
398 md5( $this->title->getPrefixedDBkey() ),
399 $table,
400 $batchSize
401 );
402
403 // 3) ... fallback to memcached ...
404 $memcValue = $cache->get( $memcKey );
405 if ( is_array( $memcValue ) ) {
406 $cacheEntry = $memcValue;
407 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
408
409 return $cacheEntry['batches'];
410 }
411
412 // 4) ... finally fetch from the slow database :(
413 $cacheEntry = [ 'numRows' => 0, 'batches' => [] ]; // final result
414 // Do the selects in batches to avoid client-side OOMs (T45452).
415 // Use a LIMIT that plays well with $batchSize to keep equal sized partitions.
416 $selectSize = max( $batchSize, 200000 - ( 200000 % $batchSize ) );
417 $start = false;
418 do {
419 $res = $this->queryLinks( $table, $start, false, $selectSize, 'ids' );
420 $partitions = $this->partitionResult( $res, $batchSize, false );
421 // Merge the link count and range partitions for this chunk
422 $cacheEntry['numRows'] += $partitions['numRows'];
423 $cacheEntry['batches'] = array_merge( $cacheEntry['batches'], $partitions['batches'] );
424 if ( count( $partitions['batches'] ) ) {
425 list( , $lEnd ) = end( $partitions['batches'] );
426 $start = $lEnd + 1; // pick up after this inclusive range
427 }
428 } while ( $partitions['numRows'] >= $selectSize );
429 // Make sure the first range has start=false and the last one has end=false
430 if ( count( $cacheEntry['batches'] ) ) {
431 $cacheEntry['batches'][0][0] = false;
432 $cacheEntry['batches'][count( $cacheEntry['batches'] ) - 1][1] = false;
433 }
434
435 // Save partitions to memcached
436 $cache->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
437
438 // Save backlink count to memcached
439 $memcKey = wfMemcKey( 'numbacklinks', md5( $this->title->getPrefixedDBkey() ), $table );
440 $cache->set( $memcKey, $cacheEntry['numRows'], self::CACHE_EXPIRY );
441
442 wfDebug( __METHOD__ . ": got from database\n" );
443
444 return $cacheEntry['batches'];
445 }
446
447 /**
448 * Partition a DB result with backlinks in it into batches
449 * @param ResultWrapper $res Database result
450 * @param int $batchSize
451 * @param bool $isComplete Whether $res includes all the backlinks
452 * @throws MWException
453 * @return array
454 */
455 protected function partitionResult( $res, $batchSize, $isComplete = true ) {
456 $batches = [];
457 $numRows = $res->numRows();
458 $numBatches = ceil( $numRows / $batchSize );
459
460 for ( $i = 0; $i < $numBatches; $i++ ) {
461 if ( $i == 0 && $isComplete ) {
462 $start = false;
463 } else {
464 $rowNum = $i * $batchSize;
465 $res->seek( $rowNum );
466 $row = $res->fetchObject();
467 $start = (int)$row->page_id;
468 }
469
470 if ( $i == ( $numBatches - 1 ) && $isComplete ) {
471 $end = false;
472 } else {
473 $rowNum = min( $numRows - 1, ( $i + 1 ) * $batchSize - 1 );
474 $res->seek( $rowNum );
475 $row = $res->fetchObject();
476 $end = (int)$row->page_id;
477 }
478
479 # Sanity check order
480 if ( $start && $end && $start > $end ) {
481 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
482 }
483
484 $batches[] = [ $start, $end ];
485 }
486
487 return [ 'numRows' => $numRows, 'batches' => $batches ];
488 }
489
490 /**
491 * Get a Title iterator for cascade-protected template/file use backlinks
492 *
493 * @return TitleArray
494 * @since 1.25
495 */
496 public function getCascadeProtectedLinks() {
497 $dbr = $this->getDB();
498
499 // @todo: use UNION without breaking tests that use temp tables
500 $resSets = [];
501 $resSets[] = $dbr->select(
502 [ 'templatelinks', 'page_restrictions', 'page' ],
503 [ 'page_namespace', 'page_title', 'page_id' ],
504 [
505 'tl_namespace' => $this->title->getNamespace(),
506 'tl_title' => $this->title->getDBkey(),
507 'tl_from = pr_page',
508 'pr_cascade' => 1,
509 'page_id = tl_from'
510 ],
511 __METHOD__,
512 [ 'DISTINCT' ]
513 );
514 if ( $this->title->getNamespace() == NS_FILE ) {
515 $resSets[] = $dbr->select(
516 [ 'imagelinks', 'page_restrictions', 'page' ],
517 [ 'page_namespace', 'page_title', 'page_id' ],
518 [
519 'il_to' => $this->title->getDBkey(),
520 'il_from = pr_page',
521 'pr_cascade' => 1,
522 'page_id = il_from'
523 ],
524 __METHOD__,
525 [ 'DISTINCT' ]
526 );
527 }
528
529 // Combine and de-duplicate the results
530 $mergedRes = [];
531 foreach ( $resSets as $res ) {
532 foreach ( $res as $row ) {
533 $mergedRes[$row->page_id] = $row;
534 }
535 }
536
537 return TitleArray::newFromResult(
538 new FakeResultWrapper( array_values( $mergedRes ) ) );
539 }
540 }