97b7665b08524588acf904729ee732ab8c1937b3
[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 /**
30 * Class for fetching backlink lists, approximate backlink counts and
31 * partitions. This is a shared cache.
32 *
33 * Instances of this class should typically be fetched with the method
34 * $title->getBacklinkCache().
35 *
36 * Ideally you should only get your backlinks from here when you think
37 * there is some advantage in caching them. Otherwise it's just a waste
38 * of memory.
39 *
40 * Introduced by r47317
41 */
42 class BacklinkCache {
43 /** @var ProcessCacheLRU */
44 protected static $cache;
45
46 /**
47 * Multi dimensions array representing batches. Keys are:
48 * > (string) links table name
49 * > (int) batch size
50 * > 'numRows' : Number of rows for this link table
51 * > 'batches' : array( $start, $end )
52 *
53 * @see BacklinkCache::partitionResult()
54 *
55 * Cleared with BacklinkCache::clear()
56 */
57 protected $partitionCache = array();
58
59 /**
60 * Contains the whole links from a database result.
61 * This is raw data that will be partitioned in $partitionCache
62 *
63 * Initialized with BacklinkCache::getLinks()
64 * Cleared with BacklinkCache::clear()
65 */
66 protected $fullResultCache = array();
67
68 /**
69 * Local copy of a database object.
70 *
71 * Accessor: BacklinkCache::getDB()
72 * Mutator : BacklinkCache::setDB()
73 * Cleared with BacklinkCache::clear()
74 */
75 protected $db;
76
77 /**
78 * Local copy of a Title object
79 */
80 protected $title;
81
82 const CACHE_EXPIRY = 3600;
83
84 /**
85 * Create a new BacklinkCache
86 *
87 * @param Title $title : Title object to create a backlink cache for
88 */
89 public function __construct( Title $title ) {
90 $this->title = $title;
91 }
92
93 /**
94 * Create a new BacklinkCache or reuse any existing one.
95 * Currently, only one cache instance can exist; callers that
96 * need multiple backlink cache objects should keep them in scope.
97 *
98 * @param Title $title Title object to get a backlink cache for
99 * @return BacklinkCache
100 */
101 public static function get( Title $title ) {
102 if ( !self::$cache ) { // init cache
103 self::$cache = new ProcessCacheLRU( 1 );
104 }
105 $dbKey = $title->getPrefixedDBkey();
106 if ( !self::$cache->has( $dbKey, 'obj', 3600 ) ) {
107 self::$cache->set( $dbKey, 'obj', new self( $title ) );
108 }
109
110 return self::$cache->get( $dbKey, 'obj' );
111 }
112
113 /**
114 * Serialization handler, diasallows to serialize the database to prevent
115 * failures after this class is deserialized from cache with dead DB
116 * connection.
117 *
118 * @return array
119 */
120 function __sleep() {
121 return array( 'partitionCache', 'fullResultCache', 'title' );
122 }
123
124 /**
125 * Clear locally stored data and database object.
126 */
127 public function clear() {
128 $this->partitionCache = array();
129 $this->fullResultCache = array();
130 unset( $this->db );
131 }
132
133 /**
134 * Set the Database object to use
135 *
136 * @param DatabaseBase $db
137 */
138 public function setDB( $db ) {
139 $this->db = $db;
140 }
141
142 /**
143 * Get the slave connection to the database
144 * When non existing, will initialize the connection.
145 * @return DatabaseBase
146 */
147 protected function getDB() {
148 if ( !isset( $this->db ) ) {
149 $this->db = wfGetDB( DB_SLAVE );
150 }
151
152 return $this->db;
153 }
154
155 /**
156 * Get the backlinks for a given table. Cached in process memory only.
157 * @param string $table
158 * @param int|bool $startId
159 * @param int|bool $endId
160 * @param int|INF $max
161 * @return TitleArrayFromResult
162 */
163 public function getLinks( $table, $startId = false, $endId = false, $max = INF ) {
164 return TitleArray::newFromResult( $this->queryLinks( $table, $startId, $endId, $max ) );
165 }
166
167 /**
168 * Get the backlinks for a given table. Cached in process memory only.
169 * @param string $table
170 * @param int|bool $startId
171 * @param int|bool $endId
172 * @param int|INF $max
173 * @param string $select 'all' or 'ids'
174 * @return ResultWrapper
175 */
176 protected function queryLinks( $table, $startId, $endId, $max, $select = 'all' ) {
177 wfProfileIn( __METHOD__ );
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 = array( '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 array( $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 array( $table, 'page' ),
217 array( 'page_namespace', 'page_title', 'page_id' ),
218 $conds,
219 __METHOD__,
220 array_merge( array( '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 wfProfileOut( __METHOD__ );
233
234 return $res;
235 }
236
237 /**
238 * Get the field name prefix for a given table
239 * @param string $table
240 * @throws MWException
241 * @return null|string
242 */
243 protected function getPrefix( $table ) {
244 static $prefixes = array(
245 'pagelinks' => 'pl',
246 'imagelinks' => 'il',
247 'categorylinks' => 'cl',
248 'templatelinks' => 'tl',
249 'redirect' => 'rd',
250 );
251
252 if ( isset( $prefixes[$table] ) ) {
253 return $prefixes[$table];
254 } else {
255 $prefix = null;
256 Hooks::run( 'BacklinkCacheGetPrefix', array( $table, &$prefix ) );
257 if ( $prefix ) {
258 return $prefix;
259 } else {
260 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
261 }
262 }
263 }
264
265 /**
266 * Get the SQL condition array for selecting backlinks, with a join
267 * on the page table.
268 * @param string $table
269 * @throws MWException
270 * @return array|null
271 */
272 protected function getConditions( $table ) {
273 $prefix = $this->getPrefix( $table );
274
275 switch ( $table ) {
276 case 'pagelinks':
277 case 'templatelinks':
278 $conds = array(
279 "{$prefix}_namespace" => $this->title->getNamespace(),
280 "{$prefix}_title" => $this->title->getDBkey(),
281 "page_id={$prefix}_from"
282 );
283 break;
284 case 'redirect':
285 $conds = array(
286 "{$prefix}_namespace" => $this->title->getNamespace(),
287 "{$prefix}_title" => $this->title->getDBkey(),
288 $this->getDb()->makeList( array(
289 "{$prefix}_interwiki" => '',
290 "{$prefix}_interwiki IS NULL",
291 ), LIST_OR ),
292 "page_id={$prefix}_from"
293 );
294 break;
295 case 'imagelinks':
296 case 'categorylinks':
297 $conds = array(
298 "{$prefix}_to" => $this->title->getDBkey(),
299 "page_id={$prefix}_from"
300 );
301 break;
302 default:
303 $conds = null;
304 Hooks::run( 'BacklinkCacheGetConditions', array( $table, $this->title, &$conds ) );
305 if ( !$conds ) {
306 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
307 }
308 }
309
310 return $conds;
311 }
312
313 /**
314 * Check if there are any backlinks
315 * @param string $table
316 * @return bool
317 */
318 public function hasLinks( $table ) {
319 return ( $this->getNumLinks( $table, 1 ) > 0 );
320 }
321
322 /**
323 * Get the approximate number of backlinks
324 * @param string $table
325 * @param int|INF $max Only count up to this many backlinks
326 * @return int
327 */
328 public function getNumLinks( $table, $max = INF ) {
329 global $wgMemc, $wgUpdateRowsPerJob;
330
331 // 1) try partition cache ...
332 if ( isset( $this->partitionCache[$table] ) ) {
333 $entry = reset( $this->partitionCache[$table] );
334
335 return min( $max, $entry['numRows'] );
336 }
337
338 // 2) ... then try full result cache ...
339 if ( isset( $this->fullResultCache[$table] ) ) {
340 return min( $max, $this->fullResultCache[$table]->numRows() );
341 }
342
343 $memcKey = wfMemcKey( 'numbacklinks', md5( $this->title->getPrefixedDBkey() ), $table );
344
345 // 3) ... fallback to memcached ...
346 $count = $wgMemc->get( $memcKey );
347 if ( $count ) {
348 return min( $max, $count );
349 }
350
351 // 4) fetch from the database ...
352 if ( is_infinite( $max ) ) { // no limit at all
353 // Use partition() since it will batch the query and skip the JOIN.
354 // Use $wgUpdateRowsPerJob just to encourage cache reuse for jobs.
355 $this->partition( $table, $wgUpdateRowsPerJob ); // updates $this->partitionCache
356 return $this->partitionCache[$table][$wgUpdateRowsPerJob]['numRows'];
357 } else { // probably some sane limit
358 // Fetch the full title info, since the caller will likely need it next
359 $count = $this->getLinks( $table, false, false, $max )->count();
360 if ( $count < $max ) { // full count
361 $wgMemc->set( $memcKey, $count, self::CACHE_EXPIRY );
362 }
363 }
364
365 return min( $max, $count );
366 }
367
368 /**
369 * Partition the backlinks into batches.
370 * Returns an array giving the start and end of each range. The first
371 * batch has a start of false, and the last batch has an end of false.
372 *
373 * @param string $table The links table name
374 * @param int $batchSize
375 * @return array
376 */
377 public function partition( $table, $batchSize ) {
378 global $wgMemc;
379
380 // 1) try partition cache ...
381 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
382 wfDebug( __METHOD__ . ": got from partition cache\n" );
383
384 return $this->partitionCache[$table][$batchSize]['batches'];
385 }
386
387 $this->partitionCache[$table][$batchSize] = false;
388 $cacheEntry =& $this->partitionCache[$table][$batchSize];
389
390 // 2) ... then try full result cache ...
391 if ( isset( $this->fullResultCache[$table] ) ) {
392 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
393 wfDebug( __METHOD__ . ": got from full result cache\n" );
394
395 return $cacheEntry['batches'];
396 }
397
398 $memcKey = wfMemcKey(
399 'backlinks',
400 md5( $this->title->getPrefixedDBkey() ),
401 $table,
402 $batchSize
403 );
404
405 // 3) ... fallback to memcached ...
406 $memcValue = $wgMemc->get( $memcKey );
407 if ( is_array( $memcValue ) ) {
408 $cacheEntry = $memcValue;
409 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
410
411 return $cacheEntry['batches'];
412 }
413
414 // 4) ... finally fetch from the slow database :(
415 $cacheEntry = array( 'numRows' => 0, 'batches' => array() ); // final result
416 // Do the selects in batches to avoid client-side OOMs (bug 43452).
417 // Use a LIMIT that plays well with $batchSize to keep equal sized partitions.
418 $selectSize = max( $batchSize, 200000 - ( 200000 % $batchSize ) );
419 $start = false;
420 do {
421 $res = $this->queryLinks( $table, $start, false, $selectSize, 'ids' );
422 $partitions = $this->partitionResult( $res, $batchSize, false );
423 // Merge the link count and range partitions for this chunk
424 $cacheEntry['numRows'] += $partitions['numRows'];
425 $cacheEntry['batches'] = array_merge( $cacheEntry['batches'], $partitions['batches'] );
426 if ( count( $partitions['batches'] ) ) {
427 list( , $lEnd ) = end( $partitions['batches'] );
428 $start = $lEnd + 1; // pick up after this inclusive range
429 }
430 } while ( $partitions['numRows'] >= $selectSize );
431 // Make sure the first range has start=false and the last one has end=false
432 if ( count( $cacheEntry['batches'] ) ) {
433 $cacheEntry['batches'][0][0] = false;
434 $cacheEntry['batches'][count( $cacheEntry['batches'] ) - 1][1] = false;
435 }
436
437 // Save partitions to memcached
438 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
439
440 // Save backlink count to memcached
441 $memcKey = wfMemcKey( 'numbacklinks', md5( $this->title->getPrefixedDBkey() ), $table );
442 $wgMemc->set( $memcKey, $cacheEntry['numRows'], self::CACHE_EXPIRY );
443
444 wfDebug( __METHOD__ . ": got from database\n" );
445
446 return $cacheEntry['batches'];
447 }
448
449 /**
450 * Partition a DB result with backlinks in it into batches
451 * @param ResultWrapper $res Database result
452 * @param int $batchSize
453 * @param bool $isComplete Whether $res includes all the backlinks
454 * @throws MWException
455 * @return array
456 */
457 protected function partitionResult( $res, $batchSize, $isComplete = true ) {
458 $batches = array();
459 $numRows = $res->numRows();
460 $numBatches = ceil( $numRows / $batchSize );
461
462 for ( $i = 0; $i < $numBatches; $i++ ) {
463 if ( $i == 0 && $isComplete ) {
464 $start = false;
465 } else {
466 $rowNum = $i * $batchSize;
467 $res->seek( $rowNum );
468 $row = $res->fetchObject();
469 $start = (int)$row->page_id;
470 }
471
472 if ( $i == ( $numBatches - 1 ) && $isComplete ) {
473 $end = false;
474 } else {
475 $rowNum = min( $numRows - 1, ( $i + 1 ) * $batchSize - 1 );
476 $res->seek( $rowNum );
477 $row = $res->fetchObject();
478 $end = (int)$row->page_id;
479 }
480
481 # Sanity check order
482 if ( $start && $end && $start > $end ) {
483 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
484 }
485
486 $batches[] = array( $start, $end );
487 }
488
489 return array( 'numRows' => $numRows, 'batches' => $batches );
490 }
491 }